{"repo_name": "opencode", "file_name": "/opencode/internal/tui/components/dialog/commands.go", "inference_info": {"prefix_code": "package dialog\n\nimport (\n\t\"github.com/charmbracelet/bubbles/key\"\n\ttea \"github.com/charmbracelet/bubbletea\"\n\t\"github.com/charmbracelet/lipgloss\"\n\tutilComponents \"github.com/opencode-ai/opencode/internal/tui/components/util\"\n\t\"github.com/opencode-ai/opencode/internal/tui/layout\"\n\t\"github.com/opencode-ai/opencode/internal/tui/styles\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n\t\"github.com/opencode-ai/opencode/internal/tui/util\"\n)\n\n// Command represents a command that can be executed\ntype Command struct {\n\tID string\n\tTitle string\n\tDescription string\n\tHandler func(cmd Command) tea.Cmd\n}\n\nfunc (ci Command) Render(selected bool, width int) string {\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\n\tdescStyle := baseStyle.Width(width).Foreground(t.TextMuted())\n\titemStyle := baseStyle.Width(width).\n\t\tForeground(t.Text()).\n\t\tBackground(t.Background())\n\n\tif selected {\n\t\titemStyle = itemStyle.\n\t\t\tBackground(t.Primary()).\n\t\t\tForeground(t.Background()).\n\t\t\tBold(true)\n\t\tdescStyle = descStyle.\n\t\t\tBackground(t.Primary()).\n\t\t\tForeground(t.Background())\n\t}\n\n\ttitle := itemStyle.Padding(0, 1).Render(ci.Title)\n\tif ci.Description != \"\" {\n\t\tdescription := descStyle.Padding(0, 1).Render(ci.Description)\n\t\treturn lipgloss.JoinVertical(lipgloss.Left, title, description)\n\t}\n\treturn title\n}\n\n// CommandSelectedMsg is sent when a command is selected\ntype CommandSelectedMsg struct {\n\tCommand Command\n}\n\n// CloseCommandDialogMsg is sent when the command dialog is closed\ntype CloseCommandDialogMsg struct{}\n\n// CommandDialog interface for the command selection dialog\ntype CommandDialog interface {\n\ttea.Model\n\tlayout.Bindings\n\tSetCommands(commands []Command)\n}\n\ntype commandDialogCmp struct {\n\tlistView utilComponents.SimpleList[Command]\n\twidth int\n\theight int\n}\n\ntype commandKeyMap struct {\n\tEnter key.Binding\n\tEscape key.Binding\n}\n\nvar commandKeys = commandKeyMap{\n\tEnter: key.NewBinding(\n\t\tkey.WithKeys(\"enter\"),\n\t\tkey.WithHelp(\"enter\", \"select command\"),\n\t),\n\tEscape: key.NewBinding(\n\t\tkey.WithKeys(\"esc\"),\n\t\tkey.WithHelp(\"esc\", \"close\"),\n\t),\n}\n\nfunc (c *commandDialogCmp) Init() tea.Cmd {\n\treturn c.listView.Init()\n}\n\nfunc (c *commandDialogCmp) Update(msg tea.Msg) (tea.Model, tea.Cmd) {\n\tvar cmds []tea.Cmd\n\tswitch msg := msg.(type) {\n\tcase tea.KeyMsg:\n\t\tswitch {\n\t\tcase key.Matches(msg, commandKeys.Enter):\n\t\t\tselectedItem, idx := c.listView.GetSelectedItem()\n\t\t\tif idx != -1 {\n\t\t\t\treturn c, util.CmdHandler(CommandSelectedMsg{\n\t\t\t\t\tCommand: selectedItem,\n\t\t\t\t})\n\t\t\t}\n\t\tcase key.Matches(msg, commandKeys.Escape):\n\t\t\treturn c, util.CmdHandler(CloseCommandDialogMsg{})\n\t\t}\n\tcase tea.WindowSizeMsg:\n\t\tc.width = msg.Width\n\t\tc.height = msg.Height\n\t}\n\n\tu, cmd := c.listView.Update(msg)\n\tc.listView = u.(utilComponents.SimpleList[Command])\n\tcmds = append(cmds, cmd)\n\n\treturn c, tea.Batch(cmds...)\n}\n\nfunc (c *commandDialogCmp) View() string {\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\n\tmaxWidth := 40\n\n\tcommands := c.listView.GetItems()\n\n\tfor _, cmd := range commands {\n\t\tif len(cmd.Title) > maxWidth-4 {\n\t\t\tmaxWidth = len(cmd.Title) + 4\n\t\t}\n\t\tif cmd.Description != \"\" {\n\t\t\tif len(cmd.Description) > maxWidth-4 {\n\t\t\t\tmaxWidth = len(cmd.Description) + 4\n\t\t\t}\n\t\t}\n\t}\n\n\tc.listView.SetMaxWidth(maxWidth)\n\n\ttitle := baseStyle.\n\t\tForeground(t.Primary()).\n\t\tBold(true).\n\t\tWidth(maxWidth).\n\t\tPadding(0, 1).\n\t\tRender(\"Commands\")\n\n\tcontent := lipgloss.JoinVertical(\n\t\tlipgloss.Left,\n\t\ttitle,\n\t\tbaseStyle.Width(maxWidth).Render(\"\"),\n\t\tbaseStyle.Width(maxWidth).Render(c.listView.View()),\n\t\tbaseStyle.Width(maxWidth).Render(\"\"),\n\t)\n\n\treturn baseStyle.Padding(1, 2).\n\t\tBorder(lipgloss.RoundedBorder()).\n\t\tBorderBackground(t.Background()).\n\t\tBorderForeground(t.TextMuted()).\n\t\tWidth(lipgloss.Width(content) + 4).\n\t\tRender(content)\n}\n\nfunc (c *commandDialogCmp) BindingKeys() []key.Binding {\n\treturn layout.KeyMapToSlice(commandKeys)\n}\n\nfunc (c *commandDialogCmp) SetCommands(commands []Command) {\n\tc.listView.SetItems(commands)\n}\n\n// NewCommandDialogCmp creates a new command selection dialog\n", "suffix_code": "\n", "middle_code": "func NewCommandDialogCmp() CommandDialog {\n\tlistView := utilComponents.NewSimpleList[Command](\n\t\t[]Command{},\n\t\t10,\n\t\t\"No commands available\",\n\t\ttrue,\n\t)\n\treturn &commandDialogCmp{\n\t\tlistView: listView,\n\t}\n}", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "go", "sub_task_type": null}, "context_code": [["/opencode/internal/tui/components/dialog/complete.go", "package dialog\n\nimport (\n\t\"github.com/charmbracelet/bubbles/key\"\n\t\"github.com/charmbracelet/bubbles/textarea\"\n\ttea \"github.com/charmbracelet/bubbletea\"\n\t\"github.com/charmbracelet/lipgloss\"\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n\tutilComponents \"github.com/opencode-ai/opencode/internal/tui/components/util\"\n\t\"github.com/opencode-ai/opencode/internal/tui/layout\"\n\t\"github.com/opencode-ai/opencode/internal/tui/styles\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n\t\"github.com/opencode-ai/opencode/internal/tui/util\"\n)\n\ntype CompletionItem struct {\n\ttitle string\n\tTitle string\n\tValue string\n}\n\ntype CompletionItemI interface {\n\tutilComponents.SimpleListItem\n\tGetValue() string\n\tDisplayValue() string\n}\n\nfunc (ci *CompletionItem) Render(selected bool, width int) string {\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\n\titemStyle := baseStyle.\n\t\tWidth(width).\n\t\tPadding(0, 1)\n\n\tif selected {\n\t\titemStyle = itemStyle.\n\t\t\tBackground(t.Background()).\n\t\t\tForeground(t.Primary()).\n\t\t\tBold(true)\n\t}\n\n\ttitle := itemStyle.Render(\n\t\tci.GetValue(),\n\t)\n\n\treturn title\n}\n\nfunc (ci *CompletionItem) DisplayValue() string {\n\treturn ci.Title\n}\n\nfunc (ci *CompletionItem) GetValue() string {\n\treturn ci.Value\n}\n\nfunc NewCompletionItem(completionItem CompletionItem) CompletionItemI {\n\treturn &completionItem\n}\n\ntype CompletionProvider interface {\n\tGetId() string\n\tGetEntry() CompletionItemI\n\tGetChildEntries(query string) ([]CompletionItemI, error)\n}\n\ntype CompletionSelectedMsg struct {\n\tSearchString string\n\tCompletionValue string\n}\n\ntype CompletionDialogCompleteItemMsg struct {\n\tValue string\n}\n\ntype CompletionDialogCloseMsg struct{}\n\ntype CompletionDialog interface {\n\ttea.Model\n\tlayout.Bindings\n\tSetWidth(width int)\n}\n\ntype completionDialogCmp struct {\n\tquery string\n\tcompletionProvider CompletionProvider\n\twidth int\n\theight int\n\tpseudoSearchTextArea textarea.Model\n\tlistView utilComponents.SimpleList[CompletionItemI]\n}\n\ntype completionDialogKeyMap struct {\n\tComplete key.Binding\n\tCancel key.Binding\n}\n\nvar completionDialogKeys = completionDialogKeyMap{\n\tComplete: key.NewBinding(\n\t\tkey.WithKeys(\"tab\", \"enter\"),\n\t),\n\tCancel: key.NewBinding(\n\t\tkey.WithKeys(\" \", \"esc\", \"backspace\"),\n\t),\n}\n\nfunc (c *completionDialogCmp) Init() tea.Cmd {\n\treturn nil\n}\n\nfunc (c *completionDialogCmp) complete(item CompletionItemI) tea.Cmd {\n\tvalue := c.pseudoSearchTextArea.Value()\n\n\tif value == \"\" {\n\t\treturn nil\n\t}\n\n\treturn tea.Batch(\n\t\tutil.CmdHandler(CompletionSelectedMsg{\n\t\t\tSearchString: value,\n\t\t\tCompletionValue: item.GetValue(),\n\t\t}),\n\t\tc.close(),\n\t)\n}\n\nfunc (c *completionDialogCmp) close() tea.Cmd {\n\tc.listView.SetItems([]CompletionItemI{})\n\tc.pseudoSearchTextArea.Reset()\n\tc.pseudoSearchTextArea.Blur()\n\n\treturn util.CmdHandler(CompletionDialogCloseMsg{})\n}\n\nfunc (c *completionDialogCmp) Update(msg tea.Msg) (tea.Model, tea.Cmd) {\n\tvar cmds []tea.Cmd\n\tswitch msg := msg.(type) {\n\tcase tea.KeyMsg:\n\t\tif c.pseudoSearchTextArea.Focused() {\n\n\t\t\tif !key.Matches(msg, completionDialogKeys.Complete) {\n\n\t\t\t\tvar cmd tea.Cmd\n\t\t\t\tc.pseudoSearchTextArea, cmd = c.pseudoSearchTextArea.Update(msg)\n\t\t\t\tcmds = append(cmds, cmd)\n\n\t\t\t\tvar query string\n\t\t\t\tquery = c.pseudoSearchTextArea.Value()\n\t\t\t\tif query != \"\" {\n\t\t\t\t\tquery = query[1:]\n\t\t\t\t}\n\n\t\t\t\tif query != c.query {\n\t\t\t\t\tlogging.Info(\"Query\", query)\n\t\t\t\t\titems, err := c.completionProvider.GetChildEntries(query)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlogging.Error(\"Failed to get child entries\", err)\n\t\t\t\t\t}\n\n\t\t\t\t\tc.listView.SetItems(items)\n\t\t\t\t\tc.query = query\n\t\t\t\t}\n\n\t\t\t\tu, cmd := c.listView.Update(msg)\n\t\t\t\tc.listView = u.(utilComponents.SimpleList[CompletionItemI])\n\n\t\t\t\tcmds = append(cmds, cmd)\n\t\t\t}\n\n\t\t\tswitch {\n\t\t\tcase key.Matches(msg, completionDialogKeys.Complete):\n\t\t\t\titem, i := c.listView.GetSelectedItem()\n\t\t\t\tif i == -1 {\n\t\t\t\t\treturn c, nil\n\t\t\t\t}\n\n\t\t\t\tcmd := c.complete(item)\n\n\t\t\t\treturn c, cmd\n\t\t\tcase key.Matches(msg, completionDialogKeys.Cancel):\n\t\t\t\t// Only close on backspace when there are no characters left\n\t\t\t\tif msg.String() != \"backspace\" || len(c.pseudoSearchTextArea.Value()) <= 0 {\n\t\t\t\t\treturn c, c.close()\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn c, tea.Batch(cmds...)\n\t\t} else {\n\t\t\titems, err := c.completionProvider.GetChildEntries(\"\")\n\t\t\tif err != nil {\n\t\t\t\tlogging.Error(\"Failed to get child entries\", err)\n\t\t\t}\n\n\t\t\tc.listView.SetItems(items)\n\t\t\tc.pseudoSearchTextArea.SetValue(msg.String())\n\t\t\treturn c, c.pseudoSearchTextArea.Focus()\n\t\t}\n\tcase tea.WindowSizeMsg:\n\t\tc.width = msg.Width\n\t\tc.height = msg.Height\n\t}\n\n\treturn c, tea.Batch(cmds...)\n}\n\nfunc (c *completionDialogCmp) View() string {\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\n\tmaxWidth := 40\n\n\tcompletions := c.listView.GetItems()\n\n\tfor _, cmd := range completions {\n\t\ttitle := cmd.DisplayValue()\n\t\tif len(title) > maxWidth-4 {\n\t\t\tmaxWidth = len(title) + 4\n\t\t}\n\t}\n\n\tc.listView.SetMaxWidth(maxWidth)\n\n\treturn baseStyle.Padding(0, 0).\n\t\tBorder(lipgloss.NormalBorder()).\n\t\tBorderBottom(false).\n\t\tBorderRight(false).\n\t\tBorderLeft(false).\n\t\tBorderBackground(t.Background()).\n\t\tBorderForeground(t.TextMuted()).\n\t\tWidth(c.width).\n\t\tRender(c.listView.View())\n}\n\nfunc (c *completionDialogCmp) SetWidth(width int) {\n\tc.width = width\n}\n\nfunc (c *completionDialogCmp) BindingKeys() []key.Binding {\n\treturn layout.KeyMapToSlice(completionDialogKeys)\n}\n\nfunc NewCompletionDialogCmp(completionProvider CompletionProvider) CompletionDialog {\n\tti := textarea.New()\n\n\titems, err := completionProvider.GetChildEntries(\"\")\n\tif err != nil {\n\t\tlogging.Error(\"Failed to get child entries\", err)\n\t}\n\n\tli := utilComponents.NewSimpleList(\n\t\titems,\n\t\t7,\n\t\t\"No file matches found\",\n\t\tfalse,\n\t)\n\n\treturn &completionDialogCmp{\n\t\tquery: \"\",\n\t\tcompletionProvider: completionProvider,\n\t\tpseudoSearchTextArea: ti,\n\t\tlistView: li,\n\t}\n}\n"], ["/opencode/internal/tui/components/dialog/session.go", "package dialog\n\nimport (\n\t\"github.com/charmbracelet/bubbles/key\"\n\ttea \"github.com/charmbracelet/bubbletea\"\n\t\"github.com/charmbracelet/lipgloss\"\n\t\"github.com/opencode-ai/opencode/internal/session\"\n\t\"github.com/opencode-ai/opencode/internal/tui/layout\"\n\t\"github.com/opencode-ai/opencode/internal/tui/styles\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n\t\"github.com/opencode-ai/opencode/internal/tui/util\"\n)\n\n// SessionSelectedMsg is sent when a session is selected\ntype SessionSelectedMsg struct {\n\tSession session.Session\n}\n\n// CloseSessionDialogMsg is sent when the session dialog is closed\ntype CloseSessionDialogMsg struct{}\n\n// SessionDialog interface for the session switching dialog\ntype SessionDialog interface {\n\ttea.Model\n\tlayout.Bindings\n\tSetSessions(sessions []session.Session)\n\tSetSelectedSession(sessionID string)\n}\n\ntype sessionDialogCmp struct {\n\tsessions []session.Session\n\tselectedIdx int\n\twidth int\n\theight int\n\tselectedSessionID string\n}\n\ntype sessionKeyMap struct {\n\tUp key.Binding\n\tDown key.Binding\n\tEnter key.Binding\n\tEscape key.Binding\n\tJ key.Binding\n\tK key.Binding\n}\n\nvar sessionKeys = sessionKeyMap{\n\tUp: key.NewBinding(\n\t\tkey.WithKeys(\"up\"),\n\t\tkey.WithHelp(\"↑\", \"previous session\"),\n\t),\n\tDown: key.NewBinding(\n\t\tkey.WithKeys(\"down\"),\n\t\tkey.WithHelp(\"↓\", \"next session\"),\n\t),\n\tEnter: key.NewBinding(\n\t\tkey.WithKeys(\"enter\"),\n\t\tkey.WithHelp(\"enter\", \"select session\"),\n\t),\n\tEscape: key.NewBinding(\n\t\tkey.WithKeys(\"esc\"),\n\t\tkey.WithHelp(\"esc\", \"close\"),\n\t),\n\tJ: key.NewBinding(\n\t\tkey.WithKeys(\"j\"),\n\t\tkey.WithHelp(\"j\", \"next session\"),\n\t),\n\tK: key.NewBinding(\n\t\tkey.WithKeys(\"k\"),\n\t\tkey.WithHelp(\"k\", \"previous session\"),\n\t),\n}\n\nfunc (s *sessionDialogCmp) Init() tea.Cmd {\n\treturn nil\n}\n\nfunc (s *sessionDialogCmp) Update(msg tea.Msg) (tea.Model, tea.Cmd) {\n\tswitch msg := msg.(type) {\n\tcase tea.KeyMsg:\n\t\tswitch {\n\t\tcase key.Matches(msg, sessionKeys.Up) || key.Matches(msg, sessionKeys.K):\n\t\t\tif s.selectedIdx > 0 {\n\t\t\t\ts.selectedIdx--\n\t\t\t}\n\t\t\treturn s, nil\n\t\tcase key.Matches(msg, sessionKeys.Down) || key.Matches(msg, sessionKeys.J):\n\t\t\tif s.selectedIdx < len(s.sessions)-1 {\n\t\t\t\ts.selectedIdx++\n\t\t\t}\n\t\t\treturn s, nil\n\t\tcase key.Matches(msg, sessionKeys.Enter):\n\t\t\tif len(s.sessions) > 0 {\n\t\t\t\treturn s, util.CmdHandler(SessionSelectedMsg{\n\t\t\t\t\tSession: s.sessions[s.selectedIdx],\n\t\t\t\t})\n\t\t\t}\n\t\tcase key.Matches(msg, sessionKeys.Escape):\n\t\t\treturn s, util.CmdHandler(CloseSessionDialogMsg{})\n\t\t}\n\tcase tea.WindowSizeMsg:\n\t\ts.width = msg.Width\n\t\ts.height = msg.Height\n\t}\n\treturn s, nil\n}\n\nfunc (s *sessionDialogCmp) View() string {\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\t\n\tif len(s.sessions) == 0 {\n\t\treturn baseStyle.Padding(1, 2).\n\t\t\tBorder(lipgloss.RoundedBorder()).\n\t\t\tBorderBackground(t.Background()).\n\t\t\tBorderForeground(t.TextMuted()).\n\t\t\tWidth(40).\n\t\t\tRender(\"No sessions available\")\n\t}\n\n\t// Calculate max width needed for session titles\n\tmaxWidth := 40 // Minimum width\n\tfor _, sess := range s.sessions {\n\t\tif len(sess.Title) > maxWidth-4 { // Account for padding\n\t\t\tmaxWidth = len(sess.Title) + 4\n\t\t}\n\t}\n\n\tmaxWidth = max(30, min(maxWidth, s.width-15)) // Limit width to avoid overflow\n\n\t// Limit height to avoid taking up too much screen space\n\tmaxVisibleSessions := min(10, len(s.sessions))\n\n\t// Build the session list\n\tsessionItems := make([]string, 0, maxVisibleSessions)\n\tstartIdx := 0\n\n\t// If we have more sessions than can be displayed, adjust the start index\n\tif len(s.sessions) > maxVisibleSessions {\n\t\t// Center the selected item when possible\n\t\thalfVisible := maxVisibleSessions / 2\n\t\tif s.selectedIdx >= halfVisible && s.selectedIdx < len(s.sessions)-halfVisible {\n\t\t\tstartIdx = s.selectedIdx - halfVisible\n\t\t} else if s.selectedIdx >= len(s.sessions)-halfVisible {\n\t\t\tstartIdx = len(s.sessions) - maxVisibleSessions\n\t\t}\n\t}\n\n\tendIdx := min(startIdx+maxVisibleSessions, len(s.sessions))\n\n\tfor i := startIdx; i < endIdx; i++ {\n\t\tsess := s.sessions[i]\n\t\titemStyle := baseStyle.Width(maxWidth)\n\n\t\tif i == s.selectedIdx {\n\t\t\titemStyle = itemStyle.\n\t\t\t\tBackground(t.Primary()).\n\t\t\t\tForeground(t.Background()).\n\t\t\t\tBold(true)\n\t\t}\n\n\t\tsessionItems = append(sessionItems, itemStyle.Padding(0, 1).Render(sess.Title))\n\t}\n\n\ttitle := baseStyle.\n\t\tForeground(t.Primary()).\n\t\tBold(true).\n\t\tWidth(maxWidth).\n\t\tPadding(0, 1).\n\t\tRender(\"Switch Session\")\n\n\tcontent := lipgloss.JoinVertical(\n\t\tlipgloss.Left,\n\t\ttitle,\n\t\tbaseStyle.Width(maxWidth).Render(\"\"),\n\t\tbaseStyle.Width(maxWidth).Render(lipgloss.JoinVertical(lipgloss.Left, sessionItems...)),\n\t\tbaseStyle.Width(maxWidth).Render(\"\"),\n\t)\n\n\treturn baseStyle.Padding(1, 2).\n\t\tBorder(lipgloss.RoundedBorder()).\n\t\tBorderBackground(t.Background()).\n\t\tBorderForeground(t.TextMuted()).\n\t\tWidth(lipgloss.Width(content) + 4).\n\t\tRender(content)\n}\n\nfunc (s *sessionDialogCmp) BindingKeys() []key.Binding {\n\treturn layout.KeyMapToSlice(sessionKeys)\n}\n\nfunc (s *sessionDialogCmp) SetSessions(sessions []session.Session) {\n\ts.sessions = sessions\n\n\t// If we have a selected session ID, find its index\n\tif s.selectedSessionID != \"\" {\n\t\tfor i, sess := range sessions {\n\t\t\tif sess.ID == s.selectedSessionID {\n\t\t\t\ts.selectedIdx = i\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\n\t// Default to first session if selected not found\n\ts.selectedIdx = 0\n}\n\nfunc (s *sessionDialogCmp) SetSelectedSession(sessionID string) {\n\ts.selectedSessionID = sessionID\n\n\t// Update the selected index if sessions are already loaded\n\tif len(s.sessions) > 0 {\n\t\tfor i, sess := range s.sessions {\n\t\t\tif sess.ID == sessionID {\n\t\t\t\ts.selectedIdx = i\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}\n\n// NewSessionDialogCmp creates a new session switching dialog\nfunc NewSessionDialogCmp() SessionDialog {\n\treturn &sessionDialogCmp{\n\t\tsessions: []session.Session{},\n\t\tselectedIdx: 0,\n\t\tselectedSessionID: \"\",\n\t}\n}\n"], ["/opencode/internal/tui/components/dialog/theme.go", "package dialog\n\nimport (\n\t\"github.com/charmbracelet/bubbles/key\"\n\ttea \"github.com/charmbracelet/bubbletea\"\n\t\"github.com/charmbracelet/lipgloss\"\n\t\"github.com/opencode-ai/opencode/internal/tui/layout\"\n\t\"github.com/opencode-ai/opencode/internal/tui/styles\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n\t\"github.com/opencode-ai/opencode/internal/tui/util\"\n)\n\n// ThemeChangedMsg is sent when the theme is changed\ntype ThemeChangedMsg struct {\n\tThemeName string\n}\n\n// CloseThemeDialogMsg is sent when the theme dialog is closed\ntype CloseThemeDialogMsg struct{}\n\n// ThemeDialog interface for the theme switching dialog\ntype ThemeDialog interface {\n\ttea.Model\n\tlayout.Bindings\n}\n\ntype themeDialogCmp struct {\n\tthemes []string\n\tselectedIdx int\n\twidth int\n\theight int\n\tcurrentTheme string\n}\n\ntype themeKeyMap struct {\n\tUp key.Binding\n\tDown key.Binding\n\tEnter key.Binding\n\tEscape key.Binding\n\tJ key.Binding\n\tK key.Binding\n}\n\nvar themeKeys = themeKeyMap{\n\tUp: key.NewBinding(\n\t\tkey.WithKeys(\"up\"),\n\t\tkey.WithHelp(\"↑\", \"previous theme\"),\n\t),\n\tDown: key.NewBinding(\n\t\tkey.WithKeys(\"down\"),\n\t\tkey.WithHelp(\"↓\", \"next theme\"),\n\t),\n\tEnter: key.NewBinding(\n\t\tkey.WithKeys(\"enter\"),\n\t\tkey.WithHelp(\"enter\", \"select theme\"),\n\t),\n\tEscape: key.NewBinding(\n\t\tkey.WithKeys(\"esc\"),\n\t\tkey.WithHelp(\"esc\", \"close\"),\n\t),\n\tJ: key.NewBinding(\n\t\tkey.WithKeys(\"j\"),\n\t\tkey.WithHelp(\"j\", \"next theme\"),\n\t),\n\tK: key.NewBinding(\n\t\tkey.WithKeys(\"k\"),\n\t\tkey.WithHelp(\"k\", \"previous theme\"),\n\t),\n}\n\nfunc (t *themeDialogCmp) Init() tea.Cmd {\n\t// Load available themes and update selectedIdx based on current theme\n\tt.themes = theme.AvailableThemes()\n\tt.currentTheme = theme.CurrentThemeName()\n\n\t// Find the current theme in the list\n\tfor i, name := range t.themes {\n\t\tif name == t.currentTheme {\n\t\t\tt.selectedIdx = i\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc (t *themeDialogCmp) Update(msg tea.Msg) (tea.Model, tea.Cmd) {\n\tswitch msg := msg.(type) {\n\tcase tea.KeyMsg:\n\t\tswitch {\n\t\tcase key.Matches(msg, themeKeys.Up) || key.Matches(msg, themeKeys.K):\n\t\t\tif t.selectedIdx > 0 {\n\t\t\t\tt.selectedIdx--\n\t\t\t}\n\t\t\treturn t, nil\n\t\tcase key.Matches(msg, themeKeys.Down) || key.Matches(msg, themeKeys.J):\n\t\t\tif t.selectedIdx < len(t.themes)-1 {\n\t\t\t\tt.selectedIdx++\n\t\t\t}\n\t\t\treturn t, nil\n\t\tcase key.Matches(msg, themeKeys.Enter):\n\t\t\tif len(t.themes) > 0 {\n\t\t\t\tpreviousTheme := theme.CurrentThemeName()\n\t\t\t\tselectedTheme := t.themes[t.selectedIdx]\n\t\t\t\tif previousTheme == selectedTheme {\n\t\t\t\t\treturn t, util.CmdHandler(CloseThemeDialogMsg{})\n\t\t\t\t}\n\t\t\t\tif err := theme.SetTheme(selectedTheme); err != nil {\n\t\t\t\t\treturn t, util.ReportError(err)\n\t\t\t\t}\n\t\t\t\treturn t, util.CmdHandler(ThemeChangedMsg{\n\t\t\t\t\tThemeName: selectedTheme,\n\t\t\t\t})\n\t\t\t}\n\t\tcase key.Matches(msg, themeKeys.Escape):\n\t\t\treturn t, util.CmdHandler(CloseThemeDialogMsg{})\n\t\t}\n\tcase tea.WindowSizeMsg:\n\t\tt.width = msg.Width\n\t\tt.height = msg.Height\n\t}\n\treturn t, nil\n}\n\nfunc (t *themeDialogCmp) View() string {\n\tcurrentTheme := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\n\tif len(t.themes) == 0 {\n\t\treturn baseStyle.Padding(1, 2).\n\t\t\tBorder(lipgloss.RoundedBorder()).\n\t\t\tBorderBackground(currentTheme.Background()).\n\t\t\tBorderForeground(currentTheme.TextMuted()).\n\t\t\tWidth(40).\n\t\t\tRender(\"No themes available\")\n\t}\n\n\t// Calculate max width needed for theme names\n\tmaxWidth := 40 // Minimum width\n\tfor _, themeName := range t.themes {\n\t\tif len(themeName) > maxWidth-4 { // Account for padding\n\t\t\tmaxWidth = len(themeName) + 4\n\t\t}\n\t}\n\n\tmaxWidth = max(30, min(maxWidth, t.width-15)) // Limit width to avoid overflow\n\n\t// Build the theme list\n\tthemeItems := make([]string, 0, len(t.themes))\n\tfor i, themeName := range t.themes {\n\t\titemStyle := baseStyle.Width(maxWidth)\n\n\t\tif i == t.selectedIdx {\n\t\t\titemStyle = itemStyle.\n\t\t\t\tBackground(currentTheme.Primary()).\n\t\t\t\tForeground(currentTheme.Background()).\n\t\t\t\tBold(true)\n\t\t}\n\n\t\tthemeItems = append(themeItems, itemStyle.Padding(0, 1).Render(themeName))\n\t}\n\n\ttitle := baseStyle.\n\t\tForeground(currentTheme.Primary()).\n\t\tBold(true).\n\t\tWidth(maxWidth).\n\t\tPadding(0, 1).\n\t\tRender(\"Select Theme\")\n\n\tcontent := lipgloss.JoinVertical(\n\t\tlipgloss.Left,\n\t\ttitle,\n\t\tbaseStyle.Width(maxWidth).Render(\"\"),\n\t\tbaseStyle.Width(maxWidth).Render(lipgloss.JoinVertical(lipgloss.Left, themeItems...)),\n\t\tbaseStyle.Width(maxWidth).Render(\"\"),\n\t)\n\n\treturn baseStyle.Padding(1, 2).\n\t\tBorder(lipgloss.RoundedBorder()).\n\t\tBorderBackground(currentTheme.Background()).\n\t\tBorderForeground(currentTheme.TextMuted()).\n\t\tWidth(lipgloss.Width(content) + 4).\n\t\tRender(content)\n}\n\nfunc (t *themeDialogCmp) BindingKeys() []key.Binding {\n\treturn layout.KeyMapToSlice(themeKeys)\n}\n\n// NewThemeDialogCmp creates a new theme switching dialog\nfunc NewThemeDialogCmp() ThemeDialog {\n\treturn &themeDialogCmp{\n\t\tthemes: []string{},\n\t\tselectedIdx: 0,\n\t\tcurrentTheme: \"\",\n\t}\n}\n\n"], ["/opencode/internal/tui/components/dialog/arguments.go", "package dialog\n\nimport (\n\t\"fmt\"\n\t\"github.com/charmbracelet/bubbles/key\"\n\t\"github.com/charmbracelet/bubbles/textinput\"\n\ttea \"github.com/charmbracelet/bubbletea\"\n\t\"github.com/charmbracelet/lipgloss\"\n\n\t\"github.com/opencode-ai/opencode/internal/tui/styles\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n\t\"github.com/opencode-ai/opencode/internal/tui/util\"\n)\n\ntype argumentsDialogKeyMap struct {\n\tEnter key.Binding\n\tEscape key.Binding\n}\n\n// ShortHelp implements key.Map.\nfunc (k argumentsDialogKeyMap) ShortHelp() []key.Binding {\n\treturn []key.Binding{\n\t\tkey.NewBinding(\n\t\t\tkey.WithKeys(\"enter\"),\n\t\t\tkey.WithHelp(\"enter\", \"confirm\"),\n\t\t),\n\t\tkey.NewBinding(\n\t\t\tkey.WithKeys(\"esc\"),\n\t\t\tkey.WithHelp(\"esc\", \"cancel\"),\n\t\t),\n\t}\n}\n\n// FullHelp implements key.Map.\nfunc (k argumentsDialogKeyMap) FullHelp() [][]key.Binding {\n\treturn [][]key.Binding{k.ShortHelp()}\n}\n\n// ShowMultiArgumentsDialogMsg is a message that is sent to show the multi-arguments dialog.\ntype ShowMultiArgumentsDialogMsg struct {\n\tCommandID string\n\tContent string\n\tArgNames []string\n}\n\n// CloseMultiArgumentsDialogMsg is a message that is sent when the multi-arguments dialog is closed.\ntype CloseMultiArgumentsDialogMsg struct {\n\tSubmit bool\n\tCommandID string\n\tContent string\n\tArgs map[string]string\n}\n\n// MultiArgumentsDialogCmp is a component that asks the user for multiple command arguments.\ntype MultiArgumentsDialogCmp struct {\n\twidth, height int\n\tinputs []textinput.Model\n\tfocusIndex int\n\tkeys argumentsDialogKeyMap\n\tcommandID string\n\tcontent string\n\targNames []string\n}\n\n// NewMultiArgumentsDialogCmp creates a new MultiArgumentsDialogCmp.\nfunc NewMultiArgumentsDialogCmp(commandID, content string, argNames []string) MultiArgumentsDialogCmp {\n\tt := theme.CurrentTheme()\n\tinputs := make([]textinput.Model, len(argNames))\n\n\tfor i, name := range argNames {\n\t\tti := textinput.New()\n\t\tti.Placeholder = fmt.Sprintf(\"Enter value for %s...\", name)\n\t\tti.Width = 40\n\t\tti.Prompt = \"\"\n\t\tti.PlaceholderStyle = ti.PlaceholderStyle.Background(t.Background())\n\t\tti.PromptStyle = ti.PromptStyle.Background(t.Background())\n\t\tti.TextStyle = ti.TextStyle.Background(t.Background())\n\t\t\n\t\t// Only focus the first input initially\n\t\tif i == 0 {\n\t\t\tti.Focus()\n\t\t\tti.PromptStyle = ti.PromptStyle.Foreground(t.Primary())\n\t\t\tti.TextStyle = ti.TextStyle.Foreground(t.Primary())\n\t\t} else {\n\t\t\tti.Blur()\n\t\t}\n\n\t\tinputs[i] = ti\n\t}\n\n\treturn MultiArgumentsDialogCmp{\n\t\tinputs: inputs,\n\t\tkeys: argumentsDialogKeyMap{},\n\t\tcommandID: commandID,\n\t\tcontent: content,\n\t\targNames: argNames,\n\t\tfocusIndex: 0,\n\t}\n}\n\n// Init implements tea.Model.\nfunc (m MultiArgumentsDialogCmp) Init() tea.Cmd {\n\t// Make sure only the first input is focused\n\tfor i := range m.inputs {\n\t\tif i == 0 {\n\t\t\tm.inputs[i].Focus()\n\t\t} else {\n\t\t\tm.inputs[i].Blur()\n\t\t}\n\t}\n\t\n\treturn textinput.Blink\n}\n\n// Update implements tea.Model.\nfunc (m MultiArgumentsDialogCmp) Update(msg tea.Msg) (tea.Model, tea.Cmd) {\n\tvar cmds []tea.Cmd\n\tt := theme.CurrentTheme()\n\n\tswitch msg := msg.(type) {\n\tcase tea.KeyMsg:\n\t\tswitch {\n\t\tcase key.Matches(msg, key.NewBinding(key.WithKeys(\"esc\"))):\n\t\t\treturn m, util.CmdHandler(CloseMultiArgumentsDialogMsg{\n\t\t\t\tSubmit: false,\n\t\t\t\tCommandID: m.commandID,\n\t\t\t\tContent: m.content,\n\t\t\t\tArgs: nil,\n\t\t\t})\n\t\tcase key.Matches(msg, key.NewBinding(key.WithKeys(\"enter\"))):\n\t\t\t// If we're on the last input, submit the form\n\t\t\tif m.focusIndex == len(m.inputs)-1 {\n\t\t\t\targs := make(map[string]string)\n\t\t\t\tfor i, name := range m.argNames {\n\t\t\t\t\targs[name] = m.inputs[i].Value()\n\t\t\t\t}\n\t\t\t\treturn m, util.CmdHandler(CloseMultiArgumentsDialogMsg{\n\t\t\t\t\tSubmit: true,\n\t\t\t\t\tCommandID: m.commandID,\n\t\t\t\t\tContent: m.content,\n\t\t\t\t\tArgs: args,\n\t\t\t\t})\n\t\t\t}\n\t\t\t// Otherwise, move to the next input\n\t\t\tm.inputs[m.focusIndex].Blur()\n\t\t\tm.focusIndex++\n\t\t\tm.inputs[m.focusIndex].Focus()\n\t\t\tm.inputs[m.focusIndex].PromptStyle = m.inputs[m.focusIndex].PromptStyle.Foreground(t.Primary())\n\t\t\tm.inputs[m.focusIndex].TextStyle = m.inputs[m.focusIndex].TextStyle.Foreground(t.Primary())\n\t\tcase key.Matches(msg, key.NewBinding(key.WithKeys(\"tab\"))):\n\t\t\t// Move to the next input\n\t\t\tm.inputs[m.focusIndex].Blur()\n\t\t\tm.focusIndex = (m.focusIndex + 1) % len(m.inputs)\n\t\t\tm.inputs[m.focusIndex].Focus()\n\t\t\tm.inputs[m.focusIndex].PromptStyle = m.inputs[m.focusIndex].PromptStyle.Foreground(t.Primary())\n\t\t\tm.inputs[m.focusIndex].TextStyle = m.inputs[m.focusIndex].TextStyle.Foreground(t.Primary())\n\t\tcase key.Matches(msg, key.NewBinding(key.WithKeys(\"shift+tab\"))):\n\t\t\t// Move to the previous input\n\t\t\tm.inputs[m.focusIndex].Blur()\n\t\t\tm.focusIndex = (m.focusIndex - 1 + len(m.inputs)) % len(m.inputs)\n\t\t\tm.inputs[m.focusIndex].Focus()\n\t\t\tm.inputs[m.focusIndex].PromptStyle = m.inputs[m.focusIndex].PromptStyle.Foreground(t.Primary())\n\t\t\tm.inputs[m.focusIndex].TextStyle = m.inputs[m.focusIndex].TextStyle.Foreground(t.Primary())\n\t\t}\n\tcase tea.WindowSizeMsg:\n\t\tm.width = msg.Width\n\t\tm.height = msg.Height\n\t}\n\n\t// Update the focused input\n\tvar cmd tea.Cmd\n\tm.inputs[m.focusIndex], cmd = m.inputs[m.focusIndex].Update(msg)\n\tcmds = append(cmds, cmd)\n\n\treturn m, tea.Batch(cmds...)\n}\n\n// View implements tea.Model.\nfunc (m MultiArgumentsDialogCmp) View() string {\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\n\t// Calculate width needed for content\n\tmaxWidth := 60 // Width for explanation text\n\n\ttitle := lipgloss.NewStyle().\n\t\tForeground(t.Primary()).\n\t\tBold(true).\n\t\tWidth(maxWidth).\n\t\tPadding(0, 1).\n\t\tBackground(t.Background()).\n\t\tRender(\"Command Arguments\")\n\n\texplanation := lipgloss.NewStyle().\n\t\tForeground(t.Text()).\n\t\tWidth(maxWidth).\n\t\tPadding(0, 1).\n\t\tBackground(t.Background()).\n\t\tRender(\"This command requires multiple arguments. Please enter values for each:\")\n\n\t// Create input fields for each argument\n\tinputFields := make([]string, len(m.inputs))\n\tfor i, input := range m.inputs {\n\t\t// Highlight the label of the focused input\n\t\tlabelStyle := lipgloss.NewStyle().\n\t\t\tWidth(maxWidth).\n\t\t\tPadding(1, 1, 0, 1).\n\t\t\tBackground(t.Background())\n\t\t\t\n\t\tif i == m.focusIndex {\n\t\t\tlabelStyle = labelStyle.Foreground(t.Primary()).Bold(true)\n\t\t} else {\n\t\t\tlabelStyle = labelStyle.Foreground(t.TextMuted())\n\t\t}\n\t\t\n\t\tlabel := labelStyle.Render(m.argNames[i] + \":\")\n\n\t\tfield := lipgloss.NewStyle().\n\t\t\tForeground(t.Text()).\n\t\t\tWidth(maxWidth).\n\t\t\tPadding(0, 1).\n\t\t\tBackground(t.Background()).\n\t\t\tRender(input.View())\n\n\t\tinputFields[i] = lipgloss.JoinVertical(lipgloss.Left, label, field)\n\t}\n\n\tmaxWidth = min(maxWidth, m.width-10)\n\n\t// Join all elements vertically\n\telements := []string{title, explanation}\n\telements = append(elements, inputFields...)\n\n\tcontent := lipgloss.JoinVertical(\n\t\tlipgloss.Left,\n\t\telements...,\n\t)\n\n\treturn baseStyle.Padding(1, 2).\n\t\tBorder(lipgloss.RoundedBorder()).\n\t\tBorderBackground(t.Background()).\n\t\tBorderForeground(t.TextMuted()).\n\t\tBackground(t.Background()).\n\t\tWidth(lipgloss.Width(content) + 4).\n\t\tRender(content)\n}\n\n// SetSize sets the size of the component.\nfunc (m *MultiArgumentsDialogCmp) SetSize(width, height int) {\n\tm.width = width\n\tm.height = height\n}\n\n// Bindings implements layout.Bindings.\nfunc (m MultiArgumentsDialogCmp) Bindings() []key.Binding {\n\treturn m.keys.ShortHelp()\n}"], ["/opencode/internal/tui/components/dialog/permission.go", "package dialog\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\n\t\"github.com/charmbracelet/bubbles/key\"\n\t\"github.com/charmbracelet/bubbles/viewport\"\n\ttea \"github.com/charmbracelet/bubbletea\"\n\t\"github.com/charmbracelet/lipgloss\"\n\t\"github.com/opencode-ai/opencode/internal/diff\"\n\t\"github.com/opencode-ai/opencode/internal/llm/tools\"\n\t\"github.com/opencode-ai/opencode/internal/permission\"\n\t\"github.com/opencode-ai/opencode/internal/tui/layout\"\n\t\"github.com/opencode-ai/opencode/internal/tui/styles\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n\t\"github.com/opencode-ai/opencode/internal/tui/util\"\n)\n\ntype PermissionAction string\n\n// Permission responses\nconst (\n\tPermissionAllow PermissionAction = \"allow\"\n\tPermissionAllowForSession PermissionAction = \"allow_session\"\n\tPermissionDeny PermissionAction = \"deny\"\n)\n\n// PermissionResponseMsg represents the user's response to a permission request\ntype PermissionResponseMsg struct {\n\tPermission permission.PermissionRequest\n\tAction PermissionAction\n}\n\n// PermissionDialogCmp interface for permission dialog component\ntype PermissionDialogCmp interface {\n\ttea.Model\n\tlayout.Bindings\n\tSetPermissions(permission permission.PermissionRequest) tea.Cmd\n}\n\ntype permissionsMapping struct {\n\tLeft key.Binding\n\tRight key.Binding\n\tEnterSpace key.Binding\n\tAllow key.Binding\n\tAllowSession key.Binding\n\tDeny key.Binding\n\tTab key.Binding\n}\n\nvar permissionsKeys = permissionsMapping{\n\tLeft: key.NewBinding(\n\t\tkey.WithKeys(\"left\"),\n\t\tkey.WithHelp(\"←\", \"switch options\"),\n\t),\n\tRight: key.NewBinding(\n\t\tkey.WithKeys(\"right\"),\n\t\tkey.WithHelp(\"→\", \"switch options\"),\n\t),\n\tEnterSpace: key.NewBinding(\n\t\tkey.WithKeys(\"enter\", \" \"),\n\t\tkey.WithHelp(\"enter/space\", \"confirm\"),\n\t),\n\tAllow: key.NewBinding(\n\t\tkey.WithKeys(\"a\"),\n\t\tkey.WithHelp(\"a\", \"allow\"),\n\t),\n\tAllowSession: key.NewBinding(\n\t\tkey.WithKeys(\"s\"),\n\t\tkey.WithHelp(\"s\", \"allow for session\"),\n\t),\n\tDeny: key.NewBinding(\n\t\tkey.WithKeys(\"d\"),\n\t\tkey.WithHelp(\"d\", \"deny\"),\n\t),\n\tTab: key.NewBinding(\n\t\tkey.WithKeys(\"tab\"),\n\t\tkey.WithHelp(\"tab\", \"switch options\"),\n\t),\n}\n\n// permissionDialogCmp is the implementation of PermissionDialog\ntype permissionDialogCmp struct {\n\twidth int\n\theight int\n\tpermission permission.PermissionRequest\n\twindowSize tea.WindowSizeMsg\n\tcontentViewPort viewport.Model\n\tselectedOption int // 0: Allow, 1: Allow for session, 2: Deny\n\n\tdiffCache map[string]string\n\tmarkdownCache map[string]string\n}\n\nfunc (p *permissionDialogCmp) Init() tea.Cmd {\n\treturn p.contentViewPort.Init()\n}\n\nfunc (p *permissionDialogCmp) Update(msg tea.Msg) (tea.Model, tea.Cmd) {\n\tvar cmds []tea.Cmd\n\n\tswitch msg := msg.(type) {\n\tcase tea.WindowSizeMsg:\n\t\tp.windowSize = msg\n\t\tcmd := p.SetSize()\n\t\tcmds = append(cmds, cmd)\n\t\tp.markdownCache = make(map[string]string)\n\t\tp.diffCache = make(map[string]string)\n\tcase tea.KeyMsg:\n\t\tswitch {\n\t\tcase key.Matches(msg, permissionsKeys.Right) || key.Matches(msg, permissionsKeys.Tab):\n\t\t\tp.selectedOption = (p.selectedOption + 1) % 3\n\t\t\treturn p, nil\n\t\tcase key.Matches(msg, permissionsKeys.Left):\n\t\t\tp.selectedOption = (p.selectedOption + 2) % 3\n\t\tcase key.Matches(msg, permissionsKeys.EnterSpace):\n\t\t\treturn p, p.selectCurrentOption()\n\t\tcase key.Matches(msg, permissionsKeys.Allow):\n\t\t\treturn p, util.CmdHandler(PermissionResponseMsg{Action: PermissionAllow, Permission: p.permission})\n\t\tcase key.Matches(msg, permissionsKeys.AllowSession):\n\t\t\treturn p, util.CmdHandler(PermissionResponseMsg{Action: PermissionAllowForSession, Permission: p.permission})\n\t\tcase key.Matches(msg, permissionsKeys.Deny):\n\t\t\treturn p, util.CmdHandler(PermissionResponseMsg{Action: PermissionDeny, Permission: p.permission})\n\t\tdefault:\n\t\t\t// Pass other keys to viewport\n\t\t\tviewPort, cmd := p.contentViewPort.Update(msg)\n\t\t\tp.contentViewPort = viewPort\n\t\t\tcmds = append(cmds, cmd)\n\t\t}\n\t}\n\n\treturn p, tea.Batch(cmds...)\n}\n\nfunc (p *permissionDialogCmp) selectCurrentOption() tea.Cmd {\n\tvar action PermissionAction\n\n\tswitch p.selectedOption {\n\tcase 0:\n\t\taction = PermissionAllow\n\tcase 1:\n\t\taction = PermissionAllowForSession\n\tcase 2:\n\t\taction = PermissionDeny\n\t}\n\n\treturn util.CmdHandler(PermissionResponseMsg{Action: action, Permission: p.permission})\n}\n\nfunc (p *permissionDialogCmp) renderButtons() string {\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\n\tallowStyle := baseStyle\n\tallowSessionStyle := baseStyle\n\tdenyStyle := baseStyle\n\tspacerStyle := baseStyle.Background(t.Background())\n\n\t// Style the selected button\n\tswitch p.selectedOption {\n\tcase 0:\n\t\tallowStyle = allowStyle.Background(t.Primary()).Foreground(t.Background())\n\t\tallowSessionStyle = allowSessionStyle.Background(t.Background()).Foreground(t.Primary())\n\t\tdenyStyle = denyStyle.Background(t.Background()).Foreground(t.Primary())\n\tcase 1:\n\t\tallowStyle = allowStyle.Background(t.Background()).Foreground(t.Primary())\n\t\tallowSessionStyle = allowSessionStyle.Background(t.Primary()).Foreground(t.Background())\n\t\tdenyStyle = denyStyle.Background(t.Background()).Foreground(t.Primary())\n\tcase 2:\n\t\tallowStyle = allowStyle.Background(t.Background()).Foreground(t.Primary())\n\t\tallowSessionStyle = allowSessionStyle.Background(t.Background()).Foreground(t.Primary())\n\t\tdenyStyle = denyStyle.Background(t.Primary()).Foreground(t.Background())\n\t}\n\n\tallowButton := allowStyle.Padding(0, 1).Render(\"Allow (a)\")\n\tallowSessionButton := allowSessionStyle.Padding(0, 1).Render(\"Allow for session (s)\")\n\tdenyButton := denyStyle.Padding(0, 1).Render(\"Deny (d)\")\n\n\tcontent := lipgloss.JoinHorizontal(\n\t\tlipgloss.Left,\n\t\tallowButton,\n\t\tspacerStyle.Render(\" \"),\n\t\tallowSessionButton,\n\t\tspacerStyle.Render(\" \"),\n\t\tdenyButton,\n\t\tspacerStyle.Render(\" \"),\n\t)\n\n\tremainingWidth := p.width - lipgloss.Width(content)\n\tif remainingWidth > 0 {\n\t\tcontent = spacerStyle.Render(strings.Repeat(\" \", remainingWidth)) + content\n\t}\n\treturn content\n}\n\nfunc (p *permissionDialogCmp) renderHeader() string {\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\n\ttoolKey := baseStyle.Foreground(t.TextMuted()).Bold(true).Render(\"Tool\")\n\ttoolValue := baseStyle.\n\t\tForeground(t.Text()).\n\t\tWidth(p.width - lipgloss.Width(toolKey)).\n\t\tRender(fmt.Sprintf(\": %s\", p.permission.ToolName))\n\n\tpathKey := baseStyle.Foreground(t.TextMuted()).Bold(true).Render(\"Path\")\n\tpathValue := baseStyle.\n\t\tForeground(t.Text()).\n\t\tWidth(p.width - lipgloss.Width(pathKey)).\n\t\tRender(fmt.Sprintf(\": %s\", p.permission.Path))\n\n\theaderParts := []string{\n\t\tlipgloss.JoinHorizontal(\n\t\t\tlipgloss.Left,\n\t\t\ttoolKey,\n\t\t\ttoolValue,\n\t\t),\n\t\tbaseStyle.Render(strings.Repeat(\" \", p.width)),\n\t\tlipgloss.JoinHorizontal(\n\t\t\tlipgloss.Left,\n\t\t\tpathKey,\n\t\t\tpathValue,\n\t\t),\n\t\tbaseStyle.Render(strings.Repeat(\" \", p.width)),\n\t}\n\n\t// Add tool-specific header information\n\tswitch p.permission.ToolName {\n\tcase tools.BashToolName:\n\t\theaderParts = append(headerParts, baseStyle.Foreground(t.TextMuted()).Width(p.width).Bold(true).Render(\"Command\"))\n\tcase tools.EditToolName:\n\t\tparams := p.permission.Params.(tools.EditPermissionsParams)\n\t\tfileKey := baseStyle.Foreground(t.TextMuted()).Bold(true).Render(\"File\")\n\t\tfilePath := baseStyle.\n\t\t\tForeground(t.Text()).\n\t\t\tWidth(p.width - lipgloss.Width(fileKey)).\n\t\t\tRender(fmt.Sprintf(\": %s\", params.FilePath))\n\t\theaderParts = append(headerParts,\n\t\t\tlipgloss.JoinHorizontal(\n\t\t\t\tlipgloss.Left,\n\t\t\t\tfileKey,\n\t\t\t\tfilePath,\n\t\t\t),\n\t\t\tbaseStyle.Render(strings.Repeat(\" \", p.width)),\n\t\t)\n\n\tcase tools.WriteToolName:\n\t\tparams := p.permission.Params.(tools.WritePermissionsParams)\n\t\tfileKey := baseStyle.Foreground(t.TextMuted()).Bold(true).Render(\"File\")\n\t\tfilePath := baseStyle.\n\t\t\tForeground(t.Text()).\n\t\t\tWidth(p.width - lipgloss.Width(fileKey)).\n\t\t\tRender(fmt.Sprintf(\": %s\", params.FilePath))\n\t\theaderParts = append(headerParts,\n\t\t\tlipgloss.JoinHorizontal(\n\t\t\t\tlipgloss.Left,\n\t\t\t\tfileKey,\n\t\t\t\tfilePath,\n\t\t\t),\n\t\t\tbaseStyle.Render(strings.Repeat(\" \", p.width)),\n\t\t)\n\tcase tools.FetchToolName:\n\t\theaderParts = append(headerParts, baseStyle.Foreground(t.TextMuted()).Width(p.width).Bold(true).Render(\"URL\"))\n\t}\n\n\treturn lipgloss.NewStyle().Background(t.Background()).Render(lipgloss.JoinVertical(lipgloss.Left, headerParts...))\n}\n\nfunc (p *permissionDialogCmp) renderBashContent() string {\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\n\tif pr, ok := p.permission.Params.(tools.BashPermissionsParams); ok {\n\t\tcontent := fmt.Sprintf(\"```bash\\n%s\\n```\", pr.Command)\n\n\t\t// Use the cache for markdown rendering\n\t\trenderedContent := p.GetOrSetMarkdown(p.permission.ID, func() (string, error) {\n\t\t\tr := styles.GetMarkdownRenderer(p.width - 10)\n\t\t\ts, err := r.Render(content)\n\t\t\treturn styles.ForceReplaceBackgroundWithLipgloss(s, t.Background()), err\n\t\t})\n\n\t\tfinalContent := baseStyle.\n\t\t\tWidth(p.contentViewPort.Width).\n\t\t\tRender(renderedContent)\n\t\tp.contentViewPort.SetContent(finalContent)\n\t\treturn p.styleViewport()\n\t}\n\treturn \"\"\n}\n\nfunc (p *permissionDialogCmp) renderEditContent() string {\n\tif pr, ok := p.permission.Params.(tools.EditPermissionsParams); ok {\n\t\tdiff := p.GetOrSetDiff(p.permission.ID, func() (string, error) {\n\t\t\treturn diff.FormatDiff(pr.Diff, diff.WithTotalWidth(p.contentViewPort.Width))\n\t\t})\n\n\t\tp.contentViewPort.SetContent(diff)\n\t\treturn p.styleViewport()\n\t}\n\treturn \"\"\n}\n\nfunc (p *permissionDialogCmp) renderPatchContent() string {\n\tif pr, ok := p.permission.Params.(tools.EditPermissionsParams); ok {\n\t\tdiff := p.GetOrSetDiff(p.permission.ID, func() (string, error) {\n\t\t\treturn diff.FormatDiff(pr.Diff, diff.WithTotalWidth(p.contentViewPort.Width))\n\t\t})\n\n\t\tp.contentViewPort.SetContent(diff)\n\t\treturn p.styleViewport()\n\t}\n\treturn \"\"\n}\n\nfunc (p *permissionDialogCmp) renderWriteContent() string {\n\tif pr, ok := p.permission.Params.(tools.WritePermissionsParams); ok {\n\t\t// Use the cache for diff rendering\n\t\tdiff := p.GetOrSetDiff(p.permission.ID, func() (string, error) {\n\t\t\treturn diff.FormatDiff(pr.Diff, diff.WithTotalWidth(p.contentViewPort.Width))\n\t\t})\n\n\t\tp.contentViewPort.SetContent(diff)\n\t\treturn p.styleViewport()\n\t}\n\treturn \"\"\n}\n\nfunc (p *permissionDialogCmp) renderFetchContent() string {\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\n\tif pr, ok := p.permission.Params.(tools.FetchPermissionsParams); ok {\n\t\tcontent := fmt.Sprintf(\"```bash\\n%s\\n```\", pr.URL)\n\n\t\t// Use the cache for markdown rendering\n\t\trenderedContent := p.GetOrSetMarkdown(p.permission.ID, func() (string, error) {\n\t\t\tr := styles.GetMarkdownRenderer(p.width - 10)\n\t\t\ts, err := r.Render(content)\n\t\t\treturn styles.ForceReplaceBackgroundWithLipgloss(s, t.Background()), err\n\t\t})\n\n\t\tfinalContent := baseStyle.\n\t\t\tWidth(p.contentViewPort.Width).\n\t\t\tRender(renderedContent)\n\t\tp.contentViewPort.SetContent(finalContent)\n\t\treturn p.styleViewport()\n\t}\n\treturn \"\"\n}\n\nfunc (p *permissionDialogCmp) renderDefaultContent() string {\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\n\tcontent := p.permission.Description\n\n\t// Use the cache for markdown rendering\n\trenderedContent := p.GetOrSetMarkdown(p.permission.ID, func() (string, error) {\n\t\tr := styles.GetMarkdownRenderer(p.width - 10)\n\t\ts, err := r.Render(content)\n\t\treturn styles.ForceReplaceBackgroundWithLipgloss(s, t.Background()), err\n\t})\n\n\tfinalContent := baseStyle.\n\t\tWidth(p.contentViewPort.Width).\n\t\tRender(renderedContent)\n\tp.contentViewPort.SetContent(finalContent)\n\n\tif renderedContent == \"\" {\n\t\treturn \"\"\n\t}\n\n\treturn p.styleViewport()\n}\n\nfunc (p *permissionDialogCmp) styleViewport() string {\n\tt := theme.CurrentTheme()\n\tcontentStyle := lipgloss.NewStyle().\n\t\tBackground(t.Background())\n\n\treturn contentStyle.Render(p.contentViewPort.View())\n}\n\nfunc (p *permissionDialogCmp) render() string {\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\n\ttitle := baseStyle.\n\t\tBold(true).\n\t\tWidth(p.width - 4).\n\t\tForeground(t.Primary()).\n\t\tRender(\"Permission Required\")\n\t// Render header\n\theaderContent := p.renderHeader()\n\t// Render buttons\n\tbuttons := p.renderButtons()\n\n\t// Calculate content height dynamically based on window size\n\tp.contentViewPort.Height = p.height - lipgloss.Height(headerContent) - lipgloss.Height(buttons) - 2 - lipgloss.Height(title)\n\tp.contentViewPort.Width = p.width - 4\n\n\t// Render content based on tool type\n\tvar contentFinal string\n\tswitch p.permission.ToolName {\n\tcase tools.BashToolName:\n\t\tcontentFinal = p.renderBashContent()\n\tcase tools.EditToolName:\n\t\tcontentFinal = p.renderEditContent()\n\tcase tools.PatchToolName:\n\t\tcontentFinal = p.renderPatchContent()\n\tcase tools.WriteToolName:\n\t\tcontentFinal = p.renderWriteContent()\n\tcase tools.FetchToolName:\n\t\tcontentFinal = p.renderFetchContent()\n\tdefault:\n\t\tcontentFinal = p.renderDefaultContent()\n\t}\n\n\tcontent := lipgloss.JoinVertical(\n\t\tlipgloss.Top,\n\t\ttitle,\n\t\tbaseStyle.Render(strings.Repeat(\" \", lipgloss.Width(title))),\n\t\theaderContent,\n\t\tcontentFinal,\n\t\tbuttons,\n\t\tbaseStyle.Render(strings.Repeat(\" \", p.width-4)),\n\t)\n\n\treturn baseStyle.\n\t\tPadding(1, 0, 0, 1).\n\t\tBorder(lipgloss.RoundedBorder()).\n\t\tBorderBackground(t.Background()).\n\t\tBorderForeground(t.TextMuted()).\n\t\tWidth(p.width).\n\t\tHeight(p.height).\n\t\tRender(\n\t\t\tcontent,\n\t\t)\n}\n\nfunc (p *permissionDialogCmp) View() string {\n\treturn p.render()\n}\n\nfunc (p *permissionDialogCmp) BindingKeys() []key.Binding {\n\treturn layout.KeyMapToSlice(permissionsKeys)\n}\n\nfunc (p *permissionDialogCmp) SetSize() tea.Cmd {\n\tif p.permission.ID == \"\" {\n\t\treturn nil\n\t}\n\tswitch p.permission.ToolName {\n\tcase tools.BashToolName:\n\t\tp.width = int(float64(p.windowSize.Width) * 0.4)\n\t\tp.height = int(float64(p.windowSize.Height) * 0.3)\n\tcase tools.EditToolName:\n\t\tp.width = int(float64(p.windowSize.Width) * 0.8)\n\t\tp.height = int(float64(p.windowSize.Height) * 0.8)\n\tcase tools.WriteToolName:\n\t\tp.width = int(float64(p.windowSize.Width) * 0.8)\n\t\tp.height = int(float64(p.windowSize.Height) * 0.8)\n\tcase tools.FetchToolName:\n\t\tp.width = int(float64(p.windowSize.Width) * 0.4)\n\t\tp.height = int(float64(p.windowSize.Height) * 0.3)\n\tdefault:\n\t\tp.width = int(float64(p.windowSize.Width) * 0.7)\n\t\tp.height = int(float64(p.windowSize.Height) * 0.5)\n\t}\n\treturn nil\n}\n\nfunc (p *permissionDialogCmp) SetPermissions(permission permission.PermissionRequest) tea.Cmd {\n\tp.permission = permission\n\treturn p.SetSize()\n}\n\n// Helper to get or set cached diff content\nfunc (c *permissionDialogCmp) GetOrSetDiff(key string, generator func() (string, error)) string {\n\tif cached, ok := c.diffCache[key]; ok {\n\t\treturn cached\n\t}\n\n\tcontent, err := generator()\n\tif err != nil {\n\t\treturn fmt.Sprintf(\"Error formatting diff: %v\", err)\n\t}\n\n\tc.diffCache[key] = content\n\n\treturn content\n}\n\n// Helper to get or set cached markdown content\nfunc (c *permissionDialogCmp) GetOrSetMarkdown(key string, generator func() (string, error)) string {\n\tif cached, ok := c.markdownCache[key]; ok {\n\t\treturn cached\n\t}\n\n\tcontent, err := generator()\n\tif err != nil {\n\t\treturn fmt.Sprintf(\"Error rendering markdown: %v\", err)\n\t}\n\n\tc.markdownCache[key] = content\n\n\treturn content\n}\n\nfunc NewPermissionDialogCmp() PermissionDialogCmp {\n\t// Create viewport for content\n\tcontentViewport := viewport.New(0, 0)\n\n\treturn &permissionDialogCmp{\n\t\tcontentViewPort: contentViewport,\n\t\tselectedOption: 0, // Default to \"Allow\"\n\t\tdiffCache: make(map[string]string),\n\t\tmarkdownCache: make(map[string]string),\n\t}\n}\n"], ["/opencode/internal/tui/components/dialog/init.go", "package dialog\n\nimport (\n\t\"github.com/charmbracelet/bubbles/key\"\n\ttea \"github.com/charmbracelet/bubbletea\"\n\t\"github.com/charmbracelet/lipgloss\"\n\n\t\"github.com/opencode-ai/opencode/internal/tui/styles\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n\t\"github.com/opencode-ai/opencode/internal/tui/util\"\n)\n\n// InitDialogCmp is a component that asks the user if they want to initialize the project.\ntype InitDialogCmp struct {\n\twidth, height int\n\tselected int\n\tkeys initDialogKeyMap\n}\n\n// NewInitDialogCmp creates a new InitDialogCmp.\nfunc NewInitDialogCmp() InitDialogCmp {\n\treturn InitDialogCmp{\n\t\tselected: 0,\n\t\tkeys: initDialogKeyMap{},\n\t}\n}\n\ntype initDialogKeyMap struct {\n\tTab key.Binding\n\tLeft key.Binding\n\tRight key.Binding\n\tEnter key.Binding\n\tEscape key.Binding\n\tY key.Binding\n\tN key.Binding\n}\n\n// ShortHelp implements key.Map.\nfunc (k initDialogKeyMap) ShortHelp() []key.Binding {\n\treturn []key.Binding{\n\t\tkey.NewBinding(\n\t\t\tkey.WithKeys(\"tab\", \"left\", \"right\"),\n\t\t\tkey.WithHelp(\"tab/←/→\", \"toggle selection\"),\n\t\t),\n\t\tkey.NewBinding(\n\t\t\tkey.WithKeys(\"enter\"),\n\t\t\tkey.WithHelp(\"enter\", \"confirm\"),\n\t\t),\n\t\tkey.NewBinding(\n\t\t\tkey.WithKeys(\"esc\", \"q\"),\n\t\t\tkey.WithHelp(\"esc/q\", \"cancel\"),\n\t\t),\n\t\tkey.NewBinding(\n\t\t\tkey.WithKeys(\"y\", \"n\"),\n\t\t\tkey.WithHelp(\"y/n\", \"yes/no\"),\n\t\t),\n\t}\n}\n\n// FullHelp implements key.Map.\nfunc (k initDialogKeyMap) FullHelp() [][]key.Binding {\n\treturn [][]key.Binding{k.ShortHelp()}\n}\n\n// Init implements tea.Model.\nfunc (m InitDialogCmp) Init() tea.Cmd {\n\treturn nil\n}\n\n// Update implements tea.Model.\nfunc (m InitDialogCmp) Update(msg tea.Msg) (tea.Model, tea.Cmd) {\n\tswitch msg := msg.(type) {\n\tcase tea.KeyMsg:\n\t\tswitch {\n\t\tcase key.Matches(msg, key.NewBinding(key.WithKeys(\"esc\"))):\n\t\t\treturn m, util.CmdHandler(CloseInitDialogMsg{Initialize: false})\n\t\tcase key.Matches(msg, key.NewBinding(key.WithKeys(\"tab\", \"left\", \"right\", \"h\", \"l\"))):\n\t\t\tm.selected = (m.selected + 1) % 2\n\t\t\treturn m, nil\n\t\tcase key.Matches(msg, key.NewBinding(key.WithKeys(\"enter\"))):\n\t\t\treturn m, util.CmdHandler(CloseInitDialogMsg{Initialize: m.selected == 0})\n\t\tcase key.Matches(msg, key.NewBinding(key.WithKeys(\"y\"))):\n\t\t\treturn m, util.CmdHandler(CloseInitDialogMsg{Initialize: true})\n\t\tcase key.Matches(msg, key.NewBinding(key.WithKeys(\"n\"))):\n\t\t\treturn m, util.CmdHandler(CloseInitDialogMsg{Initialize: false})\n\t\t}\n\tcase tea.WindowSizeMsg:\n\t\tm.width = msg.Width\n\t\tm.height = msg.Height\n\t}\n\treturn m, nil\n}\n\n// View implements tea.Model.\nfunc (m InitDialogCmp) View() string {\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\t\n\t// Calculate width needed for content\n\tmaxWidth := 60 // Width for explanation text\n\n\ttitle := baseStyle.\n\t\tForeground(t.Primary()).\n\t\tBold(true).\n\t\tWidth(maxWidth).\n\t\tPadding(0, 1).\n\t\tRender(\"Initialize Project\")\n\n\texplanation := baseStyle.\n\t\tForeground(t.Text()).\n\t\tWidth(maxWidth).\n\t\tPadding(0, 1).\n\t\tRender(\"Initialization generates a new OpenCode.md file that contains information about your codebase, this file serves as memory for each project, you can freely add to it to help the agents be better at their job.\")\n\n\tquestion := baseStyle.\n\t\tForeground(t.Text()).\n\t\tWidth(maxWidth).\n\t\tPadding(1, 1).\n\t\tRender(\"Would you like to initialize this project?\")\n\n\tmaxWidth = min(maxWidth, m.width-10)\n\tyesStyle := baseStyle\n\tnoStyle := baseStyle\n\n\tif m.selected == 0 {\n\t\tyesStyle = yesStyle.\n\t\t\tBackground(t.Primary()).\n\t\t\tForeground(t.Background()).\n\t\t\tBold(true)\n\t\tnoStyle = noStyle.\n\t\t\tBackground(t.Background()).\n\t\t\tForeground(t.Primary())\n\t} else {\n\t\tnoStyle = noStyle.\n\t\t\tBackground(t.Primary()).\n\t\t\tForeground(t.Background()).\n\t\t\tBold(true)\n\t\tyesStyle = yesStyle.\n\t\t\tBackground(t.Background()).\n\t\t\tForeground(t.Primary())\n\t}\n\n\tyes := yesStyle.Padding(0, 3).Render(\"Yes\")\n\tno := noStyle.Padding(0, 3).Render(\"No\")\n\n\tbuttons := lipgloss.JoinHorizontal(lipgloss.Center, yes, baseStyle.Render(\" \"), no)\n\tbuttons = baseStyle.\n\t\tWidth(maxWidth).\n\t\tPadding(1, 0).\n\t\tRender(buttons)\n\n\tcontent := lipgloss.JoinVertical(\n\t\tlipgloss.Left,\n\t\ttitle,\n\t\tbaseStyle.Width(maxWidth).Render(\"\"),\n\t\texplanation,\n\t\tquestion,\n\t\tbuttons,\n\t\tbaseStyle.Width(maxWidth).Render(\"\"),\n\t)\n\n\treturn baseStyle.Padding(1, 2).\n\t\tBorder(lipgloss.RoundedBorder()).\n\t\tBorderBackground(t.Background()).\n\t\tBorderForeground(t.TextMuted()).\n\t\tWidth(lipgloss.Width(content) + 4).\n\t\tRender(content)\n}\n\n// SetSize sets the size of the component.\nfunc (m *InitDialogCmp) SetSize(width, height int) {\n\tm.width = width\n\tm.height = height\n}\n\n// Bindings implements layout.Bindings.\nfunc (m InitDialogCmp) Bindings() []key.Binding {\n\treturn m.keys.ShortHelp()\n}\n\n// CloseInitDialogMsg is a message that is sent when the init dialog is closed.\ntype CloseInitDialogMsg struct {\n\tInitialize bool\n}\n\n// ShowInitDialogMsg is a message that is sent to show the init dialog.\ntype ShowInitDialogMsg struct {\n\tShow bool\n}\n"], ["/opencode/internal/tui/components/dialog/models.go", "package dialog\n\nimport (\n\t\"fmt\"\n\t\"slices\"\n\t\"strings\"\n\n\t\"github.com/charmbracelet/bubbles/key\"\n\ttea \"github.com/charmbracelet/bubbletea\"\n\t\"github.com/charmbracelet/lipgloss\"\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/llm/models\"\n\t\"github.com/opencode-ai/opencode/internal/tui/layout\"\n\t\"github.com/opencode-ai/opencode/internal/tui/styles\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n\t\"github.com/opencode-ai/opencode/internal/tui/util\"\n)\n\nconst (\n\tnumVisibleModels = 10\n\tmaxDialogWidth = 40\n)\n\n// ModelSelectedMsg is sent when a model is selected\ntype ModelSelectedMsg struct {\n\tModel models.Model\n}\n\n// CloseModelDialogMsg is sent when a model is selected\ntype CloseModelDialogMsg struct{}\n\n// ModelDialog interface for the model selection dialog\ntype ModelDialog interface {\n\ttea.Model\n\tlayout.Bindings\n}\n\ntype modelDialogCmp struct {\n\tmodels []models.Model\n\tprovider models.ModelProvider\n\tavailableProviders []models.ModelProvider\n\n\tselectedIdx int\n\twidth int\n\theight int\n\tscrollOffset int\n\thScrollOffset int\n\thScrollPossible bool\n}\n\ntype modelKeyMap struct {\n\tUp key.Binding\n\tDown key.Binding\n\tLeft key.Binding\n\tRight key.Binding\n\tEnter key.Binding\n\tEscape key.Binding\n\tJ key.Binding\n\tK key.Binding\n\tH key.Binding\n\tL key.Binding\n}\n\nvar modelKeys = modelKeyMap{\n\tUp: key.NewBinding(\n\t\tkey.WithKeys(\"up\"),\n\t\tkey.WithHelp(\"↑\", \"previous model\"),\n\t),\n\tDown: key.NewBinding(\n\t\tkey.WithKeys(\"down\"),\n\t\tkey.WithHelp(\"↓\", \"next model\"),\n\t),\n\tLeft: key.NewBinding(\n\t\tkey.WithKeys(\"left\"),\n\t\tkey.WithHelp(\"←\", \"scroll left\"),\n\t),\n\tRight: key.NewBinding(\n\t\tkey.WithKeys(\"right\"),\n\t\tkey.WithHelp(\"→\", \"scroll right\"),\n\t),\n\tEnter: key.NewBinding(\n\t\tkey.WithKeys(\"enter\"),\n\t\tkey.WithHelp(\"enter\", \"select model\"),\n\t),\n\tEscape: key.NewBinding(\n\t\tkey.WithKeys(\"esc\"),\n\t\tkey.WithHelp(\"esc\", \"close\"),\n\t),\n\tJ: key.NewBinding(\n\t\tkey.WithKeys(\"j\"),\n\t\tkey.WithHelp(\"j\", \"next model\"),\n\t),\n\tK: key.NewBinding(\n\t\tkey.WithKeys(\"k\"),\n\t\tkey.WithHelp(\"k\", \"previous model\"),\n\t),\n\tH: key.NewBinding(\n\t\tkey.WithKeys(\"h\"),\n\t\tkey.WithHelp(\"h\", \"scroll left\"),\n\t),\n\tL: key.NewBinding(\n\t\tkey.WithKeys(\"l\"),\n\t\tkey.WithHelp(\"l\", \"scroll right\"),\n\t),\n}\n\nfunc (m *modelDialogCmp) Init() tea.Cmd {\n\tm.setupModels()\n\treturn nil\n}\n\nfunc (m *modelDialogCmp) Update(msg tea.Msg) (tea.Model, tea.Cmd) {\n\tswitch msg := msg.(type) {\n\tcase tea.KeyMsg:\n\t\tswitch {\n\t\tcase key.Matches(msg, modelKeys.Up) || key.Matches(msg, modelKeys.K):\n\t\t\tm.moveSelectionUp()\n\t\tcase key.Matches(msg, modelKeys.Down) || key.Matches(msg, modelKeys.J):\n\t\t\tm.moveSelectionDown()\n\t\tcase key.Matches(msg, modelKeys.Left) || key.Matches(msg, modelKeys.H):\n\t\t\tif m.hScrollPossible {\n\t\t\t\tm.switchProvider(-1)\n\t\t\t}\n\t\tcase key.Matches(msg, modelKeys.Right) || key.Matches(msg, modelKeys.L):\n\t\t\tif m.hScrollPossible {\n\t\t\t\tm.switchProvider(1)\n\t\t\t}\n\t\tcase key.Matches(msg, modelKeys.Enter):\n\t\t\tutil.ReportInfo(fmt.Sprintf(\"selected model: %s\", m.models[m.selectedIdx].Name))\n\t\t\treturn m, util.CmdHandler(ModelSelectedMsg{Model: m.models[m.selectedIdx]})\n\t\tcase key.Matches(msg, modelKeys.Escape):\n\t\t\treturn m, util.CmdHandler(CloseModelDialogMsg{})\n\t\t}\n\tcase tea.WindowSizeMsg:\n\t\tm.width = msg.Width\n\t\tm.height = msg.Height\n\t}\n\n\treturn m, nil\n}\n\n// moveSelectionUp moves the selection up or wraps to bottom\nfunc (m *modelDialogCmp) moveSelectionUp() {\n\tif m.selectedIdx > 0 {\n\t\tm.selectedIdx--\n\t} else {\n\t\tm.selectedIdx = len(m.models) - 1\n\t\tm.scrollOffset = max(0, len(m.models)-numVisibleModels)\n\t}\n\n\t// Keep selection visible\n\tif m.selectedIdx < m.scrollOffset {\n\t\tm.scrollOffset = m.selectedIdx\n\t}\n}\n\n// moveSelectionDown moves the selection down or wraps to top\nfunc (m *modelDialogCmp) moveSelectionDown() {\n\tif m.selectedIdx < len(m.models)-1 {\n\t\tm.selectedIdx++\n\t} else {\n\t\tm.selectedIdx = 0\n\t\tm.scrollOffset = 0\n\t}\n\n\t// Keep selection visible\n\tif m.selectedIdx >= m.scrollOffset+numVisibleModels {\n\t\tm.scrollOffset = m.selectedIdx - (numVisibleModels - 1)\n\t}\n}\n\nfunc (m *modelDialogCmp) switchProvider(offset int) {\n\tnewOffset := m.hScrollOffset + offset\n\n\t// Ensure we stay within bounds\n\tif newOffset < 0 {\n\t\tnewOffset = len(m.availableProviders) - 1\n\t}\n\tif newOffset >= len(m.availableProviders) {\n\t\tnewOffset = 0\n\t}\n\n\tm.hScrollOffset = newOffset\n\tm.provider = m.availableProviders[m.hScrollOffset]\n\tm.setupModelsForProvider(m.provider)\n}\n\nfunc (m *modelDialogCmp) View() string {\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\n\t// Capitalize first letter of provider name\n\tproviderName := strings.ToUpper(string(m.provider)[:1]) + string(m.provider[1:])\n\ttitle := baseStyle.\n\t\tForeground(t.Primary()).\n\t\tBold(true).\n\t\tWidth(maxDialogWidth).\n\t\tPadding(0, 0, 1).\n\t\tRender(fmt.Sprintf(\"Select %s Model\", providerName))\n\n\t// Render visible models\n\tendIdx := min(m.scrollOffset+numVisibleModels, len(m.models))\n\tmodelItems := make([]string, 0, endIdx-m.scrollOffset)\n\n\tfor i := m.scrollOffset; i < endIdx; i++ {\n\t\titemStyle := baseStyle.Width(maxDialogWidth)\n\t\tif i == m.selectedIdx {\n\t\t\titemStyle = itemStyle.Background(t.Primary()).\n\t\t\t\tForeground(t.Background()).Bold(true)\n\t\t}\n\t\tmodelItems = append(modelItems, itemStyle.Render(m.models[i].Name))\n\t}\n\n\tscrollIndicator := m.getScrollIndicators(maxDialogWidth)\n\n\tcontent := lipgloss.JoinVertical(\n\t\tlipgloss.Left,\n\t\ttitle,\n\t\tbaseStyle.Width(maxDialogWidth).Render(lipgloss.JoinVertical(lipgloss.Left, modelItems...)),\n\t\tscrollIndicator,\n\t)\n\n\treturn baseStyle.Padding(1, 2).\n\t\tBorder(lipgloss.RoundedBorder()).\n\t\tBorderBackground(t.Background()).\n\t\tBorderForeground(t.TextMuted()).\n\t\tWidth(lipgloss.Width(content) + 4).\n\t\tRender(content)\n}\n\nfunc (m *modelDialogCmp) getScrollIndicators(maxWidth int) string {\n\tvar indicator string\n\n\tif len(m.models) > numVisibleModels {\n\t\tif m.scrollOffset > 0 {\n\t\t\tindicator += \"↑ \"\n\t\t}\n\t\tif m.scrollOffset+numVisibleModels < len(m.models) {\n\t\t\tindicator += \"↓ \"\n\t\t}\n\t}\n\n\tif m.hScrollPossible {\n\t\tif m.hScrollOffset > 0 {\n\t\t\tindicator = \"← \" + indicator\n\t\t}\n\t\tif m.hScrollOffset < len(m.availableProviders)-1 {\n\t\t\tindicator += \"→\"\n\t\t}\n\t}\n\n\tif indicator == \"\" {\n\t\treturn \"\"\n\t}\n\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\n\treturn baseStyle.\n\t\tForeground(t.Primary()).\n\t\tWidth(maxWidth).\n\t\tAlign(lipgloss.Right).\n\t\tBold(true).\n\t\tRender(indicator)\n}\n\nfunc (m *modelDialogCmp) BindingKeys() []key.Binding {\n\treturn layout.KeyMapToSlice(modelKeys)\n}\n\nfunc (m *modelDialogCmp) setupModels() {\n\tcfg := config.Get()\n\tmodelInfo := GetSelectedModel(cfg)\n\tm.availableProviders = getEnabledProviders(cfg)\n\tm.hScrollPossible = len(m.availableProviders) > 1\n\n\tm.provider = modelInfo.Provider\n\tm.hScrollOffset = findProviderIndex(m.availableProviders, m.provider)\n\n\tm.setupModelsForProvider(m.provider)\n}\n\nfunc GetSelectedModel(cfg *config.Config) models.Model {\n\n\tagentCfg := cfg.Agents[config.AgentCoder]\n\tselectedModelId := agentCfg.Model\n\treturn models.SupportedModels[selectedModelId]\n}\n\nfunc getEnabledProviders(cfg *config.Config) []models.ModelProvider {\n\tvar providers []models.ModelProvider\n\tfor providerId, provider := range cfg.Providers {\n\t\tif !provider.Disabled {\n\t\t\tproviders = append(providers, providerId)\n\t\t}\n\t}\n\n\t// Sort by provider popularity\n\tslices.SortFunc(providers, func(a, b models.ModelProvider) int {\n\t\trA := models.ProviderPopularity[a]\n\t\trB := models.ProviderPopularity[b]\n\n\t\t// models not included in popularity ranking default to last\n\t\tif rA == 0 {\n\t\t\trA = 999\n\t\t}\n\t\tif rB == 0 {\n\t\t\trB = 999\n\t\t}\n\t\treturn rA - rB\n\t})\n\treturn providers\n}\n\n// findProviderIndex returns the index of the provider in the list, or -1 if not found\nfunc findProviderIndex(providers []models.ModelProvider, provider models.ModelProvider) int {\n\tfor i, p := range providers {\n\t\tif p == provider {\n\t\t\treturn i\n\t\t}\n\t}\n\treturn -1\n}\n\nfunc (m *modelDialogCmp) setupModelsForProvider(provider models.ModelProvider) {\n\tcfg := config.Get()\n\tagentCfg := cfg.Agents[config.AgentCoder]\n\tselectedModelId := agentCfg.Model\n\n\tm.provider = provider\n\tm.models = getModelsForProvider(provider)\n\tm.selectedIdx = 0\n\tm.scrollOffset = 0\n\n\t// Try to select the current model if it belongs to this provider\n\tif provider == models.SupportedModels[selectedModelId].Provider {\n\t\tfor i, model := range m.models {\n\t\t\tif model.ID == selectedModelId {\n\t\t\t\tm.selectedIdx = i\n\t\t\t\t// Adjust scroll position to keep selected model visible\n\t\t\t\tif m.selectedIdx >= numVisibleModels {\n\t\t\t\t\tm.scrollOffset = m.selectedIdx - (numVisibleModels - 1)\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc getModelsForProvider(provider models.ModelProvider) []models.Model {\n\tvar providerModels []models.Model\n\tfor _, model := range models.SupportedModels {\n\t\tif model.Provider == provider {\n\t\t\tproviderModels = append(providerModels, model)\n\t\t}\n\t}\n\n\t// reverse alphabetical order (if llm naming was consistent latest would appear first)\n\tslices.SortFunc(providerModels, func(a, b models.Model) int {\n\t\tif a.Name > b.Name {\n\t\t\treturn -1\n\t\t} else if a.Name < b.Name {\n\t\t\treturn 1\n\t\t}\n\t\treturn 0\n\t})\n\n\treturn providerModels\n}\n\nfunc NewModelDialogCmp() ModelDialog {\n\treturn &modelDialogCmp{}\n}\n"], ["/opencode/internal/tui/components/dialog/quit.go", "package dialog\n\nimport (\n\t\"strings\"\n\n\t\"github.com/charmbracelet/bubbles/key\"\n\ttea \"github.com/charmbracelet/bubbletea\"\n\t\"github.com/charmbracelet/lipgloss\"\n\t\"github.com/opencode-ai/opencode/internal/tui/layout\"\n\t\"github.com/opencode-ai/opencode/internal/tui/styles\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n\t\"github.com/opencode-ai/opencode/internal/tui/util\"\n)\n\nconst question = \"Are you sure you want to quit?\"\n\ntype CloseQuitMsg struct{}\n\ntype QuitDialog interface {\n\ttea.Model\n\tlayout.Bindings\n}\n\ntype quitDialogCmp struct {\n\tselectedNo bool\n}\n\ntype helpMapping struct {\n\tLeftRight key.Binding\n\tEnterSpace key.Binding\n\tYes key.Binding\n\tNo key.Binding\n\tTab key.Binding\n}\n\nvar helpKeys = helpMapping{\n\tLeftRight: key.NewBinding(\n\t\tkey.WithKeys(\"left\", \"right\"),\n\t\tkey.WithHelp(\"←/→\", \"switch options\"),\n\t),\n\tEnterSpace: key.NewBinding(\n\t\tkey.WithKeys(\"enter\", \" \"),\n\t\tkey.WithHelp(\"enter/space\", \"confirm\"),\n\t),\n\tYes: key.NewBinding(\n\t\tkey.WithKeys(\"y\", \"Y\"),\n\t\tkey.WithHelp(\"y/Y\", \"yes\"),\n\t),\n\tNo: key.NewBinding(\n\t\tkey.WithKeys(\"n\", \"N\"),\n\t\tkey.WithHelp(\"n/N\", \"no\"),\n\t),\n\tTab: key.NewBinding(\n\t\tkey.WithKeys(\"tab\"),\n\t\tkey.WithHelp(\"tab\", \"switch options\"),\n\t),\n}\n\nfunc (q *quitDialogCmp) Init() tea.Cmd {\n\treturn nil\n}\n\nfunc (q *quitDialogCmp) Update(msg tea.Msg) (tea.Model, tea.Cmd) {\n\tswitch msg := msg.(type) {\n\tcase tea.KeyMsg:\n\t\tswitch {\n\t\tcase key.Matches(msg, helpKeys.LeftRight) || key.Matches(msg, helpKeys.Tab):\n\t\t\tq.selectedNo = !q.selectedNo\n\t\t\treturn q, nil\n\t\tcase key.Matches(msg, helpKeys.EnterSpace):\n\t\t\tif !q.selectedNo {\n\t\t\t\treturn q, tea.Quit\n\t\t\t}\n\t\t\treturn q, util.CmdHandler(CloseQuitMsg{})\n\t\tcase key.Matches(msg, helpKeys.Yes):\n\t\t\treturn q, tea.Quit\n\t\tcase key.Matches(msg, helpKeys.No):\n\t\t\treturn q, util.CmdHandler(CloseQuitMsg{})\n\t\t}\n\t}\n\treturn q, nil\n}\n\nfunc (q *quitDialogCmp) View() string {\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\t\n\tyesStyle := baseStyle\n\tnoStyle := baseStyle\n\tspacerStyle := baseStyle.Background(t.Background())\n\n\tif q.selectedNo {\n\t\tnoStyle = noStyle.Background(t.Primary()).Foreground(t.Background())\n\t\tyesStyle = yesStyle.Background(t.Background()).Foreground(t.Primary())\n\t} else {\n\t\tyesStyle = yesStyle.Background(t.Primary()).Foreground(t.Background())\n\t\tnoStyle = noStyle.Background(t.Background()).Foreground(t.Primary())\n\t}\n\n\tyesButton := yesStyle.Padding(0, 1).Render(\"Yes\")\n\tnoButton := noStyle.Padding(0, 1).Render(\"No\")\n\n\tbuttons := lipgloss.JoinHorizontal(lipgloss.Left, yesButton, spacerStyle.Render(\" \"), noButton)\n\n\twidth := lipgloss.Width(question)\n\tremainingWidth := width - lipgloss.Width(buttons)\n\tif remainingWidth > 0 {\n\t\tbuttons = spacerStyle.Render(strings.Repeat(\" \", remainingWidth)) + buttons\n\t}\n\n\tcontent := baseStyle.Render(\n\t\tlipgloss.JoinVertical(\n\t\t\tlipgloss.Center,\n\t\t\tquestion,\n\t\t\t\"\",\n\t\t\tbuttons,\n\t\t),\n\t)\n\n\treturn baseStyle.Padding(1, 2).\n\t\tBorder(lipgloss.RoundedBorder()).\n\t\tBorderBackground(t.Background()).\n\t\tBorderForeground(t.TextMuted()).\n\t\tWidth(lipgloss.Width(content) + 4).\n\t\tRender(content)\n}\n\nfunc (q *quitDialogCmp) BindingKeys() []key.Binding {\n\treturn layout.KeyMapToSlice(helpKeys)\n}\n\nfunc NewQuitCmp() QuitDialog {\n\treturn &quitDialogCmp{\n\t\tselectedNo: true,\n\t}\n}\n"], ["/opencode/internal/tui/tui.go", "package tui\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"strings\"\n\n\t\"github.com/charmbracelet/bubbles/key\"\n\ttea \"github.com/charmbracelet/bubbletea\"\n\t\"github.com/charmbracelet/lipgloss\"\n\t\"github.com/opencode-ai/opencode/internal/app\"\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/llm/agent\"\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n\t\"github.com/opencode-ai/opencode/internal/permission\"\n\t\"github.com/opencode-ai/opencode/internal/pubsub\"\n\t\"github.com/opencode-ai/opencode/internal/session\"\n\t\"github.com/opencode-ai/opencode/internal/tui/components/chat\"\n\t\"github.com/opencode-ai/opencode/internal/tui/components/core\"\n\t\"github.com/opencode-ai/opencode/internal/tui/components/dialog\"\n\t\"github.com/opencode-ai/opencode/internal/tui/layout\"\n\t\"github.com/opencode-ai/opencode/internal/tui/page\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n\t\"github.com/opencode-ai/opencode/internal/tui/util\"\n)\n\ntype keyMap struct {\n\tLogs key.Binding\n\tQuit key.Binding\n\tHelp key.Binding\n\tSwitchSession key.Binding\n\tCommands key.Binding\n\tFilepicker key.Binding\n\tModels key.Binding\n\tSwitchTheme key.Binding\n}\n\ntype startCompactSessionMsg struct{}\n\nconst (\n\tquitKey = \"q\"\n)\n\nvar keys = keyMap{\n\tLogs: key.NewBinding(\n\t\tkey.WithKeys(\"ctrl+l\"),\n\t\tkey.WithHelp(\"ctrl+l\", \"logs\"),\n\t),\n\n\tQuit: key.NewBinding(\n\t\tkey.WithKeys(\"ctrl+c\"),\n\t\tkey.WithHelp(\"ctrl+c\", \"quit\"),\n\t),\n\tHelp: key.NewBinding(\n\t\tkey.WithKeys(\"ctrl+_\", \"ctrl+h\"),\n\t\tkey.WithHelp(\"ctrl+?\", \"toggle help\"),\n\t),\n\n\tSwitchSession: key.NewBinding(\n\t\tkey.WithKeys(\"ctrl+s\"),\n\t\tkey.WithHelp(\"ctrl+s\", \"switch session\"),\n\t),\n\n\tCommands: key.NewBinding(\n\t\tkey.WithKeys(\"ctrl+k\"),\n\t\tkey.WithHelp(\"ctrl+k\", \"commands\"),\n\t),\n\tFilepicker: key.NewBinding(\n\t\tkey.WithKeys(\"ctrl+f\"),\n\t\tkey.WithHelp(\"ctrl+f\", \"select files to upload\"),\n\t),\n\tModels: key.NewBinding(\n\t\tkey.WithKeys(\"ctrl+o\"),\n\t\tkey.WithHelp(\"ctrl+o\", \"model selection\"),\n\t),\n\n\tSwitchTheme: key.NewBinding(\n\t\tkey.WithKeys(\"ctrl+t\"),\n\t\tkey.WithHelp(\"ctrl+t\", \"switch theme\"),\n\t),\n}\n\nvar helpEsc = key.NewBinding(\n\tkey.WithKeys(\"?\"),\n\tkey.WithHelp(\"?\", \"toggle help\"),\n)\n\nvar returnKey = key.NewBinding(\n\tkey.WithKeys(\"esc\"),\n\tkey.WithHelp(\"esc\", \"close\"),\n)\n\nvar logsKeyReturnKey = key.NewBinding(\n\tkey.WithKeys(\"esc\", \"backspace\", quitKey),\n\tkey.WithHelp(\"esc/q\", \"go back\"),\n)\n\ntype appModel struct {\n\twidth, height int\n\tcurrentPage page.PageID\n\tpreviousPage page.PageID\n\tpages map[page.PageID]tea.Model\n\tloadedPages map[page.PageID]bool\n\tstatus core.StatusCmp\n\tapp *app.App\n\tselectedSession session.Session\n\n\tshowPermissions bool\n\tpermissions dialog.PermissionDialogCmp\n\n\tshowHelp bool\n\thelp dialog.HelpCmp\n\n\tshowQuit bool\n\tquit dialog.QuitDialog\n\n\tshowSessionDialog bool\n\tsessionDialog dialog.SessionDialog\n\n\tshowCommandDialog bool\n\tcommandDialog dialog.CommandDialog\n\tcommands []dialog.Command\n\n\tshowModelDialog bool\n\tmodelDialog dialog.ModelDialog\n\n\tshowInitDialog bool\n\tinitDialog dialog.InitDialogCmp\n\n\tshowFilepicker bool\n\tfilepicker dialog.FilepickerCmp\n\n\tshowThemeDialog bool\n\tthemeDialog dialog.ThemeDialog\n\n\tshowMultiArgumentsDialog bool\n\tmultiArgumentsDialog dialog.MultiArgumentsDialogCmp\n\n\tisCompacting bool\n\tcompactingMessage string\n}\n\nfunc (a appModel) Init() tea.Cmd {\n\tvar cmds []tea.Cmd\n\tcmd := a.pages[a.currentPage].Init()\n\ta.loadedPages[a.currentPage] = true\n\tcmds = append(cmds, cmd)\n\tcmd = a.status.Init()\n\tcmds = append(cmds, cmd)\n\tcmd = a.quit.Init()\n\tcmds = append(cmds, cmd)\n\tcmd = a.help.Init()\n\tcmds = append(cmds, cmd)\n\tcmd = a.sessionDialog.Init()\n\tcmds = append(cmds, cmd)\n\tcmd = a.commandDialog.Init()\n\tcmds = append(cmds, cmd)\n\tcmd = a.modelDialog.Init()\n\tcmds = append(cmds, cmd)\n\tcmd = a.initDialog.Init()\n\tcmds = append(cmds, cmd)\n\tcmd = a.filepicker.Init()\n\tcmds = append(cmds, cmd)\n\tcmd = a.themeDialog.Init()\n\tcmds = append(cmds, cmd)\n\n\t// Check if we should show the init dialog\n\tcmds = append(cmds, func() tea.Msg {\n\t\tshouldShow, err := config.ShouldShowInitDialog()\n\t\tif err != nil {\n\t\t\treturn util.InfoMsg{\n\t\t\t\tType: util.InfoTypeError,\n\t\t\t\tMsg: \"Failed to check init status: \" + err.Error(),\n\t\t\t}\n\t\t}\n\t\treturn dialog.ShowInitDialogMsg{Show: shouldShow}\n\t})\n\n\treturn tea.Batch(cmds...)\n}\n\nfunc (a appModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {\n\tvar cmds []tea.Cmd\n\tvar cmd tea.Cmd\n\tswitch msg := msg.(type) {\n\tcase tea.WindowSizeMsg:\n\t\tmsg.Height -= 1 // Make space for the status bar\n\t\ta.width, a.height = msg.Width, msg.Height\n\n\t\ts, _ := a.status.Update(msg)\n\t\ta.status = s.(core.StatusCmp)\n\t\ta.pages[a.currentPage], cmd = a.pages[a.currentPage].Update(msg)\n\t\tcmds = append(cmds, cmd)\n\n\t\tprm, permCmd := a.permissions.Update(msg)\n\t\ta.permissions = prm.(dialog.PermissionDialogCmp)\n\t\tcmds = append(cmds, permCmd)\n\n\t\thelp, helpCmd := a.help.Update(msg)\n\t\ta.help = help.(dialog.HelpCmp)\n\t\tcmds = append(cmds, helpCmd)\n\n\t\tsession, sessionCmd := a.sessionDialog.Update(msg)\n\t\ta.sessionDialog = session.(dialog.SessionDialog)\n\t\tcmds = append(cmds, sessionCmd)\n\n\t\tcommand, commandCmd := a.commandDialog.Update(msg)\n\t\ta.commandDialog = command.(dialog.CommandDialog)\n\t\tcmds = append(cmds, commandCmd)\n\n\t\tfilepicker, filepickerCmd := a.filepicker.Update(msg)\n\t\ta.filepicker = filepicker.(dialog.FilepickerCmp)\n\t\tcmds = append(cmds, filepickerCmd)\n\n\t\ta.initDialog.SetSize(msg.Width, msg.Height)\n\n\t\tif a.showMultiArgumentsDialog {\n\t\t\ta.multiArgumentsDialog.SetSize(msg.Width, msg.Height)\n\t\t\targs, argsCmd := a.multiArgumentsDialog.Update(msg)\n\t\t\ta.multiArgumentsDialog = args.(dialog.MultiArgumentsDialogCmp)\n\t\t\tcmds = append(cmds, argsCmd, a.multiArgumentsDialog.Init())\n\t\t}\n\n\t\treturn a, tea.Batch(cmds...)\n\t// Status\n\tcase util.InfoMsg:\n\t\ts, cmd := a.status.Update(msg)\n\t\ta.status = s.(core.StatusCmp)\n\t\tcmds = append(cmds, cmd)\n\t\treturn a, tea.Batch(cmds...)\n\tcase pubsub.Event[logging.LogMessage]:\n\t\tif msg.Payload.Persist {\n\t\t\tswitch msg.Payload.Level {\n\t\t\tcase \"error\":\n\t\t\t\ts, cmd := a.status.Update(util.InfoMsg{\n\t\t\t\t\tType: util.InfoTypeError,\n\t\t\t\t\tMsg: msg.Payload.Message,\n\t\t\t\t\tTTL: msg.Payload.PersistTime,\n\t\t\t\t})\n\t\t\t\ta.status = s.(core.StatusCmp)\n\t\t\t\tcmds = append(cmds, cmd)\n\t\t\tcase \"info\":\n\t\t\t\ts, cmd := a.status.Update(util.InfoMsg{\n\t\t\t\t\tType: util.InfoTypeInfo,\n\t\t\t\t\tMsg: msg.Payload.Message,\n\t\t\t\t\tTTL: msg.Payload.PersistTime,\n\t\t\t\t})\n\t\t\t\ta.status = s.(core.StatusCmp)\n\t\t\t\tcmds = append(cmds, cmd)\n\n\t\t\tcase \"warn\":\n\t\t\t\ts, cmd := a.status.Update(util.InfoMsg{\n\t\t\t\t\tType: util.InfoTypeWarn,\n\t\t\t\t\tMsg: msg.Payload.Message,\n\t\t\t\t\tTTL: msg.Payload.PersistTime,\n\t\t\t\t})\n\n\t\t\t\ta.status = s.(core.StatusCmp)\n\t\t\t\tcmds = append(cmds, cmd)\n\t\t\tdefault:\n\t\t\t\ts, cmd := a.status.Update(util.InfoMsg{\n\t\t\t\t\tType: util.InfoTypeInfo,\n\t\t\t\t\tMsg: msg.Payload.Message,\n\t\t\t\t\tTTL: msg.Payload.PersistTime,\n\t\t\t\t})\n\t\t\t\ta.status = s.(core.StatusCmp)\n\t\t\t\tcmds = append(cmds, cmd)\n\t\t\t}\n\t\t}\n\tcase util.ClearStatusMsg:\n\t\ts, _ := a.status.Update(msg)\n\t\ta.status = s.(core.StatusCmp)\n\n\t// Permission\n\tcase pubsub.Event[permission.PermissionRequest]:\n\t\ta.showPermissions = true\n\t\treturn a, a.permissions.SetPermissions(msg.Payload)\n\tcase dialog.PermissionResponseMsg:\n\t\tvar cmd tea.Cmd\n\t\tswitch msg.Action {\n\t\tcase dialog.PermissionAllow:\n\t\t\ta.app.Permissions.Grant(msg.Permission)\n\t\tcase dialog.PermissionAllowForSession:\n\t\t\ta.app.Permissions.GrantPersistant(msg.Permission)\n\t\tcase dialog.PermissionDeny:\n\t\t\ta.app.Permissions.Deny(msg.Permission)\n\t\t}\n\t\ta.showPermissions = false\n\t\treturn a, cmd\n\n\tcase page.PageChangeMsg:\n\t\treturn a, a.moveToPage(msg.ID)\n\n\tcase dialog.CloseQuitMsg:\n\t\ta.showQuit = false\n\t\treturn a, nil\n\n\tcase dialog.CloseSessionDialogMsg:\n\t\ta.showSessionDialog = false\n\t\treturn a, nil\n\n\tcase dialog.CloseCommandDialogMsg:\n\t\ta.showCommandDialog = false\n\t\treturn a, nil\n\n\tcase startCompactSessionMsg:\n\t\t// Start compacting the current session\n\t\ta.isCompacting = true\n\t\ta.compactingMessage = \"Starting summarization...\"\n\n\t\tif a.selectedSession.ID == \"\" {\n\t\t\ta.isCompacting = false\n\t\t\treturn a, util.ReportWarn(\"No active session to summarize\")\n\t\t}\n\n\t\t// Start the summarization process\n\t\treturn a, func() tea.Msg {\n\t\t\tctx := context.Background()\n\t\t\ta.app.CoderAgent.Summarize(ctx, a.selectedSession.ID)\n\t\t\treturn nil\n\t\t}\n\n\tcase pubsub.Event[agent.AgentEvent]:\n\t\tpayload := msg.Payload\n\t\tif payload.Error != nil {\n\t\t\ta.isCompacting = false\n\t\t\treturn a, util.ReportError(payload.Error)\n\t\t}\n\n\t\ta.compactingMessage = payload.Progress\n\n\t\tif payload.Done && payload.Type == agent.AgentEventTypeSummarize {\n\t\t\ta.isCompacting = false\n\t\t\treturn a, util.ReportInfo(\"Session summarization complete\")\n\t\t} else if payload.Done && payload.Type == agent.AgentEventTypeResponse && a.selectedSession.ID != \"\" {\n\t\t\tmodel := a.app.CoderAgent.Model()\n\t\t\tcontextWindow := model.ContextWindow\n\t\t\ttokens := a.selectedSession.CompletionTokens + a.selectedSession.PromptTokens\n\t\t\tif (tokens >= int64(float64(contextWindow)*0.95)) && config.Get().AutoCompact {\n\t\t\t\treturn a, util.CmdHandler(startCompactSessionMsg{})\n\t\t\t}\n\t\t}\n\t\t// Continue listening for events\n\t\treturn a, nil\n\n\tcase dialog.CloseThemeDialogMsg:\n\t\ta.showThemeDialog = false\n\t\treturn a, nil\n\n\tcase dialog.ThemeChangedMsg:\n\t\ta.pages[a.currentPage], cmd = a.pages[a.currentPage].Update(msg)\n\t\ta.showThemeDialog = false\n\t\treturn a, tea.Batch(cmd, util.ReportInfo(\"Theme changed to: \"+msg.ThemeName))\n\n\tcase dialog.CloseModelDialogMsg:\n\t\ta.showModelDialog = false\n\t\treturn a, nil\n\n\tcase dialog.ModelSelectedMsg:\n\t\ta.showModelDialog = false\n\n\t\tmodel, err := a.app.CoderAgent.Update(config.AgentCoder, msg.Model.ID)\n\t\tif err != nil {\n\t\t\treturn a, util.ReportError(err)\n\t\t}\n\n\t\treturn a, util.ReportInfo(fmt.Sprintf(\"Model changed to %s\", model.Name))\n\n\tcase dialog.ShowInitDialogMsg:\n\t\ta.showInitDialog = msg.Show\n\t\treturn a, nil\n\n\tcase dialog.CloseInitDialogMsg:\n\t\ta.showInitDialog = false\n\t\tif msg.Initialize {\n\t\t\t// Run the initialization command\n\t\t\tfor _, cmd := range a.commands {\n\t\t\t\tif cmd.ID == \"init\" {\n\t\t\t\t\t// Mark the project as initialized\n\t\t\t\t\tif err := config.MarkProjectInitialized(); err != nil {\n\t\t\t\t\t\treturn a, util.ReportError(err)\n\t\t\t\t\t}\n\t\t\t\t\treturn a, cmd.Handler(cmd)\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\t// Mark the project as initialized without running the command\n\t\t\tif err := config.MarkProjectInitialized(); err != nil {\n\t\t\t\treturn a, util.ReportError(err)\n\t\t\t}\n\t\t}\n\t\treturn a, nil\n\n\tcase chat.SessionSelectedMsg:\n\t\ta.selectedSession = msg\n\t\ta.sessionDialog.SetSelectedSession(msg.ID)\n\n\tcase pubsub.Event[session.Session]:\n\t\tif msg.Type == pubsub.UpdatedEvent && msg.Payload.ID == a.selectedSession.ID {\n\t\t\ta.selectedSession = msg.Payload\n\t\t}\n\tcase dialog.SessionSelectedMsg:\n\t\ta.showSessionDialog = false\n\t\tif a.currentPage == page.ChatPage {\n\t\t\treturn a, util.CmdHandler(chat.SessionSelectedMsg(msg.Session))\n\t\t}\n\t\treturn a, nil\n\n\tcase dialog.CommandSelectedMsg:\n\t\ta.showCommandDialog = false\n\t\t// Execute the command handler if available\n\t\tif msg.Command.Handler != nil {\n\t\t\treturn a, msg.Command.Handler(msg.Command)\n\t\t}\n\t\treturn a, util.ReportInfo(\"Command selected: \" + msg.Command.Title)\n\n\tcase dialog.ShowMultiArgumentsDialogMsg:\n\t\t// Show multi-arguments dialog\n\t\ta.multiArgumentsDialog = dialog.NewMultiArgumentsDialogCmp(msg.CommandID, msg.Content, msg.ArgNames)\n\t\ta.showMultiArgumentsDialog = true\n\t\treturn a, a.multiArgumentsDialog.Init()\n\n\tcase dialog.CloseMultiArgumentsDialogMsg:\n\t\t// Close multi-arguments dialog\n\t\ta.showMultiArgumentsDialog = false\n\n\t\t// If submitted, replace all named arguments and run the command\n\t\tif msg.Submit {\n\t\t\tcontent := msg.Content\n\n\t\t\t// Replace each named argument with its value\n\t\t\tfor name, value := range msg.Args {\n\t\t\t\tplaceholder := \"$\" + name\n\t\t\t\tcontent = strings.ReplaceAll(content, placeholder, value)\n\t\t\t}\n\n\t\t\t// Execute the command with arguments\n\t\t\treturn a, util.CmdHandler(dialog.CommandRunCustomMsg{\n\t\t\t\tContent: content,\n\t\t\t\tArgs: msg.Args,\n\t\t\t})\n\t\t}\n\t\treturn a, nil\n\n\tcase tea.KeyMsg:\n\t\t// If multi-arguments dialog is open, let it handle the key press first\n\t\tif a.showMultiArgumentsDialog {\n\t\t\targs, cmd := a.multiArgumentsDialog.Update(msg)\n\t\t\ta.multiArgumentsDialog = args.(dialog.MultiArgumentsDialogCmp)\n\t\t\treturn a, cmd\n\t\t}\n\n\t\tswitch {\n\n\t\tcase key.Matches(msg, keys.Quit):\n\t\t\ta.showQuit = !a.showQuit\n\t\t\tif a.showHelp {\n\t\t\t\ta.showHelp = false\n\t\t\t}\n\t\t\tif a.showSessionDialog {\n\t\t\t\ta.showSessionDialog = false\n\t\t\t}\n\t\t\tif a.showCommandDialog {\n\t\t\t\ta.showCommandDialog = false\n\t\t\t}\n\t\t\tif a.showFilepicker {\n\t\t\t\ta.showFilepicker = false\n\t\t\t\ta.filepicker.ToggleFilepicker(a.showFilepicker)\n\t\t\t}\n\t\t\tif a.showModelDialog {\n\t\t\t\ta.showModelDialog = false\n\t\t\t}\n\t\t\tif a.showMultiArgumentsDialog {\n\t\t\t\ta.showMultiArgumentsDialog = false\n\t\t\t}\n\t\t\treturn a, nil\n\t\tcase key.Matches(msg, keys.SwitchSession):\n\t\t\tif a.currentPage == page.ChatPage && !a.showQuit && !a.showPermissions && !a.showCommandDialog {\n\t\t\t\t// Load sessions and show the dialog\n\t\t\t\tsessions, err := a.app.Sessions.List(context.Background())\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn a, util.ReportError(err)\n\t\t\t\t}\n\t\t\t\tif len(sessions) == 0 {\n\t\t\t\t\treturn a, util.ReportWarn(\"No sessions available\")\n\t\t\t\t}\n\t\t\t\ta.sessionDialog.SetSessions(sessions)\n\t\t\t\ta.showSessionDialog = true\n\t\t\t\treturn a, nil\n\t\t\t}\n\t\t\treturn a, nil\n\t\tcase key.Matches(msg, keys.Commands):\n\t\t\tif a.currentPage == page.ChatPage && !a.showQuit && !a.showPermissions && !a.showSessionDialog && !a.showThemeDialog && !a.showFilepicker {\n\t\t\t\t// Show commands dialog\n\t\t\t\tif len(a.commands) == 0 {\n\t\t\t\t\treturn a, util.ReportWarn(\"No commands available\")\n\t\t\t\t}\n\t\t\t\ta.commandDialog.SetCommands(a.commands)\n\t\t\t\ta.showCommandDialog = true\n\t\t\t\treturn a, nil\n\t\t\t}\n\t\t\treturn a, nil\n\t\tcase key.Matches(msg, keys.Models):\n\t\t\tif a.showModelDialog {\n\t\t\t\ta.showModelDialog = false\n\t\t\t\treturn a, nil\n\t\t\t}\n\t\t\tif a.currentPage == page.ChatPage && !a.showQuit && !a.showPermissions && !a.showSessionDialog && !a.showCommandDialog {\n\t\t\t\ta.showModelDialog = true\n\t\t\t\treturn a, nil\n\t\t\t}\n\t\t\treturn a, nil\n\t\tcase key.Matches(msg, keys.SwitchTheme):\n\t\t\tif !a.showQuit && !a.showPermissions && !a.showSessionDialog && !a.showCommandDialog {\n\t\t\t\t// Show theme switcher dialog\n\t\t\t\ta.showThemeDialog = true\n\t\t\t\t// Theme list is dynamically loaded by the dialog component\n\t\t\t\treturn a, a.themeDialog.Init()\n\t\t\t}\n\t\t\treturn a, nil\n\t\tcase key.Matches(msg, returnKey) || key.Matches(msg):\n\t\t\tif msg.String() == quitKey {\n\t\t\t\tif a.currentPage == page.LogsPage {\n\t\t\t\t\treturn a, a.moveToPage(page.ChatPage)\n\t\t\t\t}\n\t\t\t} else if !a.filepicker.IsCWDFocused() {\n\t\t\t\tif a.showQuit {\n\t\t\t\t\ta.showQuit = !a.showQuit\n\t\t\t\t\treturn a, nil\n\t\t\t\t}\n\t\t\t\tif a.showHelp {\n\t\t\t\t\ta.showHelp = !a.showHelp\n\t\t\t\t\treturn a, nil\n\t\t\t\t}\n\t\t\t\tif a.showInitDialog {\n\t\t\t\t\ta.showInitDialog = false\n\t\t\t\t\t// Mark the project as initialized without running the command\n\t\t\t\t\tif err := config.MarkProjectInitialized(); err != nil {\n\t\t\t\t\t\treturn a, util.ReportError(err)\n\t\t\t\t\t}\n\t\t\t\t\treturn a, nil\n\t\t\t\t}\n\t\t\t\tif a.showFilepicker {\n\t\t\t\t\ta.showFilepicker = false\n\t\t\t\t\ta.filepicker.ToggleFilepicker(a.showFilepicker)\n\t\t\t\t\treturn a, nil\n\t\t\t\t}\n\t\t\t\tif a.currentPage == page.LogsPage {\n\t\t\t\t\treturn a, a.moveToPage(page.ChatPage)\n\t\t\t\t}\n\t\t\t}\n\t\tcase key.Matches(msg, keys.Logs):\n\t\t\treturn a, a.moveToPage(page.LogsPage)\n\t\tcase key.Matches(msg, keys.Help):\n\t\t\tif a.showQuit {\n\t\t\t\treturn a, nil\n\t\t\t}\n\t\t\ta.showHelp = !a.showHelp\n\t\t\treturn a, nil\n\t\tcase key.Matches(msg, helpEsc):\n\t\t\tif a.app.CoderAgent.IsBusy() {\n\t\t\t\tif a.showQuit {\n\t\t\t\t\treturn a, nil\n\t\t\t\t}\n\t\t\t\ta.showHelp = !a.showHelp\n\t\t\t\treturn a, nil\n\t\t\t}\n\t\tcase key.Matches(msg, keys.Filepicker):\n\t\t\ta.showFilepicker = !a.showFilepicker\n\t\t\ta.filepicker.ToggleFilepicker(a.showFilepicker)\n\t\t\treturn a, nil\n\t\t}\n\tdefault:\n\t\tf, filepickerCmd := a.filepicker.Update(msg)\n\t\ta.filepicker = f.(dialog.FilepickerCmp)\n\t\tcmds = append(cmds, filepickerCmd)\n\n\t}\n\n\tif a.showFilepicker {\n\t\tf, filepickerCmd := a.filepicker.Update(msg)\n\t\ta.filepicker = f.(dialog.FilepickerCmp)\n\t\tcmds = append(cmds, filepickerCmd)\n\t\t// Only block key messages send all other messages down\n\t\tif _, ok := msg.(tea.KeyMsg); ok {\n\t\t\treturn a, tea.Batch(cmds...)\n\t\t}\n\t}\n\n\tif a.showQuit {\n\t\tq, quitCmd := a.quit.Update(msg)\n\t\ta.quit = q.(dialog.QuitDialog)\n\t\tcmds = append(cmds, quitCmd)\n\t\t// Only block key messages send all other messages down\n\t\tif _, ok := msg.(tea.KeyMsg); ok {\n\t\t\treturn a, tea.Batch(cmds...)\n\t\t}\n\t}\n\tif a.showPermissions {\n\t\td, permissionsCmd := a.permissions.Update(msg)\n\t\ta.permissions = d.(dialog.PermissionDialogCmp)\n\t\tcmds = append(cmds, permissionsCmd)\n\t\t// Only block key messages send all other messages down\n\t\tif _, ok := msg.(tea.KeyMsg); ok {\n\t\t\treturn a, tea.Batch(cmds...)\n\t\t}\n\t}\n\n\tif a.showSessionDialog {\n\t\td, sessionCmd := a.sessionDialog.Update(msg)\n\t\ta.sessionDialog = d.(dialog.SessionDialog)\n\t\tcmds = append(cmds, sessionCmd)\n\t\t// Only block key messages send all other messages down\n\t\tif _, ok := msg.(tea.KeyMsg); ok {\n\t\t\treturn a, tea.Batch(cmds...)\n\t\t}\n\t}\n\n\tif a.showCommandDialog {\n\t\td, commandCmd := a.commandDialog.Update(msg)\n\t\ta.commandDialog = d.(dialog.CommandDialog)\n\t\tcmds = append(cmds, commandCmd)\n\t\t// Only block key messages send all other messages down\n\t\tif _, ok := msg.(tea.KeyMsg); ok {\n\t\t\treturn a, tea.Batch(cmds...)\n\t\t}\n\t}\n\n\tif a.showModelDialog {\n\t\td, modelCmd := a.modelDialog.Update(msg)\n\t\ta.modelDialog = d.(dialog.ModelDialog)\n\t\tcmds = append(cmds, modelCmd)\n\t\t// Only block key messages send all other messages down\n\t\tif _, ok := msg.(tea.KeyMsg); ok {\n\t\t\treturn a, tea.Batch(cmds...)\n\t\t}\n\t}\n\n\tif a.showInitDialog {\n\t\td, initCmd := a.initDialog.Update(msg)\n\t\ta.initDialog = d.(dialog.InitDialogCmp)\n\t\tcmds = append(cmds, initCmd)\n\t\t// Only block key messages send all other messages down\n\t\tif _, ok := msg.(tea.KeyMsg); ok {\n\t\t\treturn a, tea.Batch(cmds...)\n\t\t}\n\t}\n\n\tif a.showThemeDialog {\n\t\td, themeCmd := a.themeDialog.Update(msg)\n\t\ta.themeDialog = d.(dialog.ThemeDialog)\n\t\tcmds = append(cmds, themeCmd)\n\t\t// Only block key messages send all other messages down\n\t\tif _, ok := msg.(tea.KeyMsg); ok {\n\t\t\treturn a, tea.Batch(cmds...)\n\t\t}\n\t}\n\n\ts, _ := a.status.Update(msg)\n\ta.status = s.(core.StatusCmp)\n\ta.pages[a.currentPage], cmd = a.pages[a.currentPage].Update(msg)\n\tcmds = append(cmds, cmd)\n\treturn a, tea.Batch(cmds...)\n}\n\n// RegisterCommand adds a command to the command dialog\nfunc (a *appModel) RegisterCommand(cmd dialog.Command) {\n\ta.commands = append(a.commands, cmd)\n}\n\nfunc (a *appModel) findCommand(id string) (dialog.Command, bool) {\n\tfor _, cmd := range a.commands {\n\t\tif cmd.ID == id {\n\t\t\treturn cmd, true\n\t\t}\n\t}\n\treturn dialog.Command{}, false\n}\n\nfunc (a *appModel) moveToPage(pageID page.PageID) tea.Cmd {\n\tif a.app.CoderAgent.IsBusy() {\n\t\t// For now we don't move to any page if the agent is busy\n\t\treturn util.ReportWarn(\"Agent is busy, please wait...\")\n\t}\n\n\tvar cmds []tea.Cmd\n\tif _, ok := a.loadedPages[pageID]; !ok {\n\t\tcmd := a.pages[pageID].Init()\n\t\tcmds = append(cmds, cmd)\n\t\ta.loadedPages[pageID] = true\n\t}\n\ta.previousPage = a.currentPage\n\ta.currentPage = pageID\n\tif sizable, ok := a.pages[a.currentPage].(layout.Sizeable); ok {\n\t\tcmd := sizable.SetSize(a.width, a.height)\n\t\tcmds = append(cmds, cmd)\n\t}\n\n\treturn tea.Batch(cmds...)\n}\n\nfunc (a appModel) View() string {\n\tcomponents := []string{\n\t\ta.pages[a.currentPage].View(),\n\t}\n\n\tcomponents = append(components, a.status.View())\n\n\tappView := lipgloss.JoinVertical(lipgloss.Top, components...)\n\n\tif a.showPermissions {\n\t\toverlay := a.permissions.View()\n\t\trow := lipgloss.Height(appView) / 2\n\t\trow -= lipgloss.Height(overlay) / 2\n\t\tcol := lipgloss.Width(appView) / 2\n\t\tcol -= lipgloss.Width(overlay) / 2\n\t\tappView = layout.PlaceOverlay(\n\t\t\tcol,\n\t\t\trow,\n\t\t\toverlay,\n\t\t\tappView,\n\t\t\ttrue,\n\t\t)\n\t}\n\n\tif a.showFilepicker {\n\t\toverlay := a.filepicker.View()\n\t\trow := lipgloss.Height(appView) / 2\n\t\trow -= lipgloss.Height(overlay) / 2\n\t\tcol := lipgloss.Width(appView) / 2\n\t\tcol -= lipgloss.Width(overlay) / 2\n\t\tappView = layout.PlaceOverlay(\n\t\t\tcol,\n\t\t\trow,\n\t\t\toverlay,\n\t\t\tappView,\n\t\t\ttrue,\n\t\t)\n\n\t}\n\n\t// Show compacting status overlay\n\tif a.isCompacting {\n\t\tt := theme.CurrentTheme()\n\t\tstyle := lipgloss.NewStyle().\n\t\t\tBorder(lipgloss.RoundedBorder()).\n\t\t\tBorderForeground(t.BorderFocused()).\n\t\t\tBorderBackground(t.Background()).\n\t\t\tPadding(1, 2).\n\t\t\tBackground(t.Background()).\n\t\t\tForeground(t.Text())\n\n\t\toverlay := style.Render(\"Summarizing\\n\" + a.compactingMessage)\n\t\trow := lipgloss.Height(appView) / 2\n\t\trow -= lipgloss.Height(overlay) / 2\n\t\tcol := lipgloss.Width(appView) / 2\n\t\tcol -= lipgloss.Width(overlay) / 2\n\t\tappView = layout.PlaceOverlay(\n\t\t\tcol,\n\t\t\trow,\n\t\t\toverlay,\n\t\t\tappView,\n\t\t\ttrue,\n\t\t)\n\t}\n\n\tif a.showHelp {\n\t\tbindings := layout.KeyMapToSlice(keys)\n\t\tif p, ok := a.pages[a.currentPage].(layout.Bindings); ok {\n\t\t\tbindings = append(bindings, p.BindingKeys()...)\n\t\t}\n\t\tif a.showPermissions {\n\t\t\tbindings = append(bindings, a.permissions.BindingKeys()...)\n\t\t}\n\t\tif a.currentPage == page.LogsPage {\n\t\t\tbindings = append(bindings, logsKeyReturnKey)\n\t\t}\n\t\tif !a.app.CoderAgent.IsBusy() {\n\t\t\tbindings = append(bindings, helpEsc)\n\t\t}\n\t\ta.help.SetBindings(bindings)\n\n\t\toverlay := a.help.View()\n\t\trow := lipgloss.Height(appView) / 2\n\t\trow -= lipgloss.Height(overlay) / 2\n\t\tcol := lipgloss.Width(appView) / 2\n\t\tcol -= lipgloss.Width(overlay) / 2\n\t\tappView = layout.PlaceOverlay(\n\t\t\tcol,\n\t\t\trow,\n\t\t\toverlay,\n\t\t\tappView,\n\t\t\ttrue,\n\t\t)\n\t}\n\n\tif a.showQuit {\n\t\toverlay := a.quit.View()\n\t\trow := lipgloss.Height(appView) / 2\n\t\trow -= lipgloss.Height(overlay) / 2\n\t\tcol := lipgloss.Width(appView) / 2\n\t\tcol -= lipgloss.Width(overlay) / 2\n\t\tappView = layout.PlaceOverlay(\n\t\t\tcol,\n\t\t\trow,\n\t\t\toverlay,\n\t\t\tappView,\n\t\t\ttrue,\n\t\t)\n\t}\n\n\tif a.showSessionDialog {\n\t\toverlay := a.sessionDialog.View()\n\t\trow := lipgloss.Height(appView) / 2\n\t\trow -= lipgloss.Height(overlay) / 2\n\t\tcol := lipgloss.Width(appView) / 2\n\t\tcol -= lipgloss.Width(overlay) / 2\n\t\tappView = layout.PlaceOverlay(\n\t\t\tcol,\n\t\t\trow,\n\t\t\toverlay,\n\t\t\tappView,\n\t\t\ttrue,\n\t\t)\n\t}\n\n\tif a.showModelDialog {\n\t\toverlay := a.modelDialog.View()\n\t\trow := lipgloss.Height(appView) / 2\n\t\trow -= lipgloss.Height(overlay) / 2\n\t\tcol := lipgloss.Width(appView) / 2\n\t\tcol -= lipgloss.Width(overlay) / 2\n\t\tappView = layout.PlaceOverlay(\n\t\t\tcol,\n\t\t\trow,\n\t\t\toverlay,\n\t\t\tappView,\n\t\t\ttrue,\n\t\t)\n\t}\n\n\tif a.showCommandDialog {\n\t\toverlay := a.commandDialog.View()\n\t\trow := lipgloss.Height(appView) / 2\n\t\trow -= lipgloss.Height(overlay) / 2\n\t\tcol := lipgloss.Width(appView) / 2\n\t\tcol -= lipgloss.Width(overlay) / 2\n\t\tappView = layout.PlaceOverlay(\n\t\t\tcol,\n\t\t\trow,\n\t\t\toverlay,\n\t\t\tappView,\n\t\t\ttrue,\n\t\t)\n\t}\n\n\tif a.showInitDialog {\n\t\toverlay := a.initDialog.View()\n\t\tappView = layout.PlaceOverlay(\n\t\t\ta.width/2-lipgloss.Width(overlay)/2,\n\t\t\ta.height/2-lipgloss.Height(overlay)/2,\n\t\t\toverlay,\n\t\t\tappView,\n\t\t\ttrue,\n\t\t)\n\t}\n\n\tif a.showThemeDialog {\n\t\toverlay := a.themeDialog.View()\n\t\trow := lipgloss.Height(appView) / 2\n\t\trow -= lipgloss.Height(overlay) / 2\n\t\tcol := lipgloss.Width(appView) / 2\n\t\tcol -= lipgloss.Width(overlay) / 2\n\t\tappView = layout.PlaceOverlay(\n\t\t\tcol,\n\t\t\trow,\n\t\t\toverlay,\n\t\t\tappView,\n\t\t\ttrue,\n\t\t)\n\t}\n\n\tif a.showMultiArgumentsDialog {\n\t\toverlay := a.multiArgumentsDialog.View()\n\t\trow := lipgloss.Height(appView) / 2\n\t\trow -= lipgloss.Height(overlay) / 2\n\t\tcol := lipgloss.Width(appView) / 2\n\t\tcol -= lipgloss.Width(overlay) / 2\n\t\tappView = layout.PlaceOverlay(\n\t\t\tcol,\n\t\t\trow,\n\t\t\toverlay,\n\t\t\tappView,\n\t\t\ttrue,\n\t\t)\n\t}\n\n\treturn appView\n}\n\nfunc New(app *app.App) tea.Model {\n\tstartPage := page.ChatPage\n\tmodel := &appModel{\n\t\tcurrentPage: startPage,\n\t\tloadedPages: make(map[page.PageID]bool),\n\t\tstatus: core.NewStatusCmp(app.LSPClients),\n\t\thelp: dialog.NewHelpCmp(),\n\t\tquit: dialog.NewQuitCmp(),\n\t\tsessionDialog: dialog.NewSessionDialogCmp(),\n\t\tcommandDialog: dialog.NewCommandDialogCmp(),\n\t\tmodelDialog: dialog.NewModelDialogCmp(),\n\t\tpermissions: dialog.NewPermissionDialogCmp(),\n\t\tinitDialog: dialog.NewInitDialogCmp(),\n\t\tthemeDialog: dialog.NewThemeDialogCmp(),\n\t\tapp: app,\n\t\tcommands: []dialog.Command{},\n\t\tpages: map[page.PageID]tea.Model{\n\t\t\tpage.ChatPage: page.NewChatPage(app),\n\t\t\tpage.LogsPage: page.NewLogsPage(),\n\t\t},\n\t\tfilepicker: dialog.NewFilepickerCmp(app),\n\t}\n\n\tmodel.RegisterCommand(dialog.Command{\n\t\tID: \"init\",\n\t\tTitle: \"Initialize Project\",\n\t\tDescription: \"Create/Update the OpenCode.md memory file\",\n\t\tHandler: func(cmd dialog.Command) tea.Cmd {\n\t\t\tprompt := `Please analyze this codebase and create a OpenCode.md file containing:\n1. Build/lint/test commands - especially for running a single test\n2. Code style guidelines including imports, formatting, types, naming conventions, error handling, etc.\n\nThe file you create will be given to agentic coding agents (such as yourself) that operate in this repository. Make it about 20 lines long.\nIf there's already a opencode.md, improve it.\nIf there are Cursor rules (in .cursor/rules/ or .cursorrules) or Copilot rules (in .github/copilot-instructions.md), make sure to include them.`\n\t\t\treturn tea.Batch(\n\t\t\t\tutil.CmdHandler(chat.SendMsg{\n\t\t\t\t\tText: prompt,\n\t\t\t\t}),\n\t\t\t)\n\t\t},\n\t})\n\n\tmodel.RegisterCommand(dialog.Command{\n\t\tID: \"compact\",\n\t\tTitle: \"Compact Session\",\n\t\tDescription: \"Summarize the current session and create a new one with the summary\",\n\t\tHandler: func(cmd dialog.Command) tea.Cmd {\n\t\t\treturn func() tea.Msg {\n\t\t\t\treturn startCompactSessionMsg{}\n\t\t\t}\n\t\t},\n\t})\n\t// Load custom commands\n\tcustomCommands, err := dialog.LoadCustomCommands()\n\tif err != nil {\n\t\tlogging.Warn(\"Failed to load custom commands\", \"error\", err)\n\t} else {\n\t\tfor _, cmd := range customCommands {\n\t\t\tmodel.RegisterCommand(cmd)\n\t\t}\n\t}\n\n\treturn model\n}\n"], ["/opencode/internal/tui/components/chat/list.go", "package chat\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"math\"\n\n\t\"github.com/charmbracelet/bubbles/key\"\n\t\"github.com/charmbracelet/bubbles/spinner\"\n\t\"github.com/charmbracelet/bubbles/viewport\"\n\ttea \"github.com/charmbracelet/bubbletea\"\n\t\"github.com/charmbracelet/lipgloss\"\n\t\"github.com/opencode-ai/opencode/internal/app\"\n\t\"github.com/opencode-ai/opencode/internal/message\"\n\t\"github.com/opencode-ai/opencode/internal/pubsub\"\n\t\"github.com/opencode-ai/opencode/internal/session\"\n\t\"github.com/opencode-ai/opencode/internal/tui/components/dialog\"\n\t\"github.com/opencode-ai/opencode/internal/tui/styles\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n\t\"github.com/opencode-ai/opencode/internal/tui/util\"\n)\n\ntype cacheItem struct {\n\twidth int\n\tcontent []uiMessage\n}\ntype messagesCmp struct {\n\tapp *app.App\n\twidth, height int\n\tviewport viewport.Model\n\tsession session.Session\n\tmessages []message.Message\n\tuiMessages []uiMessage\n\tcurrentMsgID string\n\tcachedContent map[string]cacheItem\n\tspinner spinner.Model\n\trendering bool\n\tattachments viewport.Model\n}\ntype renderFinishedMsg struct{}\n\ntype MessageKeys struct {\n\tPageDown key.Binding\n\tPageUp key.Binding\n\tHalfPageUp key.Binding\n\tHalfPageDown key.Binding\n}\n\nvar messageKeys = MessageKeys{\n\tPageDown: key.NewBinding(\n\t\tkey.WithKeys(\"pgdown\"),\n\t\tkey.WithHelp(\"f/pgdn\", \"page down\"),\n\t),\n\tPageUp: key.NewBinding(\n\t\tkey.WithKeys(\"pgup\"),\n\t\tkey.WithHelp(\"b/pgup\", \"page up\"),\n\t),\n\tHalfPageUp: key.NewBinding(\n\t\tkey.WithKeys(\"ctrl+u\"),\n\t\tkey.WithHelp(\"ctrl+u\", \"½ page up\"),\n\t),\n\tHalfPageDown: key.NewBinding(\n\t\tkey.WithKeys(\"ctrl+d\", \"ctrl+d\"),\n\t\tkey.WithHelp(\"ctrl+d\", \"½ page down\"),\n\t),\n}\n\nfunc (m *messagesCmp) Init() tea.Cmd {\n\treturn tea.Batch(m.viewport.Init(), m.spinner.Tick)\n}\n\nfunc (m *messagesCmp) Update(msg tea.Msg) (tea.Model, tea.Cmd) {\n\tvar cmds []tea.Cmd\n\tswitch msg := msg.(type) {\n\tcase dialog.ThemeChangedMsg:\n\t\tm.rerender()\n\t\treturn m, nil\n\tcase SessionSelectedMsg:\n\t\tif msg.ID != m.session.ID {\n\t\t\tcmd := m.SetSession(msg)\n\t\t\treturn m, cmd\n\t\t}\n\t\treturn m, nil\n\tcase SessionClearedMsg:\n\t\tm.session = session.Session{}\n\t\tm.messages = make([]message.Message, 0)\n\t\tm.currentMsgID = \"\"\n\t\tm.rendering = false\n\t\treturn m, nil\n\n\tcase tea.KeyMsg:\n\t\tif key.Matches(msg, messageKeys.PageUp) || key.Matches(msg, messageKeys.PageDown) ||\n\t\t\tkey.Matches(msg, messageKeys.HalfPageUp) || key.Matches(msg, messageKeys.HalfPageDown) {\n\t\t\tu, cmd := m.viewport.Update(msg)\n\t\t\tm.viewport = u\n\t\t\tcmds = append(cmds, cmd)\n\t\t}\n\n\tcase renderFinishedMsg:\n\t\tm.rendering = false\n\t\tm.viewport.GotoBottom()\n\tcase pubsub.Event[session.Session]:\n\t\tif msg.Type == pubsub.UpdatedEvent && msg.Payload.ID == m.session.ID {\n\t\t\tm.session = msg.Payload\n\t\t\tif m.session.SummaryMessageID == m.currentMsgID {\n\t\t\t\tdelete(m.cachedContent, m.currentMsgID)\n\t\t\t\tm.renderView()\n\t\t\t}\n\t\t}\n\tcase pubsub.Event[message.Message]:\n\t\tneedsRerender := false\n\t\tif msg.Type == pubsub.CreatedEvent {\n\t\t\tif msg.Payload.SessionID == m.session.ID {\n\n\t\t\t\tmessageExists := false\n\t\t\t\tfor _, v := range m.messages {\n\t\t\t\t\tif v.ID == msg.Payload.ID {\n\t\t\t\t\t\tmessageExists = true\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif !messageExists {\n\t\t\t\t\tif len(m.messages) > 0 {\n\t\t\t\t\t\tlastMsgID := m.messages[len(m.messages)-1].ID\n\t\t\t\t\t\tdelete(m.cachedContent, lastMsgID)\n\t\t\t\t\t}\n\n\t\t\t\t\tm.messages = append(m.messages, msg.Payload)\n\t\t\t\t\tdelete(m.cachedContent, m.currentMsgID)\n\t\t\t\t\tm.currentMsgID = msg.Payload.ID\n\t\t\t\t\tneedsRerender = true\n\t\t\t\t}\n\t\t\t}\n\t\t\t// There are tool calls from the child task\n\t\t\tfor _, v := range m.messages {\n\t\t\t\tfor _, c := range v.ToolCalls() {\n\t\t\t\t\tif c.ID == msg.Payload.SessionID {\n\t\t\t\t\t\tdelete(m.cachedContent, v.ID)\n\t\t\t\t\t\tneedsRerender = true\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t} else if msg.Type == pubsub.UpdatedEvent && msg.Payload.SessionID == m.session.ID {\n\t\t\tfor i, v := range m.messages {\n\t\t\t\tif v.ID == msg.Payload.ID {\n\t\t\t\t\tm.messages[i] = msg.Payload\n\t\t\t\t\tdelete(m.cachedContent, msg.Payload.ID)\n\t\t\t\t\tneedsRerender = true\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif needsRerender {\n\t\t\tm.renderView()\n\t\t\tif len(m.messages) > 0 {\n\t\t\t\tif (msg.Type == pubsub.CreatedEvent) ||\n\t\t\t\t\t(msg.Type == pubsub.UpdatedEvent && msg.Payload.ID == m.messages[len(m.messages)-1].ID) {\n\t\t\t\t\tm.viewport.GotoBottom()\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tspinner, cmd := m.spinner.Update(msg)\n\tm.spinner = spinner\n\tcmds = append(cmds, cmd)\n\treturn m, tea.Batch(cmds...)\n}\n\nfunc (m *messagesCmp) IsAgentWorking() bool {\n\treturn m.app.CoderAgent.IsSessionBusy(m.session.ID)\n}\n\nfunc formatTimeDifference(unixTime1, unixTime2 int64) string {\n\tdiffSeconds := float64(math.Abs(float64(unixTime2 - unixTime1)))\n\n\tif diffSeconds < 60 {\n\t\treturn fmt.Sprintf(\"%.1fs\", diffSeconds)\n\t}\n\n\tminutes := int(diffSeconds / 60)\n\tseconds := int(diffSeconds) % 60\n\treturn fmt.Sprintf(\"%dm%ds\", minutes, seconds)\n}\n\nfunc (m *messagesCmp) renderView() {\n\tm.uiMessages = make([]uiMessage, 0)\n\tpos := 0\n\tbaseStyle := styles.BaseStyle()\n\n\tif m.width == 0 {\n\t\treturn\n\t}\n\tfor inx, msg := range m.messages {\n\t\tswitch msg.Role {\n\t\tcase message.User:\n\t\t\tif cache, ok := m.cachedContent[msg.ID]; ok && cache.width == m.width {\n\t\t\t\tm.uiMessages = append(m.uiMessages, cache.content...)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tuserMsg := renderUserMessage(\n\t\t\t\tmsg,\n\t\t\t\tmsg.ID == m.currentMsgID,\n\t\t\t\tm.width,\n\t\t\t\tpos,\n\t\t\t)\n\t\t\tm.uiMessages = append(m.uiMessages, userMsg)\n\t\t\tm.cachedContent[msg.ID] = cacheItem{\n\t\t\t\twidth: m.width,\n\t\t\t\tcontent: []uiMessage{userMsg},\n\t\t\t}\n\t\t\tpos += userMsg.height + 1 // + 1 for spacing\n\t\tcase message.Assistant:\n\t\t\tif cache, ok := m.cachedContent[msg.ID]; ok && cache.width == m.width {\n\t\t\t\tm.uiMessages = append(m.uiMessages, cache.content...)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tisSummary := m.session.SummaryMessageID == msg.ID\n\n\t\t\tassistantMessages := renderAssistantMessage(\n\t\t\t\tmsg,\n\t\t\t\tinx,\n\t\t\t\tm.messages,\n\t\t\t\tm.app.Messages,\n\t\t\t\tm.currentMsgID,\n\t\t\t\tisSummary,\n\t\t\t\tm.width,\n\t\t\t\tpos,\n\t\t\t)\n\t\t\tfor _, msg := range assistantMessages {\n\t\t\t\tm.uiMessages = append(m.uiMessages, msg)\n\t\t\t\tpos += msg.height + 1 // + 1 for spacing\n\t\t\t}\n\t\t\tm.cachedContent[msg.ID] = cacheItem{\n\t\t\t\twidth: m.width,\n\t\t\t\tcontent: assistantMessages,\n\t\t\t}\n\t\t}\n\t}\n\n\tmessages := make([]string, 0)\n\tfor _, v := range m.uiMessages {\n\t\tmessages = append(messages, lipgloss.JoinVertical(lipgloss.Left, v.content),\n\t\t\tbaseStyle.\n\t\t\t\tWidth(m.width).\n\t\t\t\tRender(\n\t\t\t\t\t\"\",\n\t\t\t\t),\n\t\t)\n\t}\n\n\tm.viewport.SetContent(\n\t\tbaseStyle.\n\t\t\tWidth(m.width).\n\t\t\tRender(\n\t\t\t\tlipgloss.JoinVertical(\n\t\t\t\t\tlipgloss.Top,\n\t\t\t\t\tmessages...,\n\t\t\t\t),\n\t\t\t),\n\t)\n}\n\nfunc (m *messagesCmp) View() string {\n\tbaseStyle := styles.BaseStyle()\n\n\tif m.rendering {\n\t\treturn baseStyle.\n\t\t\tWidth(m.width).\n\t\t\tRender(\n\t\t\t\tlipgloss.JoinVertical(\n\t\t\t\t\tlipgloss.Top,\n\t\t\t\t\t\"Loading...\",\n\t\t\t\t\tm.working(),\n\t\t\t\t\tm.help(),\n\t\t\t\t),\n\t\t\t)\n\t}\n\tif len(m.messages) == 0 {\n\t\tcontent := baseStyle.\n\t\t\tWidth(m.width).\n\t\t\tHeight(m.height - 1).\n\t\t\tRender(\n\t\t\t\tm.initialScreen(),\n\t\t\t)\n\n\t\treturn baseStyle.\n\t\t\tWidth(m.width).\n\t\t\tRender(\n\t\t\t\tlipgloss.JoinVertical(\n\t\t\t\t\tlipgloss.Top,\n\t\t\t\t\tcontent,\n\t\t\t\t\t\"\",\n\t\t\t\t\tm.help(),\n\t\t\t\t),\n\t\t\t)\n\t}\n\n\treturn baseStyle.\n\t\tWidth(m.width).\n\t\tRender(\n\t\t\tlipgloss.JoinVertical(\n\t\t\t\tlipgloss.Top,\n\t\t\t\tm.viewport.View(),\n\t\t\t\tm.working(),\n\t\t\t\tm.help(),\n\t\t\t),\n\t\t)\n}\n\nfunc hasToolsWithoutResponse(messages []message.Message) bool {\n\ttoolCalls := make([]message.ToolCall, 0)\n\ttoolResults := make([]message.ToolResult, 0)\n\tfor _, m := range messages {\n\t\ttoolCalls = append(toolCalls, m.ToolCalls()...)\n\t\ttoolResults = append(toolResults, m.ToolResults()...)\n\t}\n\n\tfor _, v := range toolCalls {\n\t\tfound := false\n\t\tfor _, r := range toolResults {\n\t\t\tif v.ID == r.ToolCallID {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif !found && v.Finished {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc hasUnfinishedToolCalls(messages []message.Message) bool {\n\ttoolCalls := make([]message.ToolCall, 0)\n\tfor _, m := range messages {\n\t\ttoolCalls = append(toolCalls, m.ToolCalls()...)\n\t}\n\tfor _, v := range toolCalls {\n\t\tif !v.Finished {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc (m *messagesCmp) working() string {\n\ttext := \"\"\n\tif m.IsAgentWorking() && len(m.messages) > 0 {\n\t\tt := theme.CurrentTheme()\n\t\tbaseStyle := styles.BaseStyle()\n\n\t\ttask := \"Thinking...\"\n\t\tlastMessage := m.messages[len(m.messages)-1]\n\t\tif hasToolsWithoutResponse(m.messages) {\n\t\t\ttask = \"Waiting for tool response...\"\n\t\t} else if hasUnfinishedToolCalls(m.messages) {\n\t\t\ttask = \"Building tool call...\"\n\t\t} else if !lastMessage.IsFinished() {\n\t\t\ttask = \"Generating...\"\n\t\t}\n\t\tif task != \"\" {\n\t\t\ttext += baseStyle.\n\t\t\t\tWidth(m.width).\n\t\t\t\tForeground(t.Primary()).\n\t\t\t\tBold(true).\n\t\t\t\tRender(fmt.Sprintf(\"%s %s \", m.spinner.View(), task))\n\t\t}\n\t}\n\treturn text\n}\n\nfunc (m *messagesCmp) help() string {\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\n\ttext := \"\"\n\n\tif m.app.CoderAgent.IsBusy() {\n\t\ttext += lipgloss.JoinHorizontal(\n\t\t\tlipgloss.Left,\n\t\t\tbaseStyle.Foreground(t.TextMuted()).Bold(true).Render(\"press \"),\n\t\t\tbaseStyle.Foreground(t.Text()).Bold(true).Render(\"esc\"),\n\t\t\tbaseStyle.Foreground(t.TextMuted()).Bold(true).Render(\" to exit cancel\"),\n\t\t)\n\t} else {\n\t\ttext += lipgloss.JoinHorizontal(\n\t\t\tlipgloss.Left,\n\t\t\tbaseStyle.Foreground(t.TextMuted()).Bold(true).Render(\"press \"),\n\t\t\tbaseStyle.Foreground(t.Text()).Bold(true).Render(\"enter\"),\n\t\t\tbaseStyle.Foreground(t.TextMuted()).Bold(true).Render(\" to send the message,\"),\n\t\t\tbaseStyle.Foreground(t.TextMuted()).Bold(true).Render(\" write\"),\n\t\t\tbaseStyle.Foreground(t.Text()).Bold(true).Render(\" \\\\\"),\n\t\t\tbaseStyle.Foreground(t.TextMuted()).Bold(true).Render(\" and enter to add a new line\"),\n\t\t)\n\t}\n\treturn baseStyle.\n\t\tWidth(m.width).\n\t\tRender(text)\n}\n\nfunc (m *messagesCmp) initialScreen() string {\n\tbaseStyle := styles.BaseStyle()\n\n\treturn baseStyle.Width(m.width).Render(\n\t\tlipgloss.JoinVertical(\n\t\t\tlipgloss.Top,\n\t\t\theader(m.width),\n\t\t\t\"\",\n\t\t\tlspsConfigured(m.width),\n\t\t),\n\t)\n}\n\nfunc (m *messagesCmp) rerender() {\n\tfor _, msg := range m.messages {\n\t\tdelete(m.cachedContent, msg.ID)\n\t}\n\tm.renderView()\n}\n\nfunc (m *messagesCmp) SetSize(width, height int) tea.Cmd {\n\tif m.width == width && m.height == height {\n\t\treturn nil\n\t}\n\tm.width = width\n\tm.height = height\n\tm.viewport.Width = width\n\tm.viewport.Height = height - 2\n\tm.attachments.Width = width + 40\n\tm.attachments.Height = 3\n\tm.rerender()\n\treturn nil\n}\n\nfunc (m *messagesCmp) GetSize() (int, int) {\n\treturn m.width, m.height\n}\n\nfunc (m *messagesCmp) SetSession(session session.Session) tea.Cmd {\n\tif m.session.ID == session.ID {\n\t\treturn nil\n\t}\n\tm.session = session\n\tmessages, err := m.app.Messages.List(context.Background(), session.ID)\n\tif err != nil {\n\t\treturn util.ReportError(err)\n\t}\n\tm.messages = messages\n\tif len(m.messages) > 0 {\n\t\tm.currentMsgID = m.messages[len(m.messages)-1].ID\n\t}\n\tdelete(m.cachedContent, m.currentMsgID)\n\tm.rendering = true\n\treturn func() tea.Msg {\n\t\tm.renderView()\n\t\treturn renderFinishedMsg{}\n\t}\n}\n\nfunc (m *messagesCmp) BindingKeys() []key.Binding {\n\treturn []key.Binding{\n\t\tm.viewport.KeyMap.PageDown,\n\t\tm.viewport.KeyMap.PageUp,\n\t\tm.viewport.KeyMap.HalfPageUp,\n\t\tm.viewport.KeyMap.HalfPageDown,\n\t}\n}\n\nfunc NewMessagesCmp(app *app.App) tea.Model {\n\ts := spinner.New()\n\ts.Spinner = spinner.Pulse\n\tvp := viewport.New(0, 0)\n\tattachmets := viewport.New(0, 0)\n\tvp.KeyMap.PageUp = messageKeys.PageUp\n\tvp.KeyMap.PageDown = messageKeys.PageDown\n\tvp.KeyMap.HalfPageUp = messageKeys.HalfPageUp\n\tvp.KeyMap.HalfPageDown = messageKeys.HalfPageDown\n\treturn &messagesCmp{\n\t\tapp: app,\n\t\tcachedContent: make(map[string]cacheItem),\n\t\tviewport: vp,\n\t\tspinner: s,\n\t\tattachments: attachmets,\n\t}\n}\n"], ["/opencode/internal/tui/components/dialog/filepicker.go", "package dialog\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"sort\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/charmbracelet/bubbles/key\"\n\t\"github.com/charmbracelet/bubbles/textinput\"\n\t\"github.com/charmbracelet/bubbles/viewport\"\n\ttea \"github.com/charmbracelet/bubbletea\"\n\t\"github.com/charmbracelet/lipgloss\"\n\t\"github.com/opencode-ai/opencode/internal/app\"\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n\t\"github.com/opencode-ai/opencode/internal/message\"\n\t\"github.com/opencode-ai/opencode/internal/tui/image\"\n\t\"github.com/opencode-ai/opencode/internal/tui/styles\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n\t\"github.com/opencode-ai/opencode/internal/tui/util\"\n)\n\nconst (\n\tmaxAttachmentSize = int64(5 * 1024 * 1024) // 5MB\n\tdownArrow = \"down\"\n\tupArrow = \"up\"\n)\n\ntype FilePrickerKeyMap struct {\n\tEnter key.Binding\n\tDown key.Binding\n\tUp key.Binding\n\tForward key.Binding\n\tBackward key.Binding\n\tOpenFilePicker key.Binding\n\tEsc key.Binding\n\tInsertCWD key.Binding\n}\n\nvar filePickerKeyMap = FilePrickerKeyMap{\n\tEnter: key.NewBinding(\n\t\tkey.WithKeys(\"enter\"),\n\t\tkey.WithHelp(\"enter\", \"select file/enter directory\"),\n\t),\n\tDown: key.NewBinding(\n\t\tkey.WithKeys(\"j\", downArrow),\n\t\tkey.WithHelp(\"↓/j\", \"down\"),\n\t),\n\tUp: key.NewBinding(\n\t\tkey.WithKeys(\"k\", upArrow),\n\t\tkey.WithHelp(\"↑/k\", \"up\"),\n\t),\n\tForward: key.NewBinding(\n\t\tkey.WithKeys(\"l\"),\n\t\tkey.WithHelp(\"l\", \"enter directory\"),\n\t),\n\tBackward: key.NewBinding(\n\t\tkey.WithKeys(\"h\", \"backspace\"),\n\t\tkey.WithHelp(\"h/backspace\", \"go back\"),\n\t),\n\tOpenFilePicker: key.NewBinding(\n\t\tkey.WithKeys(\"ctrl+f\"),\n\t\tkey.WithHelp(\"ctrl+f\", \"open file picker\"),\n\t),\n\tEsc: key.NewBinding(\n\t\tkey.WithKeys(\"esc\"),\n\t\tkey.WithHelp(\"esc\", \"close/exit\"),\n\t),\n\tInsertCWD: key.NewBinding(\n\t\tkey.WithKeys(\"i\"),\n\t\tkey.WithHelp(\"i\", \"manual path input\"),\n\t),\n}\n\ntype filepickerCmp struct {\n\tbasePath string\n\twidth int\n\theight int\n\tcursor int\n\terr error\n\tcursorChain stack\n\tviewport viewport.Model\n\tdirs []os.DirEntry\n\tcwdDetails *DirNode\n\tselectedFile string\n\tcwd textinput.Model\n\tShowFilePicker bool\n\tapp *app.App\n}\n\ntype DirNode struct {\n\tparent *DirNode\n\tchild *DirNode\n\tdirectory string\n}\ntype stack []int\n\nfunc (s stack) Push(v int) stack {\n\treturn append(s, v)\n}\n\nfunc (s stack) Pop() (stack, int) {\n\tl := len(s)\n\treturn s[:l-1], s[l-1]\n}\n\ntype AttachmentAddedMsg struct {\n\tAttachment message.Attachment\n}\n\nfunc (f *filepickerCmp) Init() tea.Cmd {\n\treturn nil\n}\n\nfunc (f *filepickerCmp) Update(msg tea.Msg) (tea.Model, tea.Cmd) {\n\tvar cmd tea.Cmd\n\tswitch msg := msg.(type) {\n\tcase tea.WindowSizeMsg:\n\t\tf.width = 60\n\t\tf.height = 20\n\t\tf.viewport.Width = 80\n\t\tf.viewport.Height = 22\n\t\tf.cursor = 0\n\t\tf.getCurrentFileBelowCursor()\n\tcase tea.KeyMsg:\n\t\tif f.cwd.Focused() {\n\t\t\tf.cwd, cmd = f.cwd.Update(msg)\n\t\t}\n\t\tswitch {\n\t\tcase key.Matches(msg, filePickerKeyMap.InsertCWD):\n\t\t\tf.cwd.Focus()\n\t\t\treturn f, cmd\n\t\tcase key.Matches(msg, filePickerKeyMap.Esc):\n\t\t\tif f.cwd.Focused() {\n\t\t\t\tf.cwd.Blur()\n\t\t\t}\n\t\tcase key.Matches(msg, filePickerKeyMap.Down):\n\t\t\tif !f.cwd.Focused() || msg.String() == downArrow {\n\t\t\t\tif f.cursor < len(f.dirs)-1 {\n\t\t\t\t\tf.cursor++\n\t\t\t\t\tf.getCurrentFileBelowCursor()\n\t\t\t\t}\n\t\t\t}\n\t\tcase key.Matches(msg, filePickerKeyMap.Up):\n\t\t\tif !f.cwd.Focused() || msg.String() == upArrow {\n\t\t\t\tif f.cursor > 0 {\n\t\t\t\t\tf.cursor--\n\t\t\t\t\tf.getCurrentFileBelowCursor()\n\t\t\t\t}\n\t\t\t}\n\t\tcase key.Matches(msg, filePickerKeyMap.Enter):\n\t\t\tvar path string\n\t\t\tvar isPathDir bool\n\t\t\tif f.cwd.Focused() {\n\t\t\t\tpath = f.cwd.Value()\n\t\t\t\tfileInfo, err := os.Stat(path)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlogging.ErrorPersist(\"Invalid path\")\n\t\t\t\t\treturn f, cmd\n\t\t\t\t}\n\t\t\t\tisPathDir = fileInfo.IsDir()\n\t\t\t} else {\n\t\t\t\tpath = filepath.Join(f.cwdDetails.directory, \"/\", f.dirs[f.cursor].Name())\n\t\t\t\tisPathDir = f.dirs[f.cursor].IsDir()\n\t\t\t}\n\t\t\tif isPathDir {\n\t\t\t\tnewWorkingDir := DirNode{parent: f.cwdDetails, directory: path}\n\t\t\t\tf.cwdDetails.child = &newWorkingDir\n\t\t\t\tf.cwdDetails = f.cwdDetails.child\n\t\t\t\tf.cursorChain = f.cursorChain.Push(f.cursor)\n\t\t\t\tf.dirs = readDir(f.cwdDetails.directory, false)\n\t\t\t\tf.cursor = 0\n\t\t\t\tf.cwd.SetValue(f.cwdDetails.directory)\n\t\t\t\tf.getCurrentFileBelowCursor()\n\t\t\t} else {\n\t\t\t\tf.selectedFile = path\n\t\t\t\treturn f.addAttachmentToMessage()\n\t\t\t}\n\t\tcase key.Matches(msg, filePickerKeyMap.Esc):\n\t\t\tif !f.cwd.Focused() {\n\t\t\t\tf.cursorChain = make(stack, 0)\n\t\t\t\tf.cursor = 0\n\t\t\t} else {\n\t\t\t\tf.cwd.Blur()\n\t\t\t}\n\t\tcase key.Matches(msg, filePickerKeyMap.Forward):\n\t\t\tif !f.cwd.Focused() {\n\t\t\t\tif f.dirs[f.cursor].IsDir() {\n\t\t\t\t\tpath := filepath.Join(f.cwdDetails.directory, \"/\", f.dirs[f.cursor].Name())\n\t\t\t\t\tnewWorkingDir := DirNode{parent: f.cwdDetails, directory: path}\n\t\t\t\t\tf.cwdDetails.child = &newWorkingDir\n\t\t\t\t\tf.cwdDetails = f.cwdDetails.child\n\t\t\t\t\tf.cursorChain = f.cursorChain.Push(f.cursor)\n\t\t\t\t\tf.dirs = readDir(f.cwdDetails.directory, false)\n\t\t\t\t\tf.cursor = 0\n\t\t\t\t\tf.cwd.SetValue(f.cwdDetails.directory)\n\t\t\t\t\tf.getCurrentFileBelowCursor()\n\t\t\t\t}\n\t\t\t}\n\t\tcase key.Matches(msg, filePickerKeyMap.Backward):\n\t\t\tif !f.cwd.Focused() {\n\t\t\t\tif len(f.cursorChain) != 0 && f.cwdDetails.parent != nil {\n\t\t\t\t\tf.cursorChain, f.cursor = f.cursorChain.Pop()\n\t\t\t\t\tf.cwdDetails = f.cwdDetails.parent\n\t\t\t\t\tf.cwdDetails.child = nil\n\t\t\t\t\tf.dirs = readDir(f.cwdDetails.directory, false)\n\t\t\t\t\tf.cwd.SetValue(f.cwdDetails.directory)\n\t\t\t\t\tf.getCurrentFileBelowCursor()\n\t\t\t\t}\n\t\t\t}\n\t\tcase key.Matches(msg, filePickerKeyMap.OpenFilePicker):\n\t\t\tf.dirs = readDir(f.cwdDetails.directory, false)\n\t\t\tf.cursor = 0\n\t\t\tf.getCurrentFileBelowCursor()\n\t\t}\n\t}\n\treturn f, cmd\n}\n\nfunc (f *filepickerCmp) addAttachmentToMessage() (tea.Model, tea.Cmd) {\n\tmodeInfo := GetSelectedModel(config.Get())\n\tif !modeInfo.SupportsAttachments {\n\t\tlogging.ErrorPersist(fmt.Sprintf(\"Model %s doesn't support attachments\", modeInfo.Name))\n\t\treturn f, nil\n\t}\n\n\tselectedFilePath := f.selectedFile\n\tif !isExtSupported(selectedFilePath) {\n\t\tlogging.ErrorPersist(\"Unsupported file\")\n\t\treturn f, nil\n\t}\n\n\tisFileLarge, err := image.ValidateFileSize(selectedFilePath, maxAttachmentSize)\n\tif err != nil {\n\t\tlogging.ErrorPersist(\"unable to read the image\")\n\t\treturn f, nil\n\t}\n\tif isFileLarge {\n\t\tlogging.ErrorPersist(\"file too large, max 5MB\")\n\t\treturn f, nil\n\t}\n\n\tcontent, err := os.ReadFile(selectedFilePath)\n\tif err != nil {\n\t\tlogging.ErrorPersist(\"Unable read selected file\")\n\t\treturn f, nil\n\t}\n\n\tmimeBufferSize := min(512, len(content))\n\tmimeType := http.DetectContentType(content[:mimeBufferSize])\n\tfileName := filepath.Base(selectedFilePath)\n\tattachment := message.Attachment{FilePath: selectedFilePath, FileName: fileName, MimeType: mimeType, Content: content}\n\tf.selectedFile = \"\"\n\treturn f, util.CmdHandler(AttachmentAddedMsg{attachment})\n}\n\nfunc (f *filepickerCmp) View() string {\n\tt := theme.CurrentTheme()\n\tconst maxVisibleDirs = 20\n\tconst maxWidth = 80\n\n\tadjustedWidth := maxWidth\n\tfor _, file := range f.dirs {\n\t\tif len(file.Name()) > adjustedWidth-4 { // Account for padding\n\t\t\tadjustedWidth = len(file.Name()) + 4\n\t\t}\n\t}\n\tadjustedWidth = max(30, min(adjustedWidth, f.width-15)) + 1\n\n\tfiles := make([]string, 0, maxVisibleDirs)\n\tstartIdx := 0\n\n\tif len(f.dirs) > maxVisibleDirs {\n\t\thalfVisible := maxVisibleDirs / 2\n\t\tif f.cursor >= halfVisible && f.cursor < len(f.dirs)-halfVisible {\n\t\t\tstartIdx = f.cursor - halfVisible\n\t\t} else if f.cursor >= len(f.dirs)-halfVisible {\n\t\t\tstartIdx = len(f.dirs) - maxVisibleDirs\n\t\t}\n\t}\n\n\tendIdx := min(startIdx+maxVisibleDirs, len(f.dirs))\n\n\tfor i := startIdx; i < endIdx; i++ {\n\t\tfile := f.dirs[i]\n\t\titemStyle := styles.BaseStyle().Width(adjustedWidth)\n\n\t\tif i == f.cursor {\n\t\t\titemStyle = itemStyle.\n\t\t\t\tBackground(t.Primary()).\n\t\t\t\tForeground(t.Background()).\n\t\t\t\tBold(true)\n\t\t}\n\t\tfilename := file.Name()\n\n\t\tif len(filename) > adjustedWidth-4 {\n\t\t\tfilename = filename[:adjustedWidth-7] + \"...\"\n\t\t}\n\t\tif file.IsDir() {\n\t\t\tfilename = filename + \"/\"\n\t\t}\n\t\t// No need to reassign filename if it's not changing\n\n\t\tfiles = append(files, itemStyle.Padding(0, 1).Render(filename))\n\t}\n\n\t// Pad to always show exactly 21 lines\n\tfor len(files) < maxVisibleDirs {\n\t\tfiles = append(files, styles.BaseStyle().Width(adjustedWidth).Render(\"\"))\n\t}\n\n\tcurrentPath := styles.BaseStyle().\n\t\tHeight(1).\n\t\tWidth(adjustedWidth).\n\t\tRender(f.cwd.View())\n\n\tviewportstyle := lipgloss.NewStyle().\n\t\tWidth(f.viewport.Width).\n\t\tBackground(t.Background()).\n\t\tBorder(lipgloss.RoundedBorder()).\n\t\tBorderForeground(t.TextMuted()).\n\t\tBorderBackground(t.Background()).\n\t\tPadding(2).\n\t\tRender(f.viewport.View())\n\tvar insertExitText string\n\tif f.IsCWDFocused() {\n\t\tinsertExitText = \"Press esc to exit typing path\"\n\t} else {\n\t\tinsertExitText = \"Press i to start typing path\"\n\t}\n\n\tcontent := lipgloss.JoinVertical(\n\t\tlipgloss.Left,\n\t\tcurrentPath,\n\t\tstyles.BaseStyle().Width(adjustedWidth).Render(\"\"),\n\t\tstyles.BaseStyle().Width(adjustedWidth).Render(lipgloss.JoinVertical(lipgloss.Left, files...)),\n\t\tstyles.BaseStyle().Width(adjustedWidth).Render(\"\"),\n\t\tstyles.BaseStyle().Foreground(t.TextMuted()).Width(adjustedWidth).Render(insertExitText),\n\t)\n\n\tf.cwd.SetValue(f.cwd.Value())\n\tcontentStyle := styles.BaseStyle().Padding(1, 2).\n\t\tBorder(lipgloss.RoundedBorder()).\n\t\tBorderBackground(t.Background()).\n\t\tBorderForeground(t.TextMuted()).\n\t\tWidth(lipgloss.Width(content) + 4)\n\n\treturn lipgloss.JoinHorizontal(lipgloss.Center, contentStyle.Render(content), viewportstyle)\n}\n\ntype FilepickerCmp interface {\n\ttea.Model\n\tToggleFilepicker(showFilepicker bool)\n\tIsCWDFocused() bool\n}\n\nfunc (f *filepickerCmp) ToggleFilepicker(showFilepicker bool) {\n\tf.ShowFilePicker = showFilepicker\n}\n\nfunc (f *filepickerCmp) IsCWDFocused() bool {\n\treturn f.cwd.Focused()\n}\n\nfunc NewFilepickerCmp(app *app.App) FilepickerCmp {\n\thomepath, err := os.UserHomeDir()\n\tif err != nil {\n\t\tlogging.Error(\"error loading user files\")\n\t\treturn nil\n\t}\n\tbaseDir := DirNode{parent: nil, directory: homepath}\n\tdirs := readDir(homepath, false)\n\tviewport := viewport.New(0, 0)\n\tcurrentDirectory := textinput.New()\n\tcurrentDirectory.CharLimit = 200\n\tcurrentDirectory.Width = 44\n\tcurrentDirectory.Cursor.Blink = true\n\tcurrentDirectory.SetValue(baseDir.directory)\n\treturn &filepickerCmp{cwdDetails: &baseDir, dirs: dirs, cursorChain: make(stack, 0), viewport: viewport, cwd: currentDirectory, app: app}\n}\n\nfunc (f *filepickerCmp) getCurrentFileBelowCursor() {\n\tif len(f.dirs) == 0 || f.cursor < 0 || f.cursor >= len(f.dirs) {\n\t\tlogging.Error(fmt.Sprintf(\"Invalid cursor position. Dirs length: %d, Cursor: %d\", len(f.dirs), f.cursor))\n\t\tf.viewport.SetContent(\"Preview unavailable\")\n\t\treturn\n\t}\n\n\tdir := f.dirs[f.cursor]\n\tfilename := dir.Name()\n\tif !dir.IsDir() && isExtSupported(filename) {\n\t\tfullPath := f.cwdDetails.directory + \"/\" + dir.Name()\n\n\t\tgo func() {\n\t\t\timageString, err := image.ImagePreview(f.viewport.Width-4, fullPath)\n\t\t\tif err != nil {\n\t\t\t\tlogging.Error(err.Error())\n\t\t\t\tf.viewport.SetContent(\"Preview unavailable\")\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tf.viewport.SetContent(imageString)\n\t\t}()\n\t} else {\n\t\tf.viewport.SetContent(\"Preview unavailable\")\n\t}\n}\n\nfunc readDir(path string, showHidden bool) []os.DirEntry {\n\tlogging.Info(fmt.Sprintf(\"Reading directory: %s\", path))\n\n\tentriesChan := make(chan []os.DirEntry, 1)\n\terrChan := make(chan error, 1)\n\n\tgo func() {\n\t\tdirEntries, err := os.ReadDir(path)\n\t\tif err != nil {\n\t\t\tlogging.ErrorPersist(err.Error())\n\t\t\terrChan <- err\n\t\t\treturn\n\t\t}\n\t\tentriesChan <- dirEntries\n\t}()\n\n\tselect {\n\tcase dirEntries := <-entriesChan:\n\t\tsort.Slice(dirEntries, func(i, j int) bool {\n\t\t\tif dirEntries[i].IsDir() == dirEntries[j].IsDir() {\n\t\t\t\treturn dirEntries[i].Name() < dirEntries[j].Name()\n\t\t\t}\n\t\t\treturn dirEntries[i].IsDir()\n\t\t})\n\n\t\tif showHidden {\n\t\t\treturn dirEntries\n\t\t}\n\n\t\tvar sanitizedDirEntries []os.DirEntry\n\t\tfor _, dirEntry := range dirEntries {\n\t\t\tisHidden, _ := IsHidden(dirEntry.Name())\n\t\t\tif !isHidden {\n\t\t\t\tif dirEntry.IsDir() || isExtSupported(dirEntry.Name()) {\n\t\t\t\t\tsanitizedDirEntries = append(sanitizedDirEntries, dirEntry)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn sanitizedDirEntries\n\n\tcase err := <-errChan:\n\t\tlogging.ErrorPersist(fmt.Sprintf(\"Error reading directory %s\", path), err)\n\t\treturn []os.DirEntry{}\n\n\tcase <-time.After(5 * time.Second):\n\t\tlogging.ErrorPersist(fmt.Sprintf(\"Timeout reading directory %s\", path), nil)\n\t\treturn []os.DirEntry{}\n\t}\n}\n\nfunc IsHidden(file string) (bool, error) {\n\treturn strings.HasPrefix(file, \".\"), nil\n}\n\nfunc isExtSupported(path string) bool {\n\text := strings.ToLower(filepath.Ext(path))\n\treturn (ext == \".jpg\" || ext == \".jpeg\" || ext == \".webp\" || ext == \".png\")\n}\n"], ["/opencode/internal/tui/components/chat/editor.go", "package chat\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"os/exec\"\n\t\"slices\"\n\t\"strings\"\n\t\"unicode\"\n\n\t\"github.com/charmbracelet/bubbles/key\"\n\t\"github.com/charmbracelet/bubbles/textarea\"\n\ttea \"github.com/charmbracelet/bubbletea\"\n\t\"github.com/charmbracelet/lipgloss\"\n\t\"github.com/opencode-ai/opencode/internal/app\"\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n\t\"github.com/opencode-ai/opencode/internal/message\"\n\t\"github.com/opencode-ai/opencode/internal/session\"\n\t\"github.com/opencode-ai/opencode/internal/tui/components/dialog\"\n\t\"github.com/opencode-ai/opencode/internal/tui/layout\"\n\t\"github.com/opencode-ai/opencode/internal/tui/styles\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n\t\"github.com/opencode-ai/opencode/internal/tui/util\"\n)\n\ntype editorCmp struct {\n\twidth int\n\theight int\n\tapp *app.App\n\tsession session.Session\n\ttextarea textarea.Model\n\tattachments []message.Attachment\n\tdeleteMode bool\n}\n\ntype EditorKeyMaps struct {\n\tSend key.Binding\n\tOpenEditor key.Binding\n}\n\ntype bluredEditorKeyMaps struct {\n\tSend key.Binding\n\tFocus key.Binding\n\tOpenEditor key.Binding\n}\ntype DeleteAttachmentKeyMaps struct {\n\tAttachmentDeleteMode key.Binding\n\tEscape key.Binding\n\tDeleteAllAttachments key.Binding\n}\n\nvar editorMaps = EditorKeyMaps{\n\tSend: key.NewBinding(\n\t\tkey.WithKeys(\"enter\", \"ctrl+s\"),\n\t\tkey.WithHelp(\"enter\", \"send message\"),\n\t),\n\tOpenEditor: key.NewBinding(\n\t\tkey.WithKeys(\"ctrl+e\"),\n\t\tkey.WithHelp(\"ctrl+e\", \"open editor\"),\n\t),\n}\n\nvar DeleteKeyMaps = DeleteAttachmentKeyMaps{\n\tAttachmentDeleteMode: key.NewBinding(\n\t\tkey.WithKeys(\"ctrl+r\"),\n\t\tkey.WithHelp(\"ctrl+r+{i}\", \"delete attachment at index i\"),\n\t),\n\tEscape: key.NewBinding(\n\t\tkey.WithKeys(\"esc\"),\n\t\tkey.WithHelp(\"esc\", \"cancel delete mode\"),\n\t),\n\tDeleteAllAttachments: key.NewBinding(\n\t\tkey.WithKeys(\"r\"),\n\t\tkey.WithHelp(\"ctrl+r+r\", \"delete all attchments\"),\n\t),\n}\n\nconst (\n\tmaxAttachments = 5\n)\n\nfunc (m *editorCmp) openEditor() tea.Cmd {\n\teditor := os.Getenv(\"EDITOR\")\n\tif editor == \"\" {\n\t\teditor = \"nvim\"\n\t}\n\n\ttmpfile, err := os.CreateTemp(\"\", \"msg_*.md\")\n\tif err != nil {\n\t\treturn util.ReportError(err)\n\t}\n\ttmpfile.Close()\n\tc := exec.Command(editor, tmpfile.Name()) //nolint:gosec\n\tc.Stdin = os.Stdin\n\tc.Stdout = os.Stdout\n\tc.Stderr = os.Stderr\n\treturn tea.ExecProcess(c, func(err error) tea.Msg {\n\t\tif err != nil {\n\t\t\treturn util.ReportError(err)\n\t\t}\n\t\tcontent, err := os.ReadFile(tmpfile.Name())\n\t\tif err != nil {\n\t\t\treturn util.ReportError(err)\n\t\t}\n\t\tif len(content) == 0 {\n\t\t\treturn util.ReportWarn(\"Message is empty\")\n\t\t}\n\t\tos.Remove(tmpfile.Name())\n\t\tattachments := m.attachments\n\t\tm.attachments = nil\n\t\treturn SendMsg{\n\t\t\tText: string(content),\n\t\t\tAttachments: attachments,\n\t\t}\n\t})\n}\n\nfunc (m *editorCmp) Init() tea.Cmd {\n\treturn textarea.Blink\n}\n\nfunc (m *editorCmp) send() tea.Cmd {\n\tif m.app.CoderAgent.IsSessionBusy(m.session.ID) {\n\t\treturn util.ReportWarn(\"Agent is working, please wait...\")\n\t}\n\n\tvalue := m.textarea.Value()\n\tm.textarea.Reset()\n\tattachments := m.attachments\n\n\tm.attachments = nil\n\tif value == \"\" {\n\t\treturn nil\n\t}\n\treturn tea.Batch(\n\t\tutil.CmdHandler(SendMsg{\n\t\t\tText: value,\n\t\t\tAttachments: attachments,\n\t\t}),\n\t)\n}\n\nfunc (m *editorCmp) Update(msg tea.Msg) (tea.Model, tea.Cmd) {\n\tvar cmd tea.Cmd\n\tswitch msg := msg.(type) {\n\tcase dialog.ThemeChangedMsg:\n\t\tm.textarea = CreateTextArea(&m.textarea)\n\tcase dialog.CompletionSelectedMsg:\n\t\texistingValue := m.textarea.Value()\n\t\tmodifiedValue := strings.Replace(existingValue, msg.SearchString, msg.CompletionValue, 1)\n\n\t\tm.textarea.SetValue(modifiedValue)\n\t\treturn m, nil\n\tcase SessionSelectedMsg:\n\t\tif msg.ID != m.session.ID {\n\t\t\tm.session = msg\n\t\t}\n\t\treturn m, nil\n\tcase dialog.AttachmentAddedMsg:\n\t\tif len(m.attachments) >= maxAttachments {\n\t\t\tlogging.ErrorPersist(fmt.Sprintf(\"cannot add more than %d images\", maxAttachments))\n\t\t\treturn m, cmd\n\t\t}\n\t\tm.attachments = append(m.attachments, msg.Attachment)\n\tcase tea.KeyMsg:\n\t\tif key.Matches(msg, DeleteKeyMaps.AttachmentDeleteMode) {\n\t\t\tm.deleteMode = true\n\t\t\treturn m, nil\n\t\t}\n\t\tif key.Matches(msg, DeleteKeyMaps.DeleteAllAttachments) && m.deleteMode {\n\t\t\tm.deleteMode = false\n\t\t\tm.attachments = nil\n\t\t\treturn m, nil\n\t\t}\n\t\tif m.deleteMode && len(msg.Runes) > 0 && unicode.IsDigit(msg.Runes[0]) {\n\t\t\tnum := int(msg.Runes[0] - '0')\n\t\t\tm.deleteMode = false\n\t\t\tif num < 10 && len(m.attachments) > num {\n\t\t\t\tif num == 0 {\n\t\t\t\t\tm.attachments = m.attachments[num+1:]\n\t\t\t\t} else {\n\t\t\t\t\tm.attachments = slices.Delete(m.attachments, num, num+1)\n\t\t\t\t}\n\t\t\t\treturn m, nil\n\t\t\t}\n\t\t}\n\t\tif key.Matches(msg, messageKeys.PageUp) || key.Matches(msg, messageKeys.PageDown) ||\n\t\t\tkey.Matches(msg, messageKeys.HalfPageUp) || key.Matches(msg, messageKeys.HalfPageDown) {\n\t\t\treturn m, nil\n\t\t}\n\t\tif key.Matches(msg, editorMaps.OpenEditor) {\n\t\t\tif m.app.CoderAgent.IsSessionBusy(m.session.ID) {\n\t\t\t\treturn m, util.ReportWarn(\"Agent is working, please wait...\")\n\t\t\t}\n\t\t\treturn m, m.openEditor()\n\t\t}\n\t\tif key.Matches(msg, DeleteKeyMaps.Escape) {\n\t\t\tm.deleteMode = false\n\t\t\treturn m, nil\n\t\t}\n\t\t// Hanlde Enter key\n\t\tif m.textarea.Focused() && key.Matches(msg, editorMaps.Send) {\n\t\t\tvalue := m.textarea.Value()\n\t\t\tif len(value) > 0 && value[len(value)-1] == '\\\\' {\n\t\t\t\t// If the last character is a backslash, remove it and add a newline\n\t\t\t\tm.textarea.SetValue(value[:len(value)-1] + \"\\n\")\n\t\t\t\treturn m, nil\n\t\t\t} else {\n\t\t\t\t// Otherwise, send the message\n\t\t\t\treturn m, m.send()\n\t\t\t}\n\t\t}\n\n\t}\n\tm.textarea, cmd = m.textarea.Update(msg)\n\treturn m, cmd\n}\n\nfunc (m *editorCmp) View() string {\n\tt := theme.CurrentTheme()\n\n\t// Style the prompt with theme colors\n\tstyle := lipgloss.NewStyle().\n\t\tPadding(0, 0, 0, 1).\n\t\tBold(true).\n\t\tForeground(t.Primary())\n\n\tif len(m.attachments) == 0 {\n\t\treturn lipgloss.JoinHorizontal(lipgloss.Top, style.Render(\">\"), m.textarea.View())\n\t}\n\tm.textarea.SetHeight(m.height - 1)\n\treturn lipgloss.JoinVertical(lipgloss.Top,\n\t\tm.attachmentsContent(),\n\t\tlipgloss.JoinHorizontal(lipgloss.Top, style.Render(\">\"),\n\t\t\tm.textarea.View()),\n\t)\n}\n\nfunc (m *editorCmp) SetSize(width, height int) tea.Cmd {\n\tm.width = width\n\tm.height = height\n\tm.textarea.SetWidth(width - 3) // account for the prompt and padding right\n\tm.textarea.SetHeight(height)\n\tm.textarea.SetWidth(width)\n\treturn nil\n}\n\nfunc (m *editorCmp) GetSize() (int, int) {\n\treturn m.textarea.Width(), m.textarea.Height()\n}\n\nfunc (m *editorCmp) attachmentsContent() string {\n\tvar styledAttachments []string\n\tt := theme.CurrentTheme()\n\tattachmentStyles := styles.BaseStyle().\n\t\tMarginLeft(1).\n\t\tBackground(t.TextMuted()).\n\t\tForeground(t.Text())\n\tfor i, attachment := range m.attachments {\n\t\tvar filename string\n\t\tif len(attachment.FileName) > 10 {\n\t\t\tfilename = fmt.Sprintf(\" %s %s...\", styles.DocumentIcon, attachment.FileName[0:7])\n\t\t} else {\n\t\t\tfilename = fmt.Sprintf(\" %s %s\", styles.DocumentIcon, attachment.FileName)\n\t\t}\n\t\tif m.deleteMode {\n\t\t\tfilename = fmt.Sprintf(\"%d%s\", i, filename)\n\t\t}\n\t\tstyledAttachments = append(styledAttachments, attachmentStyles.Render(filename))\n\t}\n\tcontent := lipgloss.JoinHorizontal(lipgloss.Left, styledAttachments...)\n\treturn content\n}\n\nfunc (m *editorCmp) BindingKeys() []key.Binding {\n\tbindings := []key.Binding{}\n\tbindings = append(bindings, layout.KeyMapToSlice(editorMaps)...)\n\tbindings = append(bindings, layout.KeyMapToSlice(DeleteKeyMaps)...)\n\treturn bindings\n}\n\nfunc CreateTextArea(existing *textarea.Model) textarea.Model {\n\tt := theme.CurrentTheme()\n\tbgColor := t.Background()\n\ttextColor := t.Text()\n\ttextMutedColor := t.TextMuted()\n\n\tta := textarea.New()\n\tta.BlurredStyle.Base = styles.BaseStyle().Background(bgColor).Foreground(textColor)\n\tta.BlurredStyle.CursorLine = styles.BaseStyle().Background(bgColor)\n\tta.BlurredStyle.Placeholder = styles.BaseStyle().Background(bgColor).Foreground(textMutedColor)\n\tta.BlurredStyle.Text = styles.BaseStyle().Background(bgColor).Foreground(textColor)\n\tta.FocusedStyle.Base = styles.BaseStyle().Background(bgColor).Foreground(textColor)\n\tta.FocusedStyle.CursorLine = styles.BaseStyle().Background(bgColor)\n\tta.FocusedStyle.Placeholder = styles.BaseStyle().Background(bgColor).Foreground(textMutedColor)\n\tta.FocusedStyle.Text = styles.BaseStyle().Background(bgColor).Foreground(textColor)\n\n\tta.Prompt = \" \"\n\tta.ShowLineNumbers = false\n\tta.CharLimit = -1\n\n\tif existing != nil {\n\t\tta.SetValue(existing.Value())\n\t\tta.SetWidth(existing.Width())\n\t\tta.SetHeight(existing.Height())\n\t}\n\n\tta.Focus()\n\treturn ta\n}\n\nfunc NewEditorCmp(app *app.App) tea.Model {\n\tta := CreateTextArea(nil)\n\treturn &editorCmp{\n\t\tapp: app,\n\t\ttextarea: ta,\n\t}\n}\n"], ["/opencode/internal/tui/components/util/simple-list.go", "package utilComponents\n\nimport (\n\t\"github.com/charmbracelet/bubbles/key\"\n\ttea \"github.com/charmbracelet/bubbletea\"\n\t\"github.com/charmbracelet/lipgloss\"\n\t\"github.com/opencode-ai/opencode/internal/tui/layout\"\n\t\"github.com/opencode-ai/opencode/internal/tui/styles\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n)\n\ntype SimpleListItem interface {\n\tRender(selected bool, width int) string\n}\n\ntype SimpleList[T SimpleListItem] interface {\n\ttea.Model\n\tlayout.Bindings\n\tSetMaxWidth(maxWidth int)\n\tGetSelectedItem() (item T, idx int)\n\tSetItems(items []T)\n\tGetItems() []T\n}\n\ntype simpleListCmp[T SimpleListItem] struct {\n\tfallbackMsg string\n\titems []T\n\tselectedIdx int\n\tmaxWidth int\n\tmaxVisibleItems int\n\tuseAlphaNumericKeys bool\n\twidth int\n\theight int\n}\n\ntype simpleListKeyMap struct {\n\tUp key.Binding\n\tDown key.Binding\n\tUpAlpha key.Binding\n\tDownAlpha key.Binding\n}\n\nvar simpleListKeys = simpleListKeyMap{\n\tUp: key.NewBinding(\n\t\tkey.WithKeys(\"up\"),\n\t\tkey.WithHelp(\"↑\", \"previous list item\"),\n\t),\n\tDown: key.NewBinding(\n\t\tkey.WithKeys(\"down\"),\n\t\tkey.WithHelp(\"↓\", \"next list item\"),\n\t),\n\tUpAlpha: key.NewBinding(\n\t\tkey.WithKeys(\"k\"),\n\t\tkey.WithHelp(\"k\", \"previous list item\"),\n\t),\n\tDownAlpha: key.NewBinding(\n\t\tkey.WithKeys(\"j\"),\n\t\tkey.WithHelp(\"j\", \"next list item\"),\n\t),\n}\n\nfunc (c *simpleListCmp[T]) Init() tea.Cmd {\n\treturn nil\n}\n\nfunc (c *simpleListCmp[T]) Update(msg tea.Msg) (tea.Model, tea.Cmd) {\n\tswitch msg := msg.(type) {\n\tcase tea.KeyMsg:\n\t\tswitch {\n\t\tcase key.Matches(msg, simpleListKeys.Up) || (c.useAlphaNumericKeys && key.Matches(msg, simpleListKeys.UpAlpha)):\n\t\t\tif c.selectedIdx > 0 {\n\t\t\t\tc.selectedIdx--\n\t\t\t}\n\t\t\treturn c, nil\n\t\tcase key.Matches(msg, simpleListKeys.Down) || (c.useAlphaNumericKeys && key.Matches(msg, simpleListKeys.DownAlpha)):\n\t\t\tif c.selectedIdx < len(c.items)-1 {\n\t\t\t\tc.selectedIdx++\n\t\t\t}\n\t\t\treturn c, nil\n\t\t}\n\t}\n\n\treturn c, nil\n}\n\nfunc (c *simpleListCmp[T]) BindingKeys() []key.Binding {\n\treturn layout.KeyMapToSlice(simpleListKeys)\n}\n\nfunc (c *simpleListCmp[T]) GetSelectedItem() (T, int) {\n\tif len(c.items) > 0 {\n\t\treturn c.items[c.selectedIdx], c.selectedIdx\n\t}\n\n\tvar zero T\n\treturn zero, -1\n}\n\nfunc (c *simpleListCmp[T]) SetItems(items []T) {\n\tc.selectedIdx = 0\n\tc.items = items\n}\n\nfunc (c *simpleListCmp[T]) GetItems() []T {\n\treturn c.items\n}\n\nfunc (c *simpleListCmp[T]) SetMaxWidth(width int) {\n\tc.maxWidth = width\n}\n\nfunc (c *simpleListCmp[T]) View() string {\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\n\titems := c.items\n\tmaxWidth := c.maxWidth\n\tmaxVisibleItems := min(c.maxVisibleItems, len(items))\n\tstartIdx := 0\n\n\tif len(items) <= 0 {\n\t\treturn baseStyle.\n\t\t\tBackground(t.Background()).\n\t\t\tPadding(0, 1).\n\t\t\tWidth(maxWidth).\n\t\t\tRender(c.fallbackMsg)\n\t}\n\n\tif len(items) > maxVisibleItems {\n\t\thalfVisible := maxVisibleItems / 2\n\t\tif c.selectedIdx >= halfVisible && c.selectedIdx < len(items)-halfVisible {\n\t\t\tstartIdx = c.selectedIdx - halfVisible\n\t\t} else if c.selectedIdx >= len(items)-halfVisible {\n\t\t\tstartIdx = len(items) - maxVisibleItems\n\t\t}\n\t}\n\n\tendIdx := min(startIdx+maxVisibleItems, len(items))\n\n\tlistItems := make([]string, 0, maxVisibleItems)\n\n\tfor i := startIdx; i < endIdx; i++ {\n\t\titem := items[i]\n\t\ttitle := item.Render(i == c.selectedIdx, maxWidth)\n\t\tlistItems = append(listItems, title)\n\t}\n\n\treturn lipgloss.JoinVertical(lipgloss.Left, listItems...)\n}\n\nfunc NewSimpleList[T SimpleListItem](items []T, maxVisibleItems int, fallbackMsg string, useAlphaNumericKeys bool) SimpleList[T] {\n\treturn &simpleListCmp[T]{\n\t\tfallbackMsg: fallbackMsg,\n\t\titems: items,\n\t\tmaxVisibleItems: maxVisibleItems,\n\t\tuseAlphaNumericKeys: useAlphaNumericKeys,\n\t\tselectedIdx: 0,\n\t}\n}\n"], ["/opencode/internal/tui/components/dialog/help.go", "package dialog\n\nimport (\n\t\"strings\"\n\n\t\"github.com/charmbracelet/bubbles/key\"\n\ttea \"github.com/charmbracelet/bubbletea\"\n\t\"github.com/charmbracelet/lipgloss\"\n\t\"github.com/opencode-ai/opencode/internal/tui/styles\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n)\n\ntype helpCmp struct {\n\twidth int\n\theight int\n\tkeys []key.Binding\n}\n\nfunc (h *helpCmp) Init() tea.Cmd {\n\treturn nil\n}\n\nfunc (h *helpCmp) SetBindings(k []key.Binding) {\n\th.keys = k\n}\n\nfunc (h *helpCmp) Update(msg tea.Msg) (tea.Model, tea.Cmd) {\n\tswitch msg := msg.(type) {\n\tcase tea.WindowSizeMsg:\n\t\th.width = 90\n\t\th.height = msg.Height\n\t}\n\treturn h, nil\n}\n\nfunc removeDuplicateBindings(bindings []key.Binding) []key.Binding {\n\tseen := make(map[string]struct{})\n\tresult := make([]key.Binding, 0, len(bindings))\n\n\t// Process bindings in reverse order\n\tfor i := len(bindings) - 1; i >= 0; i-- {\n\t\tb := bindings[i]\n\t\tk := strings.Join(b.Keys(), \" \")\n\t\tif _, ok := seen[k]; ok {\n\t\t\t// duplicate, skip\n\t\t\tcontinue\n\t\t}\n\t\tseen[k] = struct{}{}\n\t\t// Add to the beginning of result to maintain original order\n\t\tresult = append([]key.Binding{b}, result...)\n\t}\n\n\treturn result\n}\n\nfunc (h *helpCmp) render() string {\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\n\thelpKeyStyle := styles.Bold().\n\t\tBackground(t.Background()).\n\t\tForeground(t.Text()).\n\t\tPadding(0, 1, 0, 0)\n\n\thelpDescStyle := styles.Regular().\n\t\tBackground(t.Background()).\n\t\tForeground(t.TextMuted())\n\n\t// Compile list of bindings to render\n\tbindings := removeDuplicateBindings(h.keys)\n\n\t// Enumerate through each group of bindings, populating a series of\n\t// pairs of columns, one for keys, one for descriptions\n\tvar (\n\t\tpairs []string\n\t\twidth int\n\t\trows = 12 - 2\n\t)\n\n\tfor i := 0; i < len(bindings); i += rows {\n\t\tvar (\n\t\t\tkeys []string\n\t\t\tdescs []string\n\t\t)\n\t\tfor j := i; j < min(i+rows, len(bindings)); j++ {\n\t\t\tkeys = append(keys, helpKeyStyle.Render(bindings[j].Help().Key))\n\t\t\tdescs = append(descs, helpDescStyle.Render(bindings[j].Help().Desc))\n\t\t}\n\n\t\t// Render pair of columns; beyond the first pair, render a three space\n\t\t// left margin, in order to visually separate the pairs.\n\t\tvar cols []string\n\t\tif len(pairs) > 0 {\n\t\t\tcols = []string{baseStyle.Render(\" \")}\n\t\t}\n\n\t\tmaxDescWidth := 0\n\t\tfor _, desc := range descs {\n\t\t\tif maxDescWidth < lipgloss.Width(desc) {\n\t\t\t\tmaxDescWidth = lipgloss.Width(desc)\n\t\t\t}\n\t\t}\n\t\tfor i := range descs {\n\t\t\tremainingWidth := maxDescWidth - lipgloss.Width(descs[i])\n\t\t\tif remainingWidth > 0 {\n\t\t\t\tdescs[i] = descs[i] + baseStyle.Render(strings.Repeat(\" \", remainingWidth))\n\t\t\t}\n\t\t}\n\t\tmaxKeyWidth := 0\n\t\tfor _, key := range keys {\n\t\t\tif maxKeyWidth < lipgloss.Width(key) {\n\t\t\t\tmaxKeyWidth = lipgloss.Width(key)\n\t\t\t}\n\t\t}\n\t\tfor i := range keys {\n\t\t\tremainingWidth := maxKeyWidth - lipgloss.Width(keys[i])\n\t\t\tif remainingWidth > 0 {\n\t\t\t\tkeys[i] = keys[i] + baseStyle.Render(strings.Repeat(\" \", remainingWidth))\n\t\t\t}\n\t\t}\n\n\t\tcols = append(cols,\n\t\t\tstrings.Join(keys, \"\\n\"),\n\t\t\tstrings.Join(descs, \"\\n\"),\n\t\t)\n\n\t\tpair := baseStyle.Render(lipgloss.JoinHorizontal(lipgloss.Top, cols...))\n\t\t// check whether it exceeds the maximum width avail (the width of the\n\t\t// terminal, subtracting 2 for the borders).\n\t\twidth += lipgloss.Width(pair)\n\t\tif width > h.width-2 {\n\t\t\tbreak\n\t\t}\n\t\tpairs = append(pairs, pair)\n\t}\n\n\t// https://github.com/charmbracelet/lipgloss/issues/209\n\tif len(pairs) > 1 {\n\t\tprefix := pairs[:len(pairs)-1]\n\t\tlastPair := pairs[len(pairs)-1]\n\t\tprefix = append(prefix, lipgloss.Place(\n\t\t\tlipgloss.Width(lastPair), // width\n\t\t\tlipgloss.Height(prefix[0]), // height\n\t\t\tlipgloss.Left, // x\n\t\t\tlipgloss.Top, // y\n\t\t\tlastPair, // content\n\t\t\tlipgloss.WithWhitespaceBackground(t.Background()),\n\t\t))\n\t\tcontent := baseStyle.Width(h.width).Render(\n\t\t\tlipgloss.JoinHorizontal(\n\t\t\t\tlipgloss.Top,\n\t\t\t\tprefix...,\n\t\t\t),\n\t\t)\n\t\treturn content\n\t}\n\n\t// Join pairs of columns and enclose in a border\n\tcontent := baseStyle.Width(h.width).Render(\n\t\tlipgloss.JoinHorizontal(\n\t\t\tlipgloss.Top,\n\t\t\tpairs...,\n\t\t),\n\t)\n\treturn content\n}\n\nfunc (h *helpCmp) View() string {\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\n\tcontent := h.render()\n\theader := baseStyle.\n\t\tBold(true).\n\t\tWidth(lipgloss.Width(content)).\n\t\tForeground(t.Primary()).\n\t\tRender(\"Keyboard Shortcuts\")\n\n\treturn baseStyle.Padding(1).\n\t\tBorder(lipgloss.RoundedBorder()).\n\t\tBorderForeground(t.TextMuted()).\n\t\tWidth(h.width).\n\t\tBorderBackground(t.Background()).\n\t\tRender(\n\t\t\tlipgloss.JoinVertical(lipgloss.Center,\n\t\t\t\theader,\n\t\t\t\tbaseStyle.Render(strings.Repeat(\" \", lipgloss.Width(header))),\n\t\t\t\tcontent,\n\t\t\t),\n\t\t)\n}\n\ntype HelpCmp interface {\n\ttea.Model\n\tSetBindings([]key.Binding)\n}\n\nfunc NewHelpCmp() HelpCmp {\n\treturn &helpCmp{}\n}\n"], ["/opencode/internal/tui/page/chat.go", "package page\n\nimport (\n\t\"context\"\n\t\"strings\"\n\n\t\"github.com/charmbracelet/bubbles/key\"\n\ttea \"github.com/charmbracelet/bubbletea\"\n\t\"github.com/charmbracelet/lipgloss\"\n\t\"github.com/opencode-ai/opencode/internal/app\"\n\t\"github.com/opencode-ai/opencode/internal/completions\"\n\t\"github.com/opencode-ai/opencode/internal/message\"\n\t\"github.com/opencode-ai/opencode/internal/session\"\n\t\"github.com/opencode-ai/opencode/internal/tui/components/chat\"\n\t\"github.com/opencode-ai/opencode/internal/tui/components/dialog\"\n\t\"github.com/opencode-ai/opencode/internal/tui/layout\"\n\t\"github.com/opencode-ai/opencode/internal/tui/util\"\n)\n\nvar ChatPage PageID = \"chat\"\n\ntype chatPage struct {\n\tapp *app.App\n\teditor layout.Container\n\tmessages layout.Container\n\tlayout layout.SplitPaneLayout\n\tsession session.Session\n\tcompletionDialog dialog.CompletionDialog\n\tshowCompletionDialog bool\n}\n\ntype ChatKeyMap struct {\n\tShowCompletionDialog key.Binding\n\tNewSession key.Binding\n\tCancel key.Binding\n}\n\nvar keyMap = ChatKeyMap{\n\tShowCompletionDialog: key.NewBinding(\n\t\tkey.WithKeys(\"@\"),\n\t\tkey.WithHelp(\"@\", \"Complete\"),\n\t),\n\tNewSession: key.NewBinding(\n\t\tkey.WithKeys(\"ctrl+n\"),\n\t\tkey.WithHelp(\"ctrl+n\", \"new session\"),\n\t),\n\tCancel: key.NewBinding(\n\t\tkey.WithKeys(\"esc\"),\n\t\tkey.WithHelp(\"esc\", \"cancel\"),\n\t),\n}\n\nfunc (p *chatPage) Init() tea.Cmd {\n\tcmds := []tea.Cmd{\n\t\tp.layout.Init(),\n\t\tp.completionDialog.Init(),\n\t}\n\treturn tea.Batch(cmds...)\n}\n\nfunc (p *chatPage) Update(msg tea.Msg) (tea.Model, tea.Cmd) {\n\tvar cmds []tea.Cmd\n\tswitch msg := msg.(type) {\n\tcase tea.WindowSizeMsg:\n\t\tcmd := p.layout.SetSize(msg.Width, msg.Height)\n\t\tcmds = append(cmds, cmd)\n\tcase dialog.CompletionDialogCloseMsg:\n\t\tp.showCompletionDialog = false\n\tcase chat.SendMsg:\n\t\tcmd := p.sendMessage(msg.Text, msg.Attachments)\n\t\tif cmd != nil {\n\t\t\treturn p, cmd\n\t\t}\n\tcase dialog.CommandRunCustomMsg:\n\t\t// Check if the agent is busy before executing custom commands\n\t\tif p.app.CoderAgent.IsBusy() {\n\t\t\treturn p, util.ReportWarn(\"Agent is busy, please wait before executing a command...\")\n\t\t}\n\t\t\n\t\t// Process the command content with arguments if any\n\t\tcontent := msg.Content\n\t\tif msg.Args != nil {\n\t\t\t// Replace all named arguments with their values\n\t\t\tfor name, value := range msg.Args {\n\t\t\t\tplaceholder := \"$\" + name\n\t\t\t\tcontent = strings.ReplaceAll(content, placeholder, value)\n\t\t\t}\n\t\t}\n\t\t\n\t\t// Handle custom command execution\n\t\tcmd := p.sendMessage(content, nil)\n\t\tif cmd != nil {\n\t\t\treturn p, cmd\n\t\t}\n\tcase chat.SessionSelectedMsg:\n\t\tif p.session.ID == \"\" {\n\t\t\tcmd := p.setSidebar()\n\t\t\tif cmd != nil {\n\t\t\t\tcmds = append(cmds, cmd)\n\t\t\t}\n\t\t}\n\t\tp.session = msg\n\tcase tea.KeyMsg:\n\t\tswitch {\n\t\tcase key.Matches(msg, keyMap.ShowCompletionDialog):\n\t\t\tp.showCompletionDialog = true\n\t\t\t// Continue sending keys to layout->chat\n\t\tcase key.Matches(msg, keyMap.NewSession):\n\t\t\tp.session = session.Session{}\n\t\t\treturn p, tea.Batch(\n\t\t\t\tp.clearSidebar(),\n\t\t\t\tutil.CmdHandler(chat.SessionClearedMsg{}),\n\t\t\t)\n\t\tcase key.Matches(msg, keyMap.Cancel):\n\t\t\tif p.session.ID != \"\" {\n\t\t\t\t// Cancel the current session's generation process\n\t\t\t\t// This allows users to interrupt long-running operations\n\t\t\t\tp.app.CoderAgent.Cancel(p.session.ID)\n\t\t\t\treturn p, nil\n\t\t\t}\n\t\t}\n\t}\n\tif p.showCompletionDialog {\n\t\tcontext, contextCmd := p.completionDialog.Update(msg)\n\t\tp.completionDialog = context.(dialog.CompletionDialog)\n\t\tcmds = append(cmds, contextCmd)\n\n\t\t// Doesn't forward event if enter key is pressed\n\t\tif keyMsg, ok := msg.(tea.KeyMsg); ok {\n\t\t\tif keyMsg.String() == \"enter\" {\n\t\t\t\treturn p, tea.Batch(cmds...)\n\t\t\t}\n\t\t}\n\t}\n\n\tu, cmd := p.layout.Update(msg)\n\tcmds = append(cmds, cmd)\n\tp.layout = u.(layout.SplitPaneLayout)\n\n\treturn p, tea.Batch(cmds...)\n}\n\nfunc (p *chatPage) setSidebar() tea.Cmd {\n\tsidebarContainer := layout.NewContainer(\n\t\tchat.NewSidebarCmp(p.session, p.app.History),\n\t\tlayout.WithPadding(1, 1, 1, 1),\n\t)\n\treturn tea.Batch(p.layout.SetRightPanel(sidebarContainer), sidebarContainer.Init())\n}\n\nfunc (p *chatPage) clearSidebar() tea.Cmd {\n\treturn p.layout.ClearRightPanel()\n}\n\nfunc (p *chatPage) sendMessage(text string, attachments []message.Attachment) tea.Cmd {\n\tvar cmds []tea.Cmd\n\tif p.session.ID == \"\" {\n\t\tsession, err := p.app.Sessions.Create(context.Background(), \"New Session\")\n\t\tif err != nil {\n\t\t\treturn util.ReportError(err)\n\t\t}\n\n\t\tp.session = session\n\t\tcmd := p.setSidebar()\n\t\tif cmd != nil {\n\t\t\tcmds = append(cmds, cmd)\n\t\t}\n\t\tcmds = append(cmds, util.CmdHandler(chat.SessionSelectedMsg(session)))\n\t}\n\n\t_, err := p.app.CoderAgent.Run(context.Background(), p.session.ID, text, attachments...)\n\tif err != nil {\n\t\treturn util.ReportError(err)\n\t}\n\treturn tea.Batch(cmds...)\n}\n\nfunc (p *chatPage) SetSize(width, height int) tea.Cmd {\n\treturn p.layout.SetSize(width, height)\n}\n\nfunc (p *chatPage) GetSize() (int, int) {\n\treturn p.layout.GetSize()\n}\n\nfunc (p *chatPage) View() string {\n\tlayoutView := p.layout.View()\n\n\tif p.showCompletionDialog {\n\t\t_, layoutHeight := p.layout.GetSize()\n\t\teditorWidth, editorHeight := p.editor.GetSize()\n\n\t\tp.completionDialog.SetWidth(editorWidth)\n\t\toverlay := p.completionDialog.View()\n\n\t\tlayoutView = layout.PlaceOverlay(\n\t\t\t0,\n\t\t\tlayoutHeight-editorHeight-lipgloss.Height(overlay),\n\t\t\toverlay,\n\t\t\tlayoutView,\n\t\t\tfalse,\n\t\t)\n\t}\n\n\treturn layoutView\n}\n\nfunc (p *chatPage) BindingKeys() []key.Binding {\n\tbindings := layout.KeyMapToSlice(keyMap)\n\tbindings = append(bindings, p.messages.BindingKeys()...)\n\tbindings = append(bindings, p.editor.BindingKeys()...)\n\treturn bindings\n}\n\nfunc NewChatPage(app *app.App) tea.Model {\n\tcg := completions.NewFileAndFolderContextGroup()\n\tcompletionDialog := dialog.NewCompletionDialogCmp(cg)\n\n\tmessagesContainer := layout.NewContainer(\n\t\tchat.NewMessagesCmp(app),\n\t\tlayout.WithPadding(1, 1, 0, 1),\n\t)\n\teditorContainer := layout.NewContainer(\n\t\tchat.NewEditorCmp(app),\n\t\tlayout.WithBorder(true, false, false, false),\n\t)\n\treturn &chatPage{\n\t\tapp: app,\n\t\teditor: editorContainer,\n\t\tmessages: messagesContainer,\n\t\tcompletionDialog: completionDialog,\n\t\tlayout: layout.NewSplitPane(\n\t\t\tlayout.WithLeftPanel(messagesContainer),\n\t\t\tlayout.WithBottomPanel(editorContainer),\n\t\t),\n\t}\n}\n"], ["/opencode/internal/tui/components/chat/sidebar.go", "package chat\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"sort\"\n\t\"strings\"\n\n\ttea \"github.com/charmbracelet/bubbletea\"\n\t\"github.com/charmbracelet/lipgloss\"\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/diff\"\n\t\"github.com/opencode-ai/opencode/internal/history\"\n\t\"github.com/opencode-ai/opencode/internal/pubsub\"\n\t\"github.com/opencode-ai/opencode/internal/session\"\n\t\"github.com/opencode-ai/opencode/internal/tui/styles\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n)\n\ntype sidebarCmp struct {\n\twidth, height int\n\tsession session.Session\n\thistory history.Service\n\tmodFiles map[string]struct {\n\t\tadditions int\n\t\tremovals int\n\t}\n}\n\nfunc (m *sidebarCmp) Init() tea.Cmd {\n\tif m.history != nil {\n\t\tctx := context.Background()\n\t\t// Subscribe to file events\n\t\tfilesCh := m.history.Subscribe(ctx)\n\n\t\t// Initialize the modified files map\n\t\tm.modFiles = make(map[string]struct {\n\t\t\tadditions int\n\t\t\tremovals int\n\t\t})\n\n\t\t// Load initial files and calculate diffs\n\t\tm.loadModifiedFiles(ctx)\n\n\t\t// Return a command that will send file events to the Update method\n\t\treturn func() tea.Msg {\n\t\t\treturn <-filesCh\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (m *sidebarCmp) Update(msg tea.Msg) (tea.Model, tea.Cmd) {\n\tswitch msg := msg.(type) {\n\tcase SessionSelectedMsg:\n\t\tif msg.ID != m.session.ID {\n\t\t\tm.session = msg\n\t\t\tctx := context.Background()\n\t\t\tm.loadModifiedFiles(ctx)\n\t\t}\n\tcase pubsub.Event[session.Session]:\n\t\tif msg.Type == pubsub.UpdatedEvent {\n\t\t\tif m.session.ID == msg.Payload.ID {\n\t\t\t\tm.session = msg.Payload\n\t\t\t}\n\t\t}\n\tcase pubsub.Event[history.File]:\n\t\tif msg.Payload.SessionID == m.session.ID {\n\t\t\t// Process the individual file change instead of reloading all files\n\t\t\tctx := context.Background()\n\t\t\tm.processFileChanges(ctx, msg.Payload)\n\n\t\t\t// Return a command to continue receiving events\n\t\t\treturn m, func() tea.Msg {\n\t\t\t\tctx := context.Background()\n\t\t\t\tfilesCh := m.history.Subscribe(ctx)\n\t\t\t\treturn <-filesCh\n\t\t\t}\n\t\t}\n\t}\n\treturn m, nil\n}\n\nfunc (m *sidebarCmp) View() string {\n\tbaseStyle := styles.BaseStyle()\n\n\treturn baseStyle.\n\t\tWidth(m.width).\n\t\tPaddingLeft(4).\n\t\tPaddingRight(2).\n\t\tHeight(m.height - 1).\n\t\tRender(\n\t\t\tlipgloss.JoinVertical(\n\t\t\t\tlipgloss.Top,\n\t\t\t\theader(m.width),\n\t\t\t\t\" \",\n\t\t\t\tm.sessionSection(),\n\t\t\t\t\" \",\n\t\t\t\tlspsConfigured(m.width),\n\t\t\t\t\" \",\n\t\t\t\tm.modifiedFiles(),\n\t\t\t),\n\t\t)\n}\n\nfunc (m *sidebarCmp) sessionSection() string {\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\n\tsessionKey := baseStyle.\n\t\tForeground(t.Primary()).\n\t\tBold(true).\n\t\tRender(\"Session\")\n\n\tsessionValue := baseStyle.\n\t\tForeground(t.Text()).\n\t\tWidth(m.width - lipgloss.Width(sessionKey)).\n\t\tRender(fmt.Sprintf(\": %s\", m.session.Title))\n\n\treturn lipgloss.JoinHorizontal(\n\t\tlipgloss.Left,\n\t\tsessionKey,\n\t\tsessionValue,\n\t)\n}\n\nfunc (m *sidebarCmp) modifiedFile(filePath string, additions, removals int) string {\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\n\tstats := \"\"\n\tif additions > 0 && removals > 0 {\n\t\tadditionsStr := baseStyle.\n\t\t\tForeground(t.Success()).\n\t\t\tPaddingLeft(1).\n\t\t\tRender(fmt.Sprintf(\"+%d\", additions))\n\n\t\tremovalsStr := baseStyle.\n\t\t\tForeground(t.Error()).\n\t\t\tPaddingLeft(1).\n\t\t\tRender(fmt.Sprintf(\"-%d\", removals))\n\n\t\tcontent := lipgloss.JoinHorizontal(lipgloss.Left, additionsStr, removalsStr)\n\t\tstats = baseStyle.Width(lipgloss.Width(content)).Render(content)\n\t} else if additions > 0 {\n\t\tadditionsStr := fmt.Sprintf(\" %s\", baseStyle.\n\t\t\tPaddingLeft(1).\n\t\t\tForeground(t.Success()).\n\t\t\tRender(fmt.Sprintf(\"+%d\", additions)))\n\t\tstats = baseStyle.Width(lipgloss.Width(additionsStr)).Render(additionsStr)\n\t} else if removals > 0 {\n\t\tremovalsStr := fmt.Sprintf(\" %s\", baseStyle.\n\t\t\tPaddingLeft(1).\n\t\t\tForeground(t.Error()).\n\t\t\tRender(fmt.Sprintf(\"-%d\", removals)))\n\t\tstats = baseStyle.Width(lipgloss.Width(removalsStr)).Render(removalsStr)\n\t}\n\n\tfilePathStr := baseStyle.Render(filePath)\n\n\treturn baseStyle.\n\t\tWidth(m.width).\n\t\tRender(\n\t\t\tlipgloss.JoinHorizontal(\n\t\t\t\tlipgloss.Left,\n\t\t\t\tfilePathStr,\n\t\t\t\tstats,\n\t\t\t),\n\t\t)\n}\n\nfunc (m *sidebarCmp) modifiedFiles() string {\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\n\tmodifiedFiles := baseStyle.\n\t\tWidth(m.width).\n\t\tForeground(t.Primary()).\n\t\tBold(true).\n\t\tRender(\"Modified Files:\")\n\n\t// If no modified files, show a placeholder message\n\tif m.modFiles == nil || len(m.modFiles) == 0 {\n\t\tmessage := \"No modified files\"\n\t\tremainingWidth := m.width - lipgloss.Width(message)\n\t\tif remainingWidth > 0 {\n\t\t\tmessage += strings.Repeat(\" \", remainingWidth)\n\t\t}\n\t\treturn baseStyle.\n\t\t\tWidth(m.width).\n\t\t\tRender(\n\t\t\t\tlipgloss.JoinVertical(\n\t\t\t\t\tlipgloss.Top,\n\t\t\t\t\tmodifiedFiles,\n\t\t\t\t\tbaseStyle.Foreground(t.TextMuted()).Render(message),\n\t\t\t\t),\n\t\t\t)\n\t}\n\n\t// Sort file paths alphabetically for consistent ordering\n\tvar paths []string\n\tfor path := range m.modFiles {\n\t\tpaths = append(paths, path)\n\t}\n\tsort.Strings(paths)\n\n\t// Create views for each file in sorted order\n\tvar fileViews []string\n\tfor _, path := range paths {\n\t\tstats := m.modFiles[path]\n\t\tfileViews = append(fileViews, m.modifiedFile(path, stats.additions, stats.removals))\n\t}\n\n\treturn baseStyle.\n\t\tWidth(m.width).\n\t\tRender(\n\t\t\tlipgloss.JoinVertical(\n\t\t\t\tlipgloss.Top,\n\t\t\t\tmodifiedFiles,\n\t\t\t\tlipgloss.JoinVertical(\n\t\t\t\t\tlipgloss.Left,\n\t\t\t\t\tfileViews...,\n\t\t\t\t),\n\t\t\t),\n\t\t)\n}\n\nfunc (m *sidebarCmp) SetSize(width, height int) tea.Cmd {\n\tm.width = width\n\tm.height = height\n\treturn nil\n}\n\nfunc (m *sidebarCmp) GetSize() (int, int) {\n\treturn m.width, m.height\n}\n\nfunc NewSidebarCmp(session session.Session, history history.Service) tea.Model {\n\treturn &sidebarCmp{\n\t\tsession: session,\n\t\thistory: history,\n\t}\n}\n\nfunc (m *sidebarCmp) loadModifiedFiles(ctx context.Context) {\n\tif m.history == nil || m.session.ID == \"\" {\n\t\treturn\n\t}\n\n\t// Get all latest files for this session\n\tlatestFiles, err := m.history.ListLatestSessionFiles(ctx, m.session.ID)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t// Get all files for this session (to find initial versions)\n\tallFiles, err := m.history.ListBySession(ctx, m.session.ID)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t// Clear the existing map to rebuild it\n\tm.modFiles = make(map[string]struct {\n\t\tadditions int\n\t\tremovals int\n\t})\n\n\t// Process each latest file\n\tfor _, file := range latestFiles {\n\t\t// Skip if this is the initial version (no changes to show)\n\t\tif file.Version == history.InitialVersion {\n\t\t\tcontinue\n\t\t}\n\n\t\t// Find the initial version for this specific file\n\t\tvar initialVersion history.File\n\t\tfor _, v := range allFiles {\n\t\t\tif v.Path == file.Path && v.Version == history.InitialVersion {\n\t\t\t\tinitialVersion = v\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\t// Skip if we can't find the initial version\n\t\tif initialVersion.ID == \"\" {\n\t\t\tcontinue\n\t\t}\n\t\tif initialVersion.Content == file.Content {\n\t\t\tcontinue\n\t\t}\n\n\t\t// Calculate diff between initial and latest version\n\t\t_, additions, removals := diff.GenerateDiff(initialVersion.Content, file.Content, file.Path)\n\n\t\t// Only add to modified files if there are changes\n\t\tif additions > 0 || removals > 0 {\n\t\t\t// Remove working directory prefix from file path\n\t\t\tdisplayPath := file.Path\n\t\t\tworkingDir := config.WorkingDirectory()\n\t\t\tdisplayPath = strings.TrimPrefix(displayPath, workingDir)\n\t\t\tdisplayPath = strings.TrimPrefix(displayPath, \"/\")\n\n\t\t\tm.modFiles[displayPath] = struct {\n\t\t\t\tadditions int\n\t\t\t\tremovals int\n\t\t\t}{\n\t\t\t\tadditions: additions,\n\t\t\t\tremovals: removals,\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc (m *sidebarCmp) processFileChanges(ctx context.Context, file history.File) {\n\t// Skip if this is the initial version (no changes to show)\n\tif file.Version == history.InitialVersion {\n\t\treturn\n\t}\n\n\t// Find the initial version for this file\n\tinitialVersion, err := m.findInitialVersion(ctx, file.Path)\n\tif err != nil || initialVersion.ID == \"\" {\n\t\treturn\n\t}\n\n\t// Skip if content hasn't changed\n\tif initialVersion.Content == file.Content {\n\t\t// If this file was previously modified but now matches the initial version,\n\t\t// remove it from the modified files list\n\t\tdisplayPath := getDisplayPath(file.Path)\n\t\tdelete(m.modFiles, displayPath)\n\t\treturn\n\t}\n\n\t// Calculate diff between initial and latest version\n\t_, additions, removals := diff.GenerateDiff(initialVersion.Content, file.Content, file.Path)\n\n\t// Only add to modified files if there are changes\n\tif additions > 0 || removals > 0 {\n\t\tdisplayPath := getDisplayPath(file.Path)\n\t\tm.modFiles[displayPath] = struct {\n\t\t\tadditions int\n\t\t\tremovals int\n\t\t}{\n\t\t\tadditions: additions,\n\t\t\tremovals: removals,\n\t\t}\n\t} else {\n\t\t// If no changes, remove from modified files\n\t\tdisplayPath := getDisplayPath(file.Path)\n\t\tdelete(m.modFiles, displayPath)\n\t}\n}\n\n// Helper function to find the initial version of a file\nfunc (m *sidebarCmp) findInitialVersion(ctx context.Context, path string) (history.File, error) {\n\t// Get all versions of this file for the session\n\tfileVersions, err := m.history.ListBySession(ctx, m.session.ID)\n\tif err != nil {\n\t\treturn history.File{}, err\n\t}\n\n\t// Find the initial version\n\tfor _, v := range fileVersions {\n\t\tif v.Path == path && v.Version == history.InitialVersion {\n\t\t\treturn v, nil\n\t\t}\n\t}\n\n\treturn history.File{}, fmt.Errorf(\"initial version not found\")\n}\n\n// Helper function to get the display path for a file\nfunc getDisplayPath(path string) string {\n\tworkingDir := config.WorkingDirectory()\n\tdisplayPath := strings.TrimPrefix(path, workingDir)\n\treturn strings.TrimPrefix(displayPath, \"/\")\n}\n"], ["/opencode/internal/tui/components/core/status.go", "package core\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\t\"time\"\n\n\ttea \"github.com/charmbracelet/bubbletea\"\n\t\"github.com/charmbracelet/lipgloss\"\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/llm/models\"\n\t\"github.com/opencode-ai/opencode/internal/lsp\"\n\t\"github.com/opencode-ai/opencode/internal/lsp/protocol\"\n\t\"github.com/opencode-ai/opencode/internal/pubsub\"\n\t\"github.com/opencode-ai/opencode/internal/session\"\n\t\"github.com/opencode-ai/opencode/internal/tui/components/chat\"\n\t\"github.com/opencode-ai/opencode/internal/tui/styles\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n\t\"github.com/opencode-ai/opencode/internal/tui/util\"\n)\n\ntype StatusCmp interface {\n\ttea.Model\n}\n\ntype statusCmp struct {\n\tinfo util.InfoMsg\n\twidth int\n\tmessageTTL time.Duration\n\tlspClients map[string]*lsp.Client\n\tsession session.Session\n}\n\n// clearMessageCmd is a command that clears status messages after a timeout\nfunc (m statusCmp) clearMessageCmd(ttl time.Duration) tea.Cmd {\n\treturn tea.Tick(ttl, func(time.Time) tea.Msg {\n\t\treturn util.ClearStatusMsg{}\n\t})\n}\n\nfunc (m statusCmp) Init() tea.Cmd {\n\treturn nil\n}\n\nfunc (m statusCmp) Update(msg tea.Msg) (tea.Model, tea.Cmd) {\n\tswitch msg := msg.(type) {\n\tcase tea.WindowSizeMsg:\n\t\tm.width = msg.Width\n\t\treturn m, nil\n\tcase chat.SessionSelectedMsg:\n\t\tm.session = msg\n\tcase chat.SessionClearedMsg:\n\t\tm.session = session.Session{}\n\tcase pubsub.Event[session.Session]:\n\t\tif msg.Type == pubsub.UpdatedEvent {\n\t\t\tif m.session.ID == msg.Payload.ID {\n\t\t\t\tm.session = msg.Payload\n\t\t\t}\n\t\t}\n\tcase util.InfoMsg:\n\t\tm.info = msg\n\t\tttl := msg.TTL\n\t\tif ttl == 0 {\n\t\t\tttl = m.messageTTL\n\t\t}\n\t\treturn m, m.clearMessageCmd(ttl)\n\tcase util.ClearStatusMsg:\n\t\tm.info = util.InfoMsg{}\n\t}\n\treturn m, nil\n}\n\nvar helpWidget = \"\"\n\n// getHelpWidget returns the help widget with current theme colors\nfunc getHelpWidget() string {\n\tt := theme.CurrentTheme()\n\thelpText := \"ctrl+? help\"\n\n\treturn styles.Padded().\n\t\tBackground(t.TextMuted()).\n\t\tForeground(t.BackgroundDarker()).\n\t\tBold(true).\n\t\tRender(helpText)\n}\n\nfunc formatTokensAndCost(tokens, contextWindow int64, cost float64) string {\n\t// Format tokens in human-readable format (e.g., 110K, 1.2M)\n\tvar formattedTokens string\n\tswitch {\n\tcase tokens >= 1_000_000:\n\t\tformattedTokens = fmt.Sprintf(\"%.1fM\", float64(tokens)/1_000_000)\n\tcase tokens >= 1_000:\n\t\tformattedTokens = fmt.Sprintf(\"%.1fK\", float64(tokens)/1_000)\n\tdefault:\n\t\tformattedTokens = fmt.Sprintf(\"%d\", tokens)\n\t}\n\n\t// Remove .0 suffix if present\n\tif strings.HasSuffix(formattedTokens, \".0K\") {\n\t\tformattedTokens = strings.Replace(formattedTokens, \".0K\", \"K\", 1)\n\t}\n\tif strings.HasSuffix(formattedTokens, \".0M\") {\n\t\tformattedTokens = strings.Replace(formattedTokens, \".0M\", \"M\", 1)\n\t}\n\n\t// Format cost with $ symbol and 2 decimal places\n\tformattedCost := fmt.Sprintf(\"$%.2f\", cost)\n\n\tpercentage := (float64(tokens) / float64(contextWindow)) * 100\n\tif percentage > 80 {\n\t\t// add the warning icon and percentage\n\t\tformattedTokens = fmt.Sprintf(\"%s(%d%%)\", styles.WarningIcon, int(percentage))\n\t}\n\n\treturn fmt.Sprintf(\"Context: %s, Cost: %s\", formattedTokens, formattedCost)\n}\n\nfunc (m statusCmp) View() string {\n\tt := theme.CurrentTheme()\n\tmodelID := config.Get().Agents[config.AgentCoder].Model\n\tmodel := models.SupportedModels[modelID]\n\n\t// Initialize the help widget\n\tstatus := getHelpWidget()\n\n\ttokenInfoWidth := 0\n\tif m.session.ID != \"\" {\n\t\ttotalTokens := m.session.PromptTokens + m.session.CompletionTokens\n\t\ttokens := formatTokensAndCost(totalTokens, model.ContextWindow, m.session.Cost)\n\t\ttokensStyle := styles.Padded().\n\t\t\tBackground(t.Text()).\n\t\t\tForeground(t.BackgroundSecondary())\n\t\tpercentage := (float64(totalTokens) / float64(model.ContextWindow)) * 100\n\t\tif percentage > 80 {\n\t\t\ttokensStyle = tokensStyle.Background(t.Warning())\n\t\t}\n\t\ttokenInfoWidth = lipgloss.Width(tokens) + 2\n\t\tstatus += tokensStyle.Render(tokens)\n\t}\n\n\tdiagnostics := styles.Padded().\n\t\tBackground(t.BackgroundDarker()).\n\t\tRender(m.projectDiagnostics())\n\n\tavailableWidht := max(0, m.width-lipgloss.Width(helpWidget)-lipgloss.Width(m.model())-lipgloss.Width(diagnostics)-tokenInfoWidth)\n\n\tif m.info.Msg != \"\" {\n\t\tinfoStyle := styles.Padded().\n\t\t\tForeground(t.Background()).\n\t\t\tWidth(availableWidht)\n\n\t\tswitch m.info.Type {\n\t\tcase util.InfoTypeInfo:\n\t\t\tinfoStyle = infoStyle.Background(t.Info())\n\t\tcase util.InfoTypeWarn:\n\t\t\tinfoStyle = infoStyle.Background(t.Warning())\n\t\tcase util.InfoTypeError:\n\t\t\tinfoStyle = infoStyle.Background(t.Error())\n\t\t}\n\n\t\tinfoWidth := availableWidht - 10\n\t\t// Truncate message if it's longer than available width\n\t\tmsg := m.info.Msg\n\t\tif len(msg) > infoWidth && infoWidth > 0 {\n\t\t\tmsg = msg[:infoWidth] + \"...\"\n\t\t}\n\t\tstatus += infoStyle.Render(msg)\n\t} else {\n\t\tstatus += styles.Padded().\n\t\t\tForeground(t.Text()).\n\t\t\tBackground(t.BackgroundSecondary()).\n\t\t\tWidth(availableWidht).\n\t\t\tRender(\"\")\n\t}\n\n\tstatus += diagnostics\n\tstatus += m.model()\n\treturn status\n}\n\nfunc (m *statusCmp) projectDiagnostics() string {\n\tt := theme.CurrentTheme()\n\n\t// Check if any LSP server is still initializing\n\tinitializing := false\n\tfor _, client := range m.lspClients {\n\t\tif client.GetServerState() == lsp.StateStarting {\n\t\t\tinitializing = true\n\t\t\tbreak\n\t\t}\n\t}\n\n\t// If any server is initializing, show that status\n\tif initializing {\n\t\treturn lipgloss.NewStyle().\n\t\t\tBackground(t.BackgroundDarker()).\n\t\t\tForeground(t.Warning()).\n\t\t\tRender(fmt.Sprintf(\"%s Initializing LSP...\", styles.SpinnerIcon))\n\t}\n\n\terrorDiagnostics := []protocol.Diagnostic{}\n\twarnDiagnostics := []protocol.Diagnostic{}\n\thintDiagnostics := []protocol.Diagnostic{}\n\tinfoDiagnostics := []protocol.Diagnostic{}\n\tfor _, client := range m.lspClients {\n\t\tfor _, d := range client.GetDiagnostics() {\n\t\t\tfor _, diag := range d {\n\t\t\t\tswitch diag.Severity {\n\t\t\t\tcase protocol.SeverityError:\n\t\t\t\t\terrorDiagnostics = append(errorDiagnostics, diag)\n\t\t\t\tcase protocol.SeverityWarning:\n\t\t\t\t\twarnDiagnostics = append(warnDiagnostics, diag)\n\t\t\t\tcase protocol.SeverityHint:\n\t\t\t\t\thintDiagnostics = append(hintDiagnostics, diag)\n\t\t\t\tcase protocol.SeverityInformation:\n\t\t\t\t\tinfoDiagnostics = append(infoDiagnostics, diag)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif len(errorDiagnostics) == 0 && len(warnDiagnostics) == 0 && len(hintDiagnostics) == 0 && len(infoDiagnostics) == 0 {\n\t\treturn \"No diagnostics\"\n\t}\n\n\tdiagnostics := []string{}\n\n\tif len(errorDiagnostics) > 0 {\n\t\terrStr := lipgloss.NewStyle().\n\t\t\tBackground(t.BackgroundDarker()).\n\t\t\tForeground(t.Error()).\n\t\t\tRender(fmt.Sprintf(\"%s %d\", styles.ErrorIcon, len(errorDiagnostics)))\n\t\tdiagnostics = append(diagnostics, errStr)\n\t}\n\tif len(warnDiagnostics) > 0 {\n\t\twarnStr := lipgloss.NewStyle().\n\t\t\tBackground(t.BackgroundDarker()).\n\t\t\tForeground(t.Warning()).\n\t\t\tRender(fmt.Sprintf(\"%s %d\", styles.WarningIcon, len(warnDiagnostics)))\n\t\tdiagnostics = append(diagnostics, warnStr)\n\t}\n\tif len(hintDiagnostics) > 0 {\n\t\thintStr := lipgloss.NewStyle().\n\t\t\tBackground(t.BackgroundDarker()).\n\t\t\tForeground(t.Text()).\n\t\t\tRender(fmt.Sprintf(\"%s %d\", styles.HintIcon, len(hintDiagnostics)))\n\t\tdiagnostics = append(diagnostics, hintStr)\n\t}\n\tif len(infoDiagnostics) > 0 {\n\t\tinfoStr := lipgloss.NewStyle().\n\t\t\tBackground(t.BackgroundDarker()).\n\t\t\tForeground(t.Info()).\n\t\t\tRender(fmt.Sprintf(\"%s %d\", styles.InfoIcon, len(infoDiagnostics)))\n\t\tdiagnostics = append(diagnostics, infoStr)\n\t}\n\n\treturn strings.Join(diagnostics, \" \")\n}\n\nfunc (m statusCmp) availableFooterMsgWidth(diagnostics, tokenInfo string) int {\n\ttokensWidth := 0\n\tif m.session.ID != \"\" {\n\t\ttokensWidth = lipgloss.Width(tokenInfo) + 2\n\t}\n\treturn max(0, m.width-lipgloss.Width(helpWidget)-lipgloss.Width(m.model())-lipgloss.Width(diagnostics)-tokensWidth)\n}\n\nfunc (m statusCmp) model() string {\n\tt := theme.CurrentTheme()\n\n\tcfg := config.Get()\n\n\tcoder, ok := cfg.Agents[config.AgentCoder]\n\tif !ok {\n\t\treturn \"Unknown\"\n\t}\n\tmodel := models.SupportedModels[coder.Model]\n\n\treturn styles.Padded().\n\t\tBackground(t.Secondary()).\n\t\tForeground(t.Background()).\n\t\tRender(model.Name)\n}\n\nfunc NewStatusCmp(lspClients map[string]*lsp.Client) StatusCmp {\n\thelpWidget = getHelpWidget()\n\n\treturn &statusCmp{\n\t\tmessageTTL: 10 * time.Second,\n\t\tlspClients: lspClients,\n\t}\n}\n"], ["/opencode/internal/tui/components/chat/message.go", "package chat\n\nimport (\n\t\"context\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"path/filepath\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/charmbracelet/lipgloss\"\n\t\"github.com/charmbracelet/x/ansi\"\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/diff\"\n\t\"github.com/opencode-ai/opencode/internal/llm/agent\"\n\t\"github.com/opencode-ai/opencode/internal/llm/models\"\n\t\"github.com/opencode-ai/opencode/internal/llm/tools\"\n\t\"github.com/opencode-ai/opencode/internal/message\"\n\t\"github.com/opencode-ai/opencode/internal/tui/styles\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n)\n\ntype uiMessageType int\n\nconst (\n\tuserMessageType uiMessageType = iota\n\tassistantMessageType\n\ttoolMessageType\n\n\tmaxResultHeight = 10\n)\n\ntype uiMessage struct {\n\tID string\n\tmessageType uiMessageType\n\tposition int\n\theight int\n\tcontent string\n}\n\nfunc toMarkdown(content string, focused bool, width int) string {\n\tr := styles.GetMarkdownRenderer(width)\n\trendered, _ := r.Render(content)\n\treturn rendered\n}\n\nfunc renderMessage(msg string, isUser bool, isFocused bool, width int, info ...string) string {\n\tt := theme.CurrentTheme()\n\n\tstyle := styles.BaseStyle().\n\t\tWidth(width - 1).\n\t\tBorderLeft(true).\n\t\tForeground(t.TextMuted()).\n\t\tBorderForeground(t.Primary()).\n\t\tBorderStyle(lipgloss.ThickBorder())\n\n\tif isUser {\n\t\tstyle = style.BorderForeground(t.Secondary())\n\t}\n\n\t// Apply markdown formatting and handle background color\n\tparts := []string{\n\t\tstyles.ForceReplaceBackgroundWithLipgloss(toMarkdown(msg, isFocused, width), t.Background()),\n\t}\n\n\t// Remove newline at the end\n\tparts[0] = strings.TrimSuffix(parts[0], \"\\n\")\n\tif len(info) > 0 {\n\t\tparts = append(parts, info...)\n\t}\n\n\trendered := style.Render(\n\t\tlipgloss.JoinVertical(\n\t\t\tlipgloss.Left,\n\t\t\tparts...,\n\t\t),\n\t)\n\n\treturn rendered\n}\n\nfunc renderUserMessage(msg message.Message, isFocused bool, width int, position int) uiMessage {\n\tvar styledAttachments []string\n\tt := theme.CurrentTheme()\n\tattachmentStyles := styles.BaseStyle().\n\t\tMarginLeft(1).\n\t\tBackground(t.TextMuted()).\n\t\tForeground(t.Text())\n\tfor _, attachment := range msg.BinaryContent() {\n\t\tfile := filepath.Base(attachment.Path)\n\t\tvar filename string\n\t\tif len(file) > 10 {\n\t\t\tfilename = fmt.Sprintf(\" %s %s...\", styles.DocumentIcon, file[0:7])\n\t\t} else {\n\t\t\tfilename = fmt.Sprintf(\" %s %s\", styles.DocumentIcon, file)\n\t\t}\n\t\tstyledAttachments = append(styledAttachments, attachmentStyles.Render(filename))\n\t}\n\tcontent := \"\"\n\tif len(styledAttachments) > 0 {\n\t\tattachmentContent := styles.BaseStyle().Width(width).Render(lipgloss.JoinHorizontal(lipgloss.Left, styledAttachments...))\n\t\tcontent = renderMessage(msg.Content().String(), true, isFocused, width, attachmentContent)\n\t} else {\n\t\tcontent = renderMessage(msg.Content().String(), true, isFocused, width)\n\t}\n\tuserMsg := uiMessage{\n\t\tID: msg.ID,\n\t\tmessageType: userMessageType,\n\t\tposition: position,\n\t\theight: lipgloss.Height(content),\n\t\tcontent: content,\n\t}\n\treturn userMsg\n}\n\n// Returns multiple uiMessages because of the tool calls\nfunc renderAssistantMessage(\n\tmsg message.Message,\n\tmsgIndex int,\n\tallMessages []message.Message, // we need this to get tool results and the user message\n\tmessagesService message.Service, // We need this to get the task tool messages\n\tfocusedUIMessageId string,\n\tisSummary bool,\n\twidth int,\n\tposition int,\n) []uiMessage {\n\tmessages := []uiMessage{}\n\tcontent := msg.Content().String()\n\tthinking := msg.IsThinking()\n\tthinkingContent := msg.ReasoningContent().Thinking\n\tfinished := msg.IsFinished()\n\tfinishData := msg.FinishPart()\n\tinfo := []string{}\n\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\n\t// Add finish info if available\n\tif finished {\n\t\tswitch finishData.Reason {\n\t\tcase message.FinishReasonEndTurn:\n\t\t\ttook := formatTimestampDiff(msg.CreatedAt, finishData.Time)\n\t\t\tinfo = append(info, baseStyle.\n\t\t\t\tWidth(width-1).\n\t\t\t\tForeground(t.TextMuted()).\n\t\t\t\tRender(fmt.Sprintf(\" %s (%s)\", models.SupportedModels[msg.Model].Name, took)),\n\t\t\t)\n\t\tcase message.FinishReasonCanceled:\n\t\t\tinfo = append(info, baseStyle.\n\t\t\t\tWidth(width-1).\n\t\t\t\tForeground(t.TextMuted()).\n\t\t\t\tRender(fmt.Sprintf(\" %s (%s)\", models.SupportedModels[msg.Model].Name, \"canceled\")),\n\t\t\t)\n\t\tcase message.FinishReasonError:\n\t\t\tinfo = append(info, baseStyle.\n\t\t\t\tWidth(width-1).\n\t\t\t\tForeground(t.TextMuted()).\n\t\t\t\tRender(fmt.Sprintf(\" %s (%s)\", models.SupportedModels[msg.Model].Name, \"error\")),\n\t\t\t)\n\t\tcase message.FinishReasonPermissionDenied:\n\t\t\tinfo = append(info, baseStyle.\n\t\t\t\tWidth(width-1).\n\t\t\t\tForeground(t.TextMuted()).\n\t\t\t\tRender(fmt.Sprintf(\" %s (%s)\", models.SupportedModels[msg.Model].Name, \"permission denied\")),\n\t\t\t)\n\t\t}\n\t}\n\tif content != \"\" || (finished && finishData.Reason == message.FinishReasonEndTurn) {\n\t\tif content == \"\" {\n\t\t\tcontent = \"*Finished without output*\"\n\t\t}\n\t\tif isSummary {\n\t\t\tinfo = append(info, baseStyle.Width(width-1).Foreground(t.TextMuted()).Render(\" (summary)\"))\n\t\t}\n\n\t\tcontent = renderMessage(content, false, true, width, info...)\n\t\tmessages = append(messages, uiMessage{\n\t\t\tID: msg.ID,\n\t\t\tmessageType: assistantMessageType,\n\t\t\tposition: position,\n\t\t\theight: lipgloss.Height(content),\n\t\t\tcontent: content,\n\t\t})\n\t\tposition += messages[0].height\n\t\tposition++ // for the space\n\t} else if thinking && thinkingContent != \"\" {\n\t\t// Render the thinking content\n\t\tcontent = renderMessage(thinkingContent, false, msg.ID == focusedUIMessageId, width)\n\t}\n\n\tfor i, toolCall := range msg.ToolCalls() {\n\t\ttoolCallContent := renderToolMessage(\n\t\t\ttoolCall,\n\t\t\tallMessages,\n\t\t\tmessagesService,\n\t\t\tfocusedUIMessageId,\n\t\t\tfalse,\n\t\t\twidth,\n\t\t\ti+1,\n\t\t)\n\t\tmessages = append(messages, toolCallContent)\n\t\tposition += toolCallContent.height\n\t\tposition++ // for the space\n\t}\n\treturn messages\n}\n\nfunc findToolResponse(toolCallID string, futureMessages []message.Message) *message.ToolResult {\n\tfor _, msg := range futureMessages {\n\t\tfor _, result := range msg.ToolResults() {\n\t\t\tif result.ToolCallID == toolCallID {\n\t\t\t\treturn &result\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc toolName(name string) string {\n\tswitch name {\n\tcase agent.AgentToolName:\n\t\treturn \"Task\"\n\tcase tools.BashToolName:\n\t\treturn \"Bash\"\n\tcase tools.EditToolName:\n\t\treturn \"Edit\"\n\tcase tools.FetchToolName:\n\t\treturn \"Fetch\"\n\tcase tools.GlobToolName:\n\t\treturn \"Glob\"\n\tcase tools.GrepToolName:\n\t\treturn \"Grep\"\n\tcase tools.LSToolName:\n\t\treturn \"List\"\n\tcase tools.SourcegraphToolName:\n\t\treturn \"Sourcegraph\"\n\tcase tools.ViewToolName:\n\t\treturn \"View\"\n\tcase tools.WriteToolName:\n\t\treturn \"Write\"\n\tcase tools.PatchToolName:\n\t\treturn \"Patch\"\n\t}\n\treturn name\n}\n\nfunc getToolAction(name string) string {\n\tswitch name {\n\tcase agent.AgentToolName:\n\t\treturn \"Preparing prompt...\"\n\tcase tools.BashToolName:\n\t\treturn \"Building command...\"\n\tcase tools.EditToolName:\n\t\treturn \"Preparing edit...\"\n\tcase tools.FetchToolName:\n\t\treturn \"Writing fetch...\"\n\tcase tools.GlobToolName:\n\t\treturn \"Finding files...\"\n\tcase tools.GrepToolName:\n\t\treturn \"Searching content...\"\n\tcase tools.LSToolName:\n\t\treturn \"Listing directory...\"\n\tcase tools.SourcegraphToolName:\n\t\treturn \"Searching code...\"\n\tcase tools.ViewToolName:\n\t\treturn \"Reading file...\"\n\tcase tools.WriteToolName:\n\t\treturn \"Preparing write...\"\n\tcase tools.PatchToolName:\n\t\treturn \"Preparing patch...\"\n\t}\n\treturn \"Working...\"\n}\n\n// renders params, params[0] (params[1]=params[2] ....)\nfunc renderParams(paramsWidth int, params ...string) string {\n\tif len(params) == 0 {\n\t\treturn \"\"\n\t}\n\tmainParam := params[0]\n\tif len(mainParam) > paramsWidth {\n\t\tmainParam = mainParam[:paramsWidth-3] + \"...\"\n\t}\n\n\tif len(params) == 1 {\n\t\treturn mainParam\n\t}\n\totherParams := params[1:]\n\t// create pairs of key/value\n\t// if odd number of params, the last one is a key without value\n\tif len(otherParams)%2 != 0 {\n\t\totherParams = append(otherParams, \"\")\n\t}\n\tparts := make([]string, 0, len(otherParams)/2)\n\tfor i := 0; i < len(otherParams); i += 2 {\n\t\tkey := otherParams[i]\n\t\tvalue := otherParams[i+1]\n\t\tif value == \"\" {\n\t\t\tcontinue\n\t\t}\n\t\tparts = append(parts, fmt.Sprintf(\"%s=%s\", key, value))\n\t}\n\n\tpartsRendered := strings.Join(parts, \", \")\n\tremainingWidth := paramsWidth - lipgloss.Width(partsRendered) - 5 // for the space\n\tif remainingWidth < 30 {\n\t\t// No space for the params, just show the main\n\t\treturn mainParam\n\t}\n\n\tif len(parts) > 0 {\n\t\tmainParam = fmt.Sprintf(\"%s (%s)\", mainParam, strings.Join(parts, \", \"))\n\t}\n\n\treturn ansi.Truncate(mainParam, paramsWidth, \"...\")\n}\n\nfunc removeWorkingDirPrefix(path string) string {\n\twd := config.WorkingDirectory()\n\tif strings.HasPrefix(path, wd) {\n\t\tpath = strings.TrimPrefix(path, wd)\n\t}\n\tif strings.HasPrefix(path, \"/\") {\n\t\tpath = strings.TrimPrefix(path, \"/\")\n\t}\n\tif strings.HasPrefix(path, \"./\") {\n\t\tpath = strings.TrimPrefix(path, \"./\")\n\t}\n\tif strings.HasPrefix(path, \"../\") {\n\t\tpath = strings.TrimPrefix(path, \"../\")\n\t}\n\treturn path\n}\n\nfunc renderToolParams(paramWidth int, toolCall message.ToolCall) string {\n\tparams := \"\"\n\tswitch toolCall.Name {\n\tcase agent.AgentToolName:\n\t\tvar params agent.AgentParams\n\t\tjson.Unmarshal([]byte(toolCall.Input), ¶ms)\n\t\tprompt := strings.ReplaceAll(params.Prompt, \"\\n\", \" \")\n\t\treturn renderParams(paramWidth, prompt)\n\tcase tools.BashToolName:\n\t\tvar params tools.BashParams\n\t\tjson.Unmarshal([]byte(toolCall.Input), ¶ms)\n\t\tcommand := strings.ReplaceAll(params.Command, \"\\n\", \" \")\n\t\treturn renderParams(paramWidth, command)\n\tcase tools.EditToolName:\n\t\tvar params tools.EditParams\n\t\tjson.Unmarshal([]byte(toolCall.Input), ¶ms)\n\t\tfilePath := removeWorkingDirPrefix(params.FilePath)\n\t\treturn renderParams(paramWidth, filePath)\n\tcase tools.FetchToolName:\n\t\tvar params tools.FetchParams\n\t\tjson.Unmarshal([]byte(toolCall.Input), ¶ms)\n\t\turl := params.URL\n\t\ttoolParams := []string{\n\t\t\turl,\n\t\t}\n\t\tif params.Format != \"\" {\n\t\t\ttoolParams = append(toolParams, \"format\", params.Format)\n\t\t}\n\t\tif params.Timeout != 0 {\n\t\t\ttoolParams = append(toolParams, \"timeout\", (time.Duration(params.Timeout) * time.Second).String())\n\t\t}\n\t\treturn renderParams(paramWidth, toolParams...)\n\tcase tools.GlobToolName:\n\t\tvar params tools.GlobParams\n\t\tjson.Unmarshal([]byte(toolCall.Input), ¶ms)\n\t\tpattern := params.Pattern\n\t\ttoolParams := []string{\n\t\t\tpattern,\n\t\t}\n\t\tif params.Path != \"\" {\n\t\t\ttoolParams = append(toolParams, \"path\", params.Path)\n\t\t}\n\t\treturn renderParams(paramWidth, toolParams...)\n\tcase tools.GrepToolName:\n\t\tvar params tools.GrepParams\n\t\tjson.Unmarshal([]byte(toolCall.Input), ¶ms)\n\t\tpattern := params.Pattern\n\t\ttoolParams := []string{\n\t\t\tpattern,\n\t\t}\n\t\tif params.Path != \"\" {\n\t\t\ttoolParams = append(toolParams, \"path\", params.Path)\n\t\t}\n\t\tif params.Include != \"\" {\n\t\t\ttoolParams = append(toolParams, \"include\", params.Include)\n\t\t}\n\t\tif params.LiteralText {\n\t\t\ttoolParams = append(toolParams, \"literal\", \"true\")\n\t\t}\n\t\treturn renderParams(paramWidth, toolParams...)\n\tcase tools.LSToolName:\n\t\tvar params tools.LSParams\n\t\tjson.Unmarshal([]byte(toolCall.Input), ¶ms)\n\t\tpath := params.Path\n\t\tif path == \"\" {\n\t\t\tpath = \".\"\n\t\t}\n\t\treturn renderParams(paramWidth, path)\n\tcase tools.SourcegraphToolName:\n\t\tvar params tools.SourcegraphParams\n\t\tjson.Unmarshal([]byte(toolCall.Input), ¶ms)\n\t\treturn renderParams(paramWidth, params.Query)\n\tcase tools.ViewToolName:\n\t\tvar params tools.ViewParams\n\t\tjson.Unmarshal([]byte(toolCall.Input), ¶ms)\n\t\tfilePath := removeWorkingDirPrefix(params.FilePath)\n\t\ttoolParams := []string{\n\t\t\tfilePath,\n\t\t}\n\t\tif params.Limit != 0 {\n\t\t\ttoolParams = append(toolParams, \"limit\", fmt.Sprintf(\"%d\", params.Limit))\n\t\t}\n\t\tif params.Offset != 0 {\n\t\t\ttoolParams = append(toolParams, \"offset\", fmt.Sprintf(\"%d\", params.Offset))\n\t\t}\n\t\treturn renderParams(paramWidth, toolParams...)\n\tcase tools.WriteToolName:\n\t\tvar params tools.WriteParams\n\t\tjson.Unmarshal([]byte(toolCall.Input), ¶ms)\n\t\tfilePath := removeWorkingDirPrefix(params.FilePath)\n\t\treturn renderParams(paramWidth, filePath)\n\tdefault:\n\t\tinput := strings.ReplaceAll(toolCall.Input, \"\\n\", \" \")\n\t\tparams = renderParams(paramWidth, input)\n\t}\n\treturn params\n}\n\nfunc truncateHeight(content string, height int) string {\n\tlines := strings.Split(content, \"\\n\")\n\tif len(lines) > height {\n\t\treturn strings.Join(lines[:height], \"\\n\")\n\t}\n\treturn content\n}\n\nfunc renderToolResponse(toolCall message.ToolCall, response message.ToolResult, width int) string {\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\n\tif response.IsError {\n\t\terrContent := fmt.Sprintf(\"Error: %s\", strings.ReplaceAll(response.Content, \"\\n\", \" \"))\n\t\terrContent = ansi.Truncate(errContent, width-1, \"...\")\n\t\treturn baseStyle.\n\t\t\tWidth(width).\n\t\t\tForeground(t.Error()).\n\t\t\tRender(errContent)\n\t}\n\n\tresultContent := truncateHeight(response.Content, maxResultHeight)\n\tswitch toolCall.Name {\n\tcase agent.AgentToolName:\n\t\treturn styles.ForceReplaceBackgroundWithLipgloss(\n\t\t\ttoMarkdown(resultContent, false, width),\n\t\t\tt.Background(),\n\t\t)\n\tcase tools.BashToolName:\n\t\tresultContent = fmt.Sprintf(\"```bash\\n%s\\n```\", resultContent)\n\t\treturn styles.ForceReplaceBackgroundWithLipgloss(\n\t\t\ttoMarkdown(resultContent, true, width),\n\t\t\tt.Background(),\n\t\t)\n\tcase tools.EditToolName:\n\t\tmetadata := tools.EditResponseMetadata{}\n\t\tjson.Unmarshal([]byte(response.Metadata), &metadata)\n\t\ttruncDiff := truncateHeight(metadata.Diff, maxResultHeight)\n\t\tformattedDiff, _ := diff.FormatDiff(truncDiff, diff.WithTotalWidth(width))\n\t\treturn formattedDiff\n\tcase tools.FetchToolName:\n\t\tvar params tools.FetchParams\n\t\tjson.Unmarshal([]byte(toolCall.Input), ¶ms)\n\t\tmdFormat := \"markdown\"\n\t\tswitch params.Format {\n\t\tcase \"text\":\n\t\t\tmdFormat = \"text\"\n\t\tcase \"html\":\n\t\t\tmdFormat = \"html\"\n\t\t}\n\t\tresultContent = fmt.Sprintf(\"```%s\\n%s\\n```\", mdFormat, resultContent)\n\t\treturn styles.ForceReplaceBackgroundWithLipgloss(\n\t\t\ttoMarkdown(resultContent, true, width),\n\t\t\tt.Background(),\n\t\t)\n\tcase tools.GlobToolName:\n\t\treturn baseStyle.Width(width).Foreground(t.TextMuted()).Render(resultContent)\n\tcase tools.GrepToolName:\n\t\treturn baseStyle.Width(width).Foreground(t.TextMuted()).Render(resultContent)\n\tcase tools.LSToolName:\n\t\treturn baseStyle.Width(width).Foreground(t.TextMuted()).Render(resultContent)\n\tcase tools.SourcegraphToolName:\n\t\treturn baseStyle.Width(width).Foreground(t.TextMuted()).Render(resultContent)\n\tcase tools.ViewToolName:\n\t\tmetadata := tools.ViewResponseMetadata{}\n\t\tjson.Unmarshal([]byte(response.Metadata), &metadata)\n\t\text := filepath.Ext(metadata.FilePath)\n\t\tif ext == \"\" {\n\t\t\text = \"\"\n\t\t} else {\n\t\t\text = strings.ToLower(ext[1:])\n\t\t}\n\t\tresultContent = fmt.Sprintf(\"```%s\\n%s\\n```\", ext, truncateHeight(metadata.Content, maxResultHeight))\n\t\treturn styles.ForceReplaceBackgroundWithLipgloss(\n\t\t\ttoMarkdown(resultContent, true, width),\n\t\t\tt.Background(),\n\t\t)\n\tcase tools.WriteToolName:\n\t\tparams := tools.WriteParams{}\n\t\tjson.Unmarshal([]byte(toolCall.Input), ¶ms)\n\t\tmetadata := tools.WriteResponseMetadata{}\n\t\tjson.Unmarshal([]byte(response.Metadata), &metadata)\n\t\text := filepath.Ext(params.FilePath)\n\t\tif ext == \"\" {\n\t\t\text = \"\"\n\t\t} else {\n\t\t\text = strings.ToLower(ext[1:])\n\t\t}\n\t\tresultContent = fmt.Sprintf(\"```%s\\n%s\\n```\", ext, truncateHeight(params.Content, maxResultHeight))\n\t\treturn styles.ForceReplaceBackgroundWithLipgloss(\n\t\t\ttoMarkdown(resultContent, true, width),\n\t\t\tt.Background(),\n\t\t)\n\tdefault:\n\t\tresultContent = fmt.Sprintf(\"```text\\n%s\\n```\", resultContent)\n\t\treturn styles.ForceReplaceBackgroundWithLipgloss(\n\t\t\ttoMarkdown(resultContent, true, width),\n\t\t\tt.Background(),\n\t\t)\n\t}\n}\n\nfunc renderToolMessage(\n\ttoolCall message.ToolCall,\n\tallMessages []message.Message,\n\tmessagesService message.Service,\n\tfocusedUIMessageId string,\n\tnested bool,\n\twidth int,\n\tposition int,\n) uiMessage {\n\tif nested {\n\t\twidth = width - 3\n\t}\n\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\n\tstyle := baseStyle.\n\t\tWidth(width - 1).\n\t\tBorderLeft(true).\n\t\tBorderStyle(lipgloss.ThickBorder()).\n\t\tPaddingLeft(1).\n\t\tBorderForeground(t.TextMuted())\n\n\tresponse := findToolResponse(toolCall.ID, allMessages)\n\ttoolNameText := baseStyle.Foreground(t.TextMuted()).\n\t\tRender(fmt.Sprintf(\"%s: \", toolName(toolCall.Name)))\n\n\tif !toolCall.Finished {\n\t\t// Get a brief description of what the tool is doing\n\t\ttoolAction := getToolAction(toolCall.Name)\n\n\t\tprogressText := baseStyle.\n\t\t\tWidth(width - 2 - lipgloss.Width(toolNameText)).\n\t\t\tForeground(t.TextMuted()).\n\t\t\tRender(fmt.Sprintf(\"%s\", toolAction))\n\n\t\tcontent := style.Render(lipgloss.JoinHorizontal(lipgloss.Left, toolNameText, progressText))\n\t\ttoolMsg := uiMessage{\n\t\t\tmessageType: toolMessageType,\n\t\t\tposition: position,\n\t\t\theight: lipgloss.Height(content),\n\t\t\tcontent: content,\n\t\t}\n\t\treturn toolMsg\n\t}\n\n\tparams := renderToolParams(width-2-lipgloss.Width(toolNameText), toolCall)\n\tresponseContent := \"\"\n\tif response != nil {\n\t\tresponseContent = renderToolResponse(toolCall, *response, width-2)\n\t\tresponseContent = strings.TrimSuffix(responseContent, \"\\n\")\n\t} else {\n\t\tresponseContent = baseStyle.\n\t\t\tItalic(true).\n\t\t\tWidth(width - 2).\n\t\t\tForeground(t.TextMuted()).\n\t\t\tRender(\"Waiting for response...\")\n\t}\n\n\tparts := []string{}\n\tif !nested {\n\t\tformattedParams := baseStyle.\n\t\t\tWidth(width - 2 - lipgloss.Width(toolNameText)).\n\t\t\tForeground(t.TextMuted()).\n\t\t\tRender(params)\n\n\t\tparts = append(parts, lipgloss.JoinHorizontal(lipgloss.Left, toolNameText, formattedParams))\n\t} else {\n\t\tprefix := baseStyle.\n\t\t\tForeground(t.TextMuted()).\n\t\t\tRender(\" └ \")\n\t\tformattedParams := baseStyle.\n\t\t\tWidth(width - 2 - lipgloss.Width(toolNameText)).\n\t\t\tForeground(t.TextMuted()).\n\t\t\tRender(params)\n\t\tparts = append(parts, lipgloss.JoinHorizontal(lipgloss.Left, prefix, toolNameText, formattedParams))\n\t}\n\n\tif toolCall.Name == agent.AgentToolName {\n\t\ttaskMessages, _ := messagesService.List(context.Background(), toolCall.ID)\n\t\ttoolCalls := []message.ToolCall{}\n\t\tfor _, v := range taskMessages {\n\t\t\ttoolCalls = append(toolCalls, v.ToolCalls()...)\n\t\t}\n\t\tfor _, call := range toolCalls {\n\t\t\trendered := renderToolMessage(call, []message.Message{}, messagesService, focusedUIMessageId, true, width, 0)\n\t\t\tparts = append(parts, rendered.content)\n\t\t}\n\t}\n\tif responseContent != \"\" && !nested {\n\t\tparts = append(parts, responseContent)\n\t}\n\n\tcontent := style.Render(\n\t\tlipgloss.JoinVertical(\n\t\t\tlipgloss.Left,\n\t\t\tparts...,\n\t\t),\n\t)\n\tif nested {\n\t\tcontent = lipgloss.JoinVertical(\n\t\t\tlipgloss.Left,\n\t\t\tparts...,\n\t\t)\n\t}\n\ttoolMsg := uiMessage{\n\t\tmessageType: toolMessageType,\n\t\tposition: position,\n\t\theight: lipgloss.Height(content),\n\t\tcontent: content,\n\t}\n\treturn toolMsg\n}\n\n// Helper function to format the time difference between two Unix timestamps\nfunc formatTimestampDiff(start, end int64) string {\n\tdiffSeconds := float64(end-start) / 1000.0 // Convert to seconds\n\tif diffSeconds < 1 {\n\t\treturn fmt.Sprintf(\"%dms\", int(diffSeconds*1000))\n\t}\n\tif diffSeconds < 60 {\n\t\treturn fmt.Sprintf(\"%.1fs\", diffSeconds)\n\t}\n\treturn fmt.Sprintf(\"%.1fm\", diffSeconds/60)\n}\n"], ["/opencode/internal/tui/components/logs/details.go", "package logs\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/charmbracelet/bubbles/key\"\n\t\"github.com/charmbracelet/bubbles/viewport\"\n\ttea \"github.com/charmbracelet/bubbletea\"\n\t\"github.com/charmbracelet/lipgloss\"\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n\t\"github.com/opencode-ai/opencode/internal/tui/layout\"\n\t\"github.com/opencode-ai/opencode/internal/tui/styles\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n)\n\ntype DetailComponent interface {\n\ttea.Model\n\tlayout.Sizeable\n\tlayout.Bindings\n}\n\ntype detailCmp struct {\n\twidth, height int\n\tcurrentLog logging.LogMessage\n\tviewport viewport.Model\n}\n\nfunc (i *detailCmp) Init() tea.Cmd {\n\tmessages := logging.List()\n\tif len(messages) == 0 {\n\t\treturn nil\n\t}\n\ti.currentLog = messages[0]\n\treturn nil\n}\n\nfunc (i *detailCmp) Update(msg tea.Msg) (tea.Model, tea.Cmd) {\n\tswitch msg := msg.(type) {\n\tcase selectedLogMsg:\n\t\tif msg.ID != i.currentLog.ID {\n\t\t\ti.currentLog = logging.LogMessage(msg)\n\t\t\ti.updateContent()\n\t\t}\n\t}\n\n\treturn i, nil\n}\n\nfunc (i *detailCmp) updateContent() {\n\tvar content strings.Builder\n\tt := theme.CurrentTheme()\n\n\t// Format the header with timestamp and level\n\ttimeStyle := lipgloss.NewStyle().Foreground(t.TextMuted())\n\tlevelStyle := getLevelStyle(i.currentLog.Level)\n\n\theader := lipgloss.JoinHorizontal(\n\t\tlipgloss.Center,\n\t\ttimeStyle.Render(i.currentLog.Time.Format(time.RFC3339)),\n\t\t\" \",\n\t\tlevelStyle.Render(i.currentLog.Level),\n\t)\n\n\tcontent.WriteString(lipgloss.NewStyle().Bold(true).Render(header))\n\tcontent.WriteString(\"\\n\\n\")\n\n\t// Message with styling\n\tmessageStyle := lipgloss.NewStyle().Bold(true).Foreground(t.Text())\n\tcontent.WriteString(messageStyle.Render(\"Message:\"))\n\tcontent.WriteString(\"\\n\")\n\tcontent.WriteString(lipgloss.NewStyle().Padding(0, 2).Render(i.currentLog.Message))\n\tcontent.WriteString(\"\\n\\n\")\n\n\t// Attributes section\n\tif len(i.currentLog.Attributes) > 0 {\n\t\tattrHeaderStyle := lipgloss.NewStyle().Bold(true).Foreground(t.Text())\n\t\tcontent.WriteString(attrHeaderStyle.Render(\"Attributes:\"))\n\t\tcontent.WriteString(\"\\n\")\n\n\t\t// Create a table-like display for attributes\n\t\tkeyStyle := lipgloss.NewStyle().Foreground(t.Primary()).Bold(true)\n\t\tvalueStyle := lipgloss.NewStyle().Foreground(t.Text())\n\n\t\tfor _, attr := range i.currentLog.Attributes {\n\t\t\tattrLine := fmt.Sprintf(\"%s: %s\",\n\t\t\t\tkeyStyle.Render(attr.Key),\n\t\t\t\tvalueStyle.Render(attr.Value),\n\t\t\t)\n\t\t\tcontent.WriteString(lipgloss.NewStyle().Padding(0, 2).Render(attrLine))\n\t\t\tcontent.WriteString(\"\\n\")\n\t\t}\n\t}\n\n\ti.viewport.SetContent(content.String())\n}\n\nfunc getLevelStyle(level string) lipgloss.Style {\n\tstyle := lipgloss.NewStyle().Bold(true)\n\tt := theme.CurrentTheme()\n\t\n\tswitch strings.ToLower(level) {\n\tcase \"info\":\n\t\treturn style.Foreground(t.Info())\n\tcase \"warn\", \"warning\":\n\t\treturn style.Foreground(t.Warning())\n\tcase \"error\", \"err\":\n\t\treturn style.Foreground(t.Error())\n\tcase \"debug\":\n\t\treturn style.Foreground(t.Success())\n\tdefault:\n\t\treturn style.Foreground(t.Text())\n\t}\n}\n\nfunc (i *detailCmp) View() string {\n\tt := theme.CurrentTheme()\n\treturn styles.ForceReplaceBackgroundWithLipgloss(i.viewport.View(), t.Background())\n}\n\nfunc (i *detailCmp) GetSize() (int, int) {\n\treturn i.width, i.height\n}\n\nfunc (i *detailCmp) SetSize(width int, height int) tea.Cmd {\n\ti.width = width\n\ti.height = height\n\ti.viewport.Width = i.width\n\ti.viewport.Height = i.height\n\ti.updateContent()\n\treturn nil\n}\n\nfunc (i *detailCmp) BindingKeys() []key.Binding {\n\treturn layout.KeyMapToSlice(i.viewport.KeyMap)\n}\n\nfunc NewLogsDetails() DetailComponent {\n\treturn &detailCmp{\n\t\tviewport: viewport.New(0, 0),\n\t}\n}\n"], ["/opencode/internal/tui/components/logs/table.go", "package logs\n\nimport (\n\t\"encoding/json\"\n\t\"slices\"\n\n\t\"github.com/charmbracelet/bubbles/key\"\n\t\"github.com/charmbracelet/bubbles/table\"\n\ttea \"github.com/charmbracelet/bubbletea\"\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n\t\"github.com/opencode-ai/opencode/internal/pubsub\"\n\t\"github.com/opencode-ai/opencode/internal/tui/layout\"\n\t\"github.com/opencode-ai/opencode/internal/tui/styles\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n\t\"github.com/opencode-ai/opencode/internal/tui/util\"\n)\n\ntype TableComponent interface {\n\ttea.Model\n\tlayout.Sizeable\n\tlayout.Bindings\n}\n\ntype tableCmp struct {\n\ttable table.Model\n}\n\ntype selectedLogMsg logging.LogMessage\n\nfunc (i *tableCmp) Init() tea.Cmd {\n\ti.setRows()\n\treturn nil\n}\n\nfunc (i *tableCmp) Update(msg tea.Msg) (tea.Model, tea.Cmd) {\n\tvar cmds []tea.Cmd\n\tswitch msg.(type) {\n\tcase pubsub.Event[logging.LogMessage]:\n\t\ti.setRows()\n\t\treturn i, nil\n\t}\n\tprevSelectedRow := i.table.SelectedRow()\n\tt, cmd := i.table.Update(msg)\n\tcmds = append(cmds, cmd)\n\ti.table = t\n\tselectedRow := i.table.SelectedRow()\n\tif selectedRow != nil {\n\t\tif prevSelectedRow == nil || selectedRow[0] == prevSelectedRow[0] {\n\t\t\tvar log logging.LogMessage\n\t\t\tfor _, row := range logging.List() {\n\t\t\t\tif row.ID == selectedRow[0] {\n\t\t\t\t\tlog = row\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\tif log.ID != \"\" {\n\t\t\t\tcmds = append(cmds, util.CmdHandler(selectedLogMsg(log)))\n\t\t\t}\n\t\t}\n\t}\n\treturn i, tea.Batch(cmds...)\n}\n\nfunc (i *tableCmp) View() string {\n\tt := theme.CurrentTheme()\n\tdefaultStyles := table.DefaultStyles()\n\tdefaultStyles.Selected = defaultStyles.Selected.Foreground(t.Primary())\n\ti.table.SetStyles(defaultStyles)\n\treturn styles.ForceReplaceBackgroundWithLipgloss(i.table.View(), t.Background())\n}\n\nfunc (i *tableCmp) GetSize() (int, int) {\n\treturn i.table.Width(), i.table.Height()\n}\n\nfunc (i *tableCmp) SetSize(width int, height int) tea.Cmd {\n\ti.table.SetWidth(width)\n\ti.table.SetHeight(height)\n\tcloumns := i.table.Columns()\n\tfor i, col := range cloumns {\n\t\tcol.Width = (width / len(cloumns)) - 2\n\t\tcloumns[i] = col\n\t}\n\ti.table.SetColumns(cloumns)\n\treturn nil\n}\n\nfunc (i *tableCmp) BindingKeys() []key.Binding {\n\treturn layout.KeyMapToSlice(i.table.KeyMap)\n}\n\nfunc (i *tableCmp) setRows() {\n\trows := []table.Row{}\n\n\tlogs := logging.List()\n\tslices.SortFunc(logs, func(a, b logging.LogMessage) int {\n\t\tif a.Time.Before(b.Time) {\n\t\t\treturn 1\n\t\t}\n\t\tif a.Time.After(b.Time) {\n\t\t\treturn -1\n\t\t}\n\t\treturn 0\n\t})\n\n\tfor _, log := range logs {\n\t\tbm, _ := json.Marshal(log.Attributes)\n\n\t\trow := table.Row{\n\t\t\tlog.ID,\n\t\t\tlog.Time.Format(\"15:04:05\"),\n\t\t\tlog.Level,\n\t\t\tlog.Message,\n\t\t\tstring(bm),\n\t\t}\n\t\trows = append(rows, row)\n\t}\n\ti.table.SetRows(rows)\n}\n\nfunc NewLogsTable() TableComponent {\n\tcolumns := []table.Column{\n\t\t{Title: \"ID\", Width: 4},\n\t\t{Title: \"Time\", Width: 4},\n\t\t{Title: \"Level\", Width: 10},\n\t\t{Title: \"Message\", Width: 10},\n\t\t{Title: \"Attributes\", Width: 10},\n\t}\n\n\ttableModel := table.New(\n\t\ttable.WithColumns(columns),\n\t)\n\ttableModel.Focus()\n\treturn &tableCmp{\n\t\ttable: tableModel,\n\t}\n}\n"], ["/opencode/internal/tui/layout/container.go", "package layout\n\nimport (\n\t\"github.com/charmbracelet/bubbles/key\"\n\ttea \"github.com/charmbracelet/bubbletea\"\n\t\"github.com/charmbracelet/lipgloss\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n)\n\ntype Container interface {\n\ttea.Model\n\tSizeable\n\tBindings\n}\ntype container struct {\n\twidth int\n\theight int\n\n\tcontent tea.Model\n\n\t// Style options\n\tpaddingTop int\n\tpaddingRight int\n\tpaddingBottom int\n\tpaddingLeft int\n\n\tborderTop bool\n\tborderRight bool\n\tborderBottom bool\n\tborderLeft bool\n\tborderStyle lipgloss.Border\n}\n\nfunc (c *container) Init() tea.Cmd {\n\treturn c.content.Init()\n}\n\nfunc (c *container) Update(msg tea.Msg) (tea.Model, tea.Cmd) {\n\tu, cmd := c.content.Update(msg)\n\tc.content = u\n\treturn c, cmd\n}\n\nfunc (c *container) View() string {\n\tt := theme.CurrentTheme()\n\tstyle := lipgloss.NewStyle()\n\twidth := c.width\n\theight := c.height\n\n\tstyle = style.Background(t.Background())\n\n\t// Apply border if any side is enabled\n\tif c.borderTop || c.borderRight || c.borderBottom || c.borderLeft {\n\t\t// Adjust width and height for borders\n\t\tif c.borderTop {\n\t\t\theight--\n\t\t}\n\t\tif c.borderBottom {\n\t\t\theight--\n\t\t}\n\t\tif c.borderLeft {\n\t\t\twidth--\n\t\t}\n\t\tif c.borderRight {\n\t\t\twidth--\n\t\t}\n\t\tstyle = style.Border(c.borderStyle, c.borderTop, c.borderRight, c.borderBottom, c.borderLeft)\n\t\tstyle = style.BorderBackground(t.Background()).BorderForeground(t.BorderNormal())\n\t}\n\tstyle = style.\n\t\tWidth(width).\n\t\tHeight(height).\n\t\tPaddingTop(c.paddingTop).\n\t\tPaddingRight(c.paddingRight).\n\t\tPaddingBottom(c.paddingBottom).\n\t\tPaddingLeft(c.paddingLeft)\n\n\treturn style.Render(c.content.View())\n}\n\nfunc (c *container) SetSize(width, height int) tea.Cmd {\n\tc.width = width\n\tc.height = height\n\n\t// If the content implements Sizeable, adjust its size to account for padding and borders\n\tif sizeable, ok := c.content.(Sizeable); ok {\n\t\t// Calculate horizontal space taken by padding and borders\n\t\thorizontalSpace := c.paddingLeft + c.paddingRight\n\t\tif c.borderLeft {\n\t\t\thorizontalSpace++\n\t\t}\n\t\tif c.borderRight {\n\t\t\thorizontalSpace++\n\t\t}\n\n\t\t// Calculate vertical space taken by padding and borders\n\t\tverticalSpace := c.paddingTop + c.paddingBottom\n\t\tif c.borderTop {\n\t\t\tverticalSpace++\n\t\t}\n\t\tif c.borderBottom {\n\t\t\tverticalSpace++\n\t\t}\n\n\t\t// Set content size with adjusted dimensions\n\t\tcontentWidth := max(0, width-horizontalSpace)\n\t\tcontentHeight := max(0, height-verticalSpace)\n\t\treturn sizeable.SetSize(contentWidth, contentHeight)\n\t}\n\treturn nil\n}\n\nfunc (c *container) GetSize() (int, int) {\n\treturn c.width, c.height\n}\n\nfunc (c *container) BindingKeys() []key.Binding {\n\tif b, ok := c.content.(Bindings); ok {\n\t\treturn b.BindingKeys()\n\t}\n\treturn []key.Binding{}\n}\n\ntype ContainerOption func(*container)\n\nfunc NewContainer(content tea.Model, options ...ContainerOption) Container {\n\n\tc := &container{\n\t\tcontent: content,\n\t\tborderStyle: lipgloss.NormalBorder(),\n\t}\n\n\tfor _, option := range options {\n\t\toption(c)\n\t}\n\n\treturn c\n}\n\n// Padding options\nfunc WithPadding(top, right, bottom, left int) ContainerOption {\n\treturn func(c *container) {\n\t\tc.paddingTop = top\n\t\tc.paddingRight = right\n\t\tc.paddingBottom = bottom\n\t\tc.paddingLeft = left\n\t}\n}\n\nfunc WithPaddingAll(padding int) ContainerOption {\n\treturn WithPadding(padding, padding, padding, padding)\n}\n\nfunc WithPaddingHorizontal(padding int) ContainerOption {\n\treturn func(c *container) {\n\t\tc.paddingLeft = padding\n\t\tc.paddingRight = padding\n\t}\n}\n\nfunc WithPaddingVertical(padding int) ContainerOption {\n\treturn func(c *container) {\n\t\tc.paddingTop = padding\n\t\tc.paddingBottom = padding\n\t}\n}\n\nfunc WithBorder(top, right, bottom, left bool) ContainerOption {\n\treturn func(c *container) {\n\t\tc.borderTop = top\n\t\tc.borderRight = right\n\t\tc.borderBottom = bottom\n\t\tc.borderLeft = left\n\t}\n}\n\nfunc WithBorderAll() ContainerOption {\n\treturn WithBorder(true, true, true, true)\n}\n\nfunc WithBorderHorizontal() ContainerOption {\n\treturn WithBorder(true, false, true, false)\n}\n\nfunc WithBorderVertical() ContainerOption {\n\treturn WithBorder(false, true, false, true)\n}\n\nfunc WithBorderStyle(style lipgloss.Border) ContainerOption {\n\treturn func(c *container) {\n\t\tc.borderStyle = style\n\t}\n}\n\nfunc WithRoundedBorder() ContainerOption {\n\treturn WithBorderStyle(lipgloss.RoundedBorder())\n}\n\nfunc WithThickBorder() ContainerOption {\n\treturn WithBorderStyle(lipgloss.ThickBorder())\n}\n\nfunc WithDoubleBorder() ContainerOption {\n\treturn WithBorderStyle(lipgloss.DoubleBorder())\n}\n"], ["/opencode/internal/tui/components/chat/chat.go", "package chat\n\nimport (\n\t\"fmt\"\n\t\"sort\"\n\n\t\"github.com/charmbracelet/lipgloss\"\n\t\"github.com/charmbracelet/x/ansi\"\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/message\"\n\t\"github.com/opencode-ai/opencode/internal/session\"\n\t\"github.com/opencode-ai/opencode/internal/tui/styles\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n\t\"github.com/opencode-ai/opencode/internal/version\"\n)\n\ntype SendMsg struct {\n\tText string\n\tAttachments []message.Attachment\n}\n\ntype SessionSelectedMsg = session.Session\n\ntype SessionClearedMsg struct{}\n\ntype EditorFocusMsg bool\n\nfunc header(width int) string {\n\treturn lipgloss.JoinVertical(\n\t\tlipgloss.Top,\n\t\tlogo(width),\n\t\trepo(width),\n\t\t\"\",\n\t\tcwd(width),\n\t)\n}\n\nfunc lspsConfigured(width int) string {\n\tcfg := config.Get()\n\ttitle := \"LSP Configuration\"\n\ttitle = ansi.Truncate(title, width, \"…\")\n\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\n\tlsps := baseStyle.\n\t\tWidth(width).\n\t\tForeground(t.Primary()).\n\t\tBold(true).\n\t\tRender(title)\n\n\t// Get LSP names and sort them for consistent ordering\n\tvar lspNames []string\n\tfor name := range cfg.LSP {\n\t\tlspNames = append(lspNames, name)\n\t}\n\tsort.Strings(lspNames)\n\n\tvar lspViews []string\n\tfor _, name := range lspNames {\n\t\tlsp := cfg.LSP[name]\n\t\tlspName := baseStyle.\n\t\t\tForeground(t.Text()).\n\t\t\tRender(fmt.Sprintf(\"• %s\", name))\n\n\t\tcmd := lsp.Command\n\t\tcmd = ansi.Truncate(cmd, width-lipgloss.Width(lspName)-3, \"…\")\n\n\t\tlspPath := baseStyle.\n\t\t\tForeground(t.TextMuted()).\n\t\t\tRender(fmt.Sprintf(\" (%s)\", cmd))\n\n\t\tlspViews = append(lspViews,\n\t\t\tbaseStyle.\n\t\t\t\tWidth(width).\n\t\t\t\tRender(\n\t\t\t\t\tlipgloss.JoinHorizontal(\n\t\t\t\t\t\tlipgloss.Left,\n\t\t\t\t\t\tlspName,\n\t\t\t\t\t\tlspPath,\n\t\t\t\t\t),\n\t\t\t\t),\n\t\t)\n\t}\n\n\treturn baseStyle.\n\t\tWidth(width).\n\t\tRender(\n\t\t\tlipgloss.JoinVertical(\n\t\t\t\tlipgloss.Left,\n\t\t\t\tlsps,\n\t\t\t\tlipgloss.JoinVertical(\n\t\t\t\t\tlipgloss.Left,\n\t\t\t\t\tlspViews...,\n\t\t\t\t),\n\t\t\t),\n\t\t)\n}\n\nfunc logo(width int) string {\n\tlogo := fmt.Sprintf(\"%s %s\", styles.OpenCodeIcon, \"OpenCode\")\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\n\tversionText := baseStyle.\n\t\tForeground(t.TextMuted()).\n\t\tRender(version.Version)\n\n\treturn baseStyle.\n\t\tBold(true).\n\t\tWidth(width).\n\t\tRender(\n\t\t\tlipgloss.JoinHorizontal(\n\t\t\t\tlipgloss.Left,\n\t\t\t\tlogo,\n\t\t\t\t\" \",\n\t\t\t\tversionText,\n\t\t\t),\n\t\t)\n}\n\nfunc repo(width int) string {\n\trepo := \"https://github.com/opencode-ai/opencode\"\n\tt := theme.CurrentTheme()\n\n\treturn styles.BaseStyle().\n\t\tForeground(t.TextMuted()).\n\t\tWidth(width).\n\t\tRender(repo)\n}\n\nfunc cwd(width int) string {\n\tcwd := fmt.Sprintf(\"cwd: %s\", config.WorkingDirectory())\n\tt := theme.CurrentTheme()\n\n\treturn styles.BaseStyle().\n\t\tForeground(t.TextMuted()).\n\t\tWidth(width).\n\t\tRender(cwd)\n}\n\n"], ["/opencode/internal/tui/layout/split.go", "package layout\n\nimport (\n\t\"github.com/charmbracelet/bubbles/key\"\n\ttea \"github.com/charmbracelet/bubbletea\"\n\t\"github.com/charmbracelet/lipgloss\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n)\n\ntype SplitPaneLayout interface {\n\ttea.Model\n\tSizeable\n\tBindings\n\tSetLeftPanel(panel Container) tea.Cmd\n\tSetRightPanel(panel Container) tea.Cmd\n\tSetBottomPanel(panel Container) tea.Cmd\n\n\tClearLeftPanel() tea.Cmd\n\tClearRightPanel() tea.Cmd\n\tClearBottomPanel() tea.Cmd\n}\n\ntype splitPaneLayout struct {\n\twidth int\n\theight int\n\tratio float64\n\tverticalRatio float64\n\n\trightPanel Container\n\tleftPanel Container\n\tbottomPanel Container\n}\n\ntype SplitPaneOption func(*splitPaneLayout)\n\nfunc (s *splitPaneLayout) Init() tea.Cmd {\n\tvar cmds []tea.Cmd\n\n\tif s.leftPanel != nil {\n\t\tcmds = append(cmds, s.leftPanel.Init())\n\t}\n\n\tif s.rightPanel != nil {\n\t\tcmds = append(cmds, s.rightPanel.Init())\n\t}\n\n\tif s.bottomPanel != nil {\n\t\tcmds = append(cmds, s.bottomPanel.Init())\n\t}\n\n\treturn tea.Batch(cmds...)\n}\n\nfunc (s *splitPaneLayout) Update(msg tea.Msg) (tea.Model, tea.Cmd) {\n\tvar cmds []tea.Cmd\n\tswitch msg := msg.(type) {\n\tcase tea.WindowSizeMsg:\n\t\treturn s, s.SetSize(msg.Width, msg.Height)\n\t}\n\n\tif s.rightPanel != nil {\n\t\tu, cmd := s.rightPanel.Update(msg)\n\t\ts.rightPanel = u.(Container)\n\t\tif cmd != nil {\n\t\t\tcmds = append(cmds, cmd)\n\t\t}\n\t}\n\n\tif s.leftPanel != nil {\n\t\tu, cmd := s.leftPanel.Update(msg)\n\t\ts.leftPanel = u.(Container)\n\t\tif cmd != nil {\n\t\t\tcmds = append(cmds, cmd)\n\t\t}\n\t}\n\n\tif s.bottomPanel != nil {\n\t\tu, cmd := s.bottomPanel.Update(msg)\n\t\ts.bottomPanel = u.(Container)\n\t\tif cmd != nil {\n\t\t\tcmds = append(cmds, cmd)\n\t\t}\n\t}\n\n\treturn s, tea.Batch(cmds...)\n}\n\nfunc (s *splitPaneLayout) View() string {\n\tvar topSection string\n\n\tif s.leftPanel != nil && s.rightPanel != nil {\n\t\tleftView := s.leftPanel.View()\n\t\trightView := s.rightPanel.View()\n\t\ttopSection = lipgloss.JoinHorizontal(lipgloss.Top, leftView, rightView)\n\t} else if s.leftPanel != nil {\n\t\ttopSection = s.leftPanel.View()\n\t} else if s.rightPanel != nil {\n\t\ttopSection = s.rightPanel.View()\n\t} else {\n\t\ttopSection = \"\"\n\t}\n\n\tvar finalView string\n\n\tif s.bottomPanel != nil && topSection != \"\" {\n\t\tbottomView := s.bottomPanel.View()\n\t\tfinalView = lipgloss.JoinVertical(lipgloss.Left, topSection, bottomView)\n\t} else if s.bottomPanel != nil {\n\t\tfinalView = s.bottomPanel.View()\n\t} else {\n\t\tfinalView = topSection\n\t}\n\n\tif finalView != \"\" {\n\t\tt := theme.CurrentTheme()\n\n\t\tstyle := lipgloss.NewStyle().\n\t\t\tWidth(s.width).\n\t\t\tHeight(s.height).\n\t\t\tBackground(t.Background())\n\n\t\treturn style.Render(finalView)\n\t}\n\n\treturn finalView\n}\n\nfunc (s *splitPaneLayout) SetSize(width, height int) tea.Cmd {\n\ts.width = width\n\ts.height = height\n\n\tvar topHeight, bottomHeight int\n\tif s.bottomPanel != nil {\n\t\ttopHeight = int(float64(height) * s.verticalRatio)\n\t\tbottomHeight = height - topHeight\n\t} else {\n\t\ttopHeight = height\n\t\tbottomHeight = 0\n\t}\n\n\tvar leftWidth, rightWidth int\n\tif s.leftPanel != nil && s.rightPanel != nil {\n\t\tleftWidth = int(float64(width) * s.ratio)\n\t\trightWidth = width - leftWidth\n\t} else if s.leftPanel != nil {\n\t\tleftWidth = width\n\t\trightWidth = 0\n\t} else if s.rightPanel != nil {\n\t\tleftWidth = 0\n\t\trightWidth = width\n\t}\n\n\tvar cmds []tea.Cmd\n\tif s.leftPanel != nil {\n\t\tcmd := s.leftPanel.SetSize(leftWidth, topHeight)\n\t\tcmds = append(cmds, cmd)\n\t}\n\n\tif s.rightPanel != nil {\n\t\tcmd := s.rightPanel.SetSize(rightWidth, topHeight)\n\t\tcmds = append(cmds, cmd)\n\t}\n\n\tif s.bottomPanel != nil {\n\t\tcmd := s.bottomPanel.SetSize(width, bottomHeight)\n\t\tcmds = append(cmds, cmd)\n\t}\n\treturn tea.Batch(cmds...)\n}\n\nfunc (s *splitPaneLayout) GetSize() (int, int) {\n\treturn s.width, s.height\n}\n\nfunc (s *splitPaneLayout) SetLeftPanel(panel Container) tea.Cmd {\n\ts.leftPanel = panel\n\tif s.width > 0 && s.height > 0 {\n\t\treturn s.SetSize(s.width, s.height)\n\t}\n\treturn nil\n}\n\nfunc (s *splitPaneLayout) SetRightPanel(panel Container) tea.Cmd {\n\ts.rightPanel = panel\n\tif s.width > 0 && s.height > 0 {\n\t\treturn s.SetSize(s.width, s.height)\n\t}\n\treturn nil\n}\n\nfunc (s *splitPaneLayout) SetBottomPanel(panel Container) tea.Cmd {\n\ts.bottomPanel = panel\n\tif s.width > 0 && s.height > 0 {\n\t\treturn s.SetSize(s.width, s.height)\n\t}\n\treturn nil\n}\n\nfunc (s *splitPaneLayout) ClearLeftPanel() tea.Cmd {\n\ts.leftPanel = nil\n\tif s.width > 0 && s.height > 0 {\n\t\treturn s.SetSize(s.width, s.height)\n\t}\n\treturn nil\n}\n\nfunc (s *splitPaneLayout) ClearRightPanel() tea.Cmd {\n\ts.rightPanel = nil\n\tif s.width > 0 && s.height > 0 {\n\t\treturn s.SetSize(s.width, s.height)\n\t}\n\treturn nil\n}\n\nfunc (s *splitPaneLayout) ClearBottomPanel() tea.Cmd {\n\ts.bottomPanel = nil\n\tif s.width > 0 && s.height > 0 {\n\t\treturn s.SetSize(s.width, s.height)\n\t}\n\treturn nil\n}\n\nfunc (s *splitPaneLayout) BindingKeys() []key.Binding {\n\tkeys := []key.Binding{}\n\tif s.leftPanel != nil {\n\t\tif b, ok := s.leftPanel.(Bindings); ok {\n\t\t\tkeys = append(keys, b.BindingKeys()...)\n\t\t}\n\t}\n\tif s.rightPanel != nil {\n\t\tif b, ok := s.rightPanel.(Bindings); ok {\n\t\t\tkeys = append(keys, b.BindingKeys()...)\n\t\t}\n\t}\n\tif s.bottomPanel != nil {\n\t\tif b, ok := s.bottomPanel.(Bindings); ok {\n\t\t\tkeys = append(keys, b.BindingKeys()...)\n\t\t}\n\t}\n\treturn keys\n}\n\nfunc NewSplitPane(options ...SplitPaneOption) SplitPaneLayout {\n\n\tlayout := &splitPaneLayout{\n\t\tratio: 0.7,\n\t\tverticalRatio: 0.9, // Default 90% for top section, 10% for bottom\n\t}\n\tfor _, option := range options {\n\t\toption(layout)\n\t}\n\treturn layout\n}\n\nfunc WithLeftPanel(panel Container) SplitPaneOption {\n\treturn func(s *splitPaneLayout) {\n\t\ts.leftPanel = panel\n\t}\n}\n\nfunc WithRightPanel(panel Container) SplitPaneOption {\n\treturn func(s *splitPaneLayout) {\n\t\ts.rightPanel = panel\n\t}\n}\n\nfunc WithRatio(ratio float64) SplitPaneOption {\n\treturn func(s *splitPaneLayout) {\n\t\ts.ratio = ratio\n\t}\n}\n\nfunc WithBottomPanel(panel Container) SplitPaneOption {\n\treturn func(s *splitPaneLayout) {\n\t\ts.bottomPanel = panel\n\t}\n}\n\nfunc WithVerticalRatio(ratio float64) SplitPaneOption {\n\treturn func(s *splitPaneLayout) {\n\t\ts.verticalRatio = ratio\n\t}\n}\n"], ["/opencode/internal/tui/components/dialog/custom_commands.go", "package dialog\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"regexp\"\n\t\"strings\"\n\n\ttea \"github.com/charmbracelet/bubbletea\"\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/tui/util\"\n)\n\n// Command prefix constants\nconst (\n\tUserCommandPrefix = \"user:\"\n\tProjectCommandPrefix = \"project:\"\n)\n\n// namedArgPattern is a regex pattern to find named arguments in the format $NAME\nvar namedArgPattern = regexp.MustCompile(`\\$([A-Z][A-Z0-9_]*)`)\n\n// LoadCustomCommands loads custom commands from both XDG_CONFIG_HOME and project data directory\nfunc LoadCustomCommands() ([]Command, error) {\n\tcfg := config.Get()\n\tif cfg == nil {\n\t\treturn nil, fmt.Errorf(\"config not loaded\")\n\t}\n\n\tvar commands []Command\n\n\t// Load user commands from XDG_CONFIG_HOME/opencode/commands\n\txdgConfigHome := os.Getenv(\"XDG_CONFIG_HOME\")\n\tif xdgConfigHome == \"\" {\n\t\t// Default to ~/.config if XDG_CONFIG_HOME is not set\n\t\thome, err := os.UserHomeDir()\n\t\tif err == nil {\n\t\t\txdgConfigHome = filepath.Join(home, \".config\")\n\t\t}\n\t}\n\n\tif xdgConfigHome != \"\" {\n\t\tuserCommandsDir := filepath.Join(xdgConfigHome, \"opencode\", \"commands\")\n\t\tuserCommands, err := loadCommandsFromDir(userCommandsDir, UserCommandPrefix)\n\t\tif err != nil {\n\t\t\t// Log error but continue - we'll still try to load other commands\n\t\t\tfmt.Printf(\"Warning: failed to load user commands from XDG_CONFIG_HOME: %v\\n\", err)\n\t\t} else {\n\t\t\tcommands = append(commands, userCommands...)\n\t\t}\n\t}\n\n\t// Load commands from $HOME/.opencode/commands\n\thome, err := os.UserHomeDir()\n\tif err == nil {\n\t\thomeCommandsDir := filepath.Join(home, \".opencode\", \"commands\")\n\t\thomeCommands, err := loadCommandsFromDir(homeCommandsDir, UserCommandPrefix)\n\t\tif err != nil {\n\t\t\t// Log error but continue - we'll still try to load other commands\n\t\t\tfmt.Printf(\"Warning: failed to load home commands: %v\\n\", err)\n\t\t} else {\n\t\t\tcommands = append(commands, homeCommands...)\n\t\t}\n\t}\n\n\t// Load project commands from data directory\n\tprojectCommandsDir := filepath.Join(cfg.Data.Directory, \"commands\")\n\tprojectCommands, err := loadCommandsFromDir(projectCommandsDir, ProjectCommandPrefix)\n\tif err != nil {\n\t\t// Log error but return what we have so far\n\t\tfmt.Printf(\"Warning: failed to load project commands: %v\\n\", err)\n\t} else {\n\t\tcommands = append(commands, projectCommands...)\n\t}\n\n\treturn commands, nil\n}\n\n// loadCommandsFromDir loads commands from a specific directory with the given prefix\nfunc loadCommandsFromDir(commandsDir string, prefix string) ([]Command, error) {\n\t// Check if the commands directory exists\n\tif _, err := os.Stat(commandsDir); os.IsNotExist(err) {\n\t\t// Create the commands directory if it doesn't exist\n\t\tif err := os.MkdirAll(commandsDir, 0755); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to create commands directory %s: %w\", commandsDir, err)\n\t\t}\n\t\t// Return empty list since we just created the directory\n\t\treturn []Command{}, nil\n\t}\n\n\tvar commands []Command\n\n\t// Walk through the commands directory and load all .md files\n\terr := filepath.Walk(commandsDir, func(path string, info os.FileInfo, err error) error {\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Skip directories\n\t\tif info.IsDir() {\n\t\t\treturn nil\n\t\t}\n\n\t\t// Only process markdown files\n\t\tif !strings.HasSuffix(strings.ToLower(info.Name()), \".md\") {\n\t\t\treturn nil\n\t\t}\n\n\t\t// Read the file content\n\t\tcontent, err := os.ReadFile(path)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to read command file %s: %w\", path, err)\n\t\t}\n\n\t\t// Get the command ID from the file name without the .md extension\n\t\tcommandID := strings.TrimSuffix(info.Name(), filepath.Ext(info.Name()))\n\n\t\t// Get relative path from commands directory\n\t\trelPath, err := filepath.Rel(commandsDir, path)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to get relative path for %s: %w\", path, err)\n\t\t}\n\n\t\t// Create the command ID from the relative path\n\t\t// Replace directory separators with colons\n\t\tcommandIDPath := strings.ReplaceAll(filepath.Dir(relPath), string(filepath.Separator), \":\")\n\t\tif commandIDPath != \".\" {\n\t\t\tcommandID = commandIDPath + \":\" + commandID\n\t\t}\n\n\t\t// Create a command\n\t\tcommand := Command{\n\t\t\tID: prefix + commandID,\n\t\t\tTitle: prefix + commandID,\n\t\t\tDescription: fmt.Sprintf(\"Custom command from %s\", relPath),\n\t\t\tHandler: func(cmd Command) tea.Cmd {\n\t\t\t\tcommandContent := string(content)\n\n\t\t\t\t// Check for named arguments\n\t\t\t\tmatches := namedArgPattern.FindAllStringSubmatch(commandContent, -1)\n\t\t\t\tif len(matches) > 0 {\n\t\t\t\t\t// Extract unique argument names\n\t\t\t\t\targNames := make([]string, 0)\n\t\t\t\t\targMap := make(map[string]bool)\n\n\t\t\t\t\tfor _, match := range matches {\n\t\t\t\t\t\targName := match[1] // Group 1 is the name without $\n\t\t\t\t\t\tif !argMap[argName] {\n\t\t\t\t\t\t\targMap[argName] = true\n\t\t\t\t\t\t\targNames = append(argNames, argName)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\t// Show multi-arguments dialog for all named arguments\n\t\t\t\t\treturn util.CmdHandler(ShowMultiArgumentsDialogMsg{\n\t\t\t\t\t\tCommandID: cmd.ID,\n\t\t\t\t\t\tContent: commandContent,\n\t\t\t\t\t\tArgNames: argNames,\n\t\t\t\t\t})\n\t\t\t\t}\n\n\t\t\t\t// No arguments needed, run command directly\n\t\t\t\treturn util.CmdHandler(CommandRunCustomMsg{\n\t\t\t\t\tContent: commandContent,\n\t\t\t\t\tArgs: nil, // No arguments\n\t\t\t\t})\n\t\t\t},\n\t\t}\n\n\t\tcommands = append(commands, command)\n\t\treturn nil\n\t})\n\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to load custom commands from %s: %w\", commandsDir, err)\n\t}\n\n\treturn commands, nil\n}\n\n// CommandRunCustomMsg is sent when a custom command is executed\ntype CommandRunCustomMsg struct {\n\tContent string\n\tArgs map[string]string // Map of argument names to values\n}\n"], ["/opencode/internal/tui/page/logs.go", "package page\n\nimport (\n\t\"github.com/charmbracelet/bubbles/key\"\n\ttea \"github.com/charmbracelet/bubbletea\"\n\t\"github.com/charmbracelet/lipgloss\"\n\t\"github.com/opencode-ai/opencode/internal/tui/components/logs\"\n\t\"github.com/opencode-ai/opencode/internal/tui/layout\"\n\t\"github.com/opencode-ai/opencode/internal/tui/styles\"\n)\n\nvar LogsPage PageID = \"logs\"\n\ntype LogPage interface {\n\ttea.Model\n\tlayout.Sizeable\n\tlayout.Bindings\n}\ntype logsPage struct {\n\twidth, height int\n\ttable layout.Container\n\tdetails layout.Container\n}\n\nfunc (p *logsPage) Update(msg tea.Msg) (tea.Model, tea.Cmd) {\n\tvar cmds []tea.Cmd\n\tswitch msg := msg.(type) {\n\tcase tea.WindowSizeMsg:\n\t\tp.width = msg.Width\n\t\tp.height = msg.Height\n\t\treturn p, p.SetSize(msg.Width, msg.Height)\n\t}\n\n\ttable, cmd := p.table.Update(msg)\n\tcmds = append(cmds, cmd)\n\tp.table = table.(layout.Container)\n\tdetails, cmd := p.details.Update(msg)\n\tcmds = append(cmds, cmd)\n\tp.details = details.(layout.Container)\n\n\treturn p, tea.Batch(cmds...)\n}\n\nfunc (p *logsPage) View() string {\n\tstyle := styles.BaseStyle().Width(p.width).Height(p.height)\n\treturn style.Render(lipgloss.JoinVertical(lipgloss.Top,\n\t\tp.table.View(),\n\t\tp.details.View(),\n\t))\n}\n\nfunc (p *logsPage) BindingKeys() []key.Binding {\n\treturn p.table.BindingKeys()\n}\n\n// GetSize implements LogPage.\nfunc (p *logsPage) GetSize() (int, int) {\n\treturn p.width, p.height\n}\n\n// SetSize implements LogPage.\nfunc (p *logsPage) SetSize(width int, height int) tea.Cmd {\n\tp.width = width\n\tp.height = height\n\treturn tea.Batch(\n\t\tp.table.SetSize(width, height/2),\n\t\tp.details.SetSize(width, height/2),\n\t)\n}\n\nfunc (p *logsPage) Init() tea.Cmd {\n\treturn tea.Batch(\n\t\tp.table.Init(),\n\t\tp.details.Init(),\n\t)\n}\n\nfunc NewLogsPage() LogPage {\n\treturn &logsPage{\n\t\ttable: layout.NewContainer(logs.NewLogsTable(), layout.WithBorderAll()),\n\t\tdetails: layout.NewContainer(logs.NewLogsDetails(), layout.WithBorderAll()),\n\t}\n}\n"], ["/opencode/internal/diff/diff.go", "package diff\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\"\n\t\"regexp\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"github.com/alecthomas/chroma/v2\"\n\t\"github.com/alecthomas/chroma/v2/formatters\"\n\t\"github.com/alecthomas/chroma/v2/lexers\"\n\t\"github.com/alecthomas/chroma/v2/styles\"\n\t\"github.com/aymanbagabas/go-udiff\"\n\t\"github.com/charmbracelet/lipgloss\"\n\t\"github.com/charmbracelet/x/ansi\"\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n\t\"github.com/sergi/go-diff/diffmatchpatch\"\n)\n\n// -------------------------------------------------------------------------\n// Core Types\n// -------------------------------------------------------------------------\n\n// LineType represents the kind of line in a diff.\ntype LineType int\n\nconst (\n\tLineContext LineType = iota // Line exists in both files\n\tLineAdded // Line added in the new file\n\tLineRemoved // Line removed from the old file\n)\n\n// Segment represents a portion of a line for intra-line highlighting\ntype Segment struct {\n\tStart int\n\tEnd int\n\tType LineType\n\tText string\n}\n\n// DiffLine represents a single line in a diff\ntype DiffLine struct {\n\tOldLineNo int // Line number in old file (0 for added lines)\n\tNewLineNo int // Line number in new file (0 for removed lines)\n\tKind LineType // Type of line (added, removed, context)\n\tContent string // Content of the line\n\tSegments []Segment // Segments for intraline highlighting\n}\n\n// Hunk represents a section of changes in a diff\ntype Hunk struct {\n\tHeader string\n\tLines []DiffLine\n}\n\n// DiffResult contains the parsed result of a diff\ntype DiffResult struct {\n\tOldFile string\n\tNewFile string\n\tHunks []Hunk\n}\n\n// linePair represents a pair of lines for side-by-side display\ntype linePair struct {\n\tleft *DiffLine\n\tright *DiffLine\n}\n\n// -------------------------------------------------------------------------\n// Parse Configuration\n// -------------------------------------------------------------------------\n\n// ParseConfig configures the behavior of diff parsing\ntype ParseConfig struct {\n\tContextSize int // Number of context lines to include\n}\n\n// ParseOption modifies a ParseConfig\ntype ParseOption func(*ParseConfig)\n\n// WithContextSize sets the number of context lines to include\nfunc WithContextSize(size int) ParseOption {\n\treturn func(p *ParseConfig) {\n\t\tif size >= 0 {\n\t\t\tp.ContextSize = size\n\t\t}\n\t}\n}\n\n// -------------------------------------------------------------------------\n// Side-by-Side Configuration\n// -------------------------------------------------------------------------\n\n// SideBySideConfig configures the rendering of side-by-side diffs\ntype SideBySideConfig struct {\n\tTotalWidth int\n}\n\n// SideBySideOption modifies a SideBySideConfig\ntype SideBySideOption func(*SideBySideConfig)\n\n// NewSideBySideConfig creates a SideBySideConfig with default values\nfunc NewSideBySideConfig(opts ...SideBySideOption) SideBySideConfig {\n\tconfig := SideBySideConfig{\n\t\tTotalWidth: 160, // Default width for side-by-side view\n\t}\n\n\tfor _, opt := range opts {\n\t\topt(&config)\n\t}\n\n\treturn config\n}\n\n// WithTotalWidth sets the total width for side-by-side view\nfunc WithTotalWidth(width int) SideBySideOption {\n\treturn func(s *SideBySideConfig) {\n\t\tif width > 0 {\n\t\t\ts.TotalWidth = width\n\t\t}\n\t}\n}\n\n// -------------------------------------------------------------------------\n// Diff Parsing\n// -------------------------------------------------------------------------\n\n// ParseUnifiedDiff parses a unified diff format string into structured data\nfunc ParseUnifiedDiff(diff string) (DiffResult, error) {\n\tvar result DiffResult\n\tvar currentHunk *Hunk\n\n\thunkHeaderRe := regexp.MustCompile(`^@@ -(\\d+),?(\\d*) \\+(\\d+),?(\\d*) @@`)\n\tlines := strings.Split(diff, \"\\n\")\n\n\tvar oldLine, newLine int\n\tinFileHeader := true\n\n\tfor _, line := range lines {\n\t\t// Parse file headers\n\t\tif inFileHeader {\n\t\t\tif strings.HasPrefix(line, \"--- a/\") {\n\t\t\t\tresult.OldFile = strings.TrimPrefix(line, \"--- a/\")\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif strings.HasPrefix(line, \"+++ b/\") {\n\t\t\t\tresult.NewFile = strings.TrimPrefix(line, \"+++ b/\")\n\t\t\t\tinFileHeader = false\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\n\t\t// Parse hunk headers\n\t\tif matches := hunkHeaderRe.FindStringSubmatch(line); matches != nil {\n\t\t\tif currentHunk != nil {\n\t\t\t\tresult.Hunks = append(result.Hunks, *currentHunk)\n\t\t\t}\n\t\t\tcurrentHunk = &Hunk{\n\t\t\t\tHeader: line,\n\t\t\t\tLines: []DiffLine{},\n\t\t\t}\n\n\t\t\toldStart, _ := strconv.Atoi(matches[1])\n\t\t\tnewStart, _ := strconv.Atoi(matches[3])\n\t\t\toldLine = oldStart\n\t\t\tnewLine = newStart\n\t\t\tcontinue\n\t\t}\n\n\t\t// Ignore \"No newline at end of file\" markers\n\t\tif strings.HasPrefix(line, \"\\\\ No newline at end of file\") {\n\t\t\tcontinue\n\t\t}\n\n\t\tif currentHunk == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\t// Process the line based on its prefix\n\t\tif len(line) > 0 {\n\t\t\tswitch line[0] {\n\t\t\tcase '+':\n\t\t\t\tcurrentHunk.Lines = append(currentHunk.Lines, DiffLine{\n\t\t\t\t\tOldLineNo: 0,\n\t\t\t\t\tNewLineNo: newLine,\n\t\t\t\t\tKind: LineAdded,\n\t\t\t\t\tContent: line[1:],\n\t\t\t\t})\n\t\t\t\tnewLine++\n\t\t\tcase '-':\n\t\t\t\tcurrentHunk.Lines = append(currentHunk.Lines, DiffLine{\n\t\t\t\t\tOldLineNo: oldLine,\n\t\t\t\t\tNewLineNo: 0,\n\t\t\t\t\tKind: LineRemoved,\n\t\t\t\t\tContent: line[1:],\n\t\t\t\t})\n\t\t\t\toldLine++\n\t\t\tdefault:\n\t\t\t\tcurrentHunk.Lines = append(currentHunk.Lines, DiffLine{\n\t\t\t\t\tOldLineNo: oldLine,\n\t\t\t\t\tNewLineNo: newLine,\n\t\t\t\t\tKind: LineContext,\n\t\t\t\t\tContent: line,\n\t\t\t\t})\n\t\t\t\toldLine++\n\t\t\t\tnewLine++\n\t\t\t}\n\t\t} else {\n\t\t\t// Handle empty lines\n\t\t\tcurrentHunk.Lines = append(currentHunk.Lines, DiffLine{\n\t\t\t\tOldLineNo: oldLine,\n\t\t\t\tNewLineNo: newLine,\n\t\t\t\tKind: LineContext,\n\t\t\t\tContent: \"\",\n\t\t\t})\n\t\t\toldLine++\n\t\t\tnewLine++\n\t\t}\n\t}\n\n\t// Add the last hunk if there is one\n\tif currentHunk != nil {\n\t\tresult.Hunks = append(result.Hunks, *currentHunk)\n\t}\n\n\treturn result, nil\n}\n\n// HighlightIntralineChanges updates lines in a hunk to show character-level differences\nfunc HighlightIntralineChanges(h *Hunk) {\n\tvar updated []DiffLine\n\tdmp := diffmatchpatch.New()\n\n\tfor i := 0; i < len(h.Lines); i++ {\n\t\t// Look for removed line followed by added line\n\t\tif i+1 < len(h.Lines) &&\n\t\t\th.Lines[i].Kind == LineRemoved &&\n\t\t\th.Lines[i+1].Kind == LineAdded {\n\n\t\t\toldLine := h.Lines[i]\n\t\t\tnewLine := h.Lines[i+1]\n\n\t\t\t// Find character-level differences\n\t\t\tpatches := dmp.DiffMain(oldLine.Content, newLine.Content, false)\n\t\t\tpatches = dmp.DiffCleanupSemantic(patches)\n\t\t\tpatches = dmp.DiffCleanupMerge(patches)\n\t\t\tpatches = dmp.DiffCleanupEfficiency(patches)\n\n\t\t\tsegments := make([]Segment, 0)\n\n\t\t\tremoveStart := 0\n\t\t\taddStart := 0\n\t\t\tfor _, patch := range patches {\n\t\t\t\tswitch patch.Type {\n\t\t\t\tcase diffmatchpatch.DiffDelete:\n\t\t\t\t\tsegments = append(segments, Segment{\n\t\t\t\t\t\tStart: removeStart,\n\t\t\t\t\t\tEnd: removeStart + len(patch.Text),\n\t\t\t\t\t\tType: LineRemoved,\n\t\t\t\t\t\tText: patch.Text,\n\t\t\t\t\t})\n\t\t\t\t\tremoveStart += len(patch.Text)\n\t\t\t\tcase diffmatchpatch.DiffInsert:\n\t\t\t\t\tsegments = append(segments, Segment{\n\t\t\t\t\t\tStart: addStart,\n\t\t\t\t\t\tEnd: addStart + len(patch.Text),\n\t\t\t\t\t\tType: LineAdded,\n\t\t\t\t\t\tText: patch.Text,\n\t\t\t\t\t})\n\t\t\t\t\taddStart += len(patch.Text)\n\t\t\t\tdefault:\n\t\t\t\t\t// Context text, no highlighting needed\n\t\t\t\t\tremoveStart += len(patch.Text)\n\t\t\t\t\taddStart += len(patch.Text)\n\t\t\t\t}\n\t\t\t}\n\t\t\toldLine.Segments = segments\n\t\t\tnewLine.Segments = segments\n\n\t\t\tupdated = append(updated, oldLine, newLine)\n\t\t\ti++ // Skip the next line as we've already processed it\n\t\t} else {\n\t\t\tupdated = append(updated, h.Lines[i])\n\t\t}\n\t}\n\n\th.Lines = updated\n}\n\n// pairLines converts a flat list of diff lines to pairs for side-by-side display\nfunc pairLines(lines []DiffLine) []linePair {\n\tvar pairs []linePair\n\ti := 0\n\n\tfor i < len(lines) {\n\t\tswitch lines[i].Kind {\n\t\tcase LineRemoved:\n\t\t\t// Check if the next line is an addition, if so pair them\n\t\t\tif i+1 < len(lines) && lines[i+1].Kind == LineAdded {\n\t\t\t\tpairs = append(pairs, linePair{left: &lines[i], right: &lines[i+1]})\n\t\t\t\ti += 2\n\t\t\t} else {\n\t\t\t\tpairs = append(pairs, linePair{left: &lines[i], right: nil})\n\t\t\t\ti++\n\t\t\t}\n\t\tcase LineAdded:\n\t\t\tpairs = append(pairs, linePair{left: nil, right: &lines[i]})\n\t\t\ti++\n\t\tcase LineContext:\n\t\t\tpairs = append(pairs, linePair{left: &lines[i], right: &lines[i]})\n\t\t\ti++\n\t\t}\n\t}\n\n\treturn pairs\n}\n\n// -------------------------------------------------------------------------\n// Syntax Highlighting\n// -------------------------------------------------------------------------\n\n// SyntaxHighlight applies syntax highlighting to text based on file extension\nfunc SyntaxHighlight(w io.Writer, source, fileName, formatter string, bg lipgloss.TerminalColor) error {\n\tt := theme.CurrentTheme()\n\n\t// Determine the language lexer to use\n\tl := lexers.Match(fileName)\n\tif l == nil {\n\t\tl = lexers.Analyse(source)\n\t}\n\tif l == nil {\n\t\tl = lexers.Fallback\n\t}\n\tl = chroma.Coalesce(l)\n\n\t// Get the formatter\n\tf := formatters.Get(formatter)\n\tif f == nil {\n\t\tf = formatters.Fallback\n\t}\n\n\t// Dynamic theme based on current theme values\n\tsyntaxThemeXml := fmt.Sprintf(`\n\t\n`,\n\t\tgetColor(t.Background()), // Background\n\t\tgetColor(t.Text()), // Text\n\t\tgetColor(t.Text()), // Other\n\t\tgetColor(t.Error()), // Error\n\n\t\tgetColor(t.SyntaxKeyword()), // Keyword\n\t\tgetColor(t.SyntaxKeyword()), // KeywordConstant\n\t\tgetColor(t.SyntaxKeyword()), // KeywordDeclaration\n\t\tgetColor(t.SyntaxKeyword()), // KeywordNamespace\n\t\tgetColor(t.SyntaxKeyword()), // KeywordPseudo\n\t\tgetColor(t.SyntaxKeyword()), // KeywordReserved\n\t\tgetColor(t.SyntaxType()), // KeywordType\n\n\t\tgetColor(t.Text()), // Name\n\t\tgetColor(t.SyntaxVariable()), // NameAttribute\n\t\tgetColor(t.SyntaxType()), // NameBuiltin\n\t\tgetColor(t.SyntaxVariable()), // NameBuiltinPseudo\n\t\tgetColor(t.SyntaxType()), // NameClass\n\t\tgetColor(t.SyntaxVariable()), // NameConstant\n\t\tgetColor(t.SyntaxFunction()), // NameDecorator\n\t\tgetColor(t.SyntaxVariable()), // NameEntity\n\t\tgetColor(t.SyntaxType()), // NameException\n\t\tgetColor(t.SyntaxFunction()), // NameFunction\n\t\tgetColor(t.Text()), // NameLabel\n\t\tgetColor(t.SyntaxType()), // NameNamespace\n\t\tgetColor(t.SyntaxVariable()), // NameOther\n\t\tgetColor(t.SyntaxKeyword()), // NameTag\n\t\tgetColor(t.SyntaxVariable()), // NameVariable\n\t\tgetColor(t.SyntaxVariable()), // NameVariableClass\n\t\tgetColor(t.SyntaxVariable()), // NameVariableGlobal\n\t\tgetColor(t.SyntaxVariable()), // NameVariableInstance\n\n\t\tgetColor(t.SyntaxString()), // Literal\n\t\tgetColor(t.SyntaxString()), // LiteralDate\n\t\tgetColor(t.SyntaxString()), // LiteralString\n\t\tgetColor(t.SyntaxString()), // LiteralStringBacktick\n\t\tgetColor(t.SyntaxString()), // LiteralStringChar\n\t\tgetColor(t.SyntaxString()), // LiteralStringDoc\n\t\tgetColor(t.SyntaxString()), // LiteralStringDouble\n\t\tgetColor(t.SyntaxString()), // LiteralStringEscape\n\t\tgetColor(t.SyntaxString()), // LiteralStringHeredoc\n\t\tgetColor(t.SyntaxString()), // LiteralStringInterpol\n\t\tgetColor(t.SyntaxString()), // LiteralStringOther\n\t\tgetColor(t.SyntaxString()), // LiteralStringRegex\n\t\tgetColor(t.SyntaxString()), // LiteralStringSingle\n\t\tgetColor(t.SyntaxString()), // LiteralStringSymbol\n\n\t\tgetColor(t.SyntaxNumber()), // LiteralNumber\n\t\tgetColor(t.SyntaxNumber()), // LiteralNumberBin\n\t\tgetColor(t.SyntaxNumber()), // LiteralNumberFloat\n\t\tgetColor(t.SyntaxNumber()), // LiteralNumberHex\n\t\tgetColor(t.SyntaxNumber()), // LiteralNumberInteger\n\t\tgetColor(t.SyntaxNumber()), // LiteralNumberIntegerLong\n\t\tgetColor(t.SyntaxNumber()), // LiteralNumberOct\n\n\t\tgetColor(t.SyntaxOperator()), // Operator\n\t\tgetColor(t.SyntaxKeyword()), // OperatorWord\n\t\tgetColor(t.SyntaxPunctuation()), // Punctuation\n\n\t\tgetColor(t.SyntaxComment()), // Comment\n\t\tgetColor(t.SyntaxComment()), // CommentHashbang\n\t\tgetColor(t.SyntaxComment()), // CommentMultiline\n\t\tgetColor(t.SyntaxComment()), // CommentSingle\n\t\tgetColor(t.SyntaxComment()), // CommentSpecial\n\t\tgetColor(t.SyntaxKeyword()), // CommentPreproc\n\n\t\tgetColor(t.Text()), // Generic\n\t\tgetColor(t.Error()), // GenericDeleted\n\t\tgetColor(t.Text()), // GenericEmph\n\t\tgetColor(t.Error()), // GenericError\n\t\tgetColor(t.Text()), // GenericHeading\n\t\tgetColor(t.Success()), // GenericInserted\n\t\tgetColor(t.TextMuted()), // GenericOutput\n\t\tgetColor(t.Text()), // GenericPrompt\n\t\tgetColor(t.Text()), // GenericStrong\n\t\tgetColor(t.Text()), // GenericSubheading\n\t\tgetColor(t.Error()), // GenericTraceback\n\t\tgetColor(t.Text()), // TextWhitespace\n\t)\n\n\tr := strings.NewReader(syntaxThemeXml)\n\tstyle := chroma.MustNewXMLStyle(r)\n\n\t// Modify the style to use the provided background\n\ts, err := style.Builder().Transform(\n\t\tfunc(t chroma.StyleEntry) chroma.StyleEntry {\n\t\t\tr, g, b, _ := bg.RGBA()\n\t\t\tt.Background = chroma.NewColour(uint8(r>>8), uint8(g>>8), uint8(b>>8))\n\t\t\treturn t\n\t\t},\n\t).Build()\n\tif err != nil {\n\t\ts = styles.Fallback\n\t}\n\n\t// Tokenize and format\n\tit, err := l.Tokenise(nil, source)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn f.Format(w, s, it)\n}\n\n// getColor returns the appropriate hex color string based on terminal background\nfunc getColor(adaptiveColor lipgloss.AdaptiveColor) string {\n\tif lipgloss.HasDarkBackground() {\n\t\treturn adaptiveColor.Dark\n\t}\n\treturn adaptiveColor.Light\n}\n\n// highlightLine applies syntax highlighting to a single line\nfunc highlightLine(fileName string, line string, bg lipgloss.TerminalColor) string {\n\tvar buf bytes.Buffer\n\terr := SyntaxHighlight(&buf, line, fileName, \"terminal16m\", bg)\n\tif err != nil {\n\t\treturn line\n\t}\n\treturn buf.String()\n}\n\n// createStyles generates the lipgloss styles needed for rendering diffs\nfunc createStyles(t theme.Theme) (removedLineStyle, addedLineStyle, contextLineStyle, lineNumberStyle lipgloss.Style) {\n\tremovedLineStyle = lipgloss.NewStyle().Background(t.DiffRemovedBg())\n\taddedLineStyle = lipgloss.NewStyle().Background(t.DiffAddedBg())\n\tcontextLineStyle = lipgloss.NewStyle().Background(t.DiffContextBg())\n\tlineNumberStyle = lipgloss.NewStyle().Foreground(t.DiffLineNumber())\n\n\treturn\n}\n\n// -------------------------------------------------------------------------\n// Rendering Functions\n// -------------------------------------------------------------------------\n\nfunc lipglossToHex(color lipgloss.Color) string {\n\tr, g, b, a := color.RGBA()\n\n\t// Scale uint32 values (0-65535) to uint8 (0-255).\n\tr8 := uint8(r >> 8)\n\tg8 := uint8(g >> 8)\n\tb8 := uint8(b >> 8)\n\ta8 := uint8(a >> 8)\n\n\treturn fmt.Sprintf(\"#%02x%02x%02x%02x\", r8, g8, b8, a8)\n}\n\n// applyHighlighting applies intra-line highlighting to a piece of text\nfunc applyHighlighting(content string, segments []Segment, segmentType LineType, highlightBg lipgloss.AdaptiveColor) string {\n\t// Find all ANSI sequences in the content\n\tansiRegex := regexp.MustCompile(`\\x1b(?:[@-Z\\\\-_]|\\[[0-9?]*(?:;[0-9?]*)*[@-~])`)\n\tansiMatches := ansiRegex.FindAllStringIndex(content, -1)\n\n\t// Build a mapping of visible character positions to their actual indices\n\tvisibleIdx := 0\n\tansiSequences := make(map[int]string)\n\tlastAnsiSeq := \"\\x1b[0m\" // Default reset sequence\n\n\tfor i := 0; i < len(content); {\n\t\tisAnsi := false\n\t\tfor _, match := range ansiMatches {\n\t\t\tif match[0] == i {\n\t\t\t\tansiSequences[visibleIdx] = content[match[0]:match[1]]\n\t\t\t\tlastAnsiSeq = content[match[0]:match[1]]\n\t\t\t\ti = match[1]\n\t\t\t\tisAnsi = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif isAnsi {\n\t\t\tcontinue\n\t\t}\n\n\t\t// For non-ANSI positions, store the last ANSI sequence\n\t\tif _, exists := ansiSequences[visibleIdx]; !exists {\n\t\t\tansiSequences[visibleIdx] = lastAnsiSeq\n\t\t}\n\t\tvisibleIdx++\n\t\ti++\n\t}\n\n\t// Apply highlighting\n\tvar sb strings.Builder\n\tinSelection := false\n\tcurrentPos := 0\n\n\t// Get the appropriate color based on terminal background\n\tbgColor := lipgloss.Color(getColor(highlightBg))\n\tfgColor := lipgloss.Color(getColor(theme.CurrentTheme().Background()))\n\n\tfor i := 0; i < len(content); {\n\t\t// Check if we're at an ANSI sequence\n\t\tisAnsi := false\n\t\tfor _, match := range ansiMatches {\n\t\t\tif match[0] == i {\n\t\t\t\tsb.WriteString(content[match[0]:match[1]]) // Preserve ANSI sequence\n\t\t\t\ti = match[1]\n\t\t\t\tisAnsi = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif isAnsi {\n\t\t\tcontinue\n\t\t}\n\n\t\t// Check for segment boundaries\n\t\tfor _, seg := range segments {\n\t\t\tif seg.Type == segmentType {\n\t\t\t\tif currentPos == seg.Start {\n\t\t\t\t\tinSelection = true\n\t\t\t\t}\n\t\t\t\tif currentPos == seg.End {\n\t\t\t\t\tinSelection = false\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Get current character\n\t\tchar := string(content[i])\n\n\t\tif inSelection {\n\t\t\t// Get the current styling\n\t\t\tcurrentStyle := ansiSequences[currentPos]\n\n\t\t\t// Apply foreground and background highlight\n\t\t\tsb.WriteString(\"\\x1b[38;2;\")\n\t\t\tr, g, b, _ := fgColor.RGBA()\n\t\t\tsb.WriteString(fmt.Sprintf(\"%d;%d;%dm\", r>>8, g>>8, b>>8))\n\t\t\tsb.WriteString(\"\\x1b[48;2;\")\n\t\t\tr, g, b, _ = bgColor.RGBA()\n\t\t\tsb.WriteString(fmt.Sprintf(\"%d;%d;%dm\", r>>8, g>>8, b>>8))\n\t\t\tsb.WriteString(char)\n\t\t\t// Reset foreground and background\n\t\t\tsb.WriteString(\"\\x1b[39m\")\n\n\t\t\t// Reapply the original ANSI sequence\n\t\t\tsb.WriteString(currentStyle)\n\t\t} else {\n\t\t\t// Not in selection, just copy the character\n\t\t\tsb.WriteString(char)\n\t\t}\n\n\t\tcurrentPos++\n\t\ti++\n\t}\n\n\treturn sb.String()\n}\n\n// renderLeftColumn formats the left side of a side-by-side diff\nfunc renderLeftColumn(fileName string, dl *DiffLine, colWidth int) string {\n\tt := theme.CurrentTheme()\n\n\tif dl == nil {\n\t\tcontextLineStyle := lipgloss.NewStyle().Background(t.DiffContextBg())\n\t\treturn contextLineStyle.Width(colWidth).Render(\"\")\n\t}\n\n\tremovedLineStyle, _, contextLineStyle, lineNumberStyle := createStyles(t)\n\n\t// Determine line style based on line type\n\tvar marker string\n\tvar bgStyle lipgloss.Style\n\tswitch dl.Kind {\n\tcase LineRemoved:\n\t\tmarker = removedLineStyle.Foreground(t.DiffRemoved()).Render(\"-\")\n\t\tbgStyle = removedLineStyle\n\t\tlineNumberStyle = lineNumberStyle.Foreground(t.DiffRemoved()).Background(t.DiffRemovedLineNumberBg())\n\tcase LineAdded:\n\t\tmarker = \"?\"\n\t\tbgStyle = contextLineStyle\n\tcase LineContext:\n\t\tmarker = contextLineStyle.Render(\" \")\n\t\tbgStyle = contextLineStyle\n\t}\n\n\t// Format line number\n\tlineNum := \"\"\n\tif dl.OldLineNo > 0 {\n\t\tlineNum = fmt.Sprintf(\"%6d\", dl.OldLineNo)\n\t}\n\n\t// Create the line prefix\n\tprefix := lineNumberStyle.Render(lineNum + \" \" + marker)\n\n\t// Apply syntax highlighting\n\tcontent := highlightLine(fileName, dl.Content, bgStyle.GetBackground())\n\n\t// Apply intra-line highlighting for removed lines\n\tif dl.Kind == LineRemoved && len(dl.Segments) > 0 {\n\t\tcontent = applyHighlighting(content, dl.Segments, LineRemoved, t.DiffHighlightRemoved())\n\t}\n\n\t// Add a padding space for removed lines\n\tif dl.Kind == LineRemoved {\n\t\tcontent = bgStyle.Render(\" \") + content\n\t}\n\n\t// Create the final line and truncate if needed\n\tlineText := prefix + content\n\treturn bgStyle.MaxHeight(1).Width(colWidth).Render(\n\t\tansi.Truncate(\n\t\t\tlineText,\n\t\t\tcolWidth,\n\t\t\tlipgloss.NewStyle().Background(bgStyle.GetBackground()).Foreground(t.TextMuted()).Render(\"...\"),\n\t\t),\n\t)\n}\n\n// renderRightColumn formats the right side of a side-by-side diff\nfunc renderRightColumn(fileName string, dl *DiffLine, colWidth int) string {\n\tt := theme.CurrentTheme()\n\n\tif dl == nil {\n\t\tcontextLineStyle := lipgloss.NewStyle().Background(t.DiffContextBg())\n\t\treturn contextLineStyle.Width(colWidth).Render(\"\")\n\t}\n\n\t_, addedLineStyle, contextLineStyle, lineNumberStyle := createStyles(t)\n\n\t// Determine line style based on line type\n\tvar marker string\n\tvar bgStyle lipgloss.Style\n\tswitch dl.Kind {\n\tcase LineAdded:\n\t\tmarker = addedLineStyle.Foreground(t.DiffAdded()).Render(\"+\")\n\t\tbgStyle = addedLineStyle\n\t\tlineNumberStyle = lineNumberStyle.Foreground(t.DiffAdded()).Background(t.DiffAddedLineNumberBg())\n\tcase LineRemoved:\n\t\tmarker = \"?\"\n\t\tbgStyle = contextLineStyle\n\tcase LineContext:\n\t\tmarker = contextLineStyle.Render(\" \")\n\t\tbgStyle = contextLineStyle\n\t}\n\n\t// Format line number\n\tlineNum := \"\"\n\tif dl.NewLineNo > 0 {\n\t\tlineNum = fmt.Sprintf(\"%6d\", dl.NewLineNo)\n\t}\n\n\t// Create the line prefix\n\tprefix := lineNumberStyle.Render(lineNum + \" \" + marker)\n\n\t// Apply syntax highlighting\n\tcontent := highlightLine(fileName, dl.Content, bgStyle.GetBackground())\n\n\t// Apply intra-line highlighting for added lines\n\tif dl.Kind == LineAdded && len(dl.Segments) > 0 {\n\t\tcontent = applyHighlighting(content, dl.Segments, LineAdded, t.DiffHighlightAdded())\n\t}\n\n\t// Add a padding space for added lines\n\tif dl.Kind == LineAdded {\n\t\tcontent = bgStyle.Render(\" \") + content\n\t}\n\n\t// Create the final line and truncate if needed\n\tlineText := prefix + content\n\treturn bgStyle.MaxHeight(1).Width(colWidth).Render(\n\t\tansi.Truncate(\n\t\t\tlineText,\n\t\t\tcolWidth,\n\t\t\tlipgloss.NewStyle().Background(bgStyle.GetBackground()).Foreground(t.TextMuted()).Render(\"...\"),\n\t\t),\n\t)\n}\n\n// -------------------------------------------------------------------------\n// Public API\n// -------------------------------------------------------------------------\n\n// RenderSideBySideHunk formats a hunk for side-by-side display\nfunc RenderSideBySideHunk(fileName string, h Hunk, opts ...SideBySideOption) string {\n\t// Apply options to create the configuration\n\tconfig := NewSideBySideConfig(opts...)\n\n\t// Make a copy of the hunk so we don't modify the original\n\thunkCopy := Hunk{Lines: make([]DiffLine, len(h.Lines))}\n\tcopy(hunkCopy.Lines, h.Lines)\n\n\t// Highlight changes within lines\n\tHighlightIntralineChanges(&hunkCopy)\n\n\t// Pair lines for side-by-side display\n\tpairs := pairLines(hunkCopy.Lines)\n\n\t// Calculate column width\n\tcolWidth := config.TotalWidth / 2\n\n\tleftWidth := colWidth\n\trightWidth := config.TotalWidth - colWidth\n\tvar sb strings.Builder\n\tfor _, p := range pairs {\n\t\tleftStr := renderLeftColumn(fileName, p.left, leftWidth)\n\t\trightStr := renderRightColumn(fileName, p.right, rightWidth)\n\t\tsb.WriteString(leftStr + rightStr + \"\\n\")\n\t}\n\n\treturn sb.String()\n}\n\n// FormatDiff creates a side-by-side formatted view of a diff\nfunc FormatDiff(diffText string, opts ...SideBySideOption) (string, error) {\n\tdiffResult, err := ParseUnifiedDiff(diffText)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tvar sb strings.Builder\n\tfor _, h := range diffResult.Hunks {\n\t\tsb.WriteString(RenderSideBySideHunk(diffResult.OldFile, h, opts...))\n\t}\n\n\treturn sb.String(), nil\n}\n\n// GenerateDiff creates a unified diff from two file contents\nfunc GenerateDiff(beforeContent, afterContent, fileName string) (string, int, int) {\n\t// remove the cwd prefix and ensure consistent path format\n\t// this prevents issues with absolute paths in different environments\n\tcwd := config.WorkingDirectory()\n\tfileName = strings.TrimPrefix(fileName, cwd)\n\tfileName = strings.TrimPrefix(fileName, \"/\")\n\n\tvar (\n\t\tunified = udiff.Unified(\"a/\"+fileName, \"b/\"+fileName, beforeContent, afterContent)\n\t\tadditions = 0\n\t\tremovals = 0\n\t)\n\n\tlines := strings.SplitSeq(unified, \"\\n\")\n\tfor line := range lines {\n\t\tif strings.HasPrefix(line, \"+\") && !strings.HasPrefix(line, \"+++\") {\n\t\t\tadditions++\n\t\t} else if strings.HasPrefix(line, \"-\") && !strings.HasPrefix(line, \"---\") {\n\t\t\tremovals++\n\t\t}\n\t}\n\n\treturn unified, additions, removals\n}\n"], ["/opencode/internal/tui/layout/overlay.go", "package layout\n\nimport (\n\t\"strings\"\n\n\t\"github.com/charmbracelet/lipgloss\"\n\tchAnsi \"github.com/charmbracelet/x/ansi\"\n\t\"github.com/muesli/ansi\"\n\t\"github.com/muesli/reflow/truncate\"\n\t\"github.com/muesli/termenv\"\n\t\"github.com/opencode-ai/opencode/internal/tui/styles\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n\t\"github.com/opencode-ai/opencode/internal/tui/util\"\n)\n\n// Most of this code is borrowed from\n// https://github.com/charmbracelet/lipgloss/pull/102\n// as well as the lipgloss library, with some modification for what I needed.\n\n// Split a string into lines, additionally returning the size of the widest\n// line.\nfunc getLines(s string) (lines []string, widest int) {\n\tlines = strings.Split(s, \"\\n\")\n\n\tfor _, l := range lines {\n\t\tw := ansi.PrintableRuneWidth(l)\n\t\tif widest < w {\n\t\t\twidest = w\n\t\t}\n\t}\n\n\treturn lines, widest\n}\n\n// PlaceOverlay places fg on top of bg.\nfunc PlaceOverlay(\n\tx, y int,\n\tfg, bg string,\n\tshadow bool, opts ...WhitespaceOption,\n) string {\n\tfgLines, fgWidth := getLines(fg)\n\tbgLines, bgWidth := getLines(bg)\n\tbgHeight := len(bgLines)\n\tfgHeight := len(fgLines)\n\n\tif shadow {\n\t\tt := theme.CurrentTheme()\n\t\tbaseStyle := styles.BaseStyle()\n\n\t\tvar shadowbg string = \"\"\n\t\tshadowchar := lipgloss.NewStyle().\n\t\t\tBackground(t.BackgroundDarker()).\n\t\t\tForeground(t.Background()).\n\t\t\tRender(\"░\")\n\t\tbgchar := baseStyle.Render(\" \")\n\t\tfor i := 0; i <= fgHeight; i++ {\n\t\t\tif i == 0 {\n\t\t\t\tshadowbg += bgchar + strings.Repeat(bgchar, fgWidth) + \"\\n\"\n\t\t\t} else {\n\t\t\t\tshadowbg += bgchar + strings.Repeat(shadowchar, fgWidth) + \"\\n\"\n\t\t\t}\n\t\t}\n\n\t\tfg = PlaceOverlay(0, 0, fg, shadowbg, false, opts...)\n\t\tfgLines, fgWidth = getLines(fg)\n\t\tfgHeight = len(fgLines)\n\t}\n\n\tif fgWidth >= bgWidth && fgHeight >= bgHeight {\n\t\t// FIXME: return fg or bg?\n\t\treturn fg\n\t}\n\t// TODO: allow placement outside of the bg box?\n\tx = util.Clamp(x, 0, bgWidth-fgWidth)\n\ty = util.Clamp(y, 0, bgHeight-fgHeight)\n\n\tws := &whitespace{}\n\tfor _, opt := range opts {\n\t\topt(ws)\n\t}\n\n\tvar b strings.Builder\n\tfor i, bgLine := range bgLines {\n\t\tif i > 0 {\n\t\t\tb.WriteByte('\\n')\n\t\t}\n\t\tif i < y || i >= y+fgHeight {\n\t\t\tb.WriteString(bgLine)\n\t\t\tcontinue\n\t\t}\n\n\t\tpos := 0\n\t\tif x > 0 {\n\t\t\tleft := truncate.String(bgLine, uint(x))\n\t\t\tpos = ansi.PrintableRuneWidth(left)\n\t\t\tb.WriteString(left)\n\t\t\tif pos < x {\n\t\t\t\tb.WriteString(ws.render(x - pos))\n\t\t\t\tpos = x\n\t\t\t}\n\t\t}\n\n\t\tfgLine := fgLines[i-y]\n\t\tb.WriteString(fgLine)\n\t\tpos += ansi.PrintableRuneWidth(fgLine)\n\n\t\tright := cutLeft(bgLine, pos)\n\t\tbgWidth := ansi.PrintableRuneWidth(bgLine)\n\t\trightWidth := ansi.PrintableRuneWidth(right)\n\t\tif rightWidth <= bgWidth-pos {\n\t\t\tb.WriteString(ws.render(bgWidth - rightWidth - pos))\n\t\t}\n\n\t\tb.WriteString(right)\n\t}\n\n\treturn b.String()\n}\n\n// cutLeft cuts printable characters from the left.\n// This function is heavily based on muesli's ansi and truncate packages.\nfunc cutLeft(s string, cutWidth int) string {\n\treturn chAnsi.Cut(s, cutWidth, lipgloss.Width(s))\n}\n\nfunc max(a, b int) int {\n\tif a > b {\n\t\treturn a\n\t}\n\treturn b\n}\n\ntype whitespace struct {\n\tstyle termenv.Style\n\tchars string\n}\n\n// Render whitespaces.\nfunc (w whitespace) render(width int) string {\n\tif w.chars == \"\" {\n\t\tw.chars = \" \"\n\t}\n\n\tr := []rune(w.chars)\n\tj := 0\n\tb := strings.Builder{}\n\n\t// Cycle through runes and print them into the whitespace.\n\tfor i := 0; i < width; {\n\t\tb.WriteRune(r[j])\n\t\tj++\n\t\tif j >= len(r) {\n\t\t\tj = 0\n\t\t}\n\t\ti += ansi.PrintableRuneWidth(string(r[j]))\n\t}\n\n\t// Fill any extra gaps white spaces. This might be necessary if any runes\n\t// are more than one cell wide, which could leave a one-rune gap.\n\tshort := width - ansi.PrintableRuneWidth(b.String())\n\tif short > 0 {\n\t\tb.WriteString(strings.Repeat(\" \", short))\n\t}\n\n\treturn w.style.Styled(b.String())\n}\n\n// WhitespaceOption sets a styling rule for rendering whitespace.\ntype WhitespaceOption func(*whitespace)\n"], ["/opencode/internal/lsp/client.go", "package lsp\n\nimport (\n\t\"bufio\"\n\t\"context\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"os/exec\"\n\t\"path/filepath\"\n\t\"strings\"\n\t\"sync\"\n\t\"sync/atomic\"\n\t\"time\"\n\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n\t\"github.com/opencode-ai/opencode/internal/lsp/protocol\"\n)\n\ntype Client struct {\n\tCmd *exec.Cmd\n\tstdin io.WriteCloser\n\tstdout *bufio.Reader\n\tstderr io.ReadCloser\n\n\t// Request ID counter\n\tnextID atomic.Int32\n\n\t// Response handlers\n\thandlers map[int32]chan *Message\n\thandlersMu sync.RWMutex\n\n\t// Server request handlers\n\tserverRequestHandlers map[string]ServerRequestHandler\n\tserverHandlersMu sync.RWMutex\n\n\t// Notification handlers\n\tnotificationHandlers map[string]NotificationHandler\n\tnotificationMu sync.RWMutex\n\n\t// Diagnostic cache\n\tdiagnostics map[protocol.DocumentUri][]protocol.Diagnostic\n\tdiagnosticsMu sync.RWMutex\n\n\t// Files are currently opened by the LSP\n\topenFiles map[string]*OpenFileInfo\n\topenFilesMu sync.RWMutex\n\n\t// Server state\n\tserverState atomic.Value\n}\n\nfunc NewClient(ctx context.Context, command string, args ...string) (*Client, error) {\n\tcmd := exec.CommandContext(ctx, command, args...)\n\t// Copy env\n\tcmd.Env = os.Environ()\n\n\tstdin, err := cmd.StdinPipe()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to create stdin pipe: %w\", err)\n\t}\n\n\tstdout, err := cmd.StdoutPipe()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to create stdout pipe: %w\", err)\n\t}\n\n\tstderr, err := cmd.StderrPipe()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to create stderr pipe: %w\", err)\n\t}\n\n\tclient := &Client{\n\t\tCmd: cmd,\n\t\tstdin: stdin,\n\t\tstdout: bufio.NewReader(stdout),\n\t\tstderr: stderr,\n\t\thandlers: make(map[int32]chan *Message),\n\t\tnotificationHandlers: make(map[string]NotificationHandler),\n\t\tserverRequestHandlers: make(map[string]ServerRequestHandler),\n\t\tdiagnostics: make(map[protocol.DocumentUri][]protocol.Diagnostic),\n\t\topenFiles: make(map[string]*OpenFileInfo),\n\t}\n\n\t// Initialize server state\n\tclient.serverState.Store(StateStarting)\n\n\t// Start the LSP server process\n\tif err := cmd.Start(); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to start LSP server: %w\", err)\n\t}\n\n\t// Handle stderr in a separate goroutine\n\tgo func() {\n\t\tscanner := bufio.NewScanner(stderr)\n\t\tfor scanner.Scan() {\n\t\t\tfmt.Fprintf(os.Stderr, \"LSP Server: %s\\n\", scanner.Text())\n\t\t}\n\t\tif err := scanner.Err(); err != nil {\n\t\t\tfmt.Fprintf(os.Stderr, \"Error reading stderr: %v\\n\", err)\n\t\t}\n\t}()\n\n\t// Start message handling loop\n\tgo func() {\n\t\tdefer logging.RecoverPanic(\"LSP-message-handler\", func() {\n\t\t\tlogging.ErrorPersist(\"LSP message handler crashed, LSP functionality may be impaired\")\n\t\t})\n\t\tclient.handleMessages()\n\t}()\n\n\treturn client, nil\n}\n\nfunc (c *Client) RegisterNotificationHandler(method string, handler NotificationHandler) {\n\tc.notificationMu.Lock()\n\tdefer c.notificationMu.Unlock()\n\tc.notificationHandlers[method] = handler\n}\n\nfunc (c *Client) RegisterServerRequestHandler(method string, handler ServerRequestHandler) {\n\tc.serverHandlersMu.Lock()\n\tdefer c.serverHandlersMu.Unlock()\n\tc.serverRequestHandlers[method] = handler\n}\n\nfunc (c *Client) InitializeLSPClient(ctx context.Context, workspaceDir string) (*protocol.InitializeResult, error) {\n\tinitParams := &protocol.InitializeParams{\n\t\tWorkspaceFoldersInitializeParams: protocol.WorkspaceFoldersInitializeParams{\n\t\t\tWorkspaceFolders: []protocol.WorkspaceFolder{\n\t\t\t\t{\n\t\t\t\t\tURI: protocol.URI(\"file://\" + workspaceDir),\n\t\t\t\t\tName: workspaceDir,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\n\t\tXInitializeParams: protocol.XInitializeParams{\n\t\t\tProcessID: int32(os.Getpid()),\n\t\t\tClientInfo: &protocol.ClientInfo{\n\t\t\t\tName: \"mcp-language-server\",\n\t\t\t\tVersion: \"0.1.0\",\n\t\t\t},\n\t\t\tRootPath: workspaceDir,\n\t\t\tRootURI: protocol.DocumentUri(\"file://\" + workspaceDir),\n\t\t\tCapabilities: protocol.ClientCapabilities{\n\t\t\t\tWorkspace: protocol.WorkspaceClientCapabilities{\n\t\t\t\t\tConfiguration: true,\n\t\t\t\t\tDidChangeConfiguration: protocol.DidChangeConfigurationClientCapabilities{\n\t\t\t\t\t\tDynamicRegistration: true,\n\t\t\t\t\t},\n\t\t\t\t\tDidChangeWatchedFiles: protocol.DidChangeWatchedFilesClientCapabilities{\n\t\t\t\t\t\tDynamicRegistration: true,\n\t\t\t\t\t\tRelativePatternSupport: true,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tTextDocument: protocol.TextDocumentClientCapabilities{\n\t\t\t\t\tSynchronization: &protocol.TextDocumentSyncClientCapabilities{\n\t\t\t\t\t\tDynamicRegistration: true,\n\t\t\t\t\t\tDidSave: true,\n\t\t\t\t\t},\n\t\t\t\t\tCompletion: protocol.CompletionClientCapabilities{\n\t\t\t\t\t\tCompletionItem: protocol.ClientCompletionItemOptions{},\n\t\t\t\t\t},\n\t\t\t\t\tCodeLens: &protocol.CodeLensClientCapabilities{\n\t\t\t\t\t\tDynamicRegistration: true,\n\t\t\t\t\t},\n\t\t\t\t\tDocumentSymbol: protocol.DocumentSymbolClientCapabilities{},\n\t\t\t\t\tCodeAction: protocol.CodeActionClientCapabilities{\n\t\t\t\t\t\tCodeActionLiteralSupport: protocol.ClientCodeActionLiteralOptions{\n\t\t\t\t\t\t\tCodeActionKind: protocol.ClientCodeActionKindOptions{\n\t\t\t\t\t\t\t\tValueSet: []protocol.CodeActionKind{},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\tPublishDiagnostics: protocol.PublishDiagnosticsClientCapabilities{\n\t\t\t\t\t\tVersionSupport: true,\n\t\t\t\t\t},\n\t\t\t\t\tSemanticTokens: protocol.SemanticTokensClientCapabilities{\n\t\t\t\t\t\tRequests: protocol.ClientSemanticTokensRequestOptions{\n\t\t\t\t\t\t\tRange: &protocol.Or_ClientSemanticTokensRequestOptions_range{},\n\t\t\t\t\t\t\tFull: &protocol.Or_ClientSemanticTokensRequestOptions_full{},\n\t\t\t\t\t\t},\n\t\t\t\t\t\tTokenTypes: []string{},\n\t\t\t\t\t\tTokenModifiers: []string{},\n\t\t\t\t\t\tFormats: []protocol.TokenFormat{},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tWindow: protocol.WindowClientCapabilities{},\n\t\t\t},\n\t\t\tInitializationOptions: map[string]any{\n\t\t\t\t\"codelenses\": map[string]bool{\n\t\t\t\t\t\"generate\": true,\n\t\t\t\t\t\"regenerate_cgo\": true,\n\t\t\t\t\t\"test\": true,\n\t\t\t\t\t\"tidy\": true,\n\t\t\t\t\t\"upgrade_dependency\": true,\n\t\t\t\t\t\"vendor\": true,\n\t\t\t\t\t\"vulncheck\": false,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\tvar result protocol.InitializeResult\n\tif err := c.Call(ctx, \"initialize\", initParams, &result); err != nil {\n\t\treturn nil, fmt.Errorf(\"initialize failed: %w\", err)\n\t}\n\n\tif err := c.Notify(ctx, \"initialized\", struct{}{}); err != nil {\n\t\treturn nil, fmt.Errorf(\"initialized notification failed: %w\", err)\n\t}\n\n\t// Register handlers\n\tc.RegisterServerRequestHandler(\"workspace/applyEdit\", HandleApplyEdit)\n\tc.RegisterServerRequestHandler(\"workspace/configuration\", HandleWorkspaceConfiguration)\n\tc.RegisterServerRequestHandler(\"client/registerCapability\", HandleRegisterCapability)\n\tc.RegisterNotificationHandler(\"window/showMessage\", HandleServerMessage)\n\tc.RegisterNotificationHandler(\"textDocument/publishDiagnostics\",\n\t\tfunc(params json.RawMessage) { HandleDiagnostics(c, params) })\n\n\t// Notify the LSP server\n\terr := c.Initialized(ctx, protocol.InitializedParams{})\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"initialization failed: %w\", err)\n\t}\n\n\treturn &result, nil\n}\n\nfunc (c *Client) Close() error {\n\t// Try to close all open files first\n\tctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)\n\tdefer cancel()\n\n\t// Attempt to close files but continue shutdown regardless\n\tc.CloseAllFiles(ctx)\n\n\t// Close stdin to signal the server\n\tif err := c.stdin.Close(); err != nil {\n\t\treturn fmt.Errorf(\"failed to close stdin: %w\", err)\n\t}\n\n\t// Use a channel to handle the Wait with timeout\n\tdone := make(chan error, 1)\n\tgo func() {\n\t\tdone <- c.Cmd.Wait()\n\t}()\n\n\t// Wait for process to exit with timeout\n\tselect {\n\tcase err := <-done:\n\t\treturn err\n\tcase <-time.After(2 * time.Second):\n\t\t// If we timeout, try to kill the process\n\t\tif err := c.Cmd.Process.Kill(); err != nil {\n\t\t\treturn fmt.Errorf(\"failed to kill process: %w\", err)\n\t\t}\n\t\treturn fmt.Errorf(\"process killed after timeout\")\n\t}\n}\n\ntype ServerState int\n\nconst (\n\tStateStarting ServerState = iota\n\tStateReady\n\tStateError\n)\n\n// GetServerState returns the current state of the LSP server\nfunc (c *Client) GetServerState() ServerState {\n\tif val := c.serverState.Load(); val != nil {\n\t\treturn val.(ServerState)\n\t}\n\treturn StateStarting\n}\n\n// SetServerState sets the current state of the LSP server\nfunc (c *Client) SetServerState(state ServerState) {\n\tc.serverState.Store(state)\n}\n\n// WaitForServerReady waits for the server to be ready by polling the server\n// with a simple request until it responds successfully or times out\nfunc (c *Client) WaitForServerReady(ctx context.Context) error {\n\tcnf := config.Get()\n\n\t// Set initial state\n\tc.SetServerState(StateStarting)\n\n\t// Create a context with timeout\n\tctx, cancel := context.WithTimeout(ctx, 30*time.Second)\n\tdefer cancel()\n\n\t// Try to ping the server with a simple request\n\tticker := time.NewTicker(500 * time.Millisecond)\n\tdefer ticker.Stop()\n\n\tif cnf.DebugLSP {\n\t\tlogging.Debug(\"Waiting for LSP server to be ready...\")\n\t}\n\n\t// Determine server type for specialized initialization\n\tserverType := c.detectServerType()\n\n\t// For TypeScript-like servers, we need to open some key files first\n\tif serverType == ServerTypeTypeScript {\n\t\tif cnf.DebugLSP {\n\t\t\tlogging.Debug(\"TypeScript-like server detected, opening key configuration files\")\n\t\t}\n\t\tc.openKeyConfigFiles(ctx)\n\t}\n\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\tc.SetServerState(StateError)\n\t\t\treturn fmt.Errorf(\"timeout waiting for LSP server to be ready\")\n\t\tcase <-ticker.C:\n\t\t\t// Try a ping method appropriate for this server type\n\t\t\terr := c.pingServerByType(ctx, serverType)\n\t\t\tif err == nil {\n\t\t\t\t// Server responded successfully\n\t\t\t\tc.SetServerState(StateReady)\n\t\t\t\tif cnf.DebugLSP {\n\t\t\t\t\tlogging.Debug(\"LSP server is ready\")\n\t\t\t\t}\n\t\t\t\treturn nil\n\t\t\t} else {\n\t\t\t\tlogging.Debug(\"LSP server not ready yet\", \"error\", err, \"serverType\", serverType)\n\t\t\t}\n\n\t\t\tif cnf.DebugLSP {\n\t\t\t\tlogging.Debug(\"LSP server not ready yet\", \"error\", err, \"serverType\", serverType)\n\t\t\t}\n\t\t}\n\t}\n}\n\n// ServerType represents the type of LSP server\ntype ServerType int\n\nconst (\n\tServerTypeUnknown ServerType = iota\n\tServerTypeGo\n\tServerTypeTypeScript\n\tServerTypeRust\n\tServerTypePython\n\tServerTypeGeneric\n)\n\n// detectServerType tries to determine what type of LSP server we're dealing with\nfunc (c *Client) detectServerType() ServerType {\n\tif c.Cmd == nil {\n\t\treturn ServerTypeUnknown\n\t}\n\n\tcmdPath := strings.ToLower(c.Cmd.Path)\n\n\tswitch {\n\tcase strings.Contains(cmdPath, \"gopls\"):\n\t\treturn ServerTypeGo\n\tcase strings.Contains(cmdPath, \"typescript\") || strings.Contains(cmdPath, \"vtsls\") || strings.Contains(cmdPath, \"tsserver\"):\n\t\treturn ServerTypeTypeScript\n\tcase strings.Contains(cmdPath, \"rust-analyzer\"):\n\t\treturn ServerTypeRust\n\tcase strings.Contains(cmdPath, \"pyright\") || strings.Contains(cmdPath, \"pylsp\") || strings.Contains(cmdPath, \"python\"):\n\t\treturn ServerTypePython\n\tdefault:\n\t\treturn ServerTypeGeneric\n\t}\n}\n\n// openKeyConfigFiles opens important configuration files that help initialize the server\nfunc (c *Client) openKeyConfigFiles(ctx context.Context) {\n\tworkDir := config.WorkingDirectory()\n\tserverType := c.detectServerType()\n\n\tvar filesToOpen []string\n\n\tswitch serverType {\n\tcase ServerTypeTypeScript:\n\t\t// TypeScript servers need these config files to properly initialize\n\t\tfilesToOpen = []string{\n\t\t\tfilepath.Join(workDir, \"tsconfig.json\"),\n\t\t\tfilepath.Join(workDir, \"package.json\"),\n\t\t\tfilepath.Join(workDir, \"jsconfig.json\"),\n\t\t}\n\n\t\t// Also find and open a few TypeScript files to help the server initialize\n\t\tc.openTypeScriptFiles(ctx, workDir)\n\tcase ServerTypeGo:\n\t\tfilesToOpen = []string{\n\t\t\tfilepath.Join(workDir, \"go.mod\"),\n\t\t\tfilepath.Join(workDir, \"go.sum\"),\n\t\t}\n\tcase ServerTypeRust:\n\t\tfilesToOpen = []string{\n\t\t\tfilepath.Join(workDir, \"Cargo.toml\"),\n\t\t\tfilepath.Join(workDir, \"Cargo.lock\"),\n\t\t}\n\t}\n\n\t// Try to open each file, ignoring errors if they don't exist\n\tfor _, file := range filesToOpen {\n\t\tif _, err := os.Stat(file); err == nil {\n\t\t\t// File exists, try to open it\n\t\t\tif err := c.OpenFile(ctx, file); err != nil {\n\t\t\t\tlogging.Debug(\"Failed to open key config file\", \"file\", file, \"error\", err)\n\t\t\t} else {\n\t\t\t\tlogging.Debug(\"Opened key config file for initialization\", \"file\", file)\n\t\t\t}\n\t\t}\n\t}\n}\n\n// pingServerByType sends a ping request appropriate for the server type\nfunc (c *Client) pingServerByType(ctx context.Context, serverType ServerType) error {\n\tswitch serverType {\n\tcase ServerTypeTypeScript:\n\t\t// For TypeScript, try a document symbol request on an open file\n\t\treturn c.pingTypeScriptServer(ctx)\n\tcase ServerTypeGo:\n\t\t// For Go, workspace/symbol works well\n\t\treturn c.pingWithWorkspaceSymbol(ctx)\n\tcase ServerTypeRust:\n\t\t// For Rust, workspace/symbol works well\n\t\treturn c.pingWithWorkspaceSymbol(ctx)\n\tdefault:\n\t\t// Default ping method\n\t\treturn c.pingWithWorkspaceSymbol(ctx)\n\t}\n}\n\n// pingTypeScriptServer tries to ping a TypeScript server with appropriate methods\nfunc (c *Client) pingTypeScriptServer(ctx context.Context) error {\n\t// First try workspace/symbol which works for many servers\n\tif err := c.pingWithWorkspaceSymbol(ctx); err == nil {\n\t\treturn nil\n\t}\n\n\t// If that fails, try to find an open file and request document symbols\n\tc.openFilesMu.RLock()\n\tdefer c.openFilesMu.RUnlock()\n\n\t// If we have any open files, try to get document symbols for one\n\tfor uri := range c.openFiles {\n\t\tfilePath := strings.TrimPrefix(uri, \"file://\")\n\t\tif strings.HasSuffix(filePath, \".ts\") || strings.HasSuffix(filePath, \".js\") ||\n\t\t\tstrings.HasSuffix(filePath, \".tsx\") || strings.HasSuffix(filePath, \".jsx\") {\n\t\t\tvar symbols []protocol.DocumentSymbol\n\t\t\terr := c.Call(ctx, \"textDocument/documentSymbol\", protocol.DocumentSymbolParams{\n\t\t\t\tTextDocument: protocol.TextDocumentIdentifier{\n\t\t\t\t\tURI: protocol.DocumentUri(uri),\n\t\t\t\t},\n\t\t\t}, &symbols)\n\t\t\tif err == nil {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\t}\n\n\t// If we have no open TypeScript files, try to find and open one\n\tworkDir := config.WorkingDirectory()\n\terr := filepath.WalkDir(workDir, func(path string, d os.DirEntry, err error) error {\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Skip directories and non-TypeScript files\n\t\tif d.IsDir() {\n\t\t\treturn nil\n\t\t}\n\n\t\text := filepath.Ext(path)\n\t\tif ext == \".ts\" || ext == \".js\" || ext == \".tsx\" || ext == \".jsx\" {\n\t\t\t// Found a TypeScript file, try to open it\n\t\t\tif err := c.OpenFile(ctx, path); err == nil {\n\t\t\t\t// Successfully opened, stop walking\n\t\t\t\treturn filepath.SkipAll\n\t\t\t}\n\t\t}\n\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\tlogging.Debug(\"Error walking directory for TypeScript files\", \"error\", err)\n\t}\n\n\t// Final fallback - just try a generic capability\n\treturn c.pingWithServerCapabilities(ctx)\n}\n\n// openTypeScriptFiles finds and opens TypeScript files to help initialize the server\nfunc (c *Client) openTypeScriptFiles(ctx context.Context, workDir string) {\n\tcnf := config.Get()\n\tfilesOpened := 0\n\tmaxFilesToOpen := 5 // Limit to a reasonable number of files\n\n\t// Find and open TypeScript files\n\terr := filepath.WalkDir(workDir, func(path string, d os.DirEntry, err error) error {\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Skip directories and non-TypeScript files\n\t\tif d.IsDir() {\n\t\t\t// Skip common directories to avoid wasting time\n\t\t\tif shouldSkipDir(path) {\n\t\t\t\treturn filepath.SkipDir\n\t\t\t}\n\t\t\treturn nil\n\t\t}\n\n\t\t// Check if we've opened enough files\n\t\tif filesOpened >= maxFilesToOpen {\n\t\t\treturn filepath.SkipAll\n\t\t}\n\n\t\t// Check file extension\n\t\text := filepath.Ext(path)\n\t\tif ext == \".ts\" || ext == \".tsx\" || ext == \".js\" || ext == \".jsx\" {\n\t\t\t// Try to open the file\n\t\t\tif err := c.OpenFile(ctx, path); err == nil {\n\t\t\t\tfilesOpened++\n\t\t\t\tif cnf.DebugLSP {\n\t\t\t\t\tlogging.Debug(\"Opened TypeScript file for initialization\", \"file\", path)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn nil\n\t})\n\n\tif err != nil && cnf.DebugLSP {\n\t\tlogging.Debug(\"Error walking directory for TypeScript files\", \"error\", err)\n\t}\n\n\tif cnf.DebugLSP {\n\t\tlogging.Debug(\"Opened TypeScript files for initialization\", \"count\", filesOpened)\n\t}\n}\n\n// shouldSkipDir returns true if the directory should be skipped during file search\nfunc shouldSkipDir(path string) bool {\n\tdirName := filepath.Base(path)\n\n\t// Skip hidden directories\n\tif strings.HasPrefix(dirName, \".\") {\n\t\treturn true\n\t}\n\n\t// Skip common directories that won't contain relevant source files\n\tskipDirs := map[string]bool{\n\t\t\"node_modules\": true,\n\t\t\"dist\": true,\n\t\t\"build\": true,\n\t\t\"coverage\": true,\n\t\t\"vendor\": true,\n\t\t\"target\": true,\n\t}\n\n\treturn skipDirs[dirName]\n}\n\n// pingWithWorkspaceSymbol tries a workspace/symbol request\nfunc (c *Client) pingWithWorkspaceSymbol(ctx context.Context) error {\n\tvar result []protocol.SymbolInformation\n\treturn c.Call(ctx, \"workspace/symbol\", protocol.WorkspaceSymbolParams{\n\t\tQuery: \"\",\n\t}, &result)\n}\n\n// pingWithServerCapabilities tries to get server capabilities\nfunc (c *Client) pingWithServerCapabilities(ctx context.Context) error {\n\t// This is a very lightweight request that should work for most servers\n\treturn c.Notify(ctx, \"$/cancelRequest\", struct{ ID int }{ID: -1})\n}\n\ntype OpenFileInfo struct {\n\tVersion int32\n\tURI protocol.DocumentUri\n}\n\nfunc (c *Client) OpenFile(ctx context.Context, filepath string) error {\n\turi := fmt.Sprintf(\"file://%s\", filepath)\n\n\tc.openFilesMu.Lock()\n\tif _, exists := c.openFiles[uri]; exists {\n\t\tc.openFilesMu.Unlock()\n\t\treturn nil // Already open\n\t}\n\tc.openFilesMu.Unlock()\n\n\t// Skip files that do not exist or cannot be read\n\tcontent, err := os.ReadFile(filepath)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error reading file: %w\", err)\n\t}\n\n\tparams := protocol.DidOpenTextDocumentParams{\n\t\tTextDocument: protocol.TextDocumentItem{\n\t\t\tURI: protocol.DocumentUri(uri),\n\t\t\tLanguageID: DetectLanguageID(uri),\n\t\t\tVersion: 1,\n\t\t\tText: string(content),\n\t\t},\n\t}\n\n\tif err := c.Notify(ctx, \"textDocument/didOpen\", params); err != nil {\n\t\treturn err\n\t}\n\n\tc.openFilesMu.Lock()\n\tc.openFiles[uri] = &OpenFileInfo{\n\t\tVersion: 1,\n\t\tURI: protocol.DocumentUri(uri),\n\t}\n\tc.openFilesMu.Unlock()\n\n\treturn nil\n}\n\nfunc (c *Client) NotifyChange(ctx context.Context, filepath string) error {\n\turi := fmt.Sprintf(\"file://%s\", filepath)\n\n\tcontent, err := os.ReadFile(filepath)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error reading file: %w\", err)\n\t}\n\n\tc.openFilesMu.Lock()\n\tfileInfo, isOpen := c.openFiles[uri]\n\tif !isOpen {\n\t\tc.openFilesMu.Unlock()\n\t\treturn fmt.Errorf(\"cannot notify change for unopened file: %s\", filepath)\n\t}\n\n\t// Increment version\n\tfileInfo.Version++\n\tversion := fileInfo.Version\n\tc.openFilesMu.Unlock()\n\n\tparams := protocol.DidChangeTextDocumentParams{\n\t\tTextDocument: protocol.VersionedTextDocumentIdentifier{\n\t\t\tTextDocumentIdentifier: protocol.TextDocumentIdentifier{\n\t\t\t\tURI: protocol.DocumentUri(uri),\n\t\t\t},\n\t\t\tVersion: version,\n\t\t},\n\t\tContentChanges: []protocol.TextDocumentContentChangeEvent{\n\t\t\t{\n\t\t\t\tValue: protocol.TextDocumentContentChangeWholeDocument{\n\t\t\t\t\tText: string(content),\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\treturn c.Notify(ctx, \"textDocument/didChange\", params)\n}\n\nfunc (c *Client) CloseFile(ctx context.Context, filepath string) error {\n\tcnf := config.Get()\n\turi := fmt.Sprintf(\"file://%s\", filepath)\n\n\tc.openFilesMu.Lock()\n\tif _, exists := c.openFiles[uri]; !exists {\n\t\tc.openFilesMu.Unlock()\n\t\treturn nil // Already closed\n\t}\n\tc.openFilesMu.Unlock()\n\n\tparams := protocol.DidCloseTextDocumentParams{\n\t\tTextDocument: protocol.TextDocumentIdentifier{\n\t\t\tURI: protocol.DocumentUri(uri),\n\t\t},\n\t}\n\n\tif cnf.DebugLSP {\n\t\tlogging.Debug(\"Closing file\", \"file\", filepath)\n\t}\n\tif err := c.Notify(ctx, \"textDocument/didClose\", params); err != nil {\n\t\treturn err\n\t}\n\n\tc.openFilesMu.Lock()\n\tdelete(c.openFiles, uri)\n\tc.openFilesMu.Unlock()\n\n\treturn nil\n}\n\nfunc (c *Client) IsFileOpen(filepath string) bool {\n\turi := fmt.Sprintf(\"file://%s\", filepath)\n\tc.openFilesMu.RLock()\n\tdefer c.openFilesMu.RUnlock()\n\t_, exists := c.openFiles[uri]\n\treturn exists\n}\n\n// CloseAllFiles closes all currently open files\nfunc (c *Client) CloseAllFiles(ctx context.Context) {\n\tcnf := config.Get()\n\tc.openFilesMu.Lock()\n\tfilesToClose := make([]string, 0, len(c.openFiles))\n\n\t// First collect all URIs that need to be closed\n\tfor uri := range c.openFiles {\n\t\t// Convert URI back to file path by trimming \"file://\" prefix\n\t\tfilePath := strings.TrimPrefix(uri, \"file://\")\n\t\tfilesToClose = append(filesToClose, filePath)\n\t}\n\tc.openFilesMu.Unlock()\n\n\t// Then close them all\n\tfor _, filePath := range filesToClose {\n\t\terr := c.CloseFile(ctx, filePath)\n\t\tif err != nil && cnf.DebugLSP {\n\t\t\tlogging.Warn(\"Error closing file\", \"file\", filePath, \"error\", err)\n\t\t}\n\t}\n\n\tif cnf.DebugLSP {\n\t\tlogging.Debug(\"Closed all files\", \"files\", filesToClose)\n\t}\n}\n\nfunc (c *Client) GetFileDiagnostics(uri protocol.DocumentUri) []protocol.Diagnostic {\n\tc.diagnosticsMu.RLock()\n\tdefer c.diagnosticsMu.RUnlock()\n\n\treturn c.diagnostics[uri]\n}\n\n// GetDiagnostics returns all diagnostics for all files\nfunc (c *Client) GetDiagnostics() map[protocol.DocumentUri][]protocol.Diagnostic {\n\treturn c.diagnostics\n}\n\n// OpenFileOnDemand opens a file only if it's not already open\n// This is used for lazy-loading files when they're actually needed\nfunc (c *Client) OpenFileOnDemand(ctx context.Context, filepath string) error {\n\t// Check if the file is already open\n\tif c.IsFileOpen(filepath) {\n\t\treturn nil\n\t}\n\n\t// Open the file\n\treturn c.OpenFile(ctx, filepath)\n}\n\n// GetDiagnosticsForFile ensures a file is open and returns its diagnostics\n// This is useful for on-demand diagnostics when using lazy loading\nfunc (c *Client) GetDiagnosticsForFile(ctx context.Context, filepath string) ([]protocol.Diagnostic, error) {\n\turi := fmt.Sprintf(\"file://%s\", filepath)\n\tdocumentUri := protocol.DocumentUri(uri)\n\n\t// Make sure the file is open\n\tif !c.IsFileOpen(filepath) {\n\t\tif err := c.OpenFile(ctx, filepath); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to open file for diagnostics: %w\", err)\n\t\t}\n\n\t\t// Give the LSP server a moment to process the file\n\t\ttime.Sleep(100 * time.Millisecond)\n\t}\n\n\t// Get diagnostics\n\tc.diagnosticsMu.RLock()\n\tdiagnostics := c.diagnostics[documentUri]\n\tc.diagnosticsMu.RUnlock()\n\n\treturn diagnostics, nil\n}\n\n// ClearDiagnosticsForURI removes diagnostics for a specific URI from the cache\nfunc (c *Client) ClearDiagnosticsForURI(uri protocol.DocumentUri) {\n\tc.diagnosticsMu.Lock()\n\tdefer c.diagnosticsMu.Unlock()\n\tdelete(c.diagnostics, uri)\n}\n"], ["/opencode/cmd/root.go", "package cmd\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"os\"\n\t\"sync\"\n\t\"time\"\n\n\ttea \"github.com/charmbracelet/bubbletea\"\n\tzone \"github.com/lrstanley/bubblezone\"\n\t\"github.com/opencode-ai/opencode/internal/app\"\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/db\"\n\t\"github.com/opencode-ai/opencode/internal/format\"\n\t\"github.com/opencode-ai/opencode/internal/llm/agent\"\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n\t\"github.com/opencode-ai/opencode/internal/pubsub\"\n\t\"github.com/opencode-ai/opencode/internal/tui\"\n\t\"github.com/opencode-ai/opencode/internal/version\"\n\t\"github.com/spf13/cobra\"\n)\n\nvar rootCmd = &cobra.Command{\n\tUse: \"opencode\",\n\tShort: \"Terminal-based AI assistant for software development\",\n\tLong: `OpenCode is a powerful terminal-based AI assistant that helps with software development tasks.\nIt provides an interactive chat interface with AI capabilities, code analysis, and LSP integration\nto assist developers in writing, debugging, and understanding code directly from the terminal.`,\n\tExample: `\n # Run in interactive mode\n opencode\n\n # Run with debug logging\n opencode -d\n\n # Run with debug logging in a specific directory\n opencode -d -c /path/to/project\n\n # Print version\n opencode -v\n\n # Run a single non-interactive prompt\n opencode -p \"Explain the use of context in Go\"\n\n # Run a single non-interactive prompt with JSON output format\n opencode -p \"Explain the use of context in Go\" -f json\n `,\n\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t// If the help flag is set, show the help message\n\t\tif cmd.Flag(\"help\").Changed {\n\t\t\tcmd.Help()\n\t\t\treturn nil\n\t\t}\n\t\tif cmd.Flag(\"version\").Changed {\n\t\t\tfmt.Println(version.Version)\n\t\t\treturn nil\n\t\t}\n\n\t\t// Load the config\n\t\tdebug, _ := cmd.Flags().GetBool(\"debug\")\n\t\tcwd, _ := cmd.Flags().GetString(\"cwd\")\n\t\tprompt, _ := cmd.Flags().GetString(\"prompt\")\n\t\toutputFormat, _ := cmd.Flags().GetString(\"output-format\")\n\t\tquiet, _ := cmd.Flags().GetBool(\"quiet\")\n\n\t\t// Validate format option\n\t\tif !format.IsValid(outputFormat) {\n\t\t\treturn fmt.Errorf(\"invalid format option: %s\\n%s\", outputFormat, format.GetHelpText())\n\t\t}\n\n\t\tif cwd != \"\" {\n\t\t\terr := os.Chdir(cwd)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"failed to change directory: %v\", err)\n\t\t\t}\n\t\t}\n\t\tif cwd == \"\" {\n\t\t\tc, err := os.Getwd()\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"failed to get current working directory: %v\", err)\n\t\t\t}\n\t\t\tcwd = c\n\t\t}\n\t\t_, err := config.Load(cwd, debug)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Connect DB, this will also run migrations\n\t\tconn, err := db.Connect()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Create main context for the application\n\t\tctx, cancel := context.WithCancel(context.Background())\n\t\tdefer cancel()\n\n\t\tapp, err := app.New(ctx, conn)\n\t\tif err != nil {\n\t\t\tlogging.Error(\"Failed to create app: %v\", err)\n\t\t\treturn err\n\t\t}\n\t\t// Defer shutdown here so it runs for both interactive and non-interactive modes\n\t\tdefer app.Shutdown()\n\n\t\t// Initialize MCP tools early for both modes\n\t\tinitMCPTools(ctx, app)\n\n\t\t// Non-interactive mode\n\t\tif prompt != \"\" {\n\t\t\t// Run non-interactive flow using the App method\n\t\t\treturn app.RunNonInteractive(ctx, prompt, outputFormat, quiet)\n\t\t}\n\n\t\t// Interactive mode\n\t\t// Set up the TUI\n\t\tzone.NewGlobal()\n\t\tprogram := tea.NewProgram(\n\t\t\ttui.New(app),\n\t\t\ttea.WithAltScreen(),\n\t\t)\n\n\t\t// Setup the subscriptions, this will send services events to the TUI\n\t\tch, cancelSubs := setupSubscriptions(app, ctx)\n\n\t\t// Create a context for the TUI message handler\n\t\ttuiCtx, tuiCancel := context.WithCancel(ctx)\n\t\tvar tuiWg sync.WaitGroup\n\t\ttuiWg.Add(1)\n\n\t\t// Set up message handling for the TUI\n\t\tgo func() {\n\t\t\tdefer tuiWg.Done()\n\t\t\tdefer logging.RecoverPanic(\"TUI-message-handler\", func() {\n\t\t\t\tattemptTUIRecovery(program)\n\t\t\t})\n\n\t\t\tfor {\n\t\t\t\tselect {\n\t\t\t\tcase <-tuiCtx.Done():\n\t\t\t\t\tlogging.Info(\"TUI message handler shutting down\")\n\t\t\t\t\treturn\n\t\t\t\tcase msg, ok := <-ch:\n\t\t\t\t\tif !ok {\n\t\t\t\t\t\tlogging.Info(\"TUI message channel closed\")\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\tprogram.Send(msg)\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\n\t\t// Cleanup function for when the program exits\n\t\tcleanup := func() {\n\t\t\t// Shutdown the app\n\t\t\tapp.Shutdown()\n\n\t\t\t// Cancel subscriptions first\n\t\t\tcancelSubs()\n\n\t\t\t// Then cancel TUI message handler\n\t\t\ttuiCancel()\n\n\t\t\t// Wait for TUI message handler to finish\n\t\t\ttuiWg.Wait()\n\n\t\t\tlogging.Info(\"All goroutines cleaned up\")\n\t\t}\n\n\t\t// Run the TUI\n\t\tresult, err := program.Run()\n\t\tcleanup()\n\n\t\tif err != nil {\n\t\t\tlogging.Error(\"TUI error: %v\", err)\n\t\t\treturn fmt.Errorf(\"TUI error: %v\", err)\n\t\t}\n\n\t\tlogging.Info(\"TUI exited with result: %v\", result)\n\t\treturn nil\n\t},\n}\n\n// attemptTUIRecovery tries to recover the TUI after a panic\nfunc attemptTUIRecovery(program *tea.Program) {\n\tlogging.Info(\"Attempting to recover TUI after panic\")\n\n\t// We could try to restart the TUI or gracefully exit\n\t// For now, we'll just quit the program to avoid further issues\n\tprogram.Quit()\n}\n\nfunc initMCPTools(ctx context.Context, app *app.App) {\n\tgo func() {\n\t\tdefer logging.RecoverPanic(\"MCP-goroutine\", nil)\n\n\t\t// Create a context with timeout for the initial MCP tools fetch\n\t\tctxWithTimeout, cancel := context.WithTimeout(ctx, 30*time.Second)\n\t\tdefer cancel()\n\n\t\t// Set this up once with proper error handling\n\t\tagent.GetMcpTools(ctxWithTimeout, app.Permissions)\n\t\tlogging.Info(\"MCP message handling goroutine exiting\")\n\t}()\n}\n\nfunc setupSubscriber[T any](\n\tctx context.Context,\n\twg *sync.WaitGroup,\n\tname string,\n\tsubscriber func(context.Context) <-chan pubsub.Event[T],\n\toutputCh chan<- tea.Msg,\n) {\n\twg.Add(1)\n\tgo func() {\n\t\tdefer wg.Done()\n\t\tdefer logging.RecoverPanic(fmt.Sprintf(\"subscription-%s\", name), nil)\n\n\t\tsubCh := subscriber(ctx)\n\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase event, ok := <-subCh:\n\t\t\t\tif !ok {\n\t\t\t\t\tlogging.Info(\"subscription channel closed\", \"name\", name)\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tvar msg tea.Msg = event\n\n\t\t\t\tselect {\n\t\t\t\tcase outputCh <- msg:\n\t\t\t\tcase <-time.After(2 * time.Second):\n\t\t\t\t\tlogging.Warn(\"message dropped due to slow consumer\", \"name\", name)\n\t\t\t\tcase <-ctx.Done():\n\t\t\t\t\tlogging.Info(\"subscription cancelled\", \"name\", name)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\tcase <-ctx.Done():\n\t\t\t\tlogging.Info(\"subscription cancelled\", \"name\", name)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}()\n}\n\nfunc setupSubscriptions(app *app.App, parentCtx context.Context) (chan tea.Msg, func()) {\n\tch := make(chan tea.Msg, 100)\n\n\twg := sync.WaitGroup{}\n\tctx, cancel := context.WithCancel(parentCtx) // Inherit from parent context\n\n\tsetupSubscriber(ctx, &wg, \"logging\", logging.Subscribe, ch)\n\tsetupSubscriber(ctx, &wg, \"sessions\", app.Sessions.Subscribe, ch)\n\tsetupSubscriber(ctx, &wg, \"messages\", app.Messages.Subscribe, ch)\n\tsetupSubscriber(ctx, &wg, \"permissions\", app.Permissions.Subscribe, ch)\n\tsetupSubscriber(ctx, &wg, \"coderAgent\", app.CoderAgent.Subscribe, ch)\n\n\tcleanupFunc := func() {\n\t\tlogging.Info(\"Cancelling all subscriptions\")\n\t\tcancel() // Signal all goroutines to stop\n\n\t\twaitCh := make(chan struct{})\n\t\tgo func() {\n\t\t\tdefer logging.RecoverPanic(\"subscription-cleanup\", nil)\n\t\t\twg.Wait()\n\t\t\tclose(waitCh)\n\t\t}()\n\n\t\tselect {\n\t\tcase <-waitCh:\n\t\t\tlogging.Info(\"All subscription goroutines completed successfully\")\n\t\t\tclose(ch) // Only close after all writers are confirmed done\n\t\tcase <-time.After(5 * time.Second):\n\t\t\tlogging.Warn(\"Timed out waiting for some subscription goroutines to complete\")\n\t\t\tclose(ch)\n\t\t}\n\t}\n\treturn ch, cleanupFunc\n}\n\nfunc Execute() {\n\terr := rootCmd.Execute()\n\tif err != nil {\n\t\tos.Exit(1)\n\t}\n}\n\nfunc init() {\n\trootCmd.Flags().BoolP(\"help\", \"h\", false, \"Help\")\n\trootCmd.Flags().BoolP(\"version\", \"v\", false, \"Version\")\n\trootCmd.Flags().BoolP(\"debug\", \"d\", false, \"Debug\")\n\trootCmd.Flags().StringP(\"cwd\", \"c\", \"\", \"Current working directory\")\n\trootCmd.Flags().StringP(\"prompt\", \"p\", \"\", \"Prompt to run in non-interactive mode\")\n\n\t// Add format flag with validation logic\n\trootCmd.Flags().StringP(\"output-format\", \"f\", format.Text.String(),\n\t\t\"Output format for non-interactive mode (text, json)\")\n\n\t// Add quiet flag to hide spinner in non-interactive mode\n\trootCmd.Flags().BoolP(\"quiet\", \"q\", false, \"Hide spinner in non-interactive mode\")\n\n\t// Register custom validation for the format flag\n\trootCmd.RegisterFlagCompletionFunc(\"output-format\", func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {\n\t\treturn format.SupportedFormats, cobra.ShellCompDirectiveNoFileComp\n\t})\n}\n"], ["/opencode/internal/llm/provider/copilot.go", "package provider\n\nimport (\n\t\"context\"\n\t\"encoding/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"net/http\"\n\t\"os\"\n\t\"time\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n\t\"github.com/openai/openai-go/shared\"\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/llm/models\"\n\ttoolsPkg \"github.com/opencode-ai/opencode/internal/llm/tools\"\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n\t\"github.com/opencode-ai/opencode/internal/message\"\n)\n\ntype copilotOptions struct {\n\treasoningEffort string\n\textraHeaders map[string]string\n\tbearerToken string\n}\n\ntype CopilotOption func(*copilotOptions)\n\ntype copilotClient struct {\n\tproviderOptions providerClientOptions\n\toptions copilotOptions\n\tclient openai.Client\n\thttpClient *http.Client\n}\n\ntype CopilotClient ProviderClient\n\n// CopilotTokenResponse represents the response from GitHub's token exchange endpoint\ntype CopilotTokenResponse struct {\n\tToken string `json:\"token\"`\n\tExpiresAt int64 `json:\"expires_at\"`\n}\n\nfunc (c *copilotClient) isAnthropicModel() bool {\n\tfor _, modelId := range models.CopilotAnthropicModels {\n\t\tif c.providerOptions.model.ID == modelId {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n// loadGitHubToken loads the GitHub OAuth token from the standard GitHub CLI/Copilot locations\n\n// exchangeGitHubToken exchanges a GitHub token for a Copilot bearer token\nfunc (c *copilotClient) exchangeGitHubToken(githubToken string) (string, error) {\n\treq, err := http.NewRequest(\"GET\", \"https://api.github.com/copilot_internal/v2/token\", nil)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed to create token exchange request: %w\", err)\n\t}\n\n\treq.Header.Set(\"Authorization\", \"Token \"+githubToken)\n\treq.Header.Set(\"User-Agent\", \"OpenCode/1.0\")\n\n\tresp, err := c.httpClient.Do(req)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed to exchange GitHub token: %w\", err)\n\t}\n\tdefer resp.Body.Close()\n\n\tif resp.StatusCode != http.StatusOK {\n\t\tbody, _ := io.ReadAll(resp.Body)\n\t\treturn \"\", fmt.Errorf(\"token exchange failed with status %d: %s\", resp.StatusCode, string(body))\n\t}\n\n\tvar tokenResp CopilotTokenResponse\n\tif err := json.NewDecoder(resp.Body).Decode(&tokenResp); err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed to decode token response: %w\", err)\n\t}\n\n\treturn tokenResp.Token, nil\n}\n\nfunc newCopilotClient(opts providerClientOptions) CopilotClient {\n\tcopilotOpts := copilotOptions{\n\t\treasoningEffort: \"medium\",\n\t}\n\t// Apply copilot-specific options\n\tfor _, o := range opts.copilotOptions {\n\t\to(&copilotOpts)\n\t}\n\n\t// Create HTTP client for token exchange\n\thttpClient := &http.Client{\n\t\tTimeout: 30 * time.Second,\n\t}\n\n\tvar bearerToken string\n\n\t// If bearer token is already provided, use it\n\tif copilotOpts.bearerToken != \"\" {\n\t\tbearerToken = copilotOpts.bearerToken\n\t} else {\n\t\t// Try to get GitHub token from multiple sources\n\t\tvar githubToken string\n\n\t\t// 1. Environment variable\n\t\tgithubToken = os.Getenv(\"GITHUB_TOKEN\")\n\n\t\t// 2. API key from options\n\t\tif githubToken == \"\" {\n\t\t\tgithubToken = opts.apiKey\n\t\t}\n\n\t\t// 3. Standard GitHub CLI/Copilot locations\n\t\tif githubToken == \"\" {\n\t\t\tvar err error\n\t\t\tgithubToken, err = config.LoadGitHubToken()\n\t\t\tif err != nil {\n\t\t\t\tlogging.Debug(\"Failed to load GitHub token from standard locations\", \"error\", err)\n\t\t\t}\n\t\t}\n\n\t\tif githubToken == \"\" {\n\t\t\tlogging.Error(\"GitHub token is required for Copilot provider. Set GITHUB_TOKEN environment variable, configure it in opencode.json, or ensure GitHub CLI/Copilot is properly authenticated.\")\n\t\t\treturn &copilotClient{\n\t\t\t\tproviderOptions: opts,\n\t\t\t\toptions: copilotOpts,\n\t\t\t\thttpClient: httpClient,\n\t\t\t}\n\t\t}\n\n\t\t// Create a temporary client for token exchange\n\t\ttempClient := &copilotClient{\n\t\t\tproviderOptions: opts,\n\t\t\toptions: copilotOpts,\n\t\t\thttpClient: httpClient,\n\t\t}\n\n\t\t// Exchange GitHub token for bearer token\n\t\tvar err error\n\t\tbearerToken, err = tempClient.exchangeGitHubToken(githubToken)\n\t\tif err != nil {\n\t\t\tlogging.Error(\"Failed to exchange GitHub token for Copilot bearer token\", \"error\", err)\n\t\t\treturn &copilotClient{\n\t\t\t\tproviderOptions: opts,\n\t\t\t\toptions: copilotOpts,\n\t\t\t\thttpClient: httpClient,\n\t\t\t}\n\t\t}\n\t}\n\n\tcopilotOpts.bearerToken = bearerToken\n\n\t// GitHub Copilot API base URL\n\tbaseURL := \"https://api.githubcopilot.com\"\n\n\topenaiClientOptions := []option.RequestOption{\n\t\toption.WithBaseURL(baseURL),\n\t\toption.WithAPIKey(bearerToken), // Use bearer token as API key\n\t}\n\n\t// Add GitHub Copilot specific headers\n\topenaiClientOptions = append(openaiClientOptions,\n\t\toption.WithHeader(\"Editor-Version\", \"OpenCode/1.0\"),\n\t\toption.WithHeader(\"Editor-Plugin-Version\", \"OpenCode/1.0\"),\n\t\toption.WithHeader(\"Copilot-Integration-Id\", \"vscode-chat\"),\n\t)\n\n\t// Add any extra headers\n\tif copilotOpts.extraHeaders != nil {\n\t\tfor key, value := range copilotOpts.extraHeaders {\n\t\t\topenaiClientOptions = append(openaiClientOptions, option.WithHeader(key, value))\n\t\t}\n\t}\n\n\tclient := openai.NewClient(openaiClientOptions...)\n\t// logging.Debug(\"Copilot client created\", \"opts\", opts, \"copilotOpts\", copilotOpts, \"model\", opts.model)\n\treturn &copilotClient{\n\t\tproviderOptions: opts,\n\t\toptions: copilotOpts,\n\t\tclient: client,\n\t\thttpClient: httpClient,\n\t}\n}\n\nfunc (c *copilotClient) convertMessages(messages []message.Message) (copilotMessages []openai.ChatCompletionMessageParamUnion) {\n\t// Add system message first\n\tcopilotMessages = append(copilotMessages, openai.SystemMessage(c.providerOptions.systemMessage))\n\n\tfor _, msg := range messages {\n\t\tswitch msg.Role {\n\t\tcase message.User:\n\t\t\tvar content []openai.ChatCompletionContentPartUnionParam\n\t\t\ttextBlock := openai.ChatCompletionContentPartTextParam{Text: msg.Content().String()}\n\t\t\tcontent = append(content, openai.ChatCompletionContentPartUnionParam{OfText: &textBlock})\n\n\t\t\tfor _, binaryContent := range msg.BinaryContent() {\n\t\t\t\timageURL := openai.ChatCompletionContentPartImageImageURLParam{URL: binaryContent.String(models.ProviderCopilot)}\n\t\t\t\timageBlock := openai.ChatCompletionContentPartImageParam{ImageURL: imageURL}\n\t\t\t\tcontent = append(content, openai.ChatCompletionContentPartUnionParam{OfImageURL: &imageBlock})\n\t\t\t}\n\n\t\t\tcopilotMessages = append(copilotMessages, openai.UserMessage(content))\n\n\t\tcase message.Assistant:\n\t\t\tassistantMsg := openai.ChatCompletionAssistantMessageParam{\n\t\t\t\tRole: \"assistant\",\n\t\t\t}\n\n\t\t\tif msg.Content().String() != \"\" {\n\t\t\t\tassistantMsg.Content = openai.ChatCompletionAssistantMessageParamContentUnion{\n\t\t\t\t\tOfString: openai.String(msg.Content().String()),\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif len(msg.ToolCalls()) > 0 {\n\t\t\t\tassistantMsg.ToolCalls = make([]openai.ChatCompletionMessageToolCallParam, len(msg.ToolCalls()))\n\t\t\t\tfor i, call := range msg.ToolCalls() {\n\t\t\t\t\tassistantMsg.ToolCalls[i] = openai.ChatCompletionMessageToolCallParam{\n\t\t\t\t\t\tID: call.ID,\n\t\t\t\t\t\tType: \"function\",\n\t\t\t\t\t\tFunction: openai.ChatCompletionMessageToolCallFunctionParam{\n\t\t\t\t\t\t\tName: call.Name,\n\t\t\t\t\t\t\tArguments: call.Input,\n\t\t\t\t\t\t},\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tcopilotMessages = append(copilotMessages, openai.ChatCompletionMessageParamUnion{\n\t\t\t\tOfAssistant: &assistantMsg,\n\t\t\t})\n\n\t\tcase message.Tool:\n\t\t\tfor _, result := range msg.ToolResults() {\n\t\t\t\tcopilotMessages = append(copilotMessages,\n\t\t\t\t\topenai.ToolMessage(result.Content, result.ToolCallID),\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn\n}\n\nfunc (c *copilotClient) convertTools(tools []toolsPkg.BaseTool) []openai.ChatCompletionToolParam {\n\tcopilotTools := make([]openai.ChatCompletionToolParam, len(tools))\n\n\tfor i, tool := range tools {\n\t\tinfo := tool.Info()\n\t\tcopilotTools[i] = openai.ChatCompletionToolParam{\n\t\t\tFunction: openai.FunctionDefinitionParam{\n\t\t\t\tName: info.Name,\n\t\t\t\tDescription: openai.String(info.Description),\n\t\t\t\tParameters: openai.FunctionParameters{\n\t\t\t\t\t\"type\": \"object\",\n\t\t\t\t\t\"properties\": info.Parameters,\n\t\t\t\t\t\"required\": info.Required,\n\t\t\t\t},\n\t\t\t},\n\t\t}\n\t}\n\n\treturn copilotTools\n}\n\nfunc (c *copilotClient) finishReason(reason string) message.FinishReason {\n\tswitch reason {\n\tcase \"stop\":\n\t\treturn message.FinishReasonEndTurn\n\tcase \"length\":\n\t\treturn message.FinishReasonMaxTokens\n\tcase \"tool_calls\":\n\t\treturn message.FinishReasonToolUse\n\tdefault:\n\t\treturn message.FinishReasonUnknown\n\t}\n}\n\nfunc (c *copilotClient) preparedParams(messages []openai.ChatCompletionMessageParamUnion, tools []openai.ChatCompletionToolParam) openai.ChatCompletionNewParams {\n\tparams := openai.ChatCompletionNewParams{\n\t\tModel: openai.ChatModel(c.providerOptions.model.APIModel),\n\t\tMessages: messages,\n\t\tTools: tools,\n\t}\n\n\tif c.providerOptions.model.CanReason == true {\n\t\tparams.MaxCompletionTokens = openai.Int(c.providerOptions.maxTokens)\n\t\tswitch c.options.reasoningEffort {\n\t\tcase \"low\":\n\t\t\tparams.ReasoningEffort = shared.ReasoningEffortLow\n\t\tcase \"medium\":\n\t\t\tparams.ReasoningEffort = shared.ReasoningEffortMedium\n\t\tcase \"high\":\n\t\t\tparams.ReasoningEffort = shared.ReasoningEffortHigh\n\t\tdefault:\n\t\t\tparams.ReasoningEffort = shared.ReasoningEffortMedium\n\t\t}\n\t} else {\n\t\tparams.MaxTokens = openai.Int(c.providerOptions.maxTokens)\n\t}\n\n\treturn params\n}\n\nfunc (c *copilotClient) send(ctx context.Context, messages []message.Message, tools []toolsPkg.BaseTool) (response *ProviderResponse, err error) {\n\tparams := c.preparedParams(c.convertMessages(messages), c.convertTools(tools))\n\tcfg := config.Get()\n\tvar sessionId string\n\trequestSeqId := (len(messages) + 1) / 2\n\tif cfg.Debug {\n\t\t// jsonData, _ := json.Marshal(params)\n\t\t// logging.Debug(\"Prepared messages\", \"messages\", string(jsonData))\n\t\tif sid, ok := ctx.Value(toolsPkg.SessionIDContextKey).(string); ok {\n\t\t\tsessionId = sid\n\t\t}\n\t\tjsonData, _ := json.Marshal(params)\n\t\tif sessionId != \"\" {\n\t\t\tfilepath := logging.WriteRequestMessageJson(sessionId, requestSeqId, params)\n\t\t\tlogging.Debug(\"Prepared messages\", \"filepath\", filepath)\n\t\t} else {\n\t\t\tlogging.Debug(\"Prepared messages\", \"messages\", string(jsonData))\n\t\t}\n\t}\n\n\tattempts := 0\n\tfor {\n\t\tattempts++\n\t\tcopilotResponse, err := c.client.Chat.Completions.New(\n\t\t\tctx,\n\t\t\tparams,\n\t\t)\n\n\t\t// If there is an error we are going to see if we can retry the call\n\t\tif err != nil {\n\t\t\tretry, after, retryErr := c.shouldRetry(attempts, err)\n\t\t\tif retryErr != nil {\n\t\t\t\treturn nil, retryErr\n\t\t\t}\n\t\t\tif retry {\n\t\t\t\tlogging.WarnPersist(fmt.Sprintf(\"Retrying due to rate limit... attempt %d of %d\", attempts, maxRetries), logging.PersistTimeArg, time.Millisecond*time.Duration(after+100))\n\t\t\t\tselect {\n\t\t\t\tcase <-ctx.Done():\n\t\t\t\t\treturn nil, ctx.Err()\n\t\t\t\tcase <-time.After(time.Duration(after) * time.Millisecond):\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn nil, retryErr\n\t\t}\n\n\t\tcontent := \"\"\n\t\tif copilotResponse.Choices[0].Message.Content != \"\" {\n\t\t\tcontent = copilotResponse.Choices[0].Message.Content\n\t\t}\n\n\t\ttoolCalls := c.toolCalls(*copilotResponse)\n\t\tfinishReason := c.finishReason(string(copilotResponse.Choices[0].FinishReason))\n\n\t\tif len(toolCalls) > 0 {\n\t\t\tfinishReason = message.FinishReasonToolUse\n\t\t}\n\n\t\treturn &ProviderResponse{\n\t\t\tContent: content,\n\t\t\tToolCalls: toolCalls,\n\t\t\tUsage: c.usage(*copilotResponse),\n\t\t\tFinishReason: finishReason,\n\t\t}, nil\n\t}\n}\n\nfunc (c *copilotClient) stream(ctx context.Context, messages []message.Message, tools []toolsPkg.BaseTool) <-chan ProviderEvent {\n\tparams := c.preparedParams(c.convertMessages(messages), c.convertTools(tools))\n\tparams.StreamOptions = openai.ChatCompletionStreamOptionsParam{\n\t\tIncludeUsage: openai.Bool(true),\n\t}\n\n\tcfg := config.Get()\n\tvar sessionId string\n\trequestSeqId := (len(messages) + 1) / 2\n\tif cfg.Debug {\n\t\tif sid, ok := ctx.Value(toolsPkg.SessionIDContextKey).(string); ok {\n\t\t\tsessionId = sid\n\t\t}\n\t\tjsonData, _ := json.Marshal(params)\n\t\tif sessionId != \"\" {\n\t\t\tfilepath := logging.WriteRequestMessageJson(sessionId, requestSeqId, params)\n\t\t\tlogging.Debug(\"Prepared messages\", \"filepath\", filepath)\n\t\t} else {\n\t\t\tlogging.Debug(\"Prepared messages\", \"messages\", string(jsonData))\n\t\t}\n\n\t}\n\n\tattempts := 0\n\teventChan := make(chan ProviderEvent)\n\n\tgo func() {\n\t\tfor {\n\t\t\tattempts++\n\t\t\tcopilotStream := c.client.Chat.Completions.NewStreaming(\n\t\t\t\tctx,\n\t\t\t\tparams,\n\t\t\t)\n\n\t\t\tacc := openai.ChatCompletionAccumulator{}\n\t\t\tcurrentContent := \"\"\n\t\t\ttoolCalls := make([]message.ToolCall, 0)\n\n\t\t\tvar currentToolCallId string\n\t\t\tvar currentToolCall openai.ChatCompletionMessageToolCall\n\t\t\tvar msgToolCalls []openai.ChatCompletionMessageToolCall\n\t\t\tfor copilotStream.Next() {\n\t\t\t\tchunk := copilotStream.Current()\n\t\t\t\tacc.AddChunk(chunk)\n\n\t\t\t\tif cfg.Debug {\n\t\t\t\t\tlogging.AppendToStreamSessionLogJson(sessionId, requestSeqId, chunk)\n\t\t\t\t}\n\n\t\t\t\tfor _, choice := range chunk.Choices {\n\t\t\t\t\tif choice.Delta.Content != \"\" {\n\t\t\t\t\t\teventChan <- ProviderEvent{\n\t\t\t\t\t\t\tType: EventContentDelta,\n\t\t\t\t\t\t\tContent: choice.Delta.Content,\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcurrentContent += choice.Delta.Content\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif c.isAnthropicModel() {\n\t\t\t\t\t// Monkeypatch adapter for Sonnet-4 multi-tool use\n\t\t\t\t\tfor _, choice := range chunk.Choices {\n\t\t\t\t\t\tif choice.Delta.ToolCalls != nil && len(choice.Delta.ToolCalls) > 0 {\n\t\t\t\t\t\t\ttoolCall := choice.Delta.ToolCalls[0]\n\t\t\t\t\t\t\t// Detect tool use start\n\t\t\t\t\t\t\tif currentToolCallId == \"\" {\n\t\t\t\t\t\t\t\tif toolCall.ID != \"\" {\n\t\t\t\t\t\t\t\t\tcurrentToolCallId = toolCall.ID\n\t\t\t\t\t\t\t\t\tcurrentToolCall = openai.ChatCompletionMessageToolCall{\n\t\t\t\t\t\t\t\t\t\tID: toolCall.ID,\n\t\t\t\t\t\t\t\t\t\tType: \"function\",\n\t\t\t\t\t\t\t\t\t\tFunction: openai.ChatCompletionMessageToolCallFunction{\n\t\t\t\t\t\t\t\t\t\t\tName: toolCall.Function.Name,\n\t\t\t\t\t\t\t\t\t\t\tArguments: toolCall.Function.Arguments,\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t// Delta tool use\n\t\t\t\t\t\t\t\tif toolCall.ID == \"\" {\n\t\t\t\t\t\t\t\t\tcurrentToolCall.Function.Arguments += toolCall.Function.Arguments\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t// Detect new tool use\n\t\t\t\t\t\t\t\t\tif toolCall.ID != currentToolCallId {\n\t\t\t\t\t\t\t\t\t\tmsgToolCalls = append(msgToolCalls, currentToolCall)\n\t\t\t\t\t\t\t\t\t\tcurrentToolCallId = toolCall.ID\n\t\t\t\t\t\t\t\t\t\tcurrentToolCall = openai.ChatCompletionMessageToolCall{\n\t\t\t\t\t\t\t\t\t\t\tID: toolCall.ID,\n\t\t\t\t\t\t\t\t\t\t\tType: \"function\",\n\t\t\t\t\t\t\t\t\t\t\tFunction: openai.ChatCompletionMessageToolCallFunction{\n\t\t\t\t\t\t\t\t\t\t\t\tName: toolCall.Function.Name,\n\t\t\t\t\t\t\t\t\t\t\t\tArguments: toolCall.Function.Arguments,\n\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif choice.FinishReason == \"tool_calls\" {\n\t\t\t\t\t\t\tmsgToolCalls = append(msgToolCalls, currentToolCall)\n\t\t\t\t\t\t\tacc.ChatCompletion.Choices[0].Message.ToolCalls = msgToolCalls\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\terr := copilotStream.Err()\n\t\t\tif err == nil || errors.Is(err, io.EOF) {\n\t\t\t\tif cfg.Debug {\n\t\t\t\t\trespFilepath := logging.WriteChatResponseJson(sessionId, requestSeqId, acc.ChatCompletion)\n\t\t\t\t\tlogging.Debug(\"Chat completion response\", \"filepath\", respFilepath)\n\t\t\t\t}\n\t\t\t\t// Stream completed successfully\n\t\t\t\tfinishReason := c.finishReason(string(acc.ChatCompletion.Choices[0].FinishReason))\n\t\t\t\tif len(acc.ChatCompletion.Choices[0].Message.ToolCalls) > 0 {\n\t\t\t\t\ttoolCalls = append(toolCalls, c.toolCalls(acc.ChatCompletion)...)\n\t\t\t\t}\n\t\t\t\tif len(toolCalls) > 0 {\n\t\t\t\t\tfinishReason = message.FinishReasonToolUse\n\t\t\t\t}\n\n\t\t\t\teventChan <- ProviderEvent{\n\t\t\t\t\tType: EventComplete,\n\t\t\t\t\tResponse: &ProviderResponse{\n\t\t\t\t\t\tContent: currentContent,\n\t\t\t\t\t\tToolCalls: toolCalls,\n\t\t\t\t\t\tUsage: c.usage(acc.ChatCompletion),\n\t\t\t\t\t\tFinishReason: finishReason,\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t\tclose(eventChan)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\t// If there is an error we are going to see if we can retry the call\n\t\t\tretry, after, retryErr := c.shouldRetry(attempts, err)\n\t\t\tif retryErr != nil {\n\t\t\t\teventChan <- ProviderEvent{Type: EventError, Error: retryErr}\n\t\t\t\tclose(eventChan)\n\t\t\t\treturn\n\t\t\t}\n\t\t\t// shouldRetry is not catching the max retries...\n\t\t\t// TODO: Figure out why\n\t\t\tif attempts > maxRetries {\n\t\t\t\tlogging.Warn(\"Maximum retry attempts reached for rate limit\", \"attempts\", attempts, \"max_retries\", maxRetries)\n\t\t\t\tretry = false\n\t\t\t}\n\t\t\tif retry {\n\t\t\t\tlogging.WarnPersist(fmt.Sprintf(\"Retrying due to rate limit... attempt %d of %d (paused for %d ms)\", attempts, maxRetries, after), logging.PersistTimeArg, time.Millisecond*time.Duration(after+100))\n\t\t\t\tselect {\n\t\t\t\tcase <-ctx.Done():\n\t\t\t\t\t// context cancelled\n\t\t\t\t\tif ctx.Err() == nil {\n\t\t\t\t\t\teventChan <- ProviderEvent{Type: EventError, Error: ctx.Err()}\n\t\t\t\t\t}\n\t\t\t\t\tclose(eventChan)\n\t\t\t\t\treturn\n\t\t\t\tcase <-time.After(time.Duration(after) * time.Millisecond):\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t\teventChan <- ProviderEvent{Type: EventError, Error: retryErr}\n\t\t\tclose(eventChan)\n\t\t\treturn\n\t\t}\n\t}()\n\n\treturn eventChan\n}\n\nfunc (c *copilotClient) shouldRetry(attempts int, err error) (bool, int64, error) {\n\tvar apierr *openai.Error\n\tif !errors.As(err, &apierr) {\n\t\treturn false, 0, err\n\t}\n\n\t// Check for token expiration (401 Unauthorized)\n\tif apierr.StatusCode == 401 {\n\t\t// Try to refresh the bearer token\n\t\tvar githubToken string\n\n\t\t// 1. Environment variable\n\t\tgithubToken = os.Getenv(\"GITHUB_TOKEN\")\n\n\t\t// 2. API key from options\n\t\tif githubToken == \"\" {\n\t\t\tgithubToken = c.providerOptions.apiKey\n\t\t}\n\n\t\t// 3. Standard GitHub CLI/Copilot locations\n\t\tif githubToken == \"\" {\n\t\t\tvar err error\n\t\t\tgithubToken, err = config.LoadGitHubToken()\n\t\t\tif err != nil {\n\t\t\t\tlogging.Debug(\"Failed to load GitHub token from standard locations during retry\", \"error\", err)\n\t\t\t}\n\t\t}\n\n\t\tif githubToken != \"\" {\n\t\t\tnewBearerToken, tokenErr := c.exchangeGitHubToken(githubToken)\n\t\t\tif tokenErr == nil {\n\t\t\t\tc.options.bearerToken = newBearerToken\n\t\t\t\t// Update the client with the new token\n\t\t\t\t// Note: This is a simplified approach. In a production system,\n\t\t\t\t// you might want to recreate the entire client with the new token\n\t\t\t\tlogging.Info(\"Refreshed Copilot bearer token\")\n\t\t\t\treturn true, 1000, nil // Retry immediately with new token\n\t\t\t}\n\t\t\tlogging.Error(\"Failed to refresh Copilot bearer token\", \"error\", tokenErr)\n\t\t}\n\t\treturn false, 0, fmt.Errorf(\"authentication failed: %w\", err)\n\t}\n\tlogging.Debug(\"Copilot API Error\", \"status\", apierr.StatusCode, \"headers\", apierr.Response.Header, \"body\", apierr.RawJSON())\n\n\tif apierr.StatusCode != 429 && apierr.StatusCode != 500 {\n\t\treturn false, 0, err\n\t}\n\n\tif apierr.StatusCode == 500 {\n\t\tlogging.Warn(\"Copilot API returned 500 error, retrying\", \"error\", err)\n\t}\n\n\tif attempts > maxRetries {\n\t\treturn false, 0, fmt.Errorf(\"maximum retry attempts reached for rate limit: %d retries\", maxRetries)\n\t}\n\n\tretryMs := 0\n\tretryAfterValues := apierr.Response.Header.Values(\"Retry-After\")\n\n\tbackoffMs := 2000 * (1 << (attempts - 1))\n\tjitterMs := int(float64(backoffMs) * 0.2)\n\tretryMs = backoffMs + jitterMs\n\tif len(retryAfterValues) > 0 {\n\t\tif _, err := fmt.Sscanf(retryAfterValues[0], \"%d\", &retryMs); err == nil {\n\t\t\tretryMs = retryMs * 1000\n\t\t}\n\t}\n\treturn true, int64(retryMs), nil\n}\n\nfunc (c *copilotClient) toolCalls(completion openai.ChatCompletion) []message.ToolCall {\n\tvar toolCalls []message.ToolCall\n\n\tif len(completion.Choices) > 0 && len(completion.Choices[0].Message.ToolCalls) > 0 {\n\t\tfor _, call := range completion.Choices[0].Message.ToolCalls {\n\t\t\ttoolCall := message.ToolCall{\n\t\t\t\tID: call.ID,\n\t\t\t\tName: call.Function.Name,\n\t\t\t\tInput: call.Function.Arguments,\n\t\t\t\tType: \"function\",\n\t\t\t\tFinished: true,\n\t\t\t}\n\t\t\ttoolCalls = append(toolCalls, toolCall)\n\t\t}\n\t}\n\n\treturn toolCalls\n}\n\nfunc (c *copilotClient) usage(completion openai.ChatCompletion) TokenUsage {\n\tcachedTokens := completion.Usage.PromptTokensDetails.CachedTokens\n\tinputTokens := completion.Usage.PromptTokens - cachedTokens\n\n\treturn TokenUsage{\n\t\tInputTokens: inputTokens,\n\t\tOutputTokens: completion.Usage.CompletionTokens,\n\t\tCacheCreationTokens: 0, // GitHub Copilot doesn't provide this directly\n\t\tCacheReadTokens: cachedTokens,\n\t}\n}\n\nfunc WithCopilotReasoningEffort(effort string) CopilotOption {\n\treturn func(options *copilotOptions) {\n\t\tdefaultReasoningEffort := \"medium\"\n\t\tswitch effort {\n\t\tcase \"low\", \"medium\", \"high\":\n\t\t\tdefaultReasoningEffort = effort\n\t\tdefault:\n\t\t\tlogging.Warn(\"Invalid reasoning effort, using default: medium\")\n\t\t}\n\t\toptions.reasoningEffort = defaultReasoningEffort\n\t}\n}\n\nfunc WithCopilotExtraHeaders(headers map[string]string) CopilotOption {\n\treturn func(options *copilotOptions) {\n\t\toptions.extraHeaders = headers\n\t}\n}\n\nfunc WithCopilotBearerToken(bearerToken string) CopilotOption {\n\treturn func(options *copilotOptions) {\n\t\toptions.bearerToken = bearerToken\n\t}\n}\n\n"], ["/opencode/internal/llm/agent/agent.go", "package agent\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/llm/models\"\n\t\"github.com/opencode-ai/opencode/internal/llm/prompt\"\n\t\"github.com/opencode-ai/opencode/internal/llm/provider\"\n\t\"github.com/opencode-ai/opencode/internal/llm/tools\"\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n\t\"github.com/opencode-ai/opencode/internal/message\"\n\t\"github.com/opencode-ai/opencode/internal/permission\"\n\t\"github.com/opencode-ai/opencode/internal/pubsub\"\n\t\"github.com/opencode-ai/opencode/internal/session\"\n)\n\n// Common errors\nvar (\n\tErrRequestCancelled = errors.New(\"request cancelled by user\")\n\tErrSessionBusy = errors.New(\"session is currently processing another request\")\n)\n\ntype AgentEventType string\n\nconst (\n\tAgentEventTypeError AgentEventType = \"error\"\n\tAgentEventTypeResponse AgentEventType = \"response\"\n\tAgentEventTypeSummarize AgentEventType = \"summarize\"\n)\n\ntype AgentEvent struct {\n\tType AgentEventType\n\tMessage message.Message\n\tError error\n\n\t// When summarizing\n\tSessionID string\n\tProgress string\n\tDone bool\n}\n\ntype Service interface {\n\tpubsub.Suscriber[AgentEvent]\n\tModel() models.Model\n\tRun(ctx context.Context, sessionID string, content string, attachments ...message.Attachment) (<-chan AgentEvent, error)\n\tCancel(sessionID string)\n\tIsSessionBusy(sessionID string) bool\n\tIsBusy() bool\n\tUpdate(agentName config.AgentName, modelID models.ModelID) (models.Model, error)\n\tSummarize(ctx context.Context, sessionID string) error\n}\n\ntype agent struct {\n\t*pubsub.Broker[AgentEvent]\n\tsessions session.Service\n\tmessages message.Service\n\n\ttools []tools.BaseTool\n\tprovider provider.Provider\n\n\ttitleProvider provider.Provider\n\tsummarizeProvider provider.Provider\n\n\tactiveRequests sync.Map\n}\n\nfunc NewAgent(\n\tagentName config.AgentName,\n\tsessions session.Service,\n\tmessages message.Service,\n\tagentTools []tools.BaseTool,\n) (Service, error) {\n\tagentProvider, err := createAgentProvider(agentName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar titleProvider provider.Provider\n\t// Only generate titles for the coder agent\n\tif agentName == config.AgentCoder {\n\t\ttitleProvider, err = createAgentProvider(config.AgentTitle)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tvar summarizeProvider provider.Provider\n\tif agentName == config.AgentCoder {\n\t\tsummarizeProvider, err = createAgentProvider(config.AgentSummarizer)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tagent := &agent{\n\t\tBroker: pubsub.NewBroker[AgentEvent](),\n\t\tprovider: agentProvider,\n\t\tmessages: messages,\n\t\tsessions: sessions,\n\t\ttools: agentTools,\n\t\ttitleProvider: titleProvider,\n\t\tsummarizeProvider: summarizeProvider,\n\t\tactiveRequests: sync.Map{},\n\t}\n\n\treturn agent, nil\n}\n\nfunc (a *agent) Model() models.Model {\n\treturn a.provider.Model()\n}\n\nfunc (a *agent) Cancel(sessionID string) {\n\t// Cancel regular requests\n\tif cancelFunc, exists := a.activeRequests.LoadAndDelete(sessionID); exists {\n\t\tif cancel, ok := cancelFunc.(context.CancelFunc); ok {\n\t\t\tlogging.InfoPersist(fmt.Sprintf(\"Request cancellation initiated for session: %s\", sessionID))\n\t\t\tcancel()\n\t\t}\n\t}\n\n\t// Also check for summarize requests\n\tif cancelFunc, exists := a.activeRequests.LoadAndDelete(sessionID + \"-summarize\"); exists {\n\t\tif cancel, ok := cancelFunc.(context.CancelFunc); ok {\n\t\t\tlogging.InfoPersist(fmt.Sprintf(\"Summarize cancellation initiated for session: %s\", sessionID))\n\t\t\tcancel()\n\t\t}\n\t}\n}\n\nfunc (a *agent) IsBusy() bool {\n\tbusy := false\n\ta.activeRequests.Range(func(key, value interface{}) bool {\n\t\tif cancelFunc, ok := value.(context.CancelFunc); ok {\n\t\t\tif cancelFunc != nil {\n\t\t\t\tbusy = true\n\t\t\t\treturn false // Stop iterating\n\t\t\t}\n\t\t}\n\t\treturn true // Continue iterating\n\t})\n\treturn busy\n}\n\nfunc (a *agent) IsSessionBusy(sessionID string) bool {\n\t_, busy := a.activeRequests.Load(sessionID)\n\treturn busy\n}\n\nfunc (a *agent) generateTitle(ctx context.Context, sessionID string, content string) error {\n\tif content == \"\" {\n\t\treturn nil\n\t}\n\tif a.titleProvider == nil {\n\t\treturn nil\n\t}\n\tsession, err := a.sessions.Get(ctx, sessionID)\n\tif err != nil {\n\t\treturn err\n\t}\n\tctx = context.WithValue(ctx, tools.SessionIDContextKey, sessionID)\n\tparts := []message.ContentPart{message.TextContent{Text: content}}\n\tresponse, err := a.titleProvider.SendMessages(\n\t\tctx,\n\t\t[]message.Message{\n\t\t\t{\n\t\t\t\tRole: message.User,\n\t\t\t\tParts: parts,\n\t\t\t},\n\t\t},\n\t\tmake([]tools.BaseTool, 0),\n\t)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ttitle := strings.TrimSpace(strings.ReplaceAll(response.Content, \"\\n\", \" \"))\n\tif title == \"\" {\n\t\treturn nil\n\t}\n\n\tsession.Title = title\n\t_, err = a.sessions.Save(ctx, session)\n\treturn err\n}\n\nfunc (a *agent) err(err error) AgentEvent {\n\treturn AgentEvent{\n\t\tType: AgentEventTypeError,\n\t\tError: err,\n\t}\n}\n\nfunc (a *agent) Run(ctx context.Context, sessionID string, content string, attachments ...message.Attachment) (<-chan AgentEvent, error) {\n\tif !a.provider.Model().SupportsAttachments && attachments != nil {\n\t\tattachments = nil\n\t}\n\tevents := make(chan AgentEvent)\n\tif a.IsSessionBusy(sessionID) {\n\t\treturn nil, ErrSessionBusy\n\t}\n\n\tgenCtx, cancel := context.WithCancel(ctx)\n\n\ta.activeRequests.Store(sessionID, cancel)\n\tgo func() {\n\t\tlogging.Debug(\"Request started\", \"sessionID\", sessionID)\n\t\tdefer logging.RecoverPanic(\"agent.Run\", func() {\n\t\t\tevents <- a.err(fmt.Errorf(\"panic while running the agent\"))\n\t\t})\n\t\tvar attachmentParts []message.ContentPart\n\t\tfor _, attachment := range attachments {\n\t\t\tattachmentParts = append(attachmentParts, message.BinaryContent{Path: attachment.FilePath, MIMEType: attachment.MimeType, Data: attachment.Content})\n\t\t}\n\t\tresult := a.processGeneration(genCtx, sessionID, content, attachmentParts)\n\t\tif result.Error != nil && !errors.Is(result.Error, ErrRequestCancelled) && !errors.Is(result.Error, context.Canceled) {\n\t\t\tlogging.ErrorPersist(result.Error.Error())\n\t\t}\n\t\tlogging.Debug(\"Request completed\", \"sessionID\", sessionID)\n\t\ta.activeRequests.Delete(sessionID)\n\t\tcancel()\n\t\ta.Publish(pubsub.CreatedEvent, result)\n\t\tevents <- result\n\t\tclose(events)\n\t}()\n\treturn events, nil\n}\n\nfunc (a *agent) processGeneration(ctx context.Context, sessionID, content string, attachmentParts []message.ContentPart) AgentEvent {\n\tcfg := config.Get()\n\t// List existing messages; if none, start title generation asynchronously.\n\tmsgs, err := a.messages.List(ctx, sessionID)\n\tif err != nil {\n\t\treturn a.err(fmt.Errorf(\"failed to list messages: %w\", err))\n\t}\n\tif len(msgs) == 0 {\n\t\tgo func() {\n\t\t\tdefer logging.RecoverPanic(\"agent.Run\", func() {\n\t\t\t\tlogging.ErrorPersist(\"panic while generating title\")\n\t\t\t})\n\t\t\ttitleErr := a.generateTitle(context.Background(), sessionID, content)\n\t\t\tif titleErr != nil {\n\t\t\t\tlogging.ErrorPersist(fmt.Sprintf(\"failed to generate title: %v\", titleErr))\n\t\t\t}\n\t\t}()\n\t}\n\tsession, err := a.sessions.Get(ctx, sessionID)\n\tif err != nil {\n\t\treturn a.err(fmt.Errorf(\"failed to get session: %w\", err))\n\t}\n\tif session.SummaryMessageID != \"\" {\n\t\tsummaryMsgInex := -1\n\t\tfor i, msg := range msgs {\n\t\t\tif msg.ID == session.SummaryMessageID {\n\t\t\t\tsummaryMsgInex = i\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif summaryMsgInex != -1 {\n\t\t\tmsgs = msgs[summaryMsgInex:]\n\t\t\tmsgs[0].Role = message.User\n\t\t}\n\t}\n\n\tuserMsg, err := a.createUserMessage(ctx, sessionID, content, attachmentParts)\n\tif err != nil {\n\t\treturn a.err(fmt.Errorf(\"failed to create user message: %w\", err))\n\t}\n\t// Append the new user message to the conversation history.\n\tmsgHistory := append(msgs, userMsg)\n\n\tfor {\n\t\t// Check for cancellation before each iteration\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn a.err(ctx.Err())\n\t\tdefault:\n\t\t\t// Continue processing\n\t\t}\n\t\tagentMessage, toolResults, err := a.streamAndHandleEvents(ctx, sessionID, msgHistory)\n\t\tif err != nil {\n\t\t\tif errors.Is(err, context.Canceled) {\n\t\t\t\tagentMessage.AddFinish(message.FinishReasonCanceled)\n\t\t\t\ta.messages.Update(context.Background(), agentMessage)\n\t\t\t\treturn a.err(ErrRequestCancelled)\n\t\t\t}\n\t\t\treturn a.err(fmt.Errorf(\"failed to process events: %w\", err))\n\t\t}\n\t\tif cfg.Debug {\n\t\t\tseqId := (len(msgHistory) + 1) / 2\n\t\t\ttoolResultFilepath := logging.WriteToolResultsJson(sessionID, seqId, toolResults)\n\t\t\tlogging.Info(\"Result\", \"message\", agentMessage.FinishReason(), \"toolResults\", \"{}\", \"filepath\", toolResultFilepath)\n\t\t} else {\n\t\t\tlogging.Info(\"Result\", \"message\", agentMessage.FinishReason(), \"toolResults\", toolResults)\n\t\t}\n\t\tif (agentMessage.FinishReason() == message.FinishReasonToolUse) && toolResults != nil {\n\t\t\t// We are not done, we need to respond with the tool response\n\t\t\tmsgHistory = append(msgHistory, agentMessage, *toolResults)\n\t\t\tcontinue\n\t\t}\n\t\treturn AgentEvent{\n\t\t\tType: AgentEventTypeResponse,\n\t\t\tMessage: agentMessage,\n\t\t\tDone: true,\n\t\t}\n\t}\n}\n\nfunc (a *agent) createUserMessage(ctx context.Context, sessionID, content string, attachmentParts []message.ContentPart) (message.Message, error) {\n\tparts := []message.ContentPart{message.TextContent{Text: content}}\n\tparts = append(parts, attachmentParts...)\n\treturn a.messages.Create(ctx, sessionID, message.CreateMessageParams{\n\t\tRole: message.User,\n\t\tParts: parts,\n\t})\n}\n\nfunc (a *agent) streamAndHandleEvents(ctx context.Context, sessionID string, msgHistory []message.Message) (message.Message, *message.Message, error) {\n\tctx = context.WithValue(ctx, tools.SessionIDContextKey, sessionID)\n\teventChan := a.provider.StreamResponse(ctx, msgHistory, a.tools)\n\n\tassistantMsg, err := a.messages.Create(ctx, sessionID, message.CreateMessageParams{\n\t\tRole: message.Assistant,\n\t\tParts: []message.ContentPart{},\n\t\tModel: a.provider.Model().ID,\n\t})\n\tif err != nil {\n\t\treturn assistantMsg, nil, fmt.Errorf(\"failed to create assistant message: %w\", err)\n\t}\n\n\t// Add the session and message ID into the context if needed by tools.\n\tctx = context.WithValue(ctx, tools.MessageIDContextKey, assistantMsg.ID)\n\n\t// Process each event in the stream.\n\tfor event := range eventChan {\n\t\tif processErr := a.processEvent(ctx, sessionID, &assistantMsg, event); processErr != nil {\n\t\t\ta.finishMessage(ctx, &assistantMsg, message.FinishReasonCanceled)\n\t\t\treturn assistantMsg, nil, processErr\n\t\t}\n\t\tif ctx.Err() != nil {\n\t\t\ta.finishMessage(context.Background(), &assistantMsg, message.FinishReasonCanceled)\n\t\t\treturn assistantMsg, nil, ctx.Err()\n\t\t}\n\t}\n\n\ttoolResults := make([]message.ToolResult, len(assistantMsg.ToolCalls()))\n\ttoolCalls := assistantMsg.ToolCalls()\n\tfor i, toolCall := range toolCalls {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\ta.finishMessage(context.Background(), &assistantMsg, message.FinishReasonCanceled)\n\t\t\t// Make all future tool calls cancelled\n\t\t\tfor j := i; j < len(toolCalls); j++ {\n\t\t\t\ttoolResults[j] = message.ToolResult{\n\t\t\t\t\tToolCallID: toolCalls[j].ID,\n\t\t\t\t\tContent: \"Tool execution canceled by user\",\n\t\t\t\t\tIsError: true,\n\t\t\t\t}\n\t\t\t}\n\t\t\tgoto out\n\t\tdefault:\n\t\t\t// Continue processing\n\t\t\tvar tool tools.BaseTool\n\t\t\tfor _, availableTool := range a.tools {\n\t\t\t\tif availableTool.Info().Name == toolCall.Name {\n\t\t\t\t\ttool = availableTool\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\t// Monkey patch for Copilot Sonnet-4 tool repetition obfuscation\n\t\t\t\t// if strings.HasPrefix(toolCall.Name, availableTool.Info().Name) &&\n\t\t\t\t// \tstrings.HasPrefix(toolCall.Name, availableTool.Info().Name+availableTool.Info().Name) {\n\t\t\t\t// \ttool = availableTool\n\t\t\t\t// \tbreak\n\t\t\t\t// }\n\t\t\t}\n\n\t\t\t// Tool not found\n\t\t\tif tool == nil {\n\t\t\t\ttoolResults[i] = message.ToolResult{\n\t\t\t\t\tToolCallID: toolCall.ID,\n\t\t\t\t\tContent: fmt.Sprintf(\"Tool not found: %s\", toolCall.Name),\n\t\t\t\t\tIsError: true,\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\ttoolResult, toolErr := tool.Run(ctx, tools.ToolCall{\n\t\t\t\tID: toolCall.ID,\n\t\t\t\tName: toolCall.Name,\n\t\t\t\tInput: toolCall.Input,\n\t\t\t})\n\t\t\tif toolErr != nil {\n\t\t\t\tif errors.Is(toolErr, permission.ErrorPermissionDenied) {\n\t\t\t\t\ttoolResults[i] = message.ToolResult{\n\t\t\t\t\t\tToolCallID: toolCall.ID,\n\t\t\t\t\t\tContent: \"Permission denied\",\n\t\t\t\t\t\tIsError: true,\n\t\t\t\t\t}\n\t\t\t\t\tfor j := i + 1; j < len(toolCalls); j++ {\n\t\t\t\t\t\ttoolResults[j] = message.ToolResult{\n\t\t\t\t\t\t\tToolCallID: toolCalls[j].ID,\n\t\t\t\t\t\t\tContent: \"Tool execution canceled by user\",\n\t\t\t\t\t\t\tIsError: true,\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\ta.finishMessage(ctx, &assistantMsg, message.FinishReasonPermissionDenied)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\ttoolResults[i] = message.ToolResult{\n\t\t\t\tToolCallID: toolCall.ID,\n\t\t\t\tContent: toolResult.Content,\n\t\t\t\tMetadata: toolResult.Metadata,\n\t\t\t\tIsError: toolResult.IsError,\n\t\t\t}\n\t\t}\n\t}\nout:\n\tif len(toolResults) == 0 {\n\t\treturn assistantMsg, nil, nil\n\t}\n\tparts := make([]message.ContentPart, 0)\n\tfor _, tr := range toolResults {\n\t\tparts = append(parts, tr)\n\t}\n\tmsg, err := a.messages.Create(context.Background(), assistantMsg.SessionID, message.CreateMessageParams{\n\t\tRole: message.Tool,\n\t\tParts: parts,\n\t})\n\tif err != nil {\n\t\treturn assistantMsg, nil, fmt.Errorf(\"failed to create cancelled tool message: %w\", err)\n\t}\n\n\treturn assistantMsg, &msg, err\n}\n\nfunc (a *agent) finishMessage(ctx context.Context, msg *message.Message, finishReson message.FinishReason) {\n\tmsg.AddFinish(finishReson)\n\t_ = a.messages.Update(ctx, *msg)\n}\n\nfunc (a *agent) processEvent(ctx context.Context, sessionID string, assistantMsg *message.Message, event provider.ProviderEvent) error {\n\tselect {\n\tcase <-ctx.Done():\n\t\treturn ctx.Err()\n\tdefault:\n\t\t// Continue processing.\n\t}\n\n\tswitch event.Type {\n\tcase provider.EventThinkingDelta:\n\t\tassistantMsg.AppendReasoningContent(event.Content)\n\t\treturn a.messages.Update(ctx, *assistantMsg)\n\tcase provider.EventContentDelta:\n\t\tassistantMsg.AppendContent(event.Content)\n\t\treturn a.messages.Update(ctx, *assistantMsg)\n\tcase provider.EventToolUseStart:\n\t\tassistantMsg.AddToolCall(*event.ToolCall)\n\t\treturn a.messages.Update(ctx, *assistantMsg)\n\t// TODO: see how to handle this\n\t// case provider.EventToolUseDelta:\n\t// \ttm := time.Unix(assistantMsg.UpdatedAt, 0)\n\t// \tassistantMsg.AppendToolCallInput(event.ToolCall.ID, event.ToolCall.Input)\n\t// \tif time.Since(tm) > 1000*time.Millisecond {\n\t// \t\terr := a.messages.Update(ctx, *assistantMsg)\n\t// \t\tassistantMsg.UpdatedAt = time.Now().Unix()\n\t// \t\treturn err\n\t// \t}\n\tcase provider.EventToolUseStop:\n\t\tassistantMsg.FinishToolCall(event.ToolCall.ID)\n\t\treturn a.messages.Update(ctx, *assistantMsg)\n\tcase provider.EventError:\n\t\tif errors.Is(event.Error, context.Canceled) {\n\t\t\tlogging.InfoPersist(fmt.Sprintf(\"Event processing canceled for session: %s\", sessionID))\n\t\t\treturn context.Canceled\n\t\t}\n\t\tlogging.ErrorPersist(event.Error.Error())\n\t\treturn event.Error\n\tcase provider.EventComplete:\n\t\tassistantMsg.SetToolCalls(event.Response.ToolCalls)\n\t\tassistantMsg.AddFinish(event.Response.FinishReason)\n\t\tif err := a.messages.Update(ctx, *assistantMsg); err != nil {\n\t\t\treturn fmt.Errorf(\"failed to update message: %w\", err)\n\t\t}\n\t\treturn a.TrackUsage(ctx, sessionID, a.provider.Model(), event.Response.Usage)\n\t}\n\n\treturn nil\n}\n\nfunc (a *agent) TrackUsage(ctx context.Context, sessionID string, model models.Model, usage provider.TokenUsage) error {\n\tsess, err := a.sessions.Get(ctx, sessionID)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to get session: %w\", err)\n\t}\n\n\tcost := model.CostPer1MInCached/1e6*float64(usage.CacheCreationTokens) +\n\t\tmodel.CostPer1MOutCached/1e6*float64(usage.CacheReadTokens) +\n\t\tmodel.CostPer1MIn/1e6*float64(usage.InputTokens) +\n\t\tmodel.CostPer1MOut/1e6*float64(usage.OutputTokens)\n\n\tsess.Cost += cost\n\tsess.CompletionTokens = usage.OutputTokens + usage.CacheReadTokens\n\tsess.PromptTokens = usage.InputTokens + usage.CacheCreationTokens\n\n\t_, err = a.sessions.Save(ctx, sess)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to save session: %w\", err)\n\t}\n\treturn nil\n}\n\nfunc (a *agent) Update(agentName config.AgentName, modelID models.ModelID) (models.Model, error) {\n\tif a.IsBusy() {\n\t\treturn models.Model{}, fmt.Errorf(\"cannot change model while processing requests\")\n\t}\n\n\tif err := config.UpdateAgentModel(agentName, modelID); err != nil {\n\t\treturn models.Model{}, fmt.Errorf(\"failed to update config: %w\", err)\n\t}\n\n\tprovider, err := createAgentProvider(agentName)\n\tif err != nil {\n\t\treturn models.Model{}, fmt.Errorf(\"failed to create provider for model %s: %w\", modelID, err)\n\t}\n\n\ta.provider = provider\n\n\treturn a.provider.Model(), nil\n}\n\nfunc (a *agent) Summarize(ctx context.Context, sessionID string) error {\n\tif a.summarizeProvider == nil {\n\t\treturn fmt.Errorf(\"summarize provider not available\")\n\t}\n\n\t// Check if session is busy\n\tif a.IsSessionBusy(sessionID) {\n\t\treturn ErrSessionBusy\n\t}\n\n\t// Create a new context with cancellation\n\tsummarizeCtx, cancel := context.WithCancel(ctx)\n\n\t// Store the cancel function in activeRequests to allow cancellation\n\ta.activeRequests.Store(sessionID+\"-summarize\", cancel)\n\n\tgo func() {\n\t\tdefer a.activeRequests.Delete(sessionID + \"-summarize\")\n\t\tdefer cancel()\n\t\tevent := AgentEvent{\n\t\t\tType: AgentEventTypeSummarize,\n\t\t\tProgress: \"Starting summarization...\",\n\t\t}\n\n\t\ta.Publish(pubsub.CreatedEvent, event)\n\t\t// Get all messages from the session\n\t\tmsgs, err := a.messages.List(summarizeCtx, sessionID)\n\t\tif err != nil {\n\t\t\tevent = AgentEvent{\n\t\t\t\tType: AgentEventTypeError,\n\t\t\t\tError: fmt.Errorf(\"failed to list messages: %w\", err),\n\t\t\t\tDone: true,\n\t\t\t}\n\t\t\ta.Publish(pubsub.CreatedEvent, event)\n\t\t\treturn\n\t\t}\n\t\tsummarizeCtx = context.WithValue(summarizeCtx, tools.SessionIDContextKey, sessionID)\n\n\t\tif len(msgs) == 0 {\n\t\t\tevent = AgentEvent{\n\t\t\t\tType: AgentEventTypeError,\n\t\t\t\tError: fmt.Errorf(\"no messages to summarize\"),\n\t\t\t\tDone: true,\n\t\t\t}\n\t\t\ta.Publish(pubsub.CreatedEvent, event)\n\t\t\treturn\n\t\t}\n\n\t\tevent = AgentEvent{\n\t\t\tType: AgentEventTypeSummarize,\n\t\t\tProgress: \"Analyzing conversation...\",\n\t\t}\n\t\ta.Publish(pubsub.CreatedEvent, event)\n\n\t\t// Add a system message to guide the summarization\n\t\tsummarizePrompt := \"Provide a detailed but concise summary of our conversation above. Focus on information that would be helpful for continuing the conversation, including what we did, what we're doing, which files we're working on, and what we're going to do next.\"\n\n\t\t// Create a new message with the summarize prompt\n\t\tpromptMsg := message.Message{\n\t\t\tRole: message.User,\n\t\t\tParts: []message.ContentPart{message.TextContent{Text: summarizePrompt}},\n\t\t}\n\n\t\t// Append the prompt to the messages\n\t\tmsgsWithPrompt := append(msgs, promptMsg)\n\n\t\tevent = AgentEvent{\n\t\t\tType: AgentEventTypeSummarize,\n\t\t\tProgress: \"Generating summary...\",\n\t\t}\n\n\t\ta.Publish(pubsub.CreatedEvent, event)\n\n\t\t// Send the messages to the summarize provider\n\t\tresponse, err := a.summarizeProvider.SendMessages(\n\t\t\tsummarizeCtx,\n\t\t\tmsgsWithPrompt,\n\t\t\tmake([]tools.BaseTool, 0),\n\t\t)\n\t\tif err != nil {\n\t\t\tevent = AgentEvent{\n\t\t\t\tType: AgentEventTypeError,\n\t\t\t\tError: fmt.Errorf(\"failed to summarize: %w\", err),\n\t\t\t\tDone: true,\n\t\t\t}\n\t\t\ta.Publish(pubsub.CreatedEvent, event)\n\t\t\treturn\n\t\t}\n\n\t\tsummary := strings.TrimSpace(response.Content)\n\t\tif summary == \"\" {\n\t\t\tevent = AgentEvent{\n\t\t\t\tType: AgentEventTypeError,\n\t\t\t\tError: fmt.Errorf(\"empty summary returned\"),\n\t\t\t\tDone: true,\n\t\t\t}\n\t\t\ta.Publish(pubsub.CreatedEvent, event)\n\t\t\treturn\n\t\t}\n\t\tevent = AgentEvent{\n\t\t\tType: AgentEventTypeSummarize,\n\t\t\tProgress: \"Creating new session...\",\n\t\t}\n\n\t\ta.Publish(pubsub.CreatedEvent, event)\n\t\toldSession, err := a.sessions.Get(summarizeCtx, sessionID)\n\t\tif err != nil {\n\t\t\tevent = AgentEvent{\n\t\t\t\tType: AgentEventTypeError,\n\t\t\t\tError: fmt.Errorf(\"failed to get session: %w\", err),\n\t\t\t\tDone: true,\n\t\t\t}\n\n\t\t\ta.Publish(pubsub.CreatedEvent, event)\n\t\t\treturn\n\t\t}\n\t\t// Create a message in the new session with the summary\n\t\tmsg, err := a.messages.Create(summarizeCtx, oldSession.ID, message.CreateMessageParams{\n\t\t\tRole: message.Assistant,\n\t\t\tParts: []message.ContentPart{\n\t\t\t\tmessage.TextContent{Text: summary},\n\t\t\t\tmessage.Finish{\n\t\t\t\t\tReason: message.FinishReasonEndTurn,\n\t\t\t\t\tTime: time.Now().Unix(),\n\t\t\t\t},\n\t\t\t},\n\t\t\tModel: a.summarizeProvider.Model().ID,\n\t\t})\n\t\tif err != nil {\n\t\t\tevent = AgentEvent{\n\t\t\t\tType: AgentEventTypeError,\n\t\t\t\tError: fmt.Errorf(\"failed to create summary message: %w\", err),\n\t\t\t\tDone: true,\n\t\t\t}\n\n\t\t\ta.Publish(pubsub.CreatedEvent, event)\n\t\t\treturn\n\t\t}\n\t\toldSession.SummaryMessageID = msg.ID\n\t\toldSession.CompletionTokens = response.Usage.OutputTokens\n\t\toldSession.PromptTokens = 0\n\t\tmodel := a.summarizeProvider.Model()\n\t\tusage := response.Usage\n\t\tcost := model.CostPer1MInCached/1e6*float64(usage.CacheCreationTokens) +\n\t\t\tmodel.CostPer1MOutCached/1e6*float64(usage.CacheReadTokens) +\n\t\t\tmodel.CostPer1MIn/1e6*float64(usage.InputTokens) +\n\t\t\tmodel.CostPer1MOut/1e6*float64(usage.OutputTokens)\n\t\toldSession.Cost += cost\n\t\t_, err = a.sessions.Save(summarizeCtx, oldSession)\n\t\tif err != nil {\n\t\t\tevent = AgentEvent{\n\t\t\t\tType: AgentEventTypeError,\n\t\t\t\tError: fmt.Errorf(\"failed to save session: %w\", err),\n\t\t\t\tDone: true,\n\t\t\t}\n\t\t\ta.Publish(pubsub.CreatedEvent, event)\n\t\t}\n\n\t\tevent = AgentEvent{\n\t\t\tType: AgentEventTypeSummarize,\n\t\t\tSessionID: oldSession.ID,\n\t\t\tProgress: \"Summary complete\",\n\t\t\tDone: true,\n\t\t}\n\t\ta.Publish(pubsub.CreatedEvent, event)\n\t\t// Send final success event with the new session ID\n\t}()\n\n\treturn nil\n}\n\nfunc createAgentProvider(agentName config.AgentName) (provider.Provider, error) {\n\tcfg := config.Get()\n\tagentConfig, ok := cfg.Agents[agentName]\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"agent %s not found\", agentName)\n\t}\n\tmodel, ok := models.SupportedModels[agentConfig.Model]\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"model %s not supported\", agentConfig.Model)\n\t}\n\n\tproviderCfg, ok := cfg.Providers[model.Provider]\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"provider %s not supported\", model.Provider)\n\t}\n\tif providerCfg.Disabled {\n\t\treturn nil, fmt.Errorf(\"provider %s is not enabled\", model.Provider)\n\t}\n\tmaxTokens := model.DefaultMaxTokens\n\tif agentConfig.MaxTokens > 0 {\n\t\tmaxTokens = agentConfig.MaxTokens\n\t}\n\topts := []provider.ProviderClientOption{\n\t\tprovider.WithAPIKey(providerCfg.APIKey),\n\t\tprovider.WithModel(model),\n\t\tprovider.WithSystemMessage(prompt.GetAgentPrompt(agentName, model.Provider)),\n\t\tprovider.WithMaxTokens(maxTokens),\n\t}\n\tif model.Provider == models.ProviderOpenAI || model.Provider == models.ProviderLocal && model.CanReason {\n\t\topts = append(\n\t\t\topts,\n\t\t\tprovider.WithOpenAIOptions(\n\t\t\t\tprovider.WithReasoningEffort(agentConfig.ReasoningEffort),\n\t\t\t),\n\t\t)\n\t} else if model.Provider == models.ProviderAnthropic && model.CanReason && agentName == config.AgentCoder {\n\t\topts = append(\n\t\t\topts,\n\t\t\tprovider.WithAnthropicOptions(\n\t\t\t\tprovider.WithAnthropicShouldThinkFn(provider.DefaultShouldThinkFn),\n\t\t\t),\n\t\t)\n\t}\n\tagentProvider, err := provider.NewProvider(\n\t\tmodel.Provider,\n\t\topts...,\n\t)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"could not create provider: %v\", err)\n\t}\n\n\treturn agentProvider, nil\n}\n"], ["/opencode/internal/lsp/watcher/watcher.go", "package watcher\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com/bmatcuk/doublestar/v4\"\n\t\"github.com/fsnotify/fsnotify\"\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n\t\"github.com/opencode-ai/opencode/internal/lsp\"\n\t\"github.com/opencode-ai/opencode/internal/lsp/protocol\"\n)\n\n// WorkspaceWatcher manages LSP file watching\ntype WorkspaceWatcher struct {\n\tclient *lsp.Client\n\tworkspacePath string\n\n\tdebounceTime time.Duration\n\tdebounceMap map[string]*time.Timer\n\tdebounceMu sync.Mutex\n\n\t// File watchers registered by the server\n\tregistrations []protocol.FileSystemWatcher\n\tregistrationMu sync.RWMutex\n}\n\n// NewWorkspaceWatcher creates a new workspace watcher\nfunc NewWorkspaceWatcher(client *lsp.Client) *WorkspaceWatcher {\n\treturn &WorkspaceWatcher{\n\t\tclient: client,\n\t\tdebounceTime: 300 * time.Millisecond,\n\t\tdebounceMap: make(map[string]*time.Timer),\n\t\tregistrations: []protocol.FileSystemWatcher{},\n\t}\n}\n\n// AddRegistrations adds file watchers to track\nfunc (w *WorkspaceWatcher) AddRegistrations(ctx context.Context, id string, watchers []protocol.FileSystemWatcher) {\n\tcnf := config.Get()\n\n\tlogging.Debug(\"Adding file watcher registrations\")\n\tw.registrationMu.Lock()\n\tdefer w.registrationMu.Unlock()\n\n\t// Add new watchers\n\tw.registrations = append(w.registrations, watchers...)\n\n\t// Print detailed registration information for debugging\n\tif cnf.DebugLSP {\n\t\tlogging.Debug(\"Adding file watcher registrations\",\n\t\t\t\"id\", id,\n\t\t\t\"watchers\", len(watchers),\n\t\t\t\"total\", len(w.registrations),\n\t\t)\n\n\t\tfor i, watcher := range watchers {\n\t\t\tlogging.Debug(\"Registration\", \"index\", i+1)\n\n\t\t\t// Log the GlobPattern\n\t\t\tswitch v := watcher.GlobPattern.Value.(type) {\n\t\t\tcase string:\n\t\t\t\tlogging.Debug(\"GlobPattern\", \"pattern\", v)\n\t\t\tcase protocol.RelativePattern:\n\t\t\t\tlogging.Debug(\"GlobPattern\", \"pattern\", v.Pattern)\n\n\t\t\t\t// Log BaseURI details\n\t\t\t\tswitch u := v.BaseURI.Value.(type) {\n\t\t\t\tcase string:\n\t\t\t\t\tlogging.Debug(\"BaseURI\", \"baseURI\", u)\n\t\t\t\tcase protocol.DocumentUri:\n\t\t\t\t\tlogging.Debug(\"BaseURI\", \"baseURI\", u)\n\t\t\t\tdefault:\n\t\t\t\t\tlogging.Debug(\"BaseURI\", \"baseURI\", u)\n\t\t\t\t}\n\t\t\tdefault:\n\t\t\t\tlogging.Debug(\"GlobPattern\", \"unknown type\", fmt.Sprintf(\"%T\", v))\n\t\t\t}\n\n\t\t\t// Log WatchKind\n\t\t\twatchKind := protocol.WatchKind(protocol.WatchChange | protocol.WatchCreate | protocol.WatchDelete)\n\t\t\tif watcher.Kind != nil {\n\t\t\t\twatchKind = *watcher.Kind\n\t\t\t}\n\n\t\t\tlogging.Debug(\"WatchKind\", \"kind\", watchKind)\n\t\t}\n\t}\n\n\t// Determine server type for specialized handling\n\tserverName := getServerNameFromContext(ctx)\n\tlogging.Debug(\"Server type detected\", \"serverName\", serverName)\n\n\t// Check if this server has sent file watchers\n\thasFileWatchers := len(watchers) > 0\n\n\t// For servers that need file preloading, we'll use a smart approach\n\tif shouldPreloadFiles(serverName) || !hasFileWatchers {\n\t\tgo func() {\n\t\t\tstartTime := time.Now()\n\t\t\tfilesOpened := 0\n\n\t\t\t// Determine max files to open based on server type\n\t\t\tmaxFilesToOpen := 50 // Default conservative limit\n\n\t\t\tswitch serverName {\n\t\t\tcase \"typescript\", \"typescript-language-server\", \"tsserver\", \"vtsls\":\n\t\t\t\t// TypeScript servers benefit from seeing more files\n\t\t\t\tmaxFilesToOpen = 100\n\t\t\tcase \"java\", \"jdtls\":\n\t\t\t\t// Java servers need to see many files for project model\n\t\t\t\tmaxFilesToOpen = 200\n\t\t\t}\n\n\t\t\t// First, open high-priority files\n\t\t\thighPriorityFilesOpened := w.openHighPriorityFiles(ctx, serverName)\n\t\t\tfilesOpened += highPriorityFilesOpened\n\n\t\t\tif cnf.DebugLSP {\n\t\t\t\tlogging.Debug(\"Opened high-priority files\",\n\t\t\t\t\t\"count\", highPriorityFilesOpened,\n\t\t\t\t\t\"serverName\", serverName)\n\t\t\t}\n\n\t\t\t// If we've already opened enough high-priority files, we might not need more\n\t\t\tif filesOpened >= maxFilesToOpen {\n\t\t\t\tif cnf.DebugLSP {\n\t\t\t\t\tlogging.Debug(\"Reached file limit with high-priority files\",\n\t\t\t\t\t\t\"filesOpened\", filesOpened,\n\t\t\t\t\t\t\"maxFiles\", maxFilesToOpen)\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\t// For the remaining slots, walk the directory and open matching files\n\n\t\t\terr := filepath.WalkDir(w.workspacePath, func(path string, d os.DirEntry, err error) error {\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\n\t\t\t\t// Skip directories that should be excluded\n\t\t\t\tif d.IsDir() {\n\t\t\t\t\tif path != w.workspacePath && shouldExcludeDir(path) {\n\t\t\t\t\t\tif cnf.DebugLSP {\n\t\t\t\t\t\t\tlogging.Debug(\"Skipping excluded directory\", \"path\", path)\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn filepath.SkipDir\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\t// Process files, but limit the total number\n\t\t\t\t\tif filesOpened < maxFilesToOpen {\n\t\t\t\t\t\t// Only process if it's not already open (high-priority files were opened earlier)\n\t\t\t\t\t\tif !w.client.IsFileOpen(path) {\n\t\t\t\t\t\t\tw.openMatchingFile(ctx, path)\n\t\t\t\t\t\t\tfilesOpened++\n\n\t\t\t\t\t\t\t// Add a small delay after every 10 files to prevent overwhelming the server\n\t\t\t\t\t\t\tif filesOpened%10 == 0 {\n\t\t\t\t\t\t\t\ttime.Sleep(50 * time.Millisecond)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// We've reached our limit, stop walking\n\t\t\t\t\t\treturn filepath.SkipAll\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\treturn nil\n\t\t\t})\n\n\t\t\telapsedTime := time.Since(startTime)\n\t\t\tif cnf.DebugLSP {\n\t\t\t\tlogging.Debug(\"Limited workspace scan complete\",\n\t\t\t\t\t\"filesOpened\", filesOpened,\n\t\t\t\t\t\"maxFiles\", maxFilesToOpen,\n\t\t\t\t\t\"elapsedTime\", elapsedTime.Seconds(),\n\t\t\t\t\t\"workspacePath\", w.workspacePath,\n\t\t\t\t)\n\t\t\t}\n\n\t\t\tif err != nil && cnf.DebugLSP {\n\t\t\t\tlogging.Debug(\"Error scanning workspace for files to open\", \"error\", err)\n\t\t\t}\n\t\t}()\n\t} else if cnf.DebugLSP {\n\t\tlogging.Debug(\"Using on-demand file loading for server\", \"server\", serverName)\n\t}\n}\n\n// openHighPriorityFiles opens important files for the server type\n// Returns the number of files opened\nfunc (w *WorkspaceWatcher) openHighPriorityFiles(ctx context.Context, serverName string) int {\n\tcnf := config.Get()\n\tfilesOpened := 0\n\n\t// Define patterns for high-priority files based on server type\n\tvar patterns []string\n\n\tswitch serverName {\n\tcase \"typescript\", \"typescript-language-server\", \"tsserver\", \"vtsls\":\n\t\tpatterns = []string{\n\t\t\t\"**/tsconfig.json\",\n\t\t\t\"**/package.json\",\n\t\t\t\"**/jsconfig.json\",\n\t\t\t\"**/index.ts\",\n\t\t\t\"**/index.js\",\n\t\t\t\"**/main.ts\",\n\t\t\t\"**/main.js\",\n\t\t}\n\tcase \"gopls\":\n\t\tpatterns = []string{\n\t\t\t\"**/go.mod\",\n\t\t\t\"**/go.sum\",\n\t\t\t\"**/main.go\",\n\t\t}\n\tcase \"rust-analyzer\":\n\t\tpatterns = []string{\n\t\t\t\"**/Cargo.toml\",\n\t\t\t\"**/Cargo.lock\",\n\t\t\t\"**/src/lib.rs\",\n\t\t\t\"**/src/main.rs\",\n\t\t}\n\tcase \"python\", \"pyright\", \"pylsp\":\n\t\tpatterns = []string{\n\t\t\t\"**/pyproject.toml\",\n\t\t\t\"**/setup.py\",\n\t\t\t\"**/requirements.txt\",\n\t\t\t\"**/__init__.py\",\n\t\t\t\"**/__main__.py\",\n\t\t}\n\tcase \"clangd\":\n\t\tpatterns = []string{\n\t\t\t\"**/CMakeLists.txt\",\n\t\t\t\"**/Makefile\",\n\t\t\t\"**/compile_commands.json\",\n\t\t}\n\tcase \"java\", \"jdtls\":\n\t\tpatterns = []string{\n\t\t\t\"**/pom.xml\",\n\t\t\t\"**/build.gradle\",\n\t\t\t\"**/src/main/java/**/*.java\",\n\t\t}\n\tdefault:\n\t\t// For unknown servers, use common configuration files\n\t\tpatterns = []string{\n\t\t\t\"**/package.json\",\n\t\t\t\"**/Makefile\",\n\t\t\t\"**/CMakeLists.txt\",\n\t\t\t\"**/.editorconfig\",\n\t\t}\n\t}\n\n\t// For each pattern, find and open matching files\n\tfor _, pattern := range patterns {\n\t\t// Use doublestar.Glob to find files matching the pattern (supports ** patterns)\n\t\tmatches, err := doublestar.Glob(os.DirFS(w.workspacePath), pattern)\n\t\tif err != nil {\n\t\t\tif cnf.DebugLSP {\n\t\t\t\tlogging.Debug(\"Error finding high-priority files\", \"pattern\", pattern, \"error\", err)\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\tfor _, match := range matches {\n\t\t\t// Convert relative path to absolute\n\t\t\tfullPath := filepath.Join(w.workspacePath, match)\n\n\t\t\t// Skip directories and excluded files\n\t\t\tinfo, err := os.Stat(fullPath)\n\t\t\tif err != nil || info.IsDir() || shouldExcludeFile(fullPath) {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// Open the file\n\t\t\tif err := w.client.OpenFile(ctx, fullPath); err != nil {\n\t\t\t\tif cnf.DebugLSP {\n\t\t\t\t\tlogging.Debug(\"Error opening high-priority file\", \"path\", fullPath, \"error\", err)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tfilesOpened++\n\t\t\t\tif cnf.DebugLSP {\n\t\t\t\t\tlogging.Debug(\"Opened high-priority file\", \"path\", fullPath)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Add a small delay to prevent overwhelming the server\n\t\t\ttime.Sleep(20 * time.Millisecond)\n\n\t\t\t// Limit the number of files opened per pattern\n\t\t\tif filesOpened >= 5 && (serverName != \"java\" && serverName != \"jdtls\") {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\treturn filesOpened\n}\n\n// WatchWorkspace sets up file watching for a workspace\nfunc (w *WorkspaceWatcher) WatchWorkspace(ctx context.Context, workspacePath string) {\n\tcnf := config.Get()\n\tw.workspacePath = workspacePath\n\n\t// Store the watcher in the context for later use\n\tctx = context.WithValue(ctx, \"workspaceWatcher\", w)\n\n\t// If the server name isn't already in the context, try to detect it\n\tif _, ok := ctx.Value(\"serverName\").(string); !ok {\n\t\tserverName := getServerNameFromContext(ctx)\n\t\tctx = context.WithValue(ctx, \"serverName\", serverName)\n\t}\n\n\tserverName := getServerNameFromContext(ctx)\n\tlogging.Debug(\"Starting workspace watcher\", \"workspacePath\", workspacePath, \"serverName\", serverName)\n\n\t// Register handler for file watcher registrations from the server\n\tlsp.RegisterFileWatchHandler(func(id string, watchers []protocol.FileSystemWatcher) {\n\t\tw.AddRegistrations(ctx, id, watchers)\n\t})\n\n\twatcher, err := fsnotify.NewWatcher()\n\tif err != nil {\n\t\tlogging.Error(\"Error creating watcher\", \"error\", err)\n\t}\n\tdefer watcher.Close()\n\n\t// Watch the workspace recursively\n\terr = filepath.WalkDir(workspacePath, func(path string, d os.DirEntry, err error) error {\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Skip excluded directories (except workspace root)\n\t\tif d.IsDir() && path != workspacePath {\n\t\t\tif shouldExcludeDir(path) {\n\t\t\t\tif cnf.DebugLSP {\n\t\t\t\t\tlogging.Debug(\"Skipping excluded directory\", \"path\", path)\n\t\t\t\t}\n\t\t\t\treturn filepath.SkipDir\n\t\t\t}\n\t\t}\n\n\t\t// Add directories to watcher\n\t\tif d.IsDir() {\n\t\t\terr = watcher.Add(path)\n\t\t\tif err != nil {\n\t\t\t\tlogging.Error(\"Error watching path\", \"path\", path, \"error\", err)\n\t\t\t}\n\t\t}\n\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\tlogging.Error(\"Error walking workspace\", \"error\", err)\n\t}\n\n\t// Event loop\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn\n\t\tcase event, ok := <-watcher.Events:\n\t\t\tif !ok {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\turi := fmt.Sprintf(\"file://%s\", event.Name)\n\n\t\t\t// Add new directories to the watcher\n\t\t\tif event.Op&fsnotify.Create != 0 {\n\t\t\t\tif info, err := os.Stat(event.Name); err == nil {\n\t\t\t\t\tif info.IsDir() {\n\t\t\t\t\t\t// Skip excluded directories\n\t\t\t\t\t\tif !shouldExcludeDir(event.Name) {\n\t\t\t\t\t\t\tif err := watcher.Add(event.Name); err != nil {\n\t\t\t\t\t\t\t\tlogging.Error(\"Error adding directory to watcher\", \"path\", event.Name, \"error\", err)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// For newly created files\n\t\t\t\t\t\tif !shouldExcludeFile(event.Name) {\n\t\t\t\t\t\t\tw.openMatchingFile(ctx, event.Name)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Debug logging\n\t\t\tif cnf.DebugLSP {\n\t\t\t\tmatched, kind := w.isPathWatched(event.Name)\n\t\t\t\tlogging.Debug(\"File event\",\n\t\t\t\t\t\"path\", event.Name,\n\t\t\t\t\t\"operation\", event.Op.String(),\n\t\t\t\t\t\"watched\", matched,\n\t\t\t\t\t\"kind\", kind,\n\t\t\t\t)\n\n\t\t\t}\n\n\t\t\t// Check if this path should be watched according to server registrations\n\t\t\tif watched, watchKind := w.isPathWatched(event.Name); watched {\n\t\t\t\tswitch {\n\t\t\t\tcase event.Op&fsnotify.Write != 0:\n\t\t\t\t\tif watchKind&protocol.WatchChange != 0 {\n\t\t\t\t\t\tw.debounceHandleFileEvent(ctx, uri, protocol.FileChangeType(protocol.Changed))\n\t\t\t\t\t}\n\t\t\t\tcase event.Op&fsnotify.Create != 0:\n\t\t\t\t\t// Already handled earlier in the event loop\n\t\t\t\t\t// Just send the notification if needed\n\t\t\t\t\tinfo, err := os.Stat(event.Name)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlogging.Error(\"Error getting file info\", \"path\", event.Name, \"error\", err)\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\tif !info.IsDir() && watchKind&protocol.WatchCreate != 0 {\n\t\t\t\t\t\tw.debounceHandleFileEvent(ctx, uri, protocol.FileChangeType(protocol.Created))\n\t\t\t\t\t}\n\t\t\t\tcase event.Op&fsnotify.Remove != 0:\n\t\t\t\t\tif watchKind&protocol.WatchDelete != 0 {\n\t\t\t\t\t\tw.handleFileEvent(ctx, uri, protocol.FileChangeType(protocol.Deleted))\n\t\t\t\t\t}\n\t\t\t\tcase event.Op&fsnotify.Rename != 0:\n\t\t\t\t\t// For renames, first delete\n\t\t\t\t\tif watchKind&protocol.WatchDelete != 0 {\n\t\t\t\t\t\tw.handleFileEvent(ctx, uri, protocol.FileChangeType(protocol.Deleted))\n\t\t\t\t\t}\n\n\t\t\t\t\t// Then check if the new file exists and create an event\n\t\t\t\t\tif info, err := os.Stat(event.Name); err == nil && !info.IsDir() {\n\t\t\t\t\t\tif watchKind&protocol.WatchCreate != 0 {\n\t\t\t\t\t\t\tw.debounceHandleFileEvent(ctx, uri, protocol.FileChangeType(protocol.Created))\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\tcase err, ok := <-watcher.Errors:\n\t\t\tif !ok {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tlogging.Error(\"Error watching file\", \"error\", err)\n\t\t}\n\t}\n}\n\n// isPathWatched checks if a path should be watched based on server registrations\nfunc (w *WorkspaceWatcher) isPathWatched(path string) (bool, protocol.WatchKind) {\n\tw.registrationMu.RLock()\n\tdefer w.registrationMu.RUnlock()\n\n\t// If no explicit registrations, watch everything\n\tif len(w.registrations) == 0 {\n\t\treturn true, protocol.WatchKind(protocol.WatchChange | protocol.WatchCreate | protocol.WatchDelete)\n\t}\n\n\t// Check each registration\n\tfor _, reg := range w.registrations {\n\t\tisMatch := w.matchesPattern(path, reg.GlobPattern)\n\t\tif isMatch {\n\t\t\tkind := protocol.WatchKind(protocol.WatchChange | protocol.WatchCreate | protocol.WatchDelete)\n\t\t\tif reg.Kind != nil {\n\t\t\t\tkind = *reg.Kind\n\t\t\t}\n\t\t\treturn true, kind\n\t\t}\n\t}\n\n\treturn false, 0\n}\n\n// matchesGlob handles advanced glob patterns including ** and alternatives\nfunc matchesGlob(pattern, path string) bool {\n\t// Handle file extension patterns with braces like *.{go,mod,sum}\n\tif strings.Contains(pattern, \"{\") && strings.Contains(pattern, \"}\") {\n\t\t// Extract extensions from pattern like \"*.{go,mod,sum}\"\n\t\tparts := strings.SplitN(pattern, \"{\", 2)\n\t\tif len(parts) == 2 {\n\t\t\tprefix := parts[0]\n\t\t\textPart := strings.SplitN(parts[1], \"}\", 2)\n\t\t\tif len(extPart) == 2 {\n\t\t\t\textensions := strings.Split(extPart[0], \",\")\n\t\t\t\tsuffix := extPart[1]\n\n\t\t\t\t// Check if the path matches any of the extensions\n\t\t\t\tfor _, ext := range extensions {\n\t\t\t\t\textPattern := prefix + ext + suffix\n\t\t\t\t\tisMatch := matchesSimpleGlob(extPattern, path)\n\t\t\t\t\tif isMatch {\n\t\t\t\t\t\treturn true\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t}\n\n\treturn matchesSimpleGlob(pattern, path)\n}\n\n// matchesSimpleGlob handles glob patterns with ** wildcards\nfunc matchesSimpleGlob(pattern, path string) bool {\n\t// Handle special case for **/*.ext pattern (common in LSP)\n\tif strings.HasPrefix(pattern, \"**/\") {\n\t\trest := strings.TrimPrefix(pattern, \"**/\")\n\n\t\t// If the rest is a simple file extension pattern like *.go\n\t\tif strings.HasPrefix(rest, \"*.\") {\n\t\t\text := strings.TrimPrefix(rest, \"*\")\n\t\t\tisMatch := strings.HasSuffix(path, ext)\n\t\t\treturn isMatch\n\t\t}\n\n\t\t// Otherwise, try to check if the path ends with the rest part\n\t\tisMatch := strings.HasSuffix(path, rest)\n\n\t\t// If it matches directly, great!\n\t\tif isMatch {\n\t\t\treturn true\n\t\t}\n\n\t\t// Otherwise, check if any path component matches\n\t\tpathComponents := strings.Split(path, \"/\")\n\t\tfor i := range pathComponents {\n\t\t\tsubPath := strings.Join(pathComponents[i:], \"/\")\n\t\t\tif strings.HasSuffix(subPath, rest) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\n\t\treturn false\n\t}\n\n\t// Handle other ** wildcard pattern cases\n\tif strings.Contains(pattern, \"**\") {\n\t\tparts := strings.Split(pattern, \"**\")\n\n\t\t// Validate the path starts with the first part\n\t\tif !strings.HasPrefix(path, parts[0]) && parts[0] != \"\" {\n\t\t\treturn false\n\t\t}\n\n\t\t// For patterns like \"**/*.go\", just check the suffix\n\t\tif len(parts) == 2 && parts[0] == \"\" {\n\t\t\tisMatch := strings.HasSuffix(path, parts[1])\n\t\t\treturn isMatch\n\t\t}\n\n\t\t// For other patterns, handle middle part\n\t\tremaining := strings.TrimPrefix(path, parts[0])\n\t\tif len(parts) == 2 {\n\t\t\tisMatch := strings.HasSuffix(remaining, parts[1])\n\t\t\treturn isMatch\n\t\t}\n\t}\n\n\t// Handle simple * wildcard for file extension patterns (*.go, *.sum, etc)\n\tif strings.HasPrefix(pattern, \"*.\") {\n\t\text := strings.TrimPrefix(pattern, \"*\")\n\t\tisMatch := strings.HasSuffix(path, ext)\n\t\treturn isMatch\n\t}\n\n\t// Fall back to simple matching for simpler patterns\n\tmatched, err := filepath.Match(pattern, path)\n\tif err != nil {\n\t\tlogging.Error(\"Error matching pattern\", \"pattern\", pattern, \"path\", path, \"error\", err)\n\t\treturn false\n\t}\n\n\treturn matched\n}\n\n// matchesPattern checks if a path matches the glob pattern\nfunc (w *WorkspaceWatcher) matchesPattern(path string, pattern protocol.GlobPattern) bool {\n\tpatternInfo, err := pattern.AsPattern()\n\tif err != nil {\n\t\tlogging.Error(\"Error parsing pattern\", \"pattern\", pattern, \"error\", err)\n\t\treturn false\n\t}\n\n\tbasePath := patternInfo.GetBasePath()\n\tpatternText := patternInfo.GetPattern()\n\n\tpath = filepath.ToSlash(path)\n\n\t// For simple patterns without base path\n\tif basePath == \"\" {\n\t\t// Check if the pattern matches the full path or just the file extension\n\t\tfullPathMatch := matchesGlob(patternText, path)\n\t\tbaseNameMatch := matchesGlob(patternText, filepath.Base(path))\n\n\t\treturn fullPathMatch || baseNameMatch\n\t}\n\n\t// For relative patterns\n\tbasePath = strings.TrimPrefix(basePath, \"file://\")\n\tbasePath = filepath.ToSlash(basePath)\n\n\t// Make path relative to basePath for matching\n\trelPath, err := filepath.Rel(basePath, path)\n\tif err != nil {\n\t\tlogging.Error(\"Error getting relative path\", \"path\", path, \"basePath\", basePath, \"error\", err)\n\t\treturn false\n\t}\n\trelPath = filepath.ToSlash(relPath)\n\n\tisMatch := matchesGlob(patternText, relPath)\n\n\treturn isMatch\n}\n\n// debounceHandleFileEvent handles file events with debouncing to reduce notifications\nfunc (w *WorkspaceWatcher) debounceHandleFileEvent(ctx context.Context, uri string, changeType protocol.FileChangeType) {\n\tw.debounceMu.Lock()\n\tdefer w.debounceMu.Unlock()\n\n\t// Create a unique key based on URI and change type\n\tkey := fmt.Sprintf(\"%s:%d\", uri, changeType)\n\n\t// Cancel existing timer if any\n\tif timer, exists := w.debounceMap[key]; exists {\n\t\ttimer.Stop()\n\t}\n\n\t// Create new timer\n\tw.debounceMap[key] = time.AfterFunc(w.debounceTime, func() {\n\t\tw.handleFileEvent(ctx, uri, changeType)\n\n\t\t// Cleanup timer after execution\n\t\tw.debounceMu.Lock()\n\t\tdelete(w.debounceMap, key)\n\t\tw.debounceMu.Unlock()\n\t})\n}\n\n// handleFileEvent sends file change notifications\nfunc (w *WorkspaceWatcher) handleFileEvent(ctx context.Context, uri string, changeType protocol.FileChangeType) {\n\t// If the file is open and it's a change event, use didChange notification\n\tfilePath := uri[7:] // Remove \"file://\" prefix\n\tif changeType == protocol.FileChangeType(protocol.Deleted) {\n\t\tw.client.ClearDiagnosticsForURI(protocol.DocumentUri(uri))\n\t} else if changeType == protocol.FileChangeType(protocol.Changed) && w.client.IsFileOpen(filePath) {\n\t\terr := w.client.NotifyChange(ctx, filePath)\n\t\tif err != nil {\n\t\t\tlogging.Error(\"Error notifying change\", \"error\", err)\n\t\t}\n\t\treturn\n\t}\n\n\t// Notify LSP server about the file event using didChangeWatchedFiles\n\tif err := w.notifyFileEvent(ctx, uri, changeType); err != nil {\n\t\tlogging.Error(\"Error notifying LSP server about file event\", \"error\", err)\n\t}\n}\n\n// notifyFileEvent sends a didChangeWatchedFiles notification for a file event\nfunc (w *WorkspaceWatcher) notifyFileEvent(ctx context.Context, uri string, changeType protocol.FileChangeType) error {\n\tcnf := config.Get()\n\tif cnf.DebugLSP {\n\t\tlogging.Debug(\"Notifying file event\",\n\t\t\t\"uri\", uri,\n\t\t\t\"changeType\", changeType,\n\t\t)\n\t}\n\n\tparams := protocol.DidChangeWatchedFilesParams{\n\t\tChanges: []protocol.FileEvent{\n\t\t\t{\n\t\t\t\tURI: protocol.DocumentUri(uri),\n\t\t\t\tType: changeType,\n\t\t\t},\n\t\t},\n\t}\n\n\treturn w.client.DidChangeWatchedFiles(ctx, params)\n}\n\n// getServerNameFromContext extracts the server name from the context\n// This is a best-effort function that tries to identify which LSP server we're dealing with\nfunc getServerNameFromContext(ctx context.Context) string {\n\t// First check if the server name is directly stored in the context\n\tif serverName, ok := ctx.Value(\"serverName\").(string); ok && serverName != \"\" {\n\t\treturn strings.ToLower(serverName)\n\t}\n\n\t// Otherwise, try to extract server name from the client command path\n\tif w, ok := ctx.Value(\"workspaceWatcher\").(*WorkspaceWatcher); ok && w != nil && w.client != nil && w.client.Cmd != nil {\n\t\tpath := strings.ToLower(w.client.Cmd.Path)\n\n\t\t// Extract server name from path\n\t\tif strings.Contains(path, \"typescript\") || strings.Contains(path, \"tsserver\") || strings.Contains(path, \"vtsls\") {\n\t\t\treturn \"typescript\"\n\t\t} else if strings.Contains(path, \"gopls\") {\n\t\t\treturn \"gopls\"\n\t\t} else if strings.Contains(path, \"rust-analyzer\") {\n\t\t\treturn \"rust-analyzer\"\n\t\t} else if strings.Contains(path, \"pyright\") || strings.Contains(path, \"pylsp\") || strings.Contains(path, \"python\") {\n\t\t\treturn \"python\"\n\t\t} else if strings.Contains(path, \"clangd\") {\n\t\t\treturn \"clangd\"\n\t\t} else if strings.Contains(path, \"jdtls\") || strings.Contains(path, \"java\") {\n\t\t\treturn \"java\"\n\t\t}\n\n\t\t// Return the base name as fallback\n\t\treturn filepath.Base(path)\n\t}\n\n\treturn \"unknown\"\n}\n\n// shouldPreloadFiles determines if we should preload files for a specific language server\n// Some servers work better with preloaded files, others don't need it\nfunc shouldPreloadFiles(serverName string) bool {\n\t// TypeScript/JavaScript servers typically need some files preloaded\n\t// to properly resolve imports and provide intellisense\n\tswitch serverName {\n\tcase \"typescript\", \"typescript-language-server\", \"tsserver\", \"vtsls\":\n\t\treturn true\n\tcase \"java\", \"jdtls\":\n\t\t// Java servers often need to see source files to build the project model\n\t\treturn true\n\tdefault:\n\t\t// For most servers, we'll use lazy loading by default\n\t\treturn false\n\t}\n}\n\n// Common patterns for directories and files to exclude\n// TODO: make configurable\nvar (\n\texcludedDirNames = map[string]bool{\n\t\t\".git\": true,\n\t\t\"node_modules\": true,\n\t\t\"dist\": true,\n\t\t\"build\": true,\n\t\t\"out\": true,\n\t\t\"bin\": true,\n\t\t\".idea\": true,\n\t\t\".vscode\": true,\n\t\t\".cache\": true,\n\t\t\"coverage\": true,\n\t\t\"target\": true, // Rust build output\n\t\t\"vendor\": true, // Go vendor directory\n\t}\n\n\texcludedFileExtensions = map[string]bool{\n\t\t\".swp\": true,\n\t\t\".swo\": true,\n\t\t\".tmp\": true,\n\t\t\".temp\": true,\n\t\t\".bak\": true,\n\t\t\".log\": true,\n\t\t\".o\": true, // Object files\n\t\t\".so\": true, // Shared libraries\n\t\t\".dylib\": true, // macOS shared libraries\n\t\t\".dll\": true, // Windows shared libraries\n\t\t\".a\": true, // Static libraries\n\t\t\".exe\": true, // Windows executables\n\t\t\".lock\": true, // Lock files\n\t}\n\n\t// Large binary files that shouldn't be opened\n\tlargeBinaryExtensions = map[string]bool{\n\t\t\".png\": true,\n\t\t\".jpg\": true,\n\t\t\".jpeg\": true,\n\t\t\".gif\": true,\n\t\t\".bmp\": true,\n\t\t\".ico\": true,\n\t\t\".zip\": true,\n\t\t\".tar\": true,\n\t\t\".gz\": true,\n\t\t\".rar\": true,\n\t\t\".7z\": true,\n\t\t\".pdf\": true,\n\t\t\".mp3\": true,\n\t\t\".mp4\": true,\n\t\t\".mov\": true,\n\t\t\".wav\": true,\n\t\t\".wasm\": true,\n\t}\n\n\t// Maximum file size to open (5MB)\n\tmaxFileSize int64 = 5 * 1024 * 1024\n)\n\n// shouldExcludeDir returns true if the directory should be excluded from watching/opening\nfunc shouldExcludeDir(dirPath string) bool {\n\tdirName := filepath.Base(dirPath)\n\n\t// Skip dot directories\n\tif strings.HasPrefix(dirName, \".\") {\n\t\treturn true\n\t}\n\n\t// Skip common excluded directories\n\tif excludedDirNames[dirName] {\n\t\treturn true\n\t}\n\n\treturn false\n}\n\n// shouldExcludeFile returns true if the file should be excluded from opening\nfunc shouldExcludeFile(filePath string) bool {\n\tfileName := filepath.Base(filePath)\n\tcnf := config.Get()\n\t// Skip dot files\n\tif strings.HasPrefix(fileName, \".\") {\n\t\treturn true\n\t}\n\n\t// Check file extension\n\text := strings.ToLower(filepath.Ext(filePath))\n\tif excludedFileExtensions[ext] || largeBinaryExtensions[ext] {\n\t\treturn true\n\t}\n\n\t// Skip temporary files\n\tif strings.HasSuffix(filePath, \"~\") {\n\t\treturn true\n\t}\n\n\t// Check file size\n\tinfo, err := os.Stat(filePath)\n\tif err != nil {\n\t\t// If we can't stat the file, skip it\n\t\treturn true\n\t}\n\n\t// Skip large files\n\tif info.Size() > maxFileSize {\n\t\tif cnf.DebugLSP {\n\t\t\tlogging.Debug(\"Skipping large file\",\n\t\t\t\t\"path\", filePath,\n\t\t\t\t\"size\", info.Size(),\n\t\t\t\t\"maxSize\", maxFileSize,\n\t\t\t\t\"debug\", cnf.Debug,\n\t\t\t\t\"sizeMB\", float64(info.Size())/(1024*1024),\n\t\t\t\t\"maxSizeMB\", float64(maxFileSize)/(1024*1024),\n\t\t\t)\n\t\t}\n\t\treturn true\n\t}\n\n\treturn false\n}\n\n// openMatchingFile opens a file if it matches any of the registered patterns\nfunc (w *WorkspaceWatcher) openMatchingFile(ctx context.Context, path string) {\n\tcnf := config.Get()\n\t// Skip directories\n\tinfo, err := os.Stat(path)\n\tif err != nil || info.IsDir() {\n\t\treturn\n\t}\n\n\t// Skip excluded files\n\tif shouldExcludeFile(path) {\n\t\treturn\n\t}\n\n\t// Check if this path should be watched according to server registrations\n\tif watched, _ := w.isPathWatched(path); watched {\n\t\t// Get server name for specialized handling\n\t\tserverName := getServerNameFromContext(ctx)\n\n\t\t// Check if the file is a high-priority file that should be opened immediately\n\t\t// This helps with project initialization for certain language servers\n\t\tif isHighPriorityFile(path, serverName) {\n\t\t\tif cnf.DebugLSP {\n\t\t\t\tlogging.Debug(\"Opening high-priority file\", \"path\", path, \"serverName\", serverName)\n\t\t\t}\n\t\t\tif err := w.client.OpenFile(ctx, path); err != nil && cnf.DebugLSP {\n\t\t\t\tlogging.Error(\"Error opening high-priority file\", \"path\", path, \"error\", err)\n\t\t\t}\n\t\t\treturn\n\t\t}\n\n\t\t// For non-high-priority files, we'll use different strategies based on server type\n\t\tif shouldPreloadFiles(serverName) {\n\t\t\t// For servers that benefit from preloading, open files but with limits\n\n\t\t\t// Check file size - for preloading we're more conservative\n\t\t\tif info.Size() > (1 * 1024 * 1024) { // 1MB limit for preloaded files\n\t\t\t\tif cnf.DebugLSP {\n\t\t\t\t\tlogging.Debug(\"Skipping large file for preloading\", \"path\", path, \"size\", info.Size())\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\t// Check file extension for common source files\n\t\t\text := strings.ToLower(filepath.Ext(path))\n\n\t\t\t// Only preload source files for the specific language\n\t\t\tshouldOpen := false\n\n\t\t\tswitch serverName {\n\t\t\tcase \"typescript\", \"typescript-language-server\", \"tsserver\", \"vtsls\":\n\t\t\t\tshouldOpen = ext == \".ts\" || ext == \".js\" || ext == \".tsx\" || ext == \".jsx\"\n\t\t\tcase \"gopls\":\n\t\t\t\tshouldOpen = ext == \".go\"\n\t\t\tcase \"rust-analyzer\":\n\t\t\t\tshouldOpen = ext == \".rs\"\n\t\t\tcase \"python\", \"pyright\", \"pylsp\":\n\t\t\t\tshouldOpen = ext == \".py\"\n\t\t\tcase \"clangd\":\n\t\t\t\tshouldOpen = ext == \".c\" || ext == \".cpp\" || ext == \".h\" || ext == \".hpp\"\n\t\t\tcase \"java\", \"jdtls\":\n\t\t\t\tshouldOpen = ext == \".java\"\n\t\t\tdefault:\n\t\t\t\t// For unknown servers, be conservative\n\t\t\t\tshouldOpen = false\n\t\t\t}\n\n\t\t\tif shouldOpen {\n\t\t\t\t// Don't need to check if it's already open - the client.OpenFile handles that\n\t\t\t\tif err := w.client.OpenFile(ctx, path); err != nil && cnf.DebugLSP {\n\t\t\t\t\tlogging.Error(\"Error opening file\", \"path\", path, \"error\", err)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\n// isHighPriorityFile determines if a file should be opened immediately\n// regardless of the preloading strategy\nfunc isHighPriorityFile(path string, serverName string) bool {\n\tfileName := filepath.Base(path)\n\text := filepath.Ext(path)\n\n\tswitch serverName {\n\tcase \"typescript\", \"typescript-language-server\", \"tsserver\", \"vtsls\":\n\t\t// For TypeScript, we want to open configuration files immediately\n\t\treturn fileName == \"tsconfig.json\" ||\n\t\t\tfileName == \"package.json\" ||\n\t\t\tfileName == \"jsconfig.json\" ||\n\t\t\t// Also open main entry points\n\t\t\tfileName == \"index.ts\" ||\n\t\t\tfileName == \"index.js\" ||\n\t\t\tfileName == \"main.ts\" ||\n\t\t\tfileName == \"main.js\"\n\tcase \"gopls\":\n\t\t// For Go, we want to open go.mod files immediately\n\t\treturn fileName == \"go.mod\" ||\n\t\t\tfileName == \"go.sum\" ||\n\t\t\t// Also open main.go files\n\t\t\tfileName == \"main.go\"\n\tcase \"rust-analyzer\":\n\t\t// For Rust, we want to open Cargo.toml files immediately\n\t\treturn fileName == \"Cargo.toml\" ||\n\t\t\tfileName == \"Cargo.lock\" ||\n\t\t\t// Also open lib.rs and main.rs\n\t\t\tfileName == \"lib.rs\" ||\n\t\t\tfileName == \"main.rs\"\n\tcase \"python\", \"pyright\", \"pylsp\":\n\t\t// For Python, open key project files\n\t\treturn fileName == \"pyproject.toml\" ||\n\t\t\tfileName == \"setup.py\" ||\n\t\t\tfileName == \"requirements.txt\" ||\n\t\t\tfileName == \"__init__.py\" ||\n\t\t\tfileName == \"__main__.py\"\n\tcase \"clangd\":\n\t\t// For C/C++, open key project files\n\t\treturn fileName == \"CMakeLists.txt\" ||\n\t\t\tfileName == \"Makefile\" ||\n\t\t\tfileName == \"compile_commands.json\"\n\tcase \"java\", \"jdtls\":\n\t\t// For Java, open key project files\n\t\treturn fileName == \"pom.xml\" ||\n\t\t\tfileName == \"build.gradle\" ||\n\t\t\text == \".java\" // Java servers often need to see source files\n\t}\n\n\t// For unknown servers, prioritize common configuration files\n\treturn fileName == \"package.json\" ||\n\t\tfileName == \"Makefile\" ||\n\t\tfileName == \"CMakeLists.txt\" ||\n\t\tfileName == \".editorconfig\"\n}\n"], ["/opencode/internal/tui/styles/markdown.go", "package styles\n\nimport (\n\t\"github.com/charmbracelet/glamour\"\n\t\"github.com/charmbracelet/glamour/ansi\"\n\t\"github.com/charmbracelet/lipgloss\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n)\n\nconst defaultMargin = 1\n\n// Helper functions for style pointers\nfunc boolPtr(b bool) *bool { return &b }\nfunc stringPtr(s string) *string { return &s }\nfunc uintPtr(u uint) *uint { return &u }\n\n// returns a glamour TermRenderer configured with the current theme\nfunc GetMarkdownRenderer(width int) *glamour.TermRenderer {\n\tr, _ := glamour.NewTermRenderer(\n\t\tglamour.WithStyles(generateMarkdownStyleConfig()),\n\t\tglamour.WithWordWrap(width),\n\t)\n\treturn r\n}\n\n// creates an ansi.StyleConfig for markdown rendering\n// using adaptive colors from the provided theme.\nfunc generateMarkdownStyleConfig() ansi.StyleConfig {\n\tt := theme.CurrentTheme()\n\n\treturn ansi.StyleConfig{\n\t\tDocument: ansi.StyleBlock{\n\t\t\tStylePrimitive: ansi.StylePrimitive{\n\t\t\t\tBlockPrefix: \"\",\n\t\t\t\tBlockSuffix: \"\",\n\t\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownText())),\n\t\t\t},\n\t\t\tMargin: uintPtr(defaultMargin),\n\t\t},\n\t\tBlockQuote: ansi.StyleBlock{\n\t\t\tStylePrimitive: ansi.StylePrimitive{\n\t\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownBlockQuote())),\n\t\t\t\tItalic: boolPtr(true),\n\t\t\t\tPrefix: \"┃ \",\n\t\t\t},\n\t\t\tIndent: uintPtr(1),\n\t\t\tIndentToken: stringPtr(BaseStyle().Render(\" \")),\n\t\t},\n\t\tList: ansi.StyleList{\n\t\t\tLevelIndent: defaultMargin,\n\t\t\tStyleBlock: ansi.StyleBlock{\n\t\t\t\tIndentToken: stringPtr(BaseStyle().Render(\" \")),\n\t\t\t\tStylePrimitive: ansi.StylePrimitive{\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownText())),\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\tHeading: ansi.StyleBlock{\n\t\t\tStylePrimitive: ansi.StylePrimitive{\n\t\t\t\tBlockSuffix: \"\\n\",\n\t\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownHeading())),\n\t\t\t\tBold: boolPtr(true),\n\t\t\t},\n\t\t},\n\t\tH1: ansi.StyleBlock{\n\t\t\tStylePrimitive: ansi.StylePrimitive{\n\t\t\t\tPrefix: \"# \",\n\t\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownHeading())),\n\t\t\t\tBold: boolPtr(true),\n\t\t\t},\n\t\t},\n\t\tH2: ansi.StyleBlock{\n\t\t\tStylePrimitive: ansi.StylePrimitive{\n\t\t\t\tPrefix: \"## \",\n\t\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownHeading())),\n\t\t\t\tBold: boolPtr(true),\n\t\t\t},\n\t\t},\n\t\tH3: ansi.StyleBlock{\n\t\t\tStylePrimitive: ansi.StylePrimitive{\n\t\t\t\tPrefix: \"### \",\n\t\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownHeading())),\n\t\t\t\tBold: boolPtr(true),\n\t\t\t},\n\t\t},\n\t\tH4: ansi.StyleBlock{\n\t\t\tStylePrimitive: ansi.StylePrimitive{\n\t\t\t\tPrefix: \"#### \",\n\t\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownHeading())),\n\t\t\t\tBold: boolPtr(true),\n\t\t\t},\n\t\t},\n\t\tH5: ansi.StyleBlock{\n\t\t\tStylePrimitive: ansi.StylePrimitive{\n\t\t\t\tPrefix: \"##### \",\n\t\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownHeading())),\n\t\t\t\tBold: boolPtr(true),\n\t\t\t},\n\t\t},\n\t\tH6: ansi.StyleBlock{\n\t\t\tStylePrimitive: ansi.StylePrimitive{\n\t\t\t\tPrefix: \"###### \",\n\t\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownHeading())),\n\t\t\t\tBold: boolPtr(true),\n\t\t\t},\n\t\t},\n\t\tStrikethrough: ansi.StylePrimitive{\n\t\t\tCrossedOut: boolPtr(true),\n\t\t\tColor: stringPtr(adaptiveColorToString(t.TextMuted())),\n\t\t},\n\t\tEmph: ansi.StylePrimitive{\n\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownEmph())),\n\t\t\tItalic: boolPtr(true),\n\t\t},\n\t\tStrong: ansi.StylePrimitive{\n\t\t\tBold: boolPtr(true),\n\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownStrong())),\n\t\t},\n\t\tHorizontalRule: ansi.StylePrimitive{\n\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownHorizontalRule())),\n\t\t\tFormat: \"\\n─────────────────────────────────────────\\n\",\n\t\t},\n\t\tItem: ansi.StylePrimitive{\n\t\t\tBlockPrefix: \"• \",\n\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownListItem())),\n\t\t},\n\t\tEnumeration: ansi.StylePrimitive{\n\t\t\tBlockPrefix: \". \",\n\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownListEnumeration())),\n\t\t},\n\t\tTask: ansi.StyleTask{\n\t\t\tStylePrimitive: ansi.StylePrimitive{},\n\t\t\tTicked: \"[✓] \",\n\t\t\tUnticked: \"[ ] \",\n\t\t},\n\t\tLink: ansi.StylePrimitive{\n\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownLink())),\n\t\t\tUnderline: boolPtr(true),\n\t\t},\n\t\tLinkText: ansi.StylePrimitive{\n\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownLinkText())),\n\t\t\tBold: boolPtr(true),\n\t\t},\n\t\tImage: ansi.StylePrimitive{\n\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownImage())),\n\t\t\tUnderline: boolPtr(true),\n\t\t\tFormat: \"🖼 {{.text}}\",\n\t\t},\n\t\tImageText: ansi.StylePrimitive{\n\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownImageText())),\n\t\t\tFormat: \"{{.text}}\",\n\t\t},\n\t\tCode: ansi.StyleBlock{\n\t\t\tStylePrimitive: ansi.StylePrimitive{\n\t\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownCode())),\n\t\t\t\tPrefix: \"\",\n\t\t\t\tSuffix: \"\",\n\t\t\t},\n\t\t},\n\t\tCodeBlock: ansi.StyleCodeBlock{\n\t\t\tStyleBlock: ansi.StyleBlock{\n\t\t\t\tStylePrimitive: ansi.StylePrimitive{\n\t\t\t\t\tPrefix: \" \",\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownCodeBlock())),\n\t\t\t\t},\n\t\t\t\tMargin: uintPtr(defaultMargin),\n\t\t\t},\n\t\t\tChroma: &ansi.Chroma{\n\t\t\t\tText: ansi.StylePrimitive{\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownText())),\n\t\t\t\t},\n\t\t\t\tError: ansi.StylePrimitive{\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.Error())),\n\t\t\t\t},\n\t\t\t\tComment: ansi.StylePrimitive{\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.SyntaxComment())),\n\t\t\t\t},\n\t\t\t\tCommentPreproc: ansi.StylePrimitive{\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.SyntaxKeyword())),\n\t\t\t\t},\n\t\t\t\tKeyword: ansi.StylePrimitive{\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.SyntaxKeyword())),\n\t\t\t\t},\n\t\t\t\tKeywordReserved: ansi.StylePrimitive{\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.SyntaxKeyword())),\n\t\t\t\t},\n\t\t\t\tKeywordNamespace: ansi.StylePrimitive{\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.SyntaxKeyword())),\n\t\t\t\t},\n\t\t\t\tKeywordType: ansi.StylePrimitive{\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.SyntaxType())),\n\t\t\t\t},\n\t\t\t\tOperator: ansi.StylePrimitive{\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.SyntaxOperator())),\n\t\t\t\t},\n\t\t\t\tPunctuation: ansi.StylePrimitive{\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.SyntaxPunctuation())),\n\t\t\t\t},\n\t\t\t\tName: ansi.StylePrimitive{\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.SyntaxVariable())),\n\t\t\t\t},\n\t\t\t\tNameBuiltin: ansi.StylePrimitive{\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.SyntaxVariable())),\n\t\t\t\t},\n\t\t\t\tNameTag: ansi.StylePrimitive{\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.SyntaxKeyword())),\n\t\t\t\t},\n\t\t\t\tNameAttribute: ansi.StylePrimitive{\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.SyntaxFunction())),\n\t\t\t\t},\n\t\t\t\tNameClass: ansi.StylePrimitive{\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.SyntaxType())),\n\t\t\t\t},\n\t\t\t\tNameConstant: ansi.StylePrimitive{\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.SyntaxVariable())),\n\t\t\t\t},\n\t\t\t\tNameDecorator: ansi.StylePrimitive{\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.SyntaxFunction())),\n\t\t\t\t},\n\t\t\t\tNameFunction: ansi.StylePrimitive{\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.SyntaxFunction())),\n\t\t\t\t},\n\t\t\t\tLiteralNumber: ansi.StylePrimitive{\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.SyntaxNumber())),\n\t\t\t\t},\n\t\t\t\tLiteralString: ansi.StylePrimitive{\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.SyntaxString())),\n\t\t\t\t},\n\t\t\t\tLiteralStringEscape: ansi.StylePrimitive{\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.SyntaxKeyword())),\n\t\t\t\t},\n\t\t\t\tGenericDeleted: ansi.StylePrimitive{\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.DiffRemoved())),\n\t\t\t\t},\n\t\t\t\tGenericEmph: ansi.StylePrimitive{\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownEmph())),\n\t\t\t\t\tItalic: boolPtr(true),\n\t\t\t\t},\n\t\t\t\tGenericInserted: ansi.StylePrimitive{\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.DiffAdded())),\n\t\t\t\t},\n\t\t\t\tGenericStrong: ansi.StylePrimitive{\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownStrong())),\n\t\t\t\t\tBold: boolPtr(true),\n\t\t\t\t},\n\t\t\t\tGenericSubheading: ansi.StylePrimitive{\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownHeading())),\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\tTable: ansi.StyleTable{\n\t\t\tStyleBlock: ansi.StyleBlock{\n\t\t\t\tStylePrimitive: ansi.StylePrimitive{\n\t\t\t\t\tBlockPrefix: \"\\n\",\n\t\t\t\t\tBlockSuffix: \"\\n\",\n\t\t\t\t},\n\t\t\t},\n\t\t\tCenterSeparator: stringPtr(\"┼\"),\n\t\t\tColumnSeparator: stringPtr(\"│\"),\n\t\t\tRowSeparator: stringPtr(\"─\"),\n\t\t},\n\t\tDefinitionDescription: ansi.StylePrimitive{\n\t\t\tBlockPrefix: \"\\n ❯ \",\n\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownLinkText())),\n\t\t},\n\t\tText: ansi.StylePrimitive{\n\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownText())),\n\t\t},\n\t\tParagraph: ansi.StyleBlock{\n\t\t\tStylePrimitive: ansi.StylePrimitive{\n\t\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownText())),\n\t\t\t},\n\t\t},\n\t}\n}\n\n// adaptiveColorToString converts a lipgloss.AdaptiveColor to the appropriate\n// hex color string based on the current terminal background\nfunc adaptiveColorToString(color lipgloss.AdaptiveColor) string {\n\tif lipgloss.HasDarkBackground() {\n\t\treturn color.Dark\n\t}\n\treturn color.Light\n}\n"], ["/opencode/internal/tui/styles/styles.go", "package styles\n\nimport (\n\t\"github.com/charmbracelet/lipgloss\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n)\n\nvar (\n\tImageBakcground = \"#212121\"\n)\n\n// Style generation functions that use the current theme\n\n// BaseStyle returns the base style with background and foreground colors\nfunc BaseStyle() lipgloss.Style {\n\tt := theme.CurrentTheme()\n\treturn lipgloss.NewStyle().\n\t\tBackground(t.Background()).\n\t\tForeground(t.Text())\n}\n\n// Regular returns a basic unstyled lipgloss.Style\nfunc Regular() lipgloss.Style {\n\treturn lipgloss.NewStyle()\n}\n\n// Bold returns a bold style\nfunc Bold() lipgloss.Style {\n\treturn Regular().Bold(true)\n}\n\n// Padded returns a style with horizontal padding\nfunc Padded() lipgloss.Style {\n\treturn Regular().Padding(0, 1)\n}\n\n// Border returns a style with a normal border\nfunc Border() lipgloss.Style {\n\tt := theme.CurrentTheme()\n\treturn Regular().\n\t\tBorder(lipgloss.NormalBorder()).\n\t\tBorderForeground(t.BorderNormal())\n}\n\n// ThickBorder returns a style with a thick border\nfunc ThickBorder() lipgloss.Style {\n\tt := theme.CurrentTheme()\n\treturn Regular().\n\t\tBorder(lipgloss.ThickBorder()).\n\t\tBorderForeground(t.BorderNormal())\n}\n\n// DoubleBorder returns a style with a double border\nfunc DoubleBorder() lipgloss.Style {\n\tt := theme.CurrentTheme()\n\treturn Regular().\n\t\tBorder(lipgloss.DoubleBorder()).\n\t\tBorderForeground(t.BorderNormal())\n}\n\n// FocusedBorder returns a style with a border using the focused border color\nfunc FocusedBorder() lipgloss.Style {\n\tt := theme.CurrentTheme()\n\treturn Regular().\n\t\tBorder(lipgloss.NormalBorder()).\n\t\tBorderForeground(t.BorderFocused())\n}\n\n// DimBorder returns a style with a border using the dim border color\nfunc DimBorder() lipgloss.Style {\n\tt := theme.CurrentTheme()\n\treturn Regular().\n\t\tBorder(lipgloss.NormalBorder()).\n\t\tBorderForeground(t.BorderDim())\n}\n\n// PrimaryColor returns the primary color from the current theme\nfunc PrimaryColor() lipgloss.AdaptiveColor {\n\treturn theme.CurrentTheme().Primary()\n}\n\n// SecondaryColor returns the secondary color from the current theme\nfunc SecondaryColor() lipgloss.AdaptiveColor {\n\treturn theme.CurrentTheme().Secondary()\n}\n\n// AccentColor returns the accent color from the current theme\nfunc AccentColor() lipgloss.AdaptiveColor {\n\treturn theme.CurrentTheme().Accent()\n}\n\n// ErrorColor returns the error color from the current theme\nfunc ErrorColor() lipgloss.AdaptiveColor {\n\treturn theme.CurrentTheme().Error()\n}\n\n// WarningColor returns the warning color from the current theme\nfunc WarningColor() lipgloss.AdaptiveColor {\n\treturn theme.CurrentTheme().Warning()\n}\n\n// SuccessColor returns the success color from the current theme\nfunc SuccessColor() lipgloss.AdaptiveColor {\n\treturn theme.CurrentTheme().Success()\n}\n\n// InfoColor returns the info color from the current theme\nfunc InfoColor() lipgloss.AdaptiveColor {\n\treturn theme.CurrentTheme().Info()\n}\n\n// TextColor returns the text color from the current theme\nfunc TextColor() lipgloss.AdaptiveColor {\n\treturn theme.CurrentTheme().Text()\n}\n\n// TextMutedColor returns the muted text color from the current theme\nfunc TextMutedColor() lipgloss.AdaptiveColor {\n\treturn theme.CurrentTheme().TextMuted()\n}\n\n// TextEmphasizedColor returns the emphasized text color from the current theme\nfunc TextEmphasizedColor() lipgloss.AdaptiveColor {\n\treturn theme.CurrentTheme().TextEmphasized()\n}\n\n// BackgroundColor returns the background color from the current theme\nfunc BackgroundColor() lipgloss.AdaptiveColor {\n\treturn theme.CurrentTheme().Background()\n}\n\n// BackgroundSecondaryColor returns the secondary background color from the current theme\nfunc BackgroundSecondaryColor() lipgloss.AdaptiveColor {\n\treturn theme.CurrentTheme().BackgroundSecondary()\n}\n\n// BackgroundDarkerColor returns the darker background color from the current theme\nfunc BackgroundDarkerColor() lipgloss.AdaptiveColor {\n\treturn theme.CurrentTheme().BackgroundDarker()\n}\n\n// BorderNormalColor returns the normal border color from the current theme\nfunc BorderNormalColor() lipgloss.AdaptiveColor {\n\treturn theme.CurrentTheme().BorderNormal()\n}\n\n// BorderFocusedColor returns the focused border color from the current theme\nfunc BorderFocusedColor() lipgloss.AdaptiveColor {\n\treturn theme.CurrentTheme().BorderFocused()\n}\n\n// BorderDimColor returns the dim border color from the current theme\nfunc BorderDimColor() lipgloss.AdaptiveColor {\n\treturn theme.CurrentTheme().BorderDim()\n}\n"], ["/opencode/internal/llm/provider/gemini.go", "package provider\n\nimport (\n\t\"context\"\n\t\"encoding/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/google/uuid\"\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/llm/tools\"\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n\t\"github.com/opencode-ai/opencode/internal/message\"\n\t\"google.golang.org/genai\"\n)\n\ntype geminiOptions struct {\n\tdisableCache bool\n}\n\ntype GeminiOption func(*geminiOptions)\n\ntype geminiClient struct {\n\tproviderOptions providerClientOptions\n\toptions geminiOptions\n\tclient *genai.Client\n}\n\ntype GeminiClient ProviderClient\n\nfunc newGeminiClient(opts providerClientOptions) GeminiClient {\n\tgeminiOpts := geminiOptions{}\n\tfor _, o := range opts.geminiOptions {\n\t\to(&geminiOpts)\n\t}\n\n\tclient, err := genai.NewClient(context.Background(), &genai.ClientConfig{APIKey: opts.apiKey, Backend: genai.BackendGeminiAPI})\n\tif err != nil {\n\t\tlogging.Error(\"Failed to create Gemini client\", \"error\", err)\n\t\treturn nil\n\t}\n\n\treturn &geminiClient{\n\t\tproviderOptions: opts,\n\t\toptions: geminiOpts,\n\t\tclient: client,\n\t}\n}\n\nfunc (g *geminiClient) convertMessages(messages []message.Message) []*genai.Content {\n\tvar history []*genai.Content\n\tfor _, msg := range messages {\n\t\tswitch msg.Role {\n\t\tcase message.User:\n\t\t\tvar parts []*genai.Part\n\t\t\tparts = append(parts, &genai.Part{Text: msg.Content().String()})\n\t\t\tfor _, binaryContent := range msg.BinaryContent() {\n\t\t\t\timageFormat := strings.Split(binaryContent.MIMEType, \"/\")\n\t\t\t\tparts = append(parts, &genai.Part{InlineData: &genai.Blob{\n\t\t\t\t\tMIMEType: imageFormat[1],\n\t\t\t\t\tData: binaryContent.Data,\n\t\t\t\t}})\n\t\t\t}\n\t\t\thistory = append(history, &genai.Content{\n\t\t\t\tParts: parts,\n\t\t\t\tRole: \"user\",\n\t\t\t})\n\t\tcase message.Assistant:\n\t\t\tvar assistantParts []*genai.Part\n\n\t\t\tif msg.Content().String() != \"\" {\n\t\t\t\tassistantParts = append(assistantParts, &genai.Part{Text: msg.Content().String()})\n\t\t\t}\n\n\t\t\tif len(msg.ToolCalls()) > 0 {\n\t\t\t\tfor _, call := range msg.ToolCalls() {\n\t\t\t\t\targs, _ := parseJsonToMap(call.Input)\n\t\t\t\t\tassistantParts = append(assistantParts, &genai.Part{\n\t\t\t\t\t\tFunctionCall: &genai.FunctionCall{\n\t\t\t\t\t\t\tName: call.Name,\n\t\t\t\t\t\t\tArgs: args,\n\t\t\t\t\t\t},\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif len(assistantParts) > 0 {\n\t\t\t\thistory = append(history, &genai.Content{\n\t\t\t\t\tRole: \"model\",\n\t\t\t\t\tParts: assistantParts,\n\t\t\t\t})\n\t\t\t}\n\n\t\tcase message.Tool:\n\t\t\tfor _, result := range msg.ToolResults() {\n\t\t\t\tresponse := map[string]interface{}{\"result\": result.Content}\n\t\t\t\tparsed, err := parseJsonToMap(result.Content)\n\t\t\t\tif err == nil {\n\t\t\t\t\tresponse = parsed\n\t\t\t\t}\n\n\t\t\t\tvar toolCall message.ToolCall\n\t\t\t\tfor _, m := range messages {\n\t\t\t\t\tif m.Role == message.Assistant {\n\t\t\t\t\t\tfor _, call := range m.ToolCalls() {\n\t\t\t\t\t\t\tif call.ID == result.ToolCallID {\n\t\t\t\t\t\t\t\ttoolCall = call\n\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\thistory = append(history, &genai.Content{\n\t\t\t\t\tParts: []*genai.Part{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tFunctionResponse: &genai.FunctionResponse{\n\t\t\t\t\t\t\t\tName: toolCall.Name,\n\t\t\t\t\t\t\t\tResponse: response,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\tRole: \"function\",\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\t}\n\n\treturn history\n}\n\nfunc (g *geminiClient) convertTools(tools []tools.BaseTool) []*genai.Tool {\n\tgeminiTool := &genai.Tool{}\n\tgeminiTool.FunctionDeclarations = make([]*genai.FunctionDeclaration, 0, len(tools))\n\n\tfor _, tool := range tools {\n\t\tinfo := tool.Info()\n\t\tdeclaration := &genai.FunctionDeclaration{\n\t\t\tName: info.Name,\n\t\t\tDescription: info.Description,\n\t\t\tParameters: &genai.Schema{\n\t\t\t\tType: genai.TypeObject,\n\t\t\t\tProperties: convertSchemaProperties(info.Parameters),\n\t\t\t\tRequired: info.Required,\n\t\t\t},\n\t\t}\n\n\t\tgeminiTool.FunctionDeclarations = append(geminiTool.FunctionDeclarations, declaration)\n\t}\n\n\treturn []*genai.Tool{geminiTool}\n}\n\nfunc (g *geminiClient) finishReason(reason genai.FinishReason) message.FinishReason {\n\tswitch {\n\tcase reason == genai.FinishReasonStop:\n\t\treturn message.FinishReasonEndTurn\n\tcase reason == genai.FinishReasonMaxTokens:\n\t\treturn message.FinishReasonMaxTokens\n\tdefault:\n\t\treturn message.FinishReasonUnknown\n\t}\n}\n\nfunc (g *geminiClient) send(ctx context.Context, messages []message.Message, tools []tools.BaseTool) (*ProviderResponse, error) {\n\t// Convert messages\n\tgeminiMessages := g.convertMessages(messages)\n\n\tcfg := config.Get()\n\tif cfg.Debug {\n\t\tjsonData, _ := json.Marshal(geminiMessages)\n\t\tlogging.Debug(\"Prepared messages\", \"messages\", string(jsonData))\n\t}\n\n\thistory := geminiMessages[:len(geminiMessages)-1] // All but last message\n\tlastMsg := geminiMessages[len(geminiMessages)-1]\n\tconfig := &genai.GenerateContentConfig{\n\t\tMaxOutputTokens: int32(g.providerOptions.maxTokens),\n\t\tSystemInstruction: &genai.Content{\n\t\t\tParts: []*genai.Part{{Text: g.providerOptions.systemMessage}},\n\t\t},\n\t}\n\tif len(tools) > 0 {\n\t\tconfig.Tools = g.convertTools(tools)\n\t}\n\tchat, _ := g.client.Chats.Create(ctx, g.providerOptions.model.APIModel, config, history)\n\n\tattempts := 0\n\tfor {\n\t\tattempts++\n\t\tvar toolCalls []message.ToolCall\n\n\t\tvar lastMsgParts []genai.Part\n\t\tfor _, part := range lastMsg.Parts {\n\t\t\tlastMsgParts = append(lastMsgParts, *part)\n\t\t}\n\t\tresp, err := chat.SendMessage(ctx, lastMsgParts...)\n\t\t// If there is an error we are going to see if we can retry the call\n\t\tif err != nil {\n\t\t\tretry, after, retryErr := g.shouldRetry(attempts, err)\n\t\t\tif retryErr != nil {\n\t\t\t\treturn nil, retryErr\n\t\t\t}\n\t\t\tif retry {\n\t\t\t\tlogging.WarnPersist(fmt.Sprintf(\"Retrying due to rate limit... attempt %d of %d\", attempts, maxRetries), logging.PersistTimeArg, time.Millisecond*time.Duration(after+100))\n\t\t\t\tselect {\n\t\t\t\tcase <-ctx.Done():\n\t\t\t\t\treturn nil, ctx.Err()\n\t\t\t\tcase <-time.After(time.Duration(after) * time.Millisecond):\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn nil, retryErr\n\t\t}\n\n\t\tcontent := \"\"\n\n\t\tif len(resp.Candidates) > 0 && resp.Candidates[0].Content != nil {\n\t\t\tfor _, part := range resp.Candidates[0].Content.Parts {\n\t\t\t\tswitch {\n\t\t\t\tcase part.Text != \"\":\n\t\t\t\t\tcontent = string(part.Text)\n\t\t\t\tcase part.FunctionCall != nil:\n\t\t\t\t\tid := \"call_\" + uuid.New().String()\n\t\t\t\t\targs, _ := json.Marshal(part.FunctionCall.Args)\n\t\t\t\t\ttoolCalls = append(toolCalls, message.ToolCall{\n\t\t\t\t\t\tID: id,\n\t\t\t\t\t\tName: part.FunctionCall.Name,\n\t\t\t\t\t\tInput: string(args),\n\t\t\t\t\t\tType: \"function\",\n\t\t\t\t\t\tFinished: true,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tfinishReason := message.FinishReasonEndTurn\n\t\tif len(resp.Candidates) > 0 {\n\t\t\tfinishReason = g.finishReason(resp.Candidates[0].FinishReason)\n\t\t}\n\t\tif len(toolCalls) > 0 {\n\t\t\tfinishReason = message.FinishReasonToolUse\n\t\t}\n\n\t\treturn &ProviderResponse{\n\t\t\tContent: content,\n\t\t\tToolCalls: toolCalls,\n\t\t\tUsage: g.usage(resp),\n\t\t\tFinishReason: finishReason,\n\t\t}, nil\n\t}\n}\n\nfunc (g *geminiClient) stream(ctx context.Context, messages []message.Message, tools []tools.BaseTool) <-chan ProviderEvent {\n\t// Convert messages\n\tgeminiMessages := g.convertMessages(messages)\n\n\tcfg := config.Get()\n\tif cfg.Debug {\n\t\tjsonData, _ := json.Marshal(geminiMessages)\n\t\tlogging.Debug(\"Prepared messages\", \"messages\", string(jsonData))\n\t}\n\n\thistory := geminiMessages[:len(geminiMessages)-1] // All but last message\n\tlastMsg := geminiMessages[len(geminiMessages)-1]\n\tconfig := &genai.GenerateContentConfig{\n\t\tMaxOutputTokens: int32(g.providerOptions.maxTokens),\n\t\tSystemInstruction: &genai.Content{\n\t\t\tParts: []*genai.Part{{Text: g.providerOptions.systemMessage}},\n\t\t},\n\t}\n\tif len(tools) > 0 {\n\t\tconfig.Tools = g.convertTools(tools)\n\t}\n\tchat, _ := g.client.Chats.Create(ctx, g.providerOptions.model.APIModel, config, history)\n\n\tattempts := 0\n\teventChan := make(chan ProviderEvent)\n\n\tgo func() {\n\t\tdefer close(eventChan)\n\n\t\tfor {\n\t\t\tattempts++\n\n\t\t\tcurrentContent := \"\"\n\t\t\ttoolCalls := []message.ToolCall{}\n\t\t\tvar finalResp *genai.GenerateContentResponse\n\n\t\t\teventChan <- ProviderEvent{Type: EventContentStart}\n\n\t\t\tvar lastMsgParts []genai.Part\n\n\t\t\tfor _, part := range lastMsg.Parts {\n\t\t\t\tlastMsgParts = append(lastMsgParts, *part)\n\t\t\t}\n\t\t\tfor resp, err := range chat.SendMessageStream(ctx, lastMsgParts...) {\n\t\t\t\tif err != nil {\n\t\t\t\t\tretry, after, retryErr := g.shouldRetry(attempts, err)\n\t\t\t\t\tif retryErr != nil {\n\t\t\t\t\t\teventChan <- ProviderEvent{Type: EventError, Error: retryErr}\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\tif retry {\n\t\t\t\t\t\tlogging.WarnPersist(fmt.Sprintf(\"Retrying due to rate limit... attempt %d of %d\", attempts, maxRetries), logging.PersistTimeArg, time.Millisecond*time.Duration(after+100))\n\t\t\t\t\t\tselect {\n\t\t\t\t\t\tcase <-ctx.Done():\n\t\t\t\t\t\t\tif ctx.Err() != nil {\n\t\t\t\t\t\t\t\teventChan <- ProviderEvent{Type: EventError, Error: ctx.Err()}\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\treturn\n\t\t\t\t\t\tcase <-time.After(time.Duration(after) * time.Millisecond):\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\teventChan <- ProviderEvent{Type: EventError, Error: err}\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tfinalResp = resp\n\n\t\t\t\tif len(resp.Candidates) > 0 && resp.Candidates[0].Content != nil {\n\t\t\t\t\tfor _, part := range resp.Candidates[0].Content.Parts {\n\t\t\t\t\t\tswitch {\n\t\t\t\t\t\tcase part.Text != \"\":\n\t\t\t\t\t\t\tdelta := string(part.Text)\n\t\t\t\t\t\t\tif delta != \"\" {\n\t\t\t\t\t\t\t\teventChan <- ProviderEvent{\n\t\t\t\t\t\t\t\t\tType: EventContentDelta,\n\t\t\t\t\t\t\t\t\tContent: delta,\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tcurrentContent += delta\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\tcase part.FunctionCall != nil:\n\t\t\t\t\t\t\tid := \"call_\" + uuid.New().String()\n\t\t\t\t\t\t\targs, _ := json.Marshal(part.FunctionCall.Args)\n\t\t\t\t\t\t\tnewCall := message.ToolCall{\n\t\t\t\t\t\t\t\tID: id,\n\t\t\t\t\t\t\t\tName: part.FunctionCall.Name,\n\t\t\t\t\t\t\t\tInput: string(args),\n\t\t\t\t\t\t\t\tType: \"function\",\n\t\t\t\t\t\t\t\tFinished: true,\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tisNew := true\n\t\t\t\t\t\t\tfor _, existing := range toolCalls {\n\t\t\t\t\t\t\t\tif existing.Name == newCall.Name && existing.Input == newCall.Input {\n\t\t\t\t\t\t\t\t\tisNew = false\n\t\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif isNew {\n\t\t\t\t\t\t\t\ttoolCalls = append(toolCalls, newCall)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\teventChan <- ProviderEvent{Type: EventContentStop}\n\n\t\t\tif finalResp != nil {\n\n\t\t\t\tfinishReason := message.FinishReasonEndTurn\n\t\t\t\tif len(finalResp.Candidates) > 0 {\n\t\t\t\t\tfinishReason = g.finishReason(finalResp.Candidates[0].FinishReason)\n\t\t\t\t}\n\t\t\t\tif len(toolCalls) > 0 {\n\t\t\t\t\tfinishReason = message.FinishReasonToolUse\n\t\t\t\t}\n\t\t\t\teventChan <- ProviderEvent{\n\t\t\t\t\tType: EventComplete,\n\t\t\t\t\tResponse: &ProviderResponse{\n\t\t\t\t\t\tContent: currentContent,\n\t\t\t\t\t\tToolCalls: toolCalls,\n\t\t\t\t\t\tUsage: g.usage(finalResp),\n\t\t\t\t\t\tFinishReason: finishReason,\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\n\t\t}\n\t}()\n\n\treturn eventChan\n}\n\nfunc (g *geminiClient) shouldRetry(attempts int, err error) (bool, int64, error) {\n\t// Check if error is a rate limit error\n\tif attempts > maxRetries {\n\t\treturn false, 0, fmt.Errorf(\"maximum retry attempts reached for rate limit: %d retries\", maxRetries)\n\t}\n\n\t// Gemini doesn't have a standard error type we can check against\n\t// So we'll check the error message for rate limit indicators\n\tif errors.Is(err, io.EOF) {\n\t\treturn false, 0, err\n\t}\n\n\terrMsg := err.Error()\n\tisRateLimit := false\n\n\t// Check for common rate limit error messages\n\tif contains(errMsg, \"rate limit\", \"quota exceeded\", \"too many requests\") {\n\t\tisRateLimit = true\n\t}\n\n\tif !isRateLimit {\n\t\treturn false, 0, err\n\t}\n\n\t// Calculate backoff with jitter\n\tbackoffMs := 2000 * (1 << (attempts - 1))\n\tjitterMs := int(float64(backoffMs) * 0.2)\n\tretryMs := backoffMs + jitterMs\n\n\treturn true, int64(retryMs), nil\n}\n\nfunc (g *geminiClient) toolCalls(resp *genai.GenerateContentResponse) []message.ToolCall {\n\tvar toolCalls []message.ToolCall\n\n\tif len(resp.Candidates) > 0 && resp.Candidates[0].Content != nil {\n\t\tfor _, part := range resp.Candidates[0].Content.Parts {\n\t\t\tif part.FunctionCall != nil {\n\t\t\t\tid := \"call_\" + uuid.New().String()\n\t\t\t\targs, _ := json.Marshal(part.FunctionCall.Args)\n\t\t\t\ttoolCalls = append(toolCalls, message.ToolCall{\n\t\t\t\t\tID: id,\n\t\t\t\t\tName: part.FunctionCall.Name,\n\t\t\t\t\tInput: string(args),\n\t\t\t\t\tType: \"function\",\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\t}\n\n\treturn toolCalls\n}\n\nfunc (g *geminiClient) usage(resp *genai.GenerateContentResponse) TokenUsage {\n\tif resp == nil || resp.UsageMetadata == nil {\n\t\treturn TokenUsage{}\n\t}\n\n\treturn TokenUsage{\n\t\tInputTokens: int64(resp.UsageMetadata.PromptTokenCount),\n\t\tOutputTokens: int64(resp.UsageMetadata.CandidatesTokenCount),\n\t\tCacheCreationTokens: 0, // Not directly provided by Gemini\n\t\tCacheReadTokens: int64(resp.UsageMetadata.CachedContentTokenCount),\n\t}\n}\n\nfunc WithGeminiDisableCache() GeminiOption {\n\treturn func(options *geminiOptions) {\n\t\toptions.disableCache = true\n\t}\n}\n\n// Helper functions\nfunc parseJsonToMap(jsonStr string) (map[string]interface{}, error) {\n\tvar result map[string]interface{}\n\terr := json.Unmarshal([]byte(jsonStr), &result)\n\treturn result, err\n}\n\nfunc convertSchemaProperties(parameters map[string]interface{}) map[string]*genai.Schema {\n\tproperties := make(map[string]*genai.Schema)\n\n\tfor name, param := range parameters {\n\t\tproperties[name] = convertToSchema(param)\n\t}\n\n\treturn properties\n}\n\nfunc convertToSchema(param interface{}) *genai.Schema {\n\tschema := &genai.Schema{Type: genai.TypeString}\n\n\tparamMap, ok := param.(map[string]interface{})\n\tif !ok {\n\t\treturn schema\n\t}\n\n\tif desc, ok := paramMap[\"description\"].(string); ok {\n\t\tschema.Description = desc\n\t}\n\n\ttypeVal, hasType := paramMap[\"type\"]\n\tif !hasType {\n\t\treturn schema\n\t}\n\n\ttypeStr, ok := typeVal.(string)\n\tif !ok {\n\t\treturn schema\n\t}\n\n\tschema.Type = mapJSONTypeToGenAI(typeStr)\n\n\tswitch typeStr {\n\tcase \"array\":\n\t\tschema.Items = processArrayItems(paramMap)\n\tcase \"object\":\n\t\tif props, ok := paramMap[\"properties\"].(map[string]interface{}); ok {\n\t\t\tschema.Properties = convertSchemaProperties(props)\n\t\t}\n\t}\n\n\treturn schema\n}\n\nfunc processArrayItems(paramMap map[string]interface{}) *genai.Schema {\n\titems, ok := paramMap[\"items\"].(map[string]interface{})\n\tif !ok {\n\t\treturn nil\n\t}\n\n\treturn convertToSchema(items)\n}\n\nfunc mapJSONTypeToGenAI(jsonType string) genai.Type {\n\tswitch jsonType {\n\tcase \"string\":\n\t\treturn genai.TypeString\n\tcase \"number\":\n\t\treturn genai.TypeNumber\n\tcase \"integer\":\n\t\treturn genai.TypeInteger\n\tcase \"boolean\":\n\t\treturn genai.TypeBoolean\n\tcase \"array\":\n\t\treturn genai.TypeArray\n\tcase \"object\":\n\t\treturn genai.TypeObject\n\tdefault:\n\t\treturn genai.TypeString // Default to string for unknown types\n\t}\n}\n\nfunc contains(s string, substrs ...string) bool {\n\tfor _, substr := range substrs {\n\t\tif strings.Contains(strings.ToLower(s), strings.ToLower(substr)) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n"], ["/opencode/internal/format/spinner.go", "package format\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"os\"\n\n\t\"github.com/charmbracelet/bubbles/spinner\"\n\ttea \"github.com/charmbracelet/bubbletea\"\n)\n\n// Spinner wraps the bubbles spinner for non-interactive mode\ntype Spinner struct {\n\tmodel spinner.Model\n\tdone chan struct{}\n\tprog *tea.Program\n\tctx context.Context\n\tcancel context.CancelFunc\n}\n\n// spinnerModel is the tea.Model for the spinner\ntype spinnerModel struct {\n\tspinner spinner.Model\n\tmessage string\n\tquitting bool\n}\n\nfunc (m spinnerModel) Init() tea.Cmd {\n\treturn m.spinner.Tick\n}\n\nfunc (m spinnerModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {\n\tswitch msg := msg.(type) {\n\tcase tea.KeyMsg:\n\t\tm.quitting = true\n\t\treturn m, tea.Quit\n\tcase spinner.TickMsg:\n\t\tvar cmd tea.Cmd\n\t\tm.spinner, cmd = m.spinner.Update(msg)\n\t\treturn m, cmd\n\tcase quitMsg:\n\t\tm.quitting = true\n\t\treturn m, tea.Quit\n\tdefault:\n\t\treturn m, nil\n\t}\n}\n\nfunc (m spinnerModel) View() string {\n\tif m.quitting {\n\t\treturn \"\"\n\t}\n\treturn fmt.Sprintf(\"%s %s\", m.spinner.View(), m.message)\n}\n\n// quitMsg is sent when we want to quit the spinner\ntype quitMsg struct{}\n\n// NewSpinner creates a new spinner with the given message\nfunc NewSpinner(message string) *Spinner {\n\ts := spinner.New()\n\ts.Spinner = spinner.Dot\n\ts.Style = s.Style.Foreground(s.Style.GetForeground())\n\n\tctx, cancel := context.WithCancel(context.Background())\n\n\tmodel := spinnerModel{\n\t\tspinner: s,\n\t\tmessage: message,\n\t}\n\n\tprog := tea.NewProgram(model, tea.WithOutput(os.Stderr), tea.WithoutCatchPanics())\n\n\treturn &Spinner{\n\t\tmodel: s,\n\t\tdone: make(chan struct{}),\n\t\tprog: prog,\n\t\tctx: ctx,\n\t\tcancel: cancel,\n\t}\n}\n\n// Start begins the spinner animation\nfunc (s *Spinner) Start() {\n\tgo func() {\n\t\tdefer close(s.done)\n\t\tgo func() {\n\t\t\t<-s.ctx.Done()\n\t\t\ts.prog.Send(quitMsg{})\n\t\t}()\n\t\t_, err := s.prog.Run()\n\t\tif err != nil {\n\t\t\tfmt.Fprintf(os.Stderr, \"Error running spinner: %v\\n\", err)\n\t\t}\n\t}()\n}\n\n// Stop ends the spinner animation\nfunc (s *Spinner) Stop() {\n\ts.cancel()\n\t<-s.done\n}\n"], ["/opencode/internal/config/config.go", "// Package config manages application configuration from various sources.\npackage config\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"log/slog\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"runtime\"\n\t\"strings\"\n\n\t\"github.com/opencode-ai/opencode/internal/llm/models\"\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n\t\"github.com/spf13/viper\"\n)\n\n// MCPType defines the type of MCP (Model Control Protocol) server.\ntype MCPType string\n\n// Supported MCP types\nconst (\n\tMCPStdio MCPType = \"stdio\"\n\tMCPSse MCPType = \"sse\"\n)\n\n// MCPServer defines the configuration for a Model Control Protocol server.\ntype MCPServer struct {\n\tCommand string `json:\"command\"`\n\tEnv []string `json:\"env\"`\n\tArgs []string `json:\"args\"`\n\tType MCPType `json:\"type\"`\n\tURL string `json:\"url\"`\n\tHeaders map[string]string `json:\"headers\"`\n}\n\ntype AgentName string\n\nconst (\n\tAgentCoder AgentName = \"coder\"\n\tAgentSummarizer AgentName = \"summarizer\"\n\tAgentTask AgentName = \"task\"\n\tAgentTitle AgentName = \"title\"\n)\n\n// Agent defines configuration for different LLM models and their token limits.\ntype Agent struct {\n\tModel models.ModelID `json:\"model\"`\n\tMaxTokens int64 `json:\"maxTokens\"`\n\tReasoningEffort string `json:\"reasoningEffort\"` // For openai models low,medium,heigh\n}\n\n// Provider defines configuration for an LLM provider.\ntype Provider struct {\n\tAPIKey string `json:\"apiKey\"`\n\tDisabled bool `json:\"disabled\"`\n}\n\n// Data defines storage configuration.\ntype Data struct {\n\tDirectory string `json:\"directory,omitempty\"`\n}\n\n// LSPConfig defines configuration for Language Server Protocol integration.\ntype LSPConfig struct {\n\tDisabled bool `json:\"enabled\"`\n\tCommand string `json:\"command\"`\n\tArgs []string `json:\"args\"`\n\tOptions any `json:\"options\"`\n}\n\n// TUIConfig defines the configuration for the Terminal User Interface.\ntype TUIConfig struct {\n\tTheme string `json:\"theme,omitempty\"`\n}\n\n// ShellConfig defines the configuration for the shell used by the bash tool.\ntype ShellConfig struct {\n\tPath string `json:\"path,omitempty\"`\n\tArgs []string `json:\"args,omitempty\"`\n}\n\n// Config is the main configuration structure for the application.\ntype Config struct {\n\tData Data `json:\"data\"`\n\tWorkingDir string `json:\"wd,omitempty\"`\n\tMCPServers map[string]MCPServer `json:\"mcpServers,omitempty\"`\n\tProviders map[models.ModelProvider]Provider `json:\"providers,omitempty\"`\n\tLSP map[string]LSPConfig `json:\"lsp,omitempty\"`\n\tAgents map[AgentName]Agent `json:\"agents,omitempty\"`\n\tDebug bool `json:\"debug,omitempty\"`\n\tDebugLSP bool `json:\"debugLSP,omitempty\"`\n\tContextPaths []string `json:\"contextPaths,omitempty\"`\n\tTUI TUIConfig `json:\"tui\"`\n\tShell ShellConfig `json:\"shell,omitempty\"`\n\tAutoCompact bool `json:\"autoCompact,omitempty\"`\n}\n\n// Application constants\nconst (\n\tdefaultDataDirectory = \".opencode\"\n\tdefaultLogLevel = \"info\"\n\tappName = \"opencode\"\n\n\tMaxTokensFallbackDefault = 4096\n)\n\nvar defaultContextPaths = []string{\n\t\".github/copilot-instructions.md\",\n\t\".cursorrules\",\n\t\".cursor/rules/\",\n\t\"CLAUDE.md\",\n\t\"CLAUDE.local.md\",\n\t\"opencode.md\",\n\t\"opencode.local.md\",\n\t\"OpenCode.md\",\n\t\"OpenCode.local.md\",\n\t\"OPENCODE.md\",\n\t\"OPENCODE.local.md\",\n}\n\n// Global configuration instance\nvar cfg *Config\n\n// Load initializes the configuration from environment variables and config files.\n// If debug is true, debug mode is enabled and log level is set to debug.\n// It returns an error if configuration loading fails.\nfunc Load(workingDir string, debug bool) (*Config, error) {\n\tif cfg != nil {\n\t\treturn cfg, nil\n\t}\n\n\tcfg = &Config{\n\t\tWorkingDir: workingDir,\n\t\tMCPServers: make(map[string]MCPServer),\n\t\tProviders: make(map[models.ModelProvider]Provider),\n\t\tLSP: make(map[string]LSPConfig),\n\t}\n\n\tconfigureViper()\n\tsetDefaults(debug)\n\n\t// Read global config\n\tif err := readConfig(viper.ReadInConfig()); err != nil {\n\t\treturn cfg, err\n\t}\n\n\t// Load and merge local config\n\tmergeLocalConfig(workingDir)\n\n\tsetProviderDefaults()\n\n\t// Apply configuration to the struct\n\tif err := viper.Unmarshal(cfg); err != nil {\n\t\treturn cfg, fmt.Errorf(\"failed to unmarshal config: %w\", err)\n\t}\n\n\tapplyDefaultValues()\n\tdefaultLevel := slog.LevelInfo\n\tif cfg.Debug {\n\t\tdefaultLevel = slog.LevelDebug\n\t}\n\tif os.Getenv(\"OPENCODE_DEV_DEBUG\") == \"true\" {\n\t\tloggingFile := fmt.Sprintf(\"%s/%s\", cfg.Data.Directory, \"debug.log\")\n\t\tmessagesPath := fmt.Sprintf(\"%s/%s\", cfg.Data.Directory, \"messages\")\n\n\t\t// if file does not exist create it\n\t\tif _, err := os.Stat(loggingFile); os.IsNotExist(err) {\n\t\t\tif err := os.MkdirAll(cfg.Data.Directory, 0o755); err != nil {\n\t\t\t\treturn cfg, fmt.Errorf(\"failed to create directory: %w\", err)\n\t\t\t}\n\t\t\tif _, err := os.Create(loggingFile); err != nil {\n\t\t\t\treturn cfg, fmt.Errorf(\"failed to create log file: %w\", err)\n\t\t\t}\n\t\t}\n\n\t\tif _, err := os.Stat(messagesPath); os.IsNotExist(err) {\n\t\t\tif err := os.MkdirAll(messagesPath, 0o756); err != nil {\n\t\t\t\treturn cfg, fmt.Errorf(\"failed to create directory: %w\", err)\n\t\t\t}\n\t\t}\n\t\tlogging.MessageDir = messagesPath\n\n\t\tsloggingFileWriter, err := os.OpenFile(loggingFile, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o666)\n\t\tif err != nil {\n\t\t\treturn cfg, fmt.Errorf(\"failed to open log file: %w\", err)\n\t\t}\n\t\t// Configure logger\n\t\tlogger := slog.New(slog.NewTextHandler(sloggingFileWriter, &slog.HandlerOptions{\n\t\t\tLevel: defaultLevel,\n\t\t}))\n\t\tslog.SetDefault(logger)\n\t} else {\n\t\t// Configure logger\n\t\tlogger := slog.New(slog.NewTextHandler(logging.NewWriter(), &slog.HandlerOptions{\n\t\t\tLevel: defaultLevel,\n\t\t}))\n\t\tslog.SetDefault(logger)\n\t}\n\n\t// Validate configuration\n\tif err := Validate(); err != nil {\n\t\treturn cfg, fmt.Errorf(\"config validation failed: %w\", err)\n\t}\n\n\tif cfg.Agents == nil {\n\t\tcfg.Agents = make(map[AgentName]Agent)\n\t}\n\n\t// Override the max tokens for title agent\n\tcfg.Agents[AgentTitle] = Agent{\n\t\tModel: cfg.Agents[AgentTitle].Model,\n\t\tMaxTokens: 80,\n\t}\n\treturn cfg, nil\n}\n\n// configureViper sets up viper's configuration paths and environment variables.\nfunc configureViper() {\n\tviper.SetConfigName(fmt.Sprintf(\".%s\", appName))\n\tviper.SetConfigType(\"json\")\n\tviper.AddConfigPath(\"$HOME\")\n\tviper.AddConfigPath(fmt.Sprintf(\"$XDG_CONFIG_HOME/%s\", appName))\n\tviper.AddConfigPath(fmt.Sprintf(\"$HOME/.config/%s\", appName))\n\tviper.SetEnvPrefix(strings.ToUpper(appName))\n\tviper.AutomaticEnv()\n}\n\n// setDefaults configures default values for configuration options.\nfunc setDefaults(debug bool) {\n\tviper.SetDefault(\"data.directory\", defaultDataDirectory)\n\tviper.SetDefault(\"contextPaths\", defaultContextPaths)\n\tviper.SetDefault(\"tui.theme\", \"opencode\")\n\tviper.SetDefault(\"autoCompact\", true)\n\n\t// Set default shell from environment or fallback to /bin/bash\n\tshellPath := os.Getenv(\"SHELL\")\n\tif shellPath == \"\" {\n\t\tshellPath = \"/bin/bash\"\n\t}\n\tviper.SetDefault(\"shell.path\", shellPath)\n\tviper.SetDefault(\"shell.args\", []string{\"-l\"})\n\n\tif debug {\n\t\tviper.SetDefault(\"debug\", true)\n\t\tviper.Set(\"log.level\", \"debug\")\n\t} else {\n\t\tviper.SetDefault(\"debug\", false)\n\t\tviper.SetDefault(\"log.level\", defaultLogLevel)\n\t}\n}\n\n// setProviderDefaults configures LLM provider defaults based on provider provided by\n// environment variables and configuration file.\nfunc setProviderDefaults() {\n\t// Set all API keys we can find in the environment\n\t// Note: Viper does not default if the json apiKey is \"\"\n\tif apiKey := os.Getenv(\"ANTHROPIC_API_KEY\"); apiKey != \"\" {\n\t\tviper.SetDefault(\"providers.anthropic.apiKey\", apiKey)\n\t}\n\tif apiKey := os.Getenv(\"OPENAI_API_KEY\"); apiKey != \"\" {\n\t\tviper.SetDefault(\"providers.openai.apiKey\", apiKey)\n\t}\n\tif apiKey := os.Getenv(\"GEMINI_API_KEY\"); apiKey != \"\" {\n\t\tviper.SetDefault(\"providers.gemini.apiKey\", apiKey)\n\t}\n\tif apiKey := os.Getenv(\"GROQ_API_KEY\"); apiKey != \"\" {\n\t\tviper.SetDefault(\"providers.groq.apiKey\", apiKey)\n\t}\n\tif apiKey := os.Getenv(\"OPENROUTER_API_KEY\"); apiKey != \"\" {\n\t\tviper.SetDefault(\"providers.openrouter.apiKey\", apiKey)\n\t}\n\tif apiKey := os.Getenv(\"XAI_API_KEY\"); apiKey != \"\" {\n\t\tviper.SetDefault(\"providers.xai.apiKey\", apiKey)\n\t}\n\tif apiKey := os.Getenv(\"AZURE_OPENAI_ENDPOINT\"); apiKey != \"\" {\n\t\t// api-key may be empty when using Entra ID credentials – that's okay\n\t\tviper.SetDefault(\"providers.azure.apiKey\", os.Getenv(\"AZURE_OPENAI_API_KEY\"))\n\t}\n\tif apiKey, err := LoadGitHubToken(); err == nil && apiKey != \"\" {\n\t\tviper.SetDefault(\"providers.copilot.apiKey\", apiKey)\n\t\tif viper.GetString(\"providers.copilot.apiKey\") == \"\" {\n\t\t\tviper.Set(\"providers.copilot.apiKey\", apiKey)\n\t\t}\n\t}\n\n\t// Use this order to set the default models\n\t// 1. Copilot\n\t// 2. Anthropic\n\t// 3. OpenAI\n\t// 4. Google Gemini\n\t// 5. Groq\n\t// 6. OpenRouter\n\t// 7. AWS Bedrock\n\t// 8. Azure\n\t// 9. Google Cloud VertexAI\n\n\t// copilot configuration\n\tif key := viper.GetString(\"providers.copilot.apiKey\"); strings.TrimSpace(key) != \"\" {\n\t\tviper.SetDefault(\"agents.coder.model\", models.CopilotGPT4o)\n\t\tviper.SetDefault(\"agents.summarizer.model\", models.CopilotGPT4o)\n\t\tviper.SetDefault(\"agents.task.model\", models.CopilotGPT4o)\n\t\tviper.SetDefault(\"agents.title.model\", models.CopilotGPT4o)\n\t\treturn\n\t}\n\n\t// Anthropic configuration\n\tif key := viper.GetString(\"providers.anthropic.apiKey\"); strings.TrimSpace(key) != \"\" {\n\t\tviper.SetDefault(\"agents.coder.model\", models.Claude4Sonnet)\n\t\tviper.SetDefault(\"agents.summarizer.model\", models.Claude4Sonnet)\n\t\tviper.SetDefault(\"agents.task.model\", models.Claude4Sonnet)\n\t\tviper.SetDefault(\"agents.title.model\", models.Claude4Sonnet)\n\t\treturn\n\t}\n\n\t// OpenAI configuration\n\tif key := viper.GetString(\"providers.openai.apiKey\"); strings.TrimSpace(key) != \"\" {\n\t\tviper.SetDefault(\"agents.coder.model\", models.GPT41)\n\t\tviper.SetDefault(\"agents.summarizer.model\", models.GPT41)\n\t\tviper.SetDefault(\"agents.task.model\", models.GPT41Mini)\n\t\tviper.SetDefault(\"agents.title.model\", models.GPT41Mini)\n\t\treturn\n\t}\n\n\t// Google Gemini configuration\n\tif key := viper.GetString(\"providers.gemini.apiKey\"); strings.TrimSpace(key) != \"\" {\n\t\tviper.SetDefault(\"agents.coder.model\", models.Gemini25)\n\t\tviper.SetDefault(\"agents.summarizer.model\", models.Gemini25)\n\t\tviper.SetDefault(\"agents.task.model\", models.Gemini25Flash)\n\t\tviper.SetDefault(\"agents.title.model\", models.Gemini25Flash)\n\t\treturn\n\t}\n\n\t// Groq configuration\n\tif key := viper.GetString(\"providers.groq.apiKey\"); strings.TrimSpace(key) != \"\" {\n\t\tviper.SetDefault(\"agents.coder.model\", models.QWENQwq)\n\t\tviper.SetDefault(\"agents.summarizer.model\", models.QWENQwq)\n\t\tviper.SetDefault(\"agents.task.model\", models.QWENQwq)\n\t\tviper.SetDefault(\"agents.title.model\", models.QWENQwq)\n\t\treturn\n\t}\n\n\t// OpenRouter configuration\n\tif key := viper.GetString(\"providers.openrouter.apiKey\"); strings.TrimSpace(key) != \"\" {\n\t\tviper.SetDefault(\"agents.coder.model\", models.OpenRouterClaude37Sonnet)\n\t\tviper.SetDefault(\"agents.summarizer.model\", models.OpenRouterClaude37Sonnet)\n\t\tviper.SetDefault(\"agents.task.model\", models.OpenRouterClaude37Sonnet)\n\t\tviper.SetDefault(\"agents.title.model\", models.OpenRouterClaude35Haiku)\n\t\treturn\n\t}\n\n\t// XAI configuration\n\tif key := viper.GetString(\"providers.xai.apiKey\"); strings.TrimSpace(key) != \"\" {\n\t\tviper.SetDefault(\"agents.coder.model\", models.XAIGrok3Beta)\n\t\tviper.SetDefault(\"agents.summarizer.model\", models.XAIGrok3Beta)\n\t\tviper.SetDefault(\"agents.task.model\", models.XAIGrok3Beta)\n\t\tviper.SetDefault(\"agents.title.model\", models.XAiGrok3MiniFastBeta)\n\t\treturn\n\t}\n\n\t// AWS Bedrock configuration\n\tif hasAWSCredentials() {\n\t\tviper.SetDefault(\"agents.coder.model\", models.BedrockClaude37Sonnet)\n\t\tviper.SetDefault(\"agents.summarizer.model\", models.BedrockClaude37Sonnet)\n\t\tviper.SetDefault(\"agents.task.model\", models.BedrockClaude37Sonnet)\n\t\tviper.SetDefault(\"agents.title.model\", models.BedrockClaude37Sonnet)\n\t\treturn\n\t}\n\n\t// Azure OpenAI configuration\n\tif os.Getenv(\"AZURE_OPENAI_ENDPOINT\") != \"\" {\n\t\tviper.SetDefault(\"agents.coder.model\", models.AzureGPT41)\n\t\tviper.SetDefault(\"agents.summarizer.model\", models.AzureGPT41)\n\t\tviper.SetDefault(\"agents.task.model\", models.AzureGPT41Mini)\n\t\tviper.SetDefault(\"agents.title.model\", models.AzureGPT41Mini)\n\t\treturn\n\t}\n\n\t// Google Cloud VertexAI configuration\n\tif hasVertexAICredentials() {\n\t\tviper.SetDefault(\"agents.coder.model\", models.VertexAIGemini25)\n\t\tviper.SetDefault(\"agents.summarizer.model\", models.VertexAIGemini25)\n\t\tviper.SetDefault(\"agents.task.model\", models.VertexAIGemini25Flash)\n\t\tviper.SetDefault(\"agents.title.model\", models.VertexAIGemini25Flash)\n\t\treturn\n\t}\n}\n\n// hasAWSCredentials checks if AWS credentials are available in the environment.\nfunc hasAWSCredentials() bool {\n\t// Check for explicit AWS credentials\n\tif os.Getenv(\"AWS_ACCESS_KEY_ID\") != \"\" && os.Getenv(\"AWS_SECRET_ACCESS_KEY\") != \"\" {\n\t\treturn true\n\t}\n\n\t// Check for AWS profile\n\tif os.Getenv(\"AWS_PROFILE\") != \"\" || os.Getenv(\"AWS_DEFAULT_PROFILE\") != \"\" {\n\t\treturn true\n\t}\n\n\t// Check for AWS region\n\tif os.Getenv(\"AWS_REGION\") != \"\" || os.Getenv(\"AWS_DEFAULT_REGION\") != \"\" {\n\t\treturn true\n\t}\n\n\t// Check if running on EC2 with instance profile\n\tif os.Getenv(\"AWS_CONTAINER_CREDENTIALS_RELATIVE_URI\") != \"\" ||\n\t\tos.Getenv(\"AWS_CONTAINER_CREDENTIALS_FULL_URI\") != \"\" {\n\t\treturn true\n\t}\n\n\treturn false\n}\n\n// hasVertexAICredentials checks if VertexAI credentials are available in the environment.\nfunc hasVertexAICredentials() bool {\n\t// Check for explicit VertexAI parameters\n\tif os.Getenv(\"VERTEXAI_PROJECT\") != \"\" && os.Getenv(\"VERTEXAI_LOCATION\") != \"\" {\n\t\treturn true\n\t}\n\t// Check for Google Cloud project and location\n\tif os.Getenv(\"GOOGLE_CLOUD_PROJECT\") != \"\" && (os.Getenv(\"GOOGLE_CLOUD_REGION\") != \"\" || os.Getenv(\"GOOGLE_CLOUD_LOCATION\") != \"\") {\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc hasCopilotCredentials() bool {\n\t// Check for explicit Copilot parameters\n\tif token, _ := LoadGitHubToken(); token != \"\" {\n\t\treturn true\n\t}\n\treturn false\n}\n\n// readConfig handles the result of reading a configuration file.\nfunc readConfig(err error) error {\n\tif err == nil {\n\t\treturn nil\n\t}\n\n\t// It's okay if the config file doesn't exist\n\tif _, ok := err.(viper.ConfigFileNotFoundError); ok {\n\t\treturn nil\n\t}\n\n\treturn fmt.Errorf(\"failed to read config: %w\", err)\n}\n\n// mergeLocalConfig loads and merges configuration from the local directory.\nfunc mergeLocalConfig(workingDir string) {\n\tlocal := viper.New()\n\tlocal.SetConfigName(fmt.Sprintf(\".%s\", appName))\n\tlocal.SetConfigType(\"json\")\n\tlocal.AddConfigPath(workingDir)\n\n\t// Merge local config if it exists\n\tif err := local.ReadInConfig(); err == nil {\n\t\tviper.MergeConfigMap(local.AllSettings())\n\t}\n}\n\n// applyDefaultValues sets default values for configuration fields that need processing.\nfunc applyDefaultValues() {\n\t// Set default MCP type if not specified\n\tfor k, v := range cfg.MCPServers {\n\t\tif v.Type == \"\" {\n\t\t\tv.Type = MCPStdio\n\t\t\tcfg.MCPServers[k] = v\n\t\t}\n\t}\n}\n\n// It validates model IDs and providers, ensuring they are supported.\nfunc validateAgent(cfg *Config, name AgentName, agent Agent) error {\n\t// Check if model exists\n\t// TODO:\tIf a copilot model is specified, but model is not found,\n\t// \t\t \tit might be new model. The https://api.githubcopilot.com/models\n\t// \t\t \tendpoint should be queried to validate if the model is supported.\n\tmodel, modelExists := models.SupportedModels[agent.Model]\n\tif !modelExists {\n\t\tlogging.Warn(\"unsupported model configured, reverting to default\",\n\t\t\t\"agent\", name,\n\t\t\t\"configured_model\", agent.Model)\n\n\t\t// Set default model based on available providers\n\t\tif setDefaultModelForAgent(name) {\n\t\t\tlogging.Info(\"set default model for agent\", \"agent\", name, \"model\", cfg.Agents[name].Model)\n\t\t} else {\n\t\t\treturn fmt.Errorf(\"no valid provider available for agent %s\", name)\n\t\t}\n\t\treturn nil\n\t}\n\n\t// Check if provider for the model is configured\n\tprovider := model.Provider\n\tproviderCfg, providerExists := cfg.Providers[provider]\n\n\tif !providerExists {\n\t\t// Provider not configured, check if we have environment variables\n\t\tapiKey := getProviderAPIKey(provider)\n\t\tif apiKey == \"\" {\n\t\t\tlogging.Warn(\"provider not configured for model, reverting to default\",\n\t\t\t\t\"agent\", name,\n\t\t\t\t\"model\", agent.Model,\n\t\t\t\t\"provider\", provider)\n\n\t\t\t// Set default model based on available providers\n\t\t\tif setDefaultModelForAgent(name) {\n\t\t\t\tlogging.Info(\"set default model for agent\", \"agent\", name, \"model\", cfg.Agents[name].Model)\n\t\t\t} else {\n\t\t\t\treturn fmt.Errorf(\"no valid provider available for agent %s\", name)\n\t\t\t}\n\t\t} else {\n\t\t\t// Add provider with API key from environment\n\t\t\tcfg.Providers[provider] = Provider{\n\t\t\t\tAPIKey: apiKey,\n\t\t\t}\n\t\t\tlogging.Info(\"added provider from environment\", \"provider\", provider)\n\t\t}\n\t} else if providerCfg.Disabled || providerCfg.APIKey == \"\" {\n\t\t// Provider is disabled or has no API key\n\t\tlogging.Warn(\"provider is disabled or has no API key, reverting to default\",\n\t\t\t\"agent\", name,\n\t\t\t\"model\", agent.Model,\n\t\t\t\"provider\", provider)\n\n\t\t// Set default model based on available providers\n\t\tif setDefaultModelForAgent(name) {\n\t\t\tlogging.Info(\"set default model for agent\", \"agent\", name, \"model\", cfg.Agents[name].Model)\n\t\t} else {\n\t\t\treturn fmt.Errorf(\"no valid provider available for agent %s\", name)\n\t\t}\n\t}\n\n\t// Validate max tokens\n\tif agent.MaxTokens <= 0 {\n\t\tlogging.Warn(\"invalid max tokens, setting to default\",\n\t\t\t\"agent\", name,\n\t\t\t\"model\", agent.Model,\n\t\t\t\"max_tokens\", agent.MaxTokens)\n\n\t\t// Update the agent with default max tokens\n\t\tupdatedAgent := cfg.Agents[name]\n\t\tif model.DefaultMaxTokens > 0 {\n\t\t\tupdatedAgent.MaxTokens = model.DefaultMaxTokens\n\t\t} else {\n\t\t\tupdatedAgent.MaxTokens = MaxTokensFallbackDefault\n\t\t}\n\t\tcfg.Agents[name] = updatedAgent\n\t} else if model.ContextWindow > 0 && agent.MaxTokens > model.ContextWindow/2 {\n\t\t// Ensure max tokens doesn't exceed half the context window (reasonable limit)\n\t\tlogging.Warn(\"max tokens exceeds half the context window, adjusting\",\n\t\t\t\"agent\", name,\n\t\t\t\"model\", agent.Model,\n\t\t\t\"max_tokens\", agent.MaxTokens,\n\t\t\t\"context_window\", model.ContextWindow)\n\n\t\t// Update the agent with adjusted max tokens\n\t\tupdatedAgent := cfg.Agents[name]\n\t\tupdatedAgent.MaxTokens = model.ContextWindow / 2\n\t\tcfg.Agents[name] = updatedAgent\n\t}\n\n\t// Validate reasoning effort for models that support reasoning\n\tif model.CanReason && provider == models.ProviderOpenAI || provider == models.ProviderLocal {\n\t\tif agent.ReasoningEffort == \"\" {\n\t\t\t// Set default reasoning effort for models that support it\n\t\t\tlogging.Info(\"setting default reasoning effort for model that supports reasoning\",\n\t\t\t\t\"agent\", name,\n\t\t\t\t\"model\", agent.Model)\n\n\t\t\t// Update the agent with default reasoning effort\n\t\t\tupdatedAgent := cfg.Agents[name]\n\t\t\tupdatedAgent.ReasoningEffort = \"medium\"\n\t\t\tcfg.Agents[name] = updatedAgent\n\t\t} else {\n\t\t\t// Check if reasoning effort is valid (low, medium, high)\n\t\t\teffort := strings.ToLower(agent.ReasoningEffort)\n\t\t\tif effort != \"low\" && effort != \"medium\" && effort != \"high\" {\n\t\t\t\tlogging.Warn(\"invalid reasoning effort, setting to medium\",\n\t\t\t\t\t\"agent\", name,\n\t\t\t\t\t\"model\", agent.Model,\n\t\t\t\t\t\"reasoning_effort\", agent.ReasoningEffort)\n\n\t\t\t\t// Update the agent with valid reasoning effort\n\t\t\t\tupdatedAgent := cfg.Agents[name]\n\t\t\t\tupdatedAgent.ReasoningEffort = \"medium\"\n\t\t\t\tcfg.Agents[name] = updatedAgent\n\t\t\t}\n\t\t}\n\t} else if !model.CanReason && agent.ReasoningEffort != \"\" {\n\t\t// Model doesn't support reasoning but reasoning effort is set\n\t\tlogging.Warn(\"model doesn't support reasoning but reasoning effort is set, ignoring\",\n\t\t\t\"agent\", name,\n\t\t\t\"model\", agent.Model,\n\t\t\t\"reasoning_effort\", agent.ReasoningEffort)\n\n\t\t// Update the agent to remove reasoning effort\n\t\tupdatedAgent := cfg.Agents[name]\n\t\tupdatedAgent.ReasoningEffort = \"\"\n\t\tcfg.Agents[name] = updatedAgent\n\t}\n\n\treturn nil\n}\n\n// Validate checks if the configuration is valid and applies defaults where needed.\nfunc Validate() error {\n\tif cfg == nil {\n\t\treturn fmt.Errorf(\"config not loaded\")\n\t}\n\n\t// Validate agent models\n\tfor name, agent := range cfg.Agents {\n\t\tif err := validateAgent(cfg, name, agent); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// Validate providers\n\tfor provider, providerCfg := range cfg.Providers {\n\t\tif providerCfg.APIKey == \"\" && !providerCfg.Disabled {\n\t\t\tfmt.Printf(\"provider has no API key, marking as disabled %s\", provider)\n\t\t\tlogging.Warn(\"provider has no API key, marking as disabled\", \"provider\", provider)\n\t\t\tproviderCfg.Disabled = true\n\t\t\tcfg.Providers[provider] = providerCfg\n\t\t}\n\t}\n\n\t// Validate LSP configurations\n\tfor language, lspConfig := range cfg.LSP {\n\t\tif lspConfig.Command == \"\" && !lspConfig.Disabled {\n\t\t\tlogging.Warn(\"LSP configuration has no command, marking as disabled\", \"language\", language)\n\t\t\tlspConfig.Disabled = true\n\t\t\tcfg.LSP[language] = lspConfig\n\t\t}\n\t}\n\n\treturn nil\n}\n\n// getProviderAPIKey gets the API key for a provider from environment variables\nfunc getProviderAPIKey(provider models.ModelProvider) string {\n\tswitch provider {\n\tcase models.ProviderAnthropic:\n\t\treturn os.Getenv(\"ANTHROPIC_API_KEY\")\n\tcase models.ProviderOpenAI:\n\t\treturn os.Getenv(\"OPENAI_API_KEY\")\n\tcase models.ProviderGemini:\n\t\treturn os.Getenv(\"GEMINI_API_KEY\")\n\tcase models.ProviderGROQ:\n\t\treturn os.Getenv(\"GROQ_API_KEY\")\n\tcase models.ProviderAzure:\n\t\treturn os.Getenv(\"AZURE_OPENAI_API_KEY\")\n\tcase models.ProviderOpenRouter:\n\t\treturn os.Getenv(\"OPENROUTER_API_KEY\")\n\tcase models.ProviderBedrock:\n\t\tif hasAWSCredentials() {\n\t\t\treturn \"aws-credentials-available\"\n\t\t}\n\tcase models.ProviderVertexAI:\n\t\tif hasVertexAICredentials() {\n\t\t\treturn \"vertex-ai-credentials-available\"\n\t\t}\n\t}\n\treturn \"\"\n}\n\n// setDefaultModelForAgent sets a default model for an agent based on available providers\nfunc setDefaultModelForAgent(agent AgentName) bool {\n\tif hasCopilotCredentials() {\n\t\tmaxTokens := int64(5000)\n\t\tif agent == AgentTitle {\n\t\t\tmaxTokens = 80\n\t\t}\n\n\t\tcfg.Agents[agent] = Agent{\n\t\t\tModel: models.CopilotGPT4o,\n\t\t\tMaxTokens: maxTokens,\n\t\t}\n\t\treturn true\n\t}\n\t// Check providers in order of preference\n\tif apiKey := os.Getenv(\"ANTHROPIC_API_KEY\"); apiKey != \"\" {\n\t\tmaxTokens := int64(5000)\n\t\tif agent == AgentTitle {\n\t\t\tmaxTokens = 80\n\t\t}\n\t\tcfg.Agents[agent] = Agent{\n\t\t\tModel: models.Claude37Sonnet,\n\t\t\tMaxTokens: maxTokens,\n\t\t}\n\t\treturn true\n\t}\n\n\tif apiKey := os.Getenv(\"OPENAI_API_KEY\"); apiKey != \"\" {\n\t\tvar model models.ModelID\n\t\tmaxTokens := int64(5000)\n\t\treasoningEffort := \"\"\n\n\t\tswitch agent {\n\t\tcase AgentTitle:\n\t\t\tmodel = models.GPT41Mini\n\t\t\tmaxTokens = 80\n\t\tcase AgentTask:\n\t\t\tmodel = models.GPT41Mini\n\t\tdefault:\n\t\t\tmodel = models.GPT41\n\t\t}\n\n\t\t// Check if model supports reasoning\n\t\tif modelInfo, ok := models.SupportedModels[model]; ok && modelInfo.CanReason {\n\t\t\treasoningEffort = \"medium\"\n\t\t}\n\n\t\tcfg.Agents[agent] = Agent{\n\t\t\tModel: model,\n\t\t\tMaxTokens: maxTokens,\n\t\t\tReasoningEffort: reasoningEffort,\n\t\t}\n\t\treturn true\n\t}\n\n\tif apiKey := os.Getenv(\"OPENROUTER_API_KEY\"); apiKey != \"\" {\n\t\tvar model models.ModelID\n\t\tmaxTokens := int64(5000)\n\t\treasoningEffort := \"\"\n\n\t\tswitch agent {\n\t\tcase AgentTitle:\n\t\t\tmodel = models.OpenRouterClaude35Haiku\n\t\t\tmaxTokens = 80\n\t\tcase AgentTask:\n\t\t\tmodel = models.OpenRouterClaude37Sonnet\n\t\tdefault:\n\t\t\tmodel = models.OpenRouterClaude37Sonnet\n\t\t}\n\n\t\t// Check if model supports reasoning\n\t\tif modelInfo, ok := models.SupportedModels[model]; ok && modelInfo.CanReason {\n\t\t\treasoningEffort = \"medium\"\n\t\t}\n\n\t\tcfg.Agents[agent] = Agent{\n\t\t\tModel: model,\n\t\t\tMaxTokens: maxTokens,\n\t\t\tReasoningEffort: reasoningEffort,\n\t\t}\n\t\treturn true\n\t}\n\n\tif apiKey := os.Getenv(\"GEMINI_API_KEY\"); apiKey != \"\" {\n\t\tvar model models.ModelID\n\t\tmaxTokens := int64(5000)\n\n\t\tif agent == AgentTitle {\n\t\t\tmodel = models.Gemini25Flash\n\t\t\tmaxTokens = 80\n\t\t} else {\n\t\t\tmodel = models.Gemini25\n\t\t}\n\n\t\tcfg.Agents[agent] = Agent{\n\t\t\tModel: model,\n\t\t\tMaxTokens: maxTokens,\n\t\t}\n\t\treturn true\n\t}\n\n\tif apiKey := os.Getenv(\"GROQ_API_KEY\"); apiKey != \"\" {\n\t\tmaxTokens := int64(5000)\n\t\tif agent == AgentTitle {\n\t\t\tmaxTokens = 80\n\t\t}\n\n\t\tcfg.Agents[agent] = Agent{\n\t\t\tModel: models.QWENQwq,\n\t\t\tMaxTokens: maxTokens,\n\t\t}\n\t\treturn true\n\t}\n\n\tif hasAWSCredentials() {\n\t\tmaxTokens := int64(5000)\n\t\tif agent == AgentTitle {\n\t\t\tmaxTokens = 80\n\t\t}\n\n\t\tcfg.Agents[agent] = Agent{\n\t\t\tModel: models.BedrockClaude37Sonnet,\n\t\t\tMaxTokens: maxTokens,\n\t\t\tReasoningEffort: \"medium\", // Claude models support reasoning\n\t\t}\n\t\treturn true\n\t}\n\n\tif hasVertexAICredentials() {\n\t\tvar model models.ModelID\n\t\tmaxTokens := int64(5000)\n\n\t\tif agent == AgentTitle {\n\t\t\tmodel = models.VertexAIGemini25Flash\n\t\t\tmaxTokens = 80\n\t\t} else {\n\t\t\tmodel = models.VertexAIGemini25\n\t\t}\n\n\t\tcfg.Agents[agent] = Agent{\n\t\t\tModel: model,\n\t\t\tMaxTokens: maxTokens,\n\t\t}\n\t\treturn true\n\t}\n\n\treturn false\n}\n\nfunc updateCfgFile(updateCfg func(config *Config)) error {\n\tif cfg == nil {\n\t\treturn fmt.Errorf(\"config not loaded\")\n\t}\n\n\t// Get the config file path\n\tconfigFile := viper.ConfigFileUsed()\n\tvar configData []byte\n\tif configFile == \"\" {\n\t\thomeDir, err := os.UserHomeDir()\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to get home directory: %w\", err)\n\t\t}\n\t\tconfigFile = filepath.Join(homeDir, fmt.Sprintf(\".%s.json\", appName))\n\t\tlogging.Info(\"config file not found, creating new one\", \"path\", configFile)\n\t\tconfigData = []byte(`{}`)\n\t} else {\n\t\t// Read the existing config file\n\t\tdata, err := os.ReadFile(configFile)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to read config file: %w\", err)\n\t\t}\n\t\tconfigData = data\n\t}\n\n\t// Parse the JSON\n\tvar userCfg *Config\n\tif err := json.Unmarshal(configData, &userCfg); err != nil {\n\t\treturn fmt.Errorf(\"failed to parse config file: %w\", err)\n\t}\n\n\tupdateCfg(userCfg)\n\n\t// Write the updated config back to file\n\tupdatedData, err := json.MarshalIndent(userCfg, \"\", \" \")\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to marshal config: %w\", err)\n\t}\n\n\tif err := os.WriteFile(configFile, updatedData, 0o644); err != nil {\n\t\treturn fmt.Errorf(\"failed to write config file: %w\", err)\n\t}\n\n\treturn nil\n}\n\n// Get returns the current configuration.\n// It's safe to call this function multiple times.\nfunc Get() *Config {\n\treturn cfg\n}\n\n// WorkingDirectory returns the current working directory from the configuration.\nfunc WorkingDirectory() string {\n\tif cfg == nil {\n\t\tpanic(\"config not loaded\")\n\t}\n\treturn cfg.WorkingDir\n}\n\nfunc UpdateAgentModel(agentName AgentName, modelID models.ModelID) error {\n\tif cfg == nil {\n\t\tpanic(\"config not loaded\")\n\t}\n\n\texistingAgentCfg := cfg.Agents[agentName]\n\n\tmodel, ok := models.SupportedModels[modelID]\n\tif !ok {\n\t\treturn fmt.Errorf(\"model %s not supported\", modelID)\n\t}\n\n\tmaxTokens := existingAgentCfg.MaxTokens\n\tif model.DefaultMaxTokens > 0 {\n\t\tmaxTokens = model.DefaultMaxTokens\n\t}\n\n\tnewAgentCfg := Agent{\n\t\tModel: modelID,\n\t\tMaxTokens: maxTokens,\n\t\tReasoningEffort: existingAgentCfg.ReasoningEffort,\n\t}\n\tcfg.Agents[agentName] = newAgentCfg\n\n\tif err := validateAgent(cfg, agentName, newAgentCfg); err != nil {\n\t\t// revert config update on failure\n\t\tcfg.Agents[agentName] = existingAgentCfg\n\t\treturn fmt.Errorf(\"failed to update agent model: %w\", err)\n\t}\n\n\treturn updateCfgFile(func(config *Config) {\n\t\tif config.Agents == nil {\n\t\t\tconfig.Agents = make(map[AgentName]Agent)\n\t\t}\n\t\tconfig.Agents[agentName] = newAgentCfg\n\t})\n}\n\n// UpdateTheme updates the theme in the configuration and writes it to the config file.\nfunc UpdateTheme(themeName string) error {\n\tif cfg == nil {\n\t\treturn fmt.Errorf(\"config not loaded\")\n\t}\n\n\t// Update the in-memory config\n\tcfg.TUI.Theme = themeName\n\n\t// Update the file config\n\treturn updateCfgFile(func(config *Config) {\n\t\tconfig.TUI.Theme = themeName\n\t})\n}\n\n// Tries to load Github token from all possible locations\nfunc LoadGitHubToken() (string, error) {\n\t// First check environment variable\n\tif token := os.Getenv(\"GITHUB_TOKEN\"); token != \"\" {\n\t\treturn token, nil\n\t}\n\n\t// Get config directory\n\tvar configDir string\n\tif xdgConfig := os.Getenv(\"XDG_CONFIG_HOME\"); xdgConfig != \"\" {\n\t\tconfigDir = xdgConfig\n\t} else if runtime.GOOS == \"windows\" {\n\t\tif localAppData := os.Getenv(\"LOCALAPPDATA\"); localAppData != \"\" {\n\t\t\tconfigDir = localAppData\n\t\t} else {\n\t\t\tconfigDir = filepath.Join(os.Getenv(\"HOME\"), \"AppData\", \"Local\")\n\t\t}\n\t} else {\n\t\tconfigDir = filepath.Join(os.Getenv(\"HOME\"), \".config\")\n\t}\n\n\t// Try both hosts.json and apps.json files\n\tfilePaths := []string{\n\t\tfilepath.Join(configDir, \"github-copilot\", \"hosts.json\"),\n\t\tfilepath.Join(configDir, \"github-copilot\", \"apps.json\"),\n\t}\n\n\tfor _, filePath := range filePaths {\n\t\tdata, err := os.ReadFile(filePath)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tvar config map[string]map[string]interface{}\n\t\tif err := json.Unmarshal(data, &config); err != nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tfor key, value := range config {\n\t\t\tif strings.Contains(key, \"github.com\") {\n\t\t\t\tif oauthToken, ok := value[\"oauth_token\"].(string); ok {\n\t\t\t\t\treturn oauthToken, nil\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn \"\", fmt.Errorf(\"GitHub token not found in standard locations\")\n}\n"], ["/opencode/internal/tui/image/images.go", "package image\n\nimport (\n\t\"fmt\"\n\t\"image\"\n\t\"os\"\n\t\"strings\"\n\n\t\"github.com/charmbracelet/lipgloss\"\n\t\"github.com/disintegration/imaging\"\n\t\"github.com/lucasb-eyer/go-colorful\"\n)\n\nfunc ValidateFileSize(filePath string, sizeLimit int64) (bool, error) {\n\tfileInfo, err := os.Stat(filePath)\n\tif err != nil {\n\t\treturn false, fmt.Errorf(\"error getting file info: %w\", err)\n\t}\n\n\tif fileInfo.Size() > sizeLimit {\n\t\treturn true, nil\n\t}\n\n\treturn false, nil\n}\n\nfunc ToString(width int, img image.Image) string {\n\timg = imaging.Resize(img, width, 0, imaging.Lanczos)\n\tb := img.Bounds()\n\timageWidth := b.Max.X\n\th := b.Max.Y\n\tstr := strings.Builder{}\n\n\tfor heightCounter := 0; heightCounter < h; heightCounter += 2 {\n\t\tfor x := range imageWidth {\n\t\t\tc1, _ := colorful.MakeColor(img.At(x, heightCounter))\n\t\t\tcolor1 := lipgloss.Color(c1.Hex())\n\n\t\t\tvar color2 lipgloss.Color\n\t\t\tif heightCounter+1 < h {\n\t\t\t\tc2, _ := colorful.MakeColor(img.At(x, heightCounter+1))\n\t\t\t\tcolor2 = lipgloss.Color(c2.Hex())\n\t\t\t} else {\n\t\t\t\tcolor2 = color1\n\t\t\t}\n\n\t\t\tstr.WriteString(lipgloss.NewStyle().Foreground(color1).\n\t\t\t\tBackground(color2).Render(\"▀\"))\n\t\t}\n\n\t\tstr.WriteString(\"\\n\")\n\t}\n\n\treturn str.String()\n}\n\nfunc ImagePreview(width int, filename string) (string, error) {\n\timageContent, err := os.Open(filename)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer imageContent.Close()\n\n\timg, _, err := image.Decode(imageContent)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\timageString := ToString(width, img)\n\n\treturn imageString, nil\n}\n"], ["/opencode/internal/llm/provider/anthropic.go", "package provider\n\nimport (\n\t\"context\"\n\t\"encoding/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/anthropics/anthropic-sdk-go\"\n\t\"github.com/anthropics/anthropic-sdk-go/bedrock\"\n\t\"github.com/anthropics/anthropic-sdk-go/option\"\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/llm/models\"\n\ttoolsPkg \"github.com/opencode-ai/opencode/internal/llm/tools\"\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n\t\"github.com/opencode-ai/opencode/internal/message\"\n)\n\ntype anthropicOptions struct {\n\tuseBedrock bool\n\tdisableCache bool\n\tshouldThink func(userMessage string) bool\n}\n\ntype AnthropicOption func(*anthropicOptions)\n\ntype anthropicClient struct {\n\tproviderOptions providerClientOptions\n\toptions anthropicOptions\n\tclient anthropic.Client\n}\n\ntype AnthropicClient ProviderClient\n\nfunc newAnthropicClient(opts providerClientOptions) AnthropicClient {\n\tanthropicOpts := anthropicOptions{}\n\tfor _, o := range opts.anthropicOptions {\n\t\to(&anthropicOpts)\n\t}\n\n\tanthropicClientOptions := []option.RequestOption{}\n\tif opts.apiKey != \"\" {\n\t\tanthropicClientOptions = append(anthropicClientOptions, option.WithAPIKey(opts.apiKey))\n\t}\n\tif anthropicOpts.useBedrock {\n\t\tanthropicClientOptions = append(anthropicClientOptions, bedrock.WithLoadDefaultConfig(context.Background()))\n\t}\n\n\tclient := anthropic.NewClient(anthropicClientOptions...)\n\treturn &anthropicClient{\n\t\tproviderOptions: opts,\n\t\toptions: anthropicOpts,\n\t\tclient: client,\n\t}\n}\n\nfunc (a *anthropicClient) convertMessages(messages []message.Message) (anthropicMessages []anthropic.MessageParam) {\n\tfor i, msg := range messages {\n\t\tcache := false\n\t\tif i > len(messages)-3 {\n\t\t\tcache = true\n\t\t}\n\t\tswitch msg.Role {\n\t\tcase message.User:\n\t\t\tcontent := anthropic.NewTextBlock(msg.Content().String())\n\t\t\tif cache && !a.options.disableCache {\n\t\t\t\tcontent.OfText.CacheControl = anthropic.CacheControlEphemeralParam{\n\t\t\t\t\tType: \"ephemeral\",\n\t\t\t\t}\n\t\t\t}\n\t\t\tvar contentBlocks []anthropic.ContentBlockParamUnion\n\t\t\tcontentBlocks = append(contentBlocks, content)\n\t\t\tfor _, binaryContent := range msg.BinaryContent() {\n\t\t\t\tbase64Image := binaryContent.String(models.ProviderAnthropic)\n\t\t\t\timageBlock := anthropic.NewImageBlockBase64(binaryContent.MIMEType, base64Image)\n\t\t\t\tcontentBlocks = append(contentBlocks, imageBlock)\n\t\t\t}\n\t\t\tanthropicMessages = append(anthropicMessages, anthropic.NewUserMessage(contentBlocks...))\n\n\t\tcase message.Assistant:\n\t\t\tblocks := []anthropic.ContentBlockParamUnion{}\n\t\t\tif msg.Content().String() != \"\" {\n\t\t\t\tcontent := anthropic.NewTextBlock(msg.Content().String())\n\t\t\t\tif cache && !a.options.disableCache {\n\t\t\t\t\tcontent.OfText.CacheControl = anthropic.CacheControlEphemeralParam{\n\t\t\t\t\t\tType: \"ephemeral\",\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tblocks = append(blocks, content)\n\t\t\t}\n\n\t\t\tfor _, toolCall := range msg.ToolCalls() {\n\t\t\t\tvar inputMap map[string]any\n\t\t\t\terr := json.Unmarshal([]byte(toolCall.Input), &inputMap)\n\t\t\t\tif err != nil {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tblocks = append(blocks, anthropic.NewToolUseBlock(toolCall.ID, inputMap, toolCall.Name))\n\t\t\t}\n\n\t\t\tif len(blocks) == 0 {\n\t\t\t\tlogging.Warn(\"There is a message without content, investigate, this should not happen\")\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tanthropicMessages = append(anthropicMessages, anthropic.NewAssistantMessage(blocks...))\n\n\t\tcase message.Tool:\n\t\t\tresults := make([]anthropic.ContentBlockParamUnion, len(msg.ToolResults()))\n\t\t\tfor i, toolResult := range msg.ToolResults() {\n\t\t\t\tresults[i] = anthropic.NewToolResultBlock(toolResult.ToolCallID, toolResult.Content, toolResult.IsError)\n\t\t\t}\n\t\t\tanthropicMessages = append(anthropicMessages, anthropic.NewUserMessage(results...))\n\t\t}\n\t}\n\treturn\n}\n\nfunc (a *anthropicClient) convertTools(tools []toolsPkg.BaseTool) []anthropic.ToolUnionParam {\n\tanthropicTools := make([]anthropic.ToolUnionParam, len(tools))\n\n\tfor i, tool := range tools {\n\t\tinfo := tool.Info()\n\t\ttoolParam := anthropic.ToolParam{\n\t\t\tName: info.Name,\n\t\t\tDescription: anthropic.String(info.Description),\n\t\t\tInputSchema: anthropic.ToolInputSchemaParam{\n\t\t\t\tProperties: info.Parameters,\n\t\t\t\t// TODO: figure out how we can tell claude the required fields?\n\t\t\t},\n\t\t}\n\n\t\tif i == len(tools)-1 && !a.options.disableCache {\n\t\t\ttoolParam.CacheControl = anthropic.CacheControlEphemeralParam{\n\t\t\t\tType: \"ephemeral\",\n\t\t\t}\n\t\t}\n\n\t\tanthropicTools[i] = anthropic.ToolUnionParam{OfTool: &toolParam}\n\t}\n\n\treturn anthropicTools\n}\n\nfunc (a *anthropicClient) finishReason(reason string) message.FinishReason {\n\tswitch reason {\n\tcase \"end_turn\":\n\t\treturn message.FinishReasonEndTurn\n\tcase \"max_tokens\":\n\t\treturn message.FinishReasonMaxTokens\n\tcase \"tool_use\":\n\t\treturn message.FinishReasonToolUse\n\tcase \"stop_sequence\":\n\t\treturn message.FinishReasonEndTurn\n\tdefault:\n\t\treturn message.FinishReasonUnknown\n\t}\n}\n\nfunc (a *anthropicClient) preparedMessages(messages []anthropic.MessageParam, tools []anthropic.ToolUnionParam) anthropic.MessageNewParams {\n\tvar thinkingParam anthropic.ThinkingConfigParamUnion\n\tlastMessage := messages[len(messages)-1]\n\tisUser := lastMessage.Role == anthropic.MessageParamRoleUser\n\tmessageContent := \"\"\n\ttemperature := anthropic.Float(0)\n\tif isUser {\n\t\tfor _, m := range lastMessage.Content {\n\t\t\tif m.OfText != nil && m.OfText.Text != \"\" {\n\t\t\t\tmessageContent = m.OfText.Text\n\t\t\t}\n\t\t}\n\t\tif messageContent != \"\" && a.options.shouldThink != nil && a.options.shouldThink(messageContent) {\n\t\t\tthinkingParam = anthropic.ThinkingConfigParamOfEnabled(int64(float64(a.providerOptions.maxTokens) * 0.8))\n\t\t\ttemperature = anthropic.Float(1)\n\t\t}\n\t}\n\n\treturn anthropic.MessageNewParams{\n\t\tModel: anthropic.Model(a.providerOptions.model.APIModel),\n\t\tMaxTokens: a.providerOptions.maxTokens,\n\t\tTemperature: temperature,\n\t\tMessages: messages,\n\t\tTools: tools,\n\t\tThinking: thinkingParam,\n\t\tSystem: []anthropic.TextBlockParam{\n\t\t\t{\n\t\t\t\tText: a.providerOptions.systemMessage,\n\t\t\t\tCacheControl: anthropic.CacheControlEphemeralParam{\n\t\t\t\t\tType: \"ephemeral\",\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n}\n\nfunc (a *anthropicClient) send(ctx context.Context, messages []message.Message, tools []toolsPkg.BaseTool) (resposne *ProviderResponse, err error) {\n\tpreparedMessages := a.preparedMessages(a.convertMessages(messages), a.convertTools(tools))\n\tcfg := config.Get()\n\tif cfg.Debug {\n\t\tjsonData, _ := json.Marshal(preparedMessages)\n\t\tlogging.Debug(\"Prepared messages\", \"messages\", string(jsonData))\n\t}\n\n\tattempts := 0\n\tfor {\n\t\tattempts++\n\t\tanthropicResponse, err := a.client.Messages.New(\n\t\t\tctx,\n\t\t\tpreparedMessages,\n\t\t)\n\t\t// If there is an error we are going to see if we can retry the call\n\t\tif err != nil {\n\t\t\tlogging.Error(\"Error in Anthropic API call\", \"error\", err)\n\t\t\tretry, after, retryErr := a.shouldRetry(attempts, err)\n\t\t\tif retryErr != nil {\n\t\t\t\treturn nil, retryErr\n\t\t\t}\n\t\t\tif retry {\n\t\t\t\tlogging.WarnPersist(fmt.Sprintf(\"Retrying due to rate limit... attempt %d of %d\", attempts, maxRetries), logging.PersistTimeArg, time.Millisecond*time.Duration(after+100))\n\t\t\t\tselect {\n\t\t\t\tcase <-ctx.Done():\n\t\t\t\t\treturn nil, ctx.Err()\n\t\t\t\tcase <-time.After(time.Duration(after) * time.Millisecond):\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn nil, retryErr\n\t\t}\n\n\t\tcontent := \"\"\n\t\tfor _, block := range anthropicResponse.Content {\n\t\t\tif text, ok := block.AsAny().(anthropic.TextBlock); ok {\n\t\t\t\tcontent += text.Text\n\t\t\t}\n\t\t}\n\n\t\treturn &ProviderResponse{\n\t\t\tContent: content,\n\t\t\tToolCalls: a.toolCalls(*anthropicResponse),\n\t\t\tUsage: a.usage(*anthropicResponse),\n\t\t}, nil\n\t}\n}\n\nfunc (a *anthropicClient) stream(ctx context.Context, messages []message.Message, tools []toolsPkg.BaseTool) <-chan ProviderEvent {\n\tpreparedMessages := a.preparedMessages(a.convertMessages(messages), a.convertTools(tools))\n\tcfg := config.Get()\n\n\tvar sessionId string\n\trequestSeqId := (len(messages) + 1) / 2\n\tif cfg.Debug {\n\t\tif sid, ok := ctx.Value(toolsPkg.SessionIDContextKey).(string); ok {\n\t\t\tsessionId = sid\n\t\t}\n\t\tjsonData, _ := json.Marshal(preparedMessages)\n\t\tif sessionId != \"\" {\n\t\t\tfilepath := logging.WriteRequestMessageJson(sessionId, requestSeqId, preparedMessages)\n\t\t\tlogging.Debug(\"Prepared messages\", \"filepath\", filepath)\n\t\t} else {\n\t\t\tlogging.Debug(\"Prepared messages\", \"messages\", string(jsonData))\n\t\t}\n\n\t}\n\tattempts := 0\n\teventChan := make(chan ProviderEvent)\n\tgo func() {\n\t\tfor {\n\t\t\tattempts++\n\t\t\tanthropicStream := a.client.Messages.NewStreaming(\n\t\t\t\tctx,\n\t\t\t\tpreparedMessages,\n\t\t\t)\n\t\t\taccumulatedMessage := anthropic.Message{}\n\n\t\t\tcurrentToolCallID := \"\"\n\t\t\tfor anthropicStream.Next() {\n\t\t\t\tevent := anthropicStream.Current()\n\t\t\t\terr := accumulatedMessage.Accumulate(event)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlogging.Warn(\"Error accumulating message\", \"error\", err)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tswitch event := event.AsAny().(type) {\n\t\t\t\tcase anthropic.ContentBlockStartEvent:\n\t\t\t\t\tif event.ContentBlock.Type == \"text\" {\n\t\t\t\t\t\teventChan <- ProviderEvent{Type: EventContentStart}\n\t\t\t\t\t} else if event.ContentBlock.Type == \"tool_use\" {\n\t\t\t\t\t\tcurrentToolCallID = event.ContentBlock.ID\n\t\t\t\t\t\teventChan <- ProviderEvent{\n\t\t\t\t\t\t\tType: EventToolUseStart,\n\t\t\t\t\t\t\tToolCall: &message.ToolCall{\n\t\t\t\t\t\t\t\tID: event.ContentBlock.ID,\n\t\t\t\t\t\t\t\tName: event.ContentBlock.Name,\n\t\t\t\t\t\t\t\tFinished: false,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\tcase anthropic.ContentBlockDeltaEvent:\n\t\t\t\t\tif event.Delta.Type == \"thinking_delta\" && event.Delta.Thinking != \"\" {\n\t\t\t\t\t\teventChan <- ProviderEvent{\n\t\t\t\t\t\t\tType: EventThinkingDelta,\n\t\t\t\t\t\t\tThinking: event.Delta.Thinking,\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if event.Delta.Type == \"text_delta\" && event.Delta.Text != \"\" {\n\t\t\t\t\t\teventChan <- ProviderEvent{\n\t\t\t\t\t\t\tType: EventContentDelta,\n\t\t\t\t\t\t\tContent: event.Delta.Text,\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if event.Delta.Type == \"input_json_delta\" {\n\t\t\t\t\t\tif currentToolCallID != \"\" {\n\t\t\t\t\t\t\teventChan <- ProviderEvent{\n\t\t\t\t\t\t\t\tType: EventToolUseDelta,\n\t\t\t\t\t\t\t\tToolCall: &message.ToolCall{\n\t\t\t\t\t\t\t\t\tID: currentToolCallID,\n\t\t\t\t\t\t\t\t\tFinished: false,\n\t\t\t\t\t\t\t\t\tInput: event.Delta.JSON.PartialJSON.Raw(),\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\tcase anthropic.ContentBlockStopEvent:\n\t\t\t\t\tif currentToolCallID != \"\" {\n\t\t\t\t\t\teventChan <- ProviderEvent{\n\t\t\t\t\t\t\tType: EventToolUseStop,\n\t\t\t\t\t\t\tToolCall: &message.ToolCall{\n\t\t\t\t\t\t\t\tID: currentToolCallID,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcurrentToolCallID = \"\"\n\t\t\t\t\t} else {\n\t\t\t\t\t\teventChan <- ProviderEvent{Type: EventContentStop}\n\t\t\t\t\t}\n\n\t\t\t\tcase anthropic.MessageStopEvent:\n\t\t\t\t\tcontent := \"\"\n\t\t\t\t\tfor _, block := range accumulatedMessage.Content {\n\t\t\t\t\t\tif text, ok := block.AsAny().(anthropic.TextBlock); ok {\n\t\t\t\t\t\t\tcontent += text.Text\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\teventChan <- ProviderEvent{\n\t\t\t\t\t\tType: EventComplete,\n\t\t\t\t\t\tResponse: &ProviderResponse{\n\t\t\t\t\t\t\tContent: content,\n\t\t\t\t\t\t\tToolCalls: a.toolCalls(accumulatedMessage),\n\t\t\t\t\t\t\tUsage: a.usage(accumulatedMessage),\n\t\t\t\t\t\t\tFinishReason: a.finishReason(string(accumulatedMessage.StopReason)),\n\t\t\t\t\t\t},\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\terr := anthropicStream.Err()\n\t\t\tif err == nil || errors.Is(err, io.EOF) {\n\t\t\t\tclose(eventChan)\n\t\t\t\treturn\n\t\t\t}\n\t\t\t// If there is an error we are going to see if we can retry the call\n\t\t\tretry, after, retryErr := a.shouldRetry(attempts, err)\n\t\t\tif retryErr != nil {\n\t\t\t\teventChan <- ProviderEvent{Type: EventError, Error: retryErr}\n\t\t\t\tclose(eventChan)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif retry {\n\t\t\t\tlogging.WarnPersist(fmt.Sprintf(\"Retrying due to rate limit... attempt %d of %d\", attempts, maxRetries), logging.PersistTimeArg, time.Millisecond*time.Duration(after+100))\n\t\t\t\tselect {\n\t\t\t\tcase <-ctx.Done():\n\t\t\t\t\t// context cancelled\n\t\t\t\t\tif ctx.Err() != nil {\n\t\t\t\t\t\teventChan <- ProviderEvent{Type: EventError, Error: ctx.Err()}\n\t\t\t\t\t}\n\t\t\t\t\tclose(eventChan)\n\t\t\t\t\treturn\n\t\t\t\tcase <-time.After(time.Duration(after) * time.Millisecond):\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t\tif ctx.Err() != nil {\n\t\t\t\teventChan <- ProviderEvent{Type: EventError, Error: ctx.Err()}\n\t\t\t}\n\n\t\t\tclose(eventChan)\n\t\t\treturn\n\t\t}\n\t}()\n\treturn eventChan\n}\n\nfunc (a *anthropicClient) shouldRetry(attempts int, err error) (bool, int64, error) {\n\tvar apierr *anthropic.Error\n\tif !errors.As(err, &apierr) {\n\t\treturn false, 0, err\n\t}\n\n\tif apierr.StatusCode != 429 && apierr.StatusCode != 529 {\n\t\treturn false, 0, err\n\t}\n\n\tif attempts > maxRetries {\n\t\treturn false, 0, fmt.Errorf(\"maximum retry attempts reached for rate limit: %d retries\", maxRetries)\n\t}\n\n\tretryMs := 0\n\tretryAfterValues := apierr.Response.Header.Values(\"Retry-After\")\n\n\tbackoffMs := 2000 * (1 << (attempts - 1))\n\tjitterMs := int(float64(backoffMs) * 0.2)\n\tretryMs = backoffMs + jitterMs\n\tif len(retryAfterValues) > 0 {\n\t\tif _, err := fmt.Sscanf(retryAfterValues[0], \"%d\", &retryMs); err == nil {\n\t\t\tretryMs = retryMs * 1000\n\t\t}\n\t}\n\treturn true, int64(retryMs), nil\n}\n\nfunc (a *anthropicClient) toolCalls(msg anthropic.Message) []message.ToolCall {\n\tvar toolCalls []message.ToolCall\n\n\tfor _, block := range msg.Content {\n\t\tswitch variant := block.AsAny().(type) {\n\t\tcase anthropic.ToolUseBlock:\n\t\t\ttoolCall := message.ToolCall{\n\t\t\t\tID: variant.ID,\n\t\t\t\tName: variant.Name,\n\t\t\t\tInput: string(variant.Input),\n\t\t\t\tType: string(variant.Type),\n\t\t\t\tFinished: true,\n\t\t\t}\n\t\t\ttoolCalls = append(toolCalls, toolCall)\n\t\t}\n\t}\n\n\treturn toolCalls\n}\n\nfunc (a *anthropicClient) usage(msg anthropic.Message) TokenUsage {\n\treturn TokenUsage{\n\t\tInputTokens: msg.Usage.InputTokens,\n\t\tOutputTokens: msg.Usage.OutputTokens,\n\t\tCacheCreationTokens: msg.Usage.CacheCreationInputTokens,\n\t\tCacheReadTokens: msg.Usage.CacheReadInputTokens,\n\t}\n}\n\nfunc WithAnthropicBedrock(useBedrock bool) AnthropicOption {\n\treturn func(options *anthropicOptions) {\n\t\toptions.useBedrock = useBedrock\n\t}\n}\n\nfunc WithAnthropicDisableCache() AnthropicOption {\n\treturn func(options *anthropicOptions) {\n\t\toptions.disableCache = true\n\t}\n}\n\nfunc DefaultShouldThinkFn(s string) bool {\n\treturn strings.Contains(strings.ToLower(s), \"think\")\n}\n\nfunc WithAnthropicShouldThinkFn(fn func(string) bool) AnthropicOption {\n\treturn func(options *anthropicOptions) {\n\t\toptions.shouldThink = fn\n\t}\n}\n"], ["/opencode/internal/completions/files-folders.go", "package completions\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"os/exec\"\n\t\"path/filepath\"\n\n\t\"github.com/lithammer/fuzzysearch/fuzzy\"\n\t\"github.com/opencode-ai/opencode/internal/fileutil\"\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n\t\"github.com/opencode-ai/opencode/internal/tui/components/dialog\"\n)\n\ntype filesAndFoldersContextGroup struct {\n\tprefix string\n}\n\nfunc (cg *filesAndFoldersContextGroup) GetId() string {\n\treturn cg.prefix\n}\n\nfunc (cg *filesAndFoldersContextGroup) GetEntry() dialog.CompletionItemI {\n\treturn dialog.NewCompletionItem(dialog.CompletionItem{\n\t\tTitle: \"Files & Folders\",\n\t\tValue: \"files\",\n\t})\n}\n\nfunc processNullTerminatedOutput(outputBytes []byte) []string {\n\tif len(outputBytes) > 0 && outputBytes[len(outputBytes)-1] == 0 {\n\t\toutputBytes = outputBytes[:len(outputBytes)-1]\n\t}\n\n\tif len(outputBytes) == 0 {\n\t\treturn []string{}\n\t}\n\n\tsplit := bytes.Split(outputBytes, []byte{0})\n\tmatches := make([]string, 0, len(split))\n\n\tfor _, p := range split {\n\t\tif len(p) == 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\tpath := string(p)\n\t\tpath = filepath.Join(\".\", path)\n\n\t\tif !fileutil.SkipHidden(path) {\n\t\t\tmatches = append(matches, path)\n\t\t}\n\t}\n\n\treturn matches\n}\n\nfunc (cg *filesAndFoldersContextGroup) getFiles(query string) ([]string, error) {\n\tcmdRg := fileutil.GetRgCmd(\"\") // No glob pattern for this use case\n\tcmdFzf := fileutil.GetFzfCmd(query)\n\n\tvar matches []string\n\t// Case 1: Both rg and fzf available\n\tif cmdRg != nil && cmdFzf != nil {\n\t\trgPipe, err := cmdRg.StdoutPipe()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to get rg stdout pipe: %w\", err)\n\t\t}\n\t\tdefer rgPipe.Close()\n\n\t\tcmdFzf.Stdin = rgPipe\n\t\tvar fzfOut bytes.Buffer\n\t\tvar fzfErr bytes.Buffer\n\t\tcmdFzf.Stdout = &fzfOut\n\t\tcmdFzf.Stderr = &fzfErr\n\n\t\tif err := cmdFzf.Start(); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to start fzf: %w\", err)\n\t\t}\n\n\t\terrRg := cmdRg.Run()\n\t\terrFzf := cmdFzf.Wait()\n\n\t\tif errRg != nil {\n\t\t\tlogging.Warn(fmt.Sprintf(\"rg command failed during pipe: %v\", errRg))\n\t\t}\n\n\t\tif errFzf != nil {\n\t\t\tif exitErr, ok := errFzf.(*exec.ExitError); ok && exitErr.ExitCode() == 1 {\n\t\t\t\treturn []string{}, nil // No matches from fzf\n\t\t\t}\n\t\t\treturn nil, fmt.Errorf(\"fzf command failed: %w\\nStderr: %s\", errFzf, fzfErr.String())\n\t\t}\n\n\t\tmatches = processNullTerminatedOutput(fzfOut.Bytes())\n\n\t\t// Case 2: Only rg available\n\t} else if cmdRg != nil {\n\t\tlogging.Debug(\"Using Ripgrep with fuzzy match fallback for file completions\")\n\t\tvar rgOut bytes.Buffer\n\t\tvar rgErr bytes.Buffer\n\t\tcmdRg.Stdout = &rgOut\n\t\tcmdRg.Stderr = &rgErr\n\n\t\tif err := cmdRg.Run(); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"rg command failed: %w\\nStderr: %s\", err, rgErr.String())\n\t\t}\n\n\t\tallFiles := processNullTerminatedOutput(rgOut.Bytes())\n\t\tmatches = fuzzy.Find(query, allFiles)\n\n\t\t// Case 3: Only fzf available\n\t} else if cmdFzf != nil {\n\t\tlogging.Debug(\"Using FZF with doublestar fallback for file completions\")\n\t\tfiles, _, err := fileutil.GlobWithDoublestar(\"**/*\", \".\", 0)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to list files for fzf: %w\", err)\n\t\t}\n\n\t\tallFiles := make([]string, 0, len(files))\n\t\tfor _, file := range files {\n\t\t\tif !fileutil.SkipHidden(file) {\n\t\t\t\tallFiles = append(allFiles, file)\n\t\t\t}\n\t\t}\n\n\t\tvar fzfIn bytes.Buffer\n\t\tfor _, file := range allFiles {\n\t\t\tfzfIn.WriteString(file)\n\t\t\tfzfIn.WriteByte(0)\n\t\t}\n\n\t\tcmdFzf.Stdin = &fzfIn\n\t\tvar fzfOut bytes.Buffer\n\t\tvar fzfErr bytes.Buffer\n\t\tcmdFzf.Stdout = &fzfOut\n\t\tcmdFzf.Stderr = &fzfErr\n\n\t\tif err := cmdFzf.Run(); err != nil {\n\t\t\tif exitErr, ok := err.(*exec.ExitError); ok && exitErr.ExitCode() == 1 {\n\t\t\t\treturn []string{}, nil\n\t\t\t}\n\t\t\treturn nil, fmt.Errorf(\"fzf command failed: %w\\nStderr: %s\", err, fzfErr.String())\n\t\t}\n\n\t\tmatches = processNullTerminatedOutput(fzfOut.Bytes())\n\n\t\t// Case 4: Fallback to doublestar with fuzzy match\n\t} else {\n\t\tlogging.Debug(\"Using doublestar with fuzzy match for file completions\")\n\t\tallFiles, _, err := fileutil.GlobWithDoublestar(\"**/*\", \".\", 0)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to glob files: %w\", err)\n\t\t}\n\n\t\tfilteredFiles := make([]string, 0, len(allFiles))\n\t\tfor _, file := range allFiles {\n\t\t\tif !fileutil.SkipHidden(file) {\n\t\t\t\tfilteredFiles = append(filteredFiles, file)\n\t\t\t}\n\t\t}\n\n\t\tmatches = fuzzy.Find(query, filteredFiles)\n\t}\n\n\treturn matches, nil\n}\n\nfunc (cg *filesAndFoldersContextGroup) GetChildEntries(query string) ([]dialog.CompletionItemI, error) {\n\tmatches, err := cg.getFiles(query)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\titems := make([]dialog.CompletionItemI, 0, len(matches))\n\tfor _, file := range matches {\n\t\titem := dialog.NewCompletionItem(dialog.CompletionItem{\n\t\t\tTitle: file,\n\t\t\tValue: file,\n\t\t})\n\t\titems = append(items, item)\n\t}\n\n\treturn items, nil\n}\n\nfunc NewFileAndFolderContextGroup() dialog.CompletionProvider {\n\treturn &filesAndFoldersContextGroup{\n\t\tprefix: \"file\",\n\t}\n}\n"], ["/opencode/internal/llm/provider/openai.go", "package provider\n\nimport (\n\t\"context\"\n\t\"encoding/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"time\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n\t\"github.com/openai/openai-go/shared\"\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/llm/models\"\n\t\"github.com/opencode-ai/opencode/internal/llm/tools\"\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n\t\"github.com/opencode-ai/opencode/internal/message\"\n)\n\ntype openaiOptions struct {\n\tbaseURL string\n\tdisableCache bool\n\treasoningEffort string\n\textraHeaders map[string]string\n}\n\ntype OpenAIOption func(*openaiOptions)\n\ntype openaiClient struct {\n\tproviderOptions providerClientOptions\n\toptions openaiOptions\n\tclient openai.Client\n}\n\ntype OpenAIClient ProviderClient\n\nfunc newOpenAIClient(opts providerClientOptions) OpenAIClient {\n\topenaiOpts := openaiOptions{\n\t\treasoningEffort: \"medium\",\n\t}\n\tfor _, o := range opts.openaiOptions {\n\t\to(&openaiOpts)\n\t}\n\n\topenaiClientOptions := []option.RequestOption{}\n\tif opts.apiKey != \"\" {\n\t\topenaiClientOptions = append(openaiClientOptions, option.WithAPIKey(opts.apiKey))\n\t}\n\tif openaiOpts.baseURL != \"\" {\n\t\topenaiClientOptions = append(openaiClientOptions, option.WithBaseURL(openaiOpts.baseURL))\n\t}\n\n\tif openaiOpts.extraHeaders != nil {\n\t\tfor key, value := range openaiOpts.extraHeaders {\n\t\t\topenaiClientOptions = append(openaiClientOptions, option.WithHeader(key, value))\n\t\t}\n\t}\n\n\tclient := openai.NewClient(openaiClientOptions...)\n\treturn &openaiClient{\n\t\tproviderOptions: opts,\n\t\toptions: openaiOpts,\n\t\tclient: client,\n\t}\n}\n\nfunc (o *openaiClient) convertMessages(messages []message.Message) (openaiMessages []openai.ChatCompletionMessageParamUnion) {\n\t// Add system message first\n\topenaiMessages = append(openaiMessages, openai.SystemMessage(o.providerOptions.systemMessage))\n\n\tfor _, msg := range messages {\n\t\tswitch msg.Role {\n\t\tcase message.User:\n\t\t\tvar content []openai.ChatCompletionContentPartUnionParam\n\t\t\ttextBlock := openai.ChatCompletionContentPartTextParam{Text: msg.Content().String()}\n\t\t\tcontent = append(content, openai.ChatCompletionContentPartUnionParam{OfText: &textBlock})\n\t\t\tfor _, binaryContent := range msg.BinaryContent() {\n\t\t\t\timageURL := openai.ChatCompletionContentPartImageImageURLParam{URL: binaryContent.String(models.ProviderOpenAI)}\n\t\t\t\timageBlock := openai.ChatCompletionContentPartImageParam{ImageURL: imageURL}\n\n\t\t\t\tcontent = append(content, openai.ChatCompletionContentPartUnionParam{OfImageURL: &imageBlock})\n\t\t\t}\n\n\t\t\topenaiMessages = append(openaiMessages, openai.UserMessage(content))\n\n\t\tcase message.Assistant:\n\t\t\tassistantMsg := openai.ChatCompletionAssistantMessageParam{\n\t\t\t\tRole: \"assistant\",\n\t\t\t}\n\n\t\t\tif msg.Content().String() != \"\" {\n\t\t\t\tassistantMsg.Content = openai.ChatCompletionAssistantMessageParamContentUnion{\n\t\t\t\t\tOfString: openai.String(msg.Content().String()),\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif len(msg.ToolCalls()) > 0 {\n\t\t\t\tassistantMsg.ToolCalls = make([]openai.ChatCompletionMessageToolCallParam, len(msg.ToolCalls()))\n\t\t\t\tfor i, call := range msg.ToolCalls() {\n\t\t\t\t\tassistantMsg.ToolCalls[i] = openai.ChatCompletionMessageToolCallParam{\n\t\t\t\t\t\tID: call.ID,\n\t\t\t\t\t\tType: \"function\",\n\t\t\t\t\t\tFunction: openai.ChatCompletionMessageToolCallFunctionParam{\n\t\t\t\t\t\t\tName: call.Name,\n\t\t\t\t\t\t\tArguments: call.Input,\n\t\t\t\t\t\t},\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\topenaiMessages = append(openaiMessages, openai.ChatCompletionMessageParamUnion{\n\t\t\t\tOfAssistant: &assistantMsg,\n\t\t\t})\n\n\t\tcase message.Tool:\n\t\t\tfor _, result := range msg.ToolResults() {\n\t\t\t\topenaiMessages = append(openaiMessages,\n\t\t\t\t\topenai.ToolMessage(result.Content, result.ToolCallID),\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn\n}\n\nfunc (o *openaiClient) convertTools(tools []tools.BaseTool) []openai.ChatCompletionToolParam {\n\topenaiTools := make([]openai.ChatCompletionToolParam, len(tools))\n\n\tfor i, tool := range tools {\n\t\tinfo := tool.Info()\n\t\topenaiTools[i] = openai.ChatCompletionToolParam{\n\t\t\tFunction: openai.FunctionDefinitionParam{\n\t\t\t\tName: info.Name,\n\t\t\t\tDescription: openai.String(info.Description),\n\t\t\t\tParameters: openai.FunctionParameters{\n\t\t\t\t\t\"type\": \"object\",\n\t\t\t\t\t\"properties\": info.Parameters,\n\t\t\t\t\t\"required\": info.Required,\n\t\t\t\t},\n\t\t\t},\n\t\t}\n\t}\n\n\treturn openaiTools\n}\n\nfunc (o *openaiClient) finishReason(reason string) message.FinishReason {\n\tswitch reason {\n\tcase \"stop\":\n\t\treturn message.FinishReasonEndTurn\n\tcase \"length\":\n\t\treturn message.FinishReasonMaxTokens\n\tcase \"tool_calls\":\n\t\treturn message.FinishReasonToolUse\n\tdefault:\n\t\treturn message.FinishReasonUnknown\n\t}\n}\n\nfunc (o *openaiClient) preparedParams(messages []openai.ChatCompletionMessageParamUnion, tools []openai.ChatCompletionToolParam) openai.ChatCompletionNewParams {\n\tparams := openai.ChatCompletionNewParams{\n\t\tModel: openai.ChatModel(o.providerOptions.model.APIModel),\n\t\tMessages: messages,\n\t\tTools: tools,\n\t}\n\n\tif o.providerOptions.model.CanReason == true {\n\t\tparams.MaxCompletionTokens = openai.Int(o.providerOptions.maxTokens)\n\t\tswitch o.options.reasoningEffort {\n\t\tcase \"low\":\n\t\t\tparams.ReasoningEffort = shared.ReasoningEffortLow\n\t\tcase \"medium\":\n\t\t\tparams.ReasoningEffort = shared.ReasoningEffortMedium\n\t\tcase \"high\":\n\t\t\tparams.ReasoningEffort = shared.ReasoningEffortHigh\n\t\tdefault:\n\t\t\tparams.ReasoningEffort = shared.ReasoningEffortMedium\n\t\t}\n\t} else {\n\t\tparams.MaxTokens = openai.Int(o.providerOptions.maxTokens)\n\t}\n\n\treturn params\n}\n\nfunc (o *openaiClient) send(ctx context.Context, messages []message.Message, tools []tools.BaseTool) (response *ProviderResponse, err error) {\n\tparams := o.preparedParams(o.convertMessages(messages), o.convertTools(tools))\n\tcfg := config.Get()\n\tif cfg.Debug {\n\t\tjsonData, _ := json.Marshal(params)\n\t\tlogging.Debug(\"Prepared messages\", \"messages\", string(jsonData))\n\t}\n\tattempts := 0\n\tfor {\n\t\tattempts++\n\t\topenaiResponse, err := o.client.Chat.Completions.New(\n\t\t\tctx,\n\t\t\tparams,\n\t\t)\n\t\t// If there is an error we are going to see if we can retry the call\n\t\tif err != nil {\n\t\t\tretry, after, retryErr := o.shouldRetry(attempts, err)\n\t\t\tif retryErr != nil {\n\t\t\t\treturn nil, retryErr\n\t\t\t}\n\t\t\tif retry {\n\t\t\t\tlogging.WarnPersist(fmt.Sprintf(\"Retrying due to rate limit... attempt %d of %d\", attempts, maxRetries), logging.PersistTimeArg, time.Millisecond*time.Duration(after+100))\n\t\t\t\tselect {\n\t\t\t\tcase <-ctx.Done():\n\t\t\t\t\treturn nil, ctx.Err()\n\t\t\t\tcase <-time.After(time.Duration(after) * time.Millisecond):\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn nil, retryErr\n\t\t}\n\n\t\tcontent := \"\"\n\t\tif openaiResponse.Choices[0].Message.Content != \"\" {\n\t\t\tcontent = openaiResponse.Choices[0].Message.Content\n\t\t}\n\n\t\ttoolCalls := o.toolCalls(*openaiResponse)\n\t\tfinishReason := o.finishReason(string(openaiResponse.Choices[0].FinishReason))\n\n\t\tif len(toolCalls) > 0 {\n\t\t\tfinishReason = message.FinishReasonToolUse\n\t\t}\n\n\t\treturn &ProviderResponse{\n\t\t\tContent: content,\n\t\t\tToolCalls: toolCalls,\n\t\t\tUsage: o.usage(*openaiResponse),\n\t\t\tFinishReason: finishReason,\n\t\t}, nil\n\t}\n}\n\nfunc (o *openaiClient) stream(ctx context.Context, messages []message.Message, tools []tools.BaseTool) <-chan ProviderEvent {\n\tparams := o.preparedParams(o.convertMessages(messages), o.convertTools(tools))\n\tparams.StreamOptions = openai.ChatCompletionStreamOptionsParam{\n\t\tIncludeUsage: openai.Bool(true),\n\t}\n\n\tcfg := config.Get()\n\tif cfg.Debug {\n\t\tjsonData, _ := json.Marshal(params)\n\t\tlogging.Debug(\"Prepared messages\", \"messages\", string(jsonData))\n\t}\n\n\tattempts := 0\n\teventChan := make(chan ProviderEvent)\n\n\tgo func() {\n\t\tfor {\n\t\t\tattempts++\n\t\t\topenaiStream := o.client.Chat.Completions.NewStreaming(\n\t\t\t\tctx,\n\t\t\t\tparams,\n\t\t\t)\n\n\t\t\tacc := openai.ChatCompletionAccumulator{}\n\t\t\tcurrentContent := \"\"\n\t\t\ttoolCalls := make([]message.ToolCall, 0)\n\n\t\t\tfor openaiStream.Next() {\n\t\t\t\tchunk := openaiStream.Current()\n\t\t\t\tacc.AddChunk(chunk)\n\n\t\t\t\tfor _, choice := range chunk.Choices {\n\t\t\t\t\tif choice.Delta.Content != \"\" {\n\t\t\t\t\t\teventChan <- ProviderEvent{\n\t\t\t\t\t\t\tType: EventContentDelta,\n\t\t\t\t\t\t\tContent: choice.Delta.Content,\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcurrentContent += choice.Delta.Content\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\terr := openaiStream.Err()\n\t\t\tif err == nil || errors.Is(err, io.EOF) {\n\t\t\t\t// Stream completed successfully\n\t\t\t\tfinishReason := o.finishReason(string(acc.ChatCompletion.Choices[0].FinishReason))\n\t\t\t\tif len(acc.ChatCompletion.Choices[0].Message.ToolCalls) > 0 {\n\t\t\t\t\ttoolCalls = append(toolCalls, o.toolCalls(acc.ChatCompletion)...)\n\t\t\t\t}\n\t\t\t\tif len(toolCalls) > 0 {\n\t\t\t\t\tfinishReason = message.FinishReasonToolUse\n\t\t\t\t}\n\n\t\t\t\teventChan <- ProviderEvent{\n\t\t\t\t\tType: EventComplete,\n\t\t\t\t\tResponse: &ProviderResponse{\n\t\t\t\t\t\tContent: currentContent,\n\t\t\t\t\t\tToolCalls: toolCalls,\n\t\t\t\t\t\tUsage: o.usage(acc.ChatCompletion),\n\t\t\t\t\t\tFinishReason: finishReason,\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t\tclose(eventChan)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\t// If there is an error we are going to see if we can retry the call\n\t\t\tretry, after, retryErr := o.shouldRetry(attempts, err)\n\t\t\tif retryErr != nil {\n\t\t\t\teventChan <- ProviderEvent{Type: EventError, Error: retryErr}\n\t\t\t\tclose(eventChan)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif retry {\n\t\t\t\tlogging.WarnPersist(fmt.Sprintf(\"Retrying due to rate limit... attempt %d of %d\", attempts, maxRetries), logging.PersistTimeArg, time.Millisecond*time.Duration(after+100))\n\t\t\t\tselect {\n\t\t\t\tcase <-ctx.Done():\n\t\t\t\t\t// context cancelled\n\t\t\t\t\tif ctx.Err() == nil {\n\t\t\t\t\t\teventChan <- ProviderEvent{Type: EventError, Error: ctx.Err()}\n\t\t\t\t\t}\n\t\t\t\t\tclose(eventChan)\n\t\t\t\t\treturn\n\t\t\t\tcase <-time.After(time.Duration(after) * time.Millisecond):\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t\teventChan <- ProviderEvent{Type: EventError, Error: retryErr}\n\t\t\tclose(eventChan)\n\t\t\treturn\n\t\t}\n\t}()\n\n\treturn eventChan\n}\n\nfunc (o *openaiClient) shouldRetry(attempts int, err error) (bool, int64, error) {\n\tvar apierr *openai.Error\n\tif !errors.As(err, &apierr) {\n\t\treturn false, 0, err\n\t}\n\n\tif apierr.StatusCode != 429 && apierr.StatusCode != 500 {\n\t\treturn false, 0, err\n\t}\n\n\tif attempts > maxRetries {\n\t\treturn false, 0, fmt.Errorf(\"maximum retry attempts reached for rate limit: %d retries\", maxRetries)\n\t}\n\n\tretryMs := 0\n\tretryAfterValues := apierr.Response.Header.Values(\"Retry-After\")\n\n\tbackoffMs := 2000 * (1 << (attempts - 1))\n\tjitterMs := int(float64(backoffMs) * 0.2)\n\tretryMs = backoffMs + jitterMs\n\tif len(retryAfterValues) > 0 {\n\t\tif _, err := fmt.Sscanf(retryAfterValues[0], \"%d\", &retryMs); err == nil {\n\t\t\tretryMs = retryMs * 1000\n\t\t}\n\t}\n\treturn true, int64(retryMs), nil\n}\n\nfunc (o *openaiClient) toolCalls(completion openai.ChatCompletion) []message.ToolCall {\n\tvar toolCalls []message.ToolCall\n\n\tif len(completion.Choices) > 0 && len(completion.Choices[0].Message.ToolCalls) > 0 {\n\t\tfor _, call := range completion.Choices[0].Message.ToolCalls {\n\t\t\ttoolCall := message.ToolCall{\n\t\t\t\tID: call.ID,\n\t\t\t\tName: call.Function.Name,\n\t\t\t\tInput: call.Function.Arguments,\n\t\t\t\tType: \"function\",\n\t\t\t\tFinished: true,\n\t\t\t}\n\t\t\ttoolCalls = append(toolCalls, toolCall)\n\t\t}\n\t}\n\n\treturn toolCalls\n}\n\nfunc (o *openaiClient) usage(completion openai.ChatCompletion) TokenUsage {\n\tcachedTokens := completion.Usage.PromptTokensDetails.CachedTokens\n\tinputTokens := completion.Usage.PromptTokens - cachedTokens\n\n\treturn TokenUsage{\n\t\tInputTokens: inputTokens,\n\t\tOutputTokens: completion.Usage.CompletionTokens,\n\t\tCacheCreationTokens: 0, // OpenAI doesn't provide this directly\n\t\tCacheReadTokens: cachedTokens,\n\t}\n}\n\nfunc WithOpenAIBaseURL(baseURL string) OpenAIOption {\n\treturn func(options *openaiOptions) {\n\t\toptions.baseURL = baseURL\n\t}\n}\n\nfunc WithOpenAIExtraHeaders(headers map[string]string) OpenAIOption {\n\treturn func(options *openaiOptions) {\n\t\toptions.extraHeaders = headers\n\t}\n}\n\nfunc WithOpenAIDisableCache() OpenAIOption {\n\treturn func(options *openaiOptions) {\n\t\toptions.disableCache = true\n\t}\n}\n\nfunc WithReasoningEffort(effort string) OpenAIOption {\n\treturn func(options *openaiOptions) {\n\t\tdefaultReasoningEffort := \"medium\"\n\t\tswitch effort {\n\t\tcase \"low\", \"medium\", \"high\":\n\t\t\tdefaultReasoningEffort = effort\n\t\tdefault:\n\t\t\tlogging.Warn(\"Invalid reasoning effort, using default: medium\")\n\t\t}\n\t\toptions.reasoningEffort = defaultReasoningEffort\n\t}\n}\n"], ["/opencode/internal/llm/agent/mcp-tools.go", "package agent\n\nimport (\n\t\"context\"\n\t\"encoding/json\"\n\t\"fmt\"\n\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/llm/tools\"\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n\t\"github.com/opencode-ai/opencode/internal/permission\"\n\t\"github.com/opencode-ai/opencode/internal/version\"\n\n\t\"github.com/mark3labs/mcp-go/client\"\n\t\"github.com/mark3labs/mcp-go/mcp\"\n)\n\ntype mcpTool struct {\n\tmcpName string\n\ttool mcp.Tool\n\tmcpConfig config.MCPServer\n\tpermissions permission.Service\n}\n\ntype MCPClient interface {\n\tInitialize(\n\t\tctx context.Context,\n\t\trequest mcp.InitializeRequest,\n\t) (*mcp.InitializeResult, error)\n\tListTools(ctx context.Context, request mcp.ListToolsRequest) (*mcp.ListToolsResult, error)\n\tCallTool(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error)\n\tClose() error\n}\n\nfunc (b *mcpTool) Info() tools.ToolInfo {\n\trequired := b.tool.InputSchema.Required\n\tif required == nil {\n\t\trequired = make([]string, 0)\n\t}\n\treturn tools.ToolInfo{\n\t\tName: fmt.Sprintf(\"%s_%s\", b.mcpName, b.tool.Name),\n\t\tDescription: b.tool.Description,\n\t\tParameters: b.tool.InputSchema.Properties,\n\t\tRequired: required,\n\t}\n}\n\nfunc runTool(ctx context.Context, c MCPClient, toolName string, input string) (tools.ToolResponse, error) {\n\tdefer c.Close()\n\tinitRequest := mcp.InitializeRequest{}\n\tinitRequest.Params.ProtocolVersion = mcp.LATEST_PROTOCOL_VERSION\n\tinitRequest.Params.ClientInfo = mcp.Implementation{\n\t\tName: \"OpenCode\",\n\t\tVersion: version.Version,\n\t}\n\n\t_, err := c.Initialize(ctx, initRequest)\n\tif err != nil {\n\t\treturn tools.NewTextErrorResponse(err.Error()), nil\n\t}\n\n\ttoolRequest := mcp.CallToolRequest{}\n\ttoolRequest.Params.Name = toolName\n\tvar args map[string]any\n\tif err = json.Unmarshal([]byte(input), &args); err != nil {\n\t\treturn tools.NewTextErrorResponse(fmt.Sprintf(\"error parsing parameters: %s\", err)), nil\n\t}\n\ttoolRequest.Params.Arguments = args\n\tresult, err := c.CallTool(ctx, toolRequest)\n\tif err != nil {\n\t\treturn tools.NewTextErrorResponse(err.Error()), nil\n\t}\n\n\toutput := \"\"\n\tfor _, v := range result.Content {\n\t\tif v, ok := v.(mcp.TextContent); ok {\n\t\t\toutput = v.Text\n\t\t} else {\n\t\t\toutput = fmt.Sprintf(\"%v\", v)\n\t\t}\n\t}\n\n\treturn tools.NewTextResponse(output), nil\n}\n\nfunc (b *mcpTool) Run(ctx context.Context, params tools.ToolCall) (tools.ToolResponse, error) {\n\tsessionID, messageID := tools.GetContextValues(ctx)\n\tif sessionID == \"\" || messageID == \"\" {\n\t\treturn tools.ToolResponse{}, fmt.Errorf(\"session ID and message ID are required for creating a new file\")\n\t}\n\tpermissionDescription := fmt.Sprintf(\"execute %s with the following parameters: %s\", b.Info().Name, params.Input)\n\tp := b.permissions.Request(\n\t\tpermission.CreatePermissionRequest{\n\t\t\tSessionID: sessionID,\n\t\t\tPath: config.WorkingDirectory(),\n\t\t\tToolName: b.Info().Name,\n\t\t\tAction: \"execute\",\n\t\t\tDescription: permissionDescription,\n\t\t\tParams: params.Input,\n\t\t},\n\t)\n\tif !p {\n\t\treturn tools.NewTextErrorResponse(\"permission denied\"), nil\n\t}\n\n\tswitch b.mcpConfig.Type {\n\tcase config.MCPStdio:\n\t\tc, err := client.NewStdioMCPClient(\n\t\t\tb.mcpConfig.Command,\n\t\t\tb.mcpConfig.Env,\n\t\t\tb.mcpConfig.Args...,\n\t\t)\n\t\tif err != nil {\n\t\t\treturn tools.NewTextErrorResponse(err.Error()), nil\n\t\t}\n\t\treturn runTool(ctx, c, b.tool.Name, params.Input)\n\tcase config.MCPSse:\n\t\tc, err := client.NewSSEMCPClient(\n\t\t\tb.mcpConfig.URL,\n\t\t\tclient.WithHeaders(b.mcpConfig.Headers),\n\t\t)\n\t\tif err != nil {\n\t\t\treturn tools.NewTextErrorResponse(err.Error()), nil\n\t\t}\n\t\treturn runTool(ctx, c, b.tool.Name, params.Input)\n\t}\n\n\treturn tools.NewTextErrorResponse(\"invalid mcp type\"), nil\n}\n\nfunc NewMcpTool(name string, tool mcp.Tool, permissions permission.Service, mcpConfig config.MCPServer) tools.BaseTool {\n\treturn &mcpTool{\n\t\tmcpName: name,\n\t\ttool: tool,\n\t\tmcpConfig: mcpConfig,\n\t\tpermissions: permissions,\n\t}\n}\n\nvar mcpTools []tools.BaseTool\n\nfunc getTools(ctx context.Context, name string, m config.MCPServer, permissions permission.Service, c MCPClient) []tools.BaseTool {\n\tvar stdioTools []tools.BaseTool\n\tinitRequest := mcp.InitializeRequest{}\n\tinitRequest.Params.ProtocolVersion = mcp.LATEST_PROTOCOL_VERSION\n\tinitRequest.Params.ClientInfo = mcp.Implementation{\n\t\tName: \"OpenCode\",\n\t\tVersion: version.Version,\n\t}\n\n\t_, err := c.Initialize(ctx, initRequest)\n\tif err != nil {\n\t\tlogging.Error(\"error initializing mcp client\", \"error\", err)\n\t\treturn stdioTools\n\t}\n\ttoolsRequest := mcp.ListToolsRequest{}\n\ttools, err := c.ListTools(ctx, toolsRequest)\n\tif err != nil {\n\t\tlogging.Error(\"error listing tools\", \"error\", err)\n\t\treturn stdioTools\n\t}\n\tfor _, t := range tools.Tools {\n\t\tstdioTools = append(stdioTools, NewMcpTool(name, t, permissions, m))\n\t}\n\tdefer c.Close()\n\treturn stdioTools\n}\n\nfunc GetMcpTools(ctx context.Context, permissions permission.Service) []tools.BaseTool {\n\tif len(mcpTools) > 0 {\n\t\treturn mcpTools\n\t}\n\tfor name, m := range config.Get().MCPServers {\n\t\tswitch m.Type {\n\t\tcase config.MCPStdio:\n\t\t\tc, err := client.NewStdioMCPClient(\n\t\t\t\tm.Command,\n\t\t\t\tm.Env,\n\t\t\t\tm.Args...,\n\t\t\t)\n\t\t\tif err != nil {\n\t\t\t\tlogging.Error(\"error creating mcp client\", \"error\", err)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tmcpTools = append(mcpTools, getTools(ctx, name, m, permissions, c)...)\n\t\tcase config.MCPSse:\n\t\t\tc, err := client.NewSSEMCPClient(\n\t\t\t\tm.URL,\n\t\t\t\tclient.WithHeaders(m.Headers),\n\t\t\t)\n\t\t\tif err != nil {\n\t\t\t\tlogging.Error(\"error creating mcp client\", \"error\", err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tmcpTools = append(mcpTools, getTools(ctx, name, m, permissions, c)...)\n\t\t}\n\t}\n\n\treturn mcpTools\n}\n"], ["/opencode/internal/lsp/transport.go", "package lsp\n\nimport (\n\t\"bufio\"\n\t\"context\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"strings\"\n\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n)\n\n// Write writes an LSP message to the given writer\nfunc WriteMessage(w io.Writer, msg *Message) error {\n\tdata, err := json.Marshal(msg)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to marshal message: %w\", err)\n\t}\n\tcnf := config.Get()\n\n\tif cnf.DebugLSP {\n\t\tlogging.Debug(\"Sending message to server\", \"method\", msg.Method, \"id\", msg.ID)\n\t}\n\n\t_, err = fmt.Fprintf(w, \"Content-Length: %d\\r\\n\\r\\n\", len(data))\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to write header: %w\", err)\n\t}\n\n\t_, err = w.Write(data)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to write message: %w\", err)\n\t}\n\n\treturn nil\n}\n\n// ReadMessage reads a single LSP message from the given reader\nfunc ReadMessage(r *bufio.Reader) (*Message, error) {\n\tcnf := config.Get()\n\t// Read headers\n\tvar contentLength int\n\tfor {\n\t\tline, err := r.ReadString('\\n')\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to read header: %w\", err)\n\t\t}\n\t\tline = strings.TrimSpace(line)\n\n\t\tif cnf.DebugLSP {\n\t\t\tlogging.Debug(\"Received header\", \"line\", line)\n\t\t}\n\n\t\tif line == \"\" {\n\t\t\tbreak // End of headers\n\t\t}\n\n\t\tif strings.HasPrefix(line, \"Content-Length: \") {\n\t\t\t_, err := fmt.Sscanf(line, \"Content-Length: %d\", &contentLength)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"invalid Content-Length: %w\", err)\n\t\t\t}\n\t\t}\n\t}\n\n\tif cnf.DebugLSP {\n\t\tlogging.Debug(\"Content-Length\", \"length\", contentLength)\n\t}\n\n\t// Read content\n\tcontent := make([]byte, contentLength)\n\t_, err := io.ReadFull(r, content)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to read content: %w\", err)\n\t}\n\n\tif cnf.DebugLSP {\n\t\tlogging.Debug(\"Received content\", \"content\", string(content))\n\t}\n\n\t// Parse message\n\tvar msg Message\n\tif err := json.Unmarshal(content, &msg); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to unmarshal message: %w\", err)\n\t}\n\n\treturn &msg, nil\n}\n\n// handleMessages reads and dispatches messages in a loop\nfunc (c *Client) handleMessages() {\n\tcnf := config.Get()\n\tfor {\n\t\tmsg, err := ReadMessage(c.stdout)\n\t\tif err != nil {\n\t\t\tif cnf.DebugLSP {\n\t\t\t\tlogging.Error(\"Error reading message\", \"error\", err)\n\t\t\t}\n\t\t\treturn\n\t\t}\n\n\t\t// Handle server->client request (has both Method and ID)\n\t\tif msg.Method != \"\" && msg.ID != 0 {\n\t\t\tif cnf.DebugLSP {\n\t\t\t\tlogging.Debug(\"Received request from server\", \"method\", msg.Method, \"id\", msg.ID)\n\t\t\t}\n\n\t\t\tresponse := &Message{\n\t\t\t\tJSONRPC: \"2.0\",\n\t\t\t\tID: msg.ID,\n\t\t\t}\n\n\t\t\t// Look up handler for this method\n\t\t\tc.serverHandlersMu.RLock()\n\t\t\thandler, ok := c.serverRequestHandlers[msg.Method]\n\t\t\tc.serverHandlersMu.RUnlock()\n\n\t\t\tif ok {\n\t\t\t\tresult, err := handler(msg.Params)\n\t\t\t\tif err != nil {\n\t\t\t\t\tresponse.Error = &ResponseError{\n\t\t\t\t\t\tCode: -32603,\n\t\t\t\t\t\tMessage: err.Error(),\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\trawJSON, err := json.Marshal(result)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tresponse.Error = &ResponseError{\n\t\t\t\t\t\t\tCode: -32603,\n\t\t\t\t\t\t\tMessage: fmt.Sprintf(\"failed to marshal response: %v\", err),\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tresponse.Result = rawJSON\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tresponse.Error = &ResponseError{\n\t\t\t\t\tCode: -32601,\n\t\t\t\t\tMessage: fmt.Sprintf(\"method not found: %s\", msg.Method),\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Send response back to server\n\t\t\tif err := WriteMessage(c.stdin, response); err != nil {\n\t\t\t\tlogging.Error(\"Error sending response to server\", \"error\", err)\n\t\t\t}\n\n\t\t\tcontinue\n\t\t}\n\n\t\t// Handle notification (has Method but no ID)\n\t\tif msg.Method != \"\" && msg.ID == 0 {\n\t\t\tc.notificationMu.RLock()\n\t\t\thandler, ok := c.notificationHandlers[msg.Method]\n\t\t\tc.notificationMu.RUnlock()\n\n\t\t\tif ok {\n\t\t\t\tif cnf.DebugLSP {\n\t\t\t\t\tlogging.Debug(\"Handling notification\", \"method\", msg.Method)\n\t\t\t\t}\n\t\t\t\tgo handler(msg.Params)\n\t\t\t} else if cnf.DebugLSP {\n\t\t\t\tlogging.Debug(\"No handler for notification\", \"method\", msg.Method)\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\t// Handle response to our request (has ID but no Method)\n\t\tif msg.ID != 0 && msg.Method == \"\" {\n\t\t\tc.handlersMu.RLock()\n\t\t\tch, ok := c.handlers[msg.ID]\n\t\t\tc.handlersMu.RUnlock()\n\n\t\t\tif ok {\n\t\t\t\tif cnf.DebugLSP {\n\t\t\t\t\tlogging.Debug(\"Received response for request\", \"id\", msg.ID)\n\t\t\t\t}\n\t\t\t\tch <- msg\n\t\t\t\tclose(ch)\n\t\t\t} else if cnf.DebugLSP {\n\t\t\t\tlogging.Debug(\"No handler for response\", \"id\", msg.ID)\n\t\t\t}\n\t\t}\n\t}\n}\n\n// Call makes a request and waits for the response\nfunc (c *Client) Call(ctx context.Context, method string, params any, result any) error {\n\tcnf := config.Get()\n\tid := c.nextID.Add(1)\n\n\tif cnf.DebugLSP {\n\t\tlogging.Debug(\"Making call\", \"method\", method, \"id\", id)\n\t}\n\n\tmsg, err := NewRequest(id, method, params)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to create request: %w\", err)\n\t}\n\n\t// Create response channel\n\tch := make(chan *Message, 1)\n\tc.handlersMu.Lock()\n\tc.handlers[id] = ch\n\tc.handlersMu.Unlock()\n\n\tdefer func() {\n\t\tc.handlersMu.Lock()\n\t\tdelete(c.handlers, id)\n\t\tc.handlersMu.Unlock()\n\t}()\n\n\t// Send request\n\tif err := WriteMessage(c.stdin, msg); err != nil {\n\t\treturn fmt.Errorf(\"failed to send request: %w\", err)\n\t}\n\n\tif cnf.DebugLSP {\n\t\tlogging.Debug(\"Request sent\", \"method\", method, \"id\", id)\n\t}\n\n\t// Wait for response\n\tresp := <-ch\n\n\tif cnf.DebugLSP {\n\t\tlogging.Debug(\"Received response\", \"id\", id)\n\t}\n\n\tif resp.Error != nil {\n\t\treturn fmt.Errorf(\"request failed: %s (code: %d)\", resp.Error.Message, resp.Error.Code)\n\t}\n\n\tif result != nil {\n\t\t// If result is a json.RawMessage, just copy the raw bytes\n\t\tif rawMsg, ok := result.(*json.RawMessage); ok {\n\t\t\t*rawMsg = resp.Result\n\t\t\treturn nil\n\t\t}\n\t\t// Otherwise unmarshal into the provided type\n\t\tif err := json.Unmarshal(resp.Result, result); err != nil {\n\t\t\treturn fmt.Errorf(\"failed to unmarshal result: %w\", err)\n\t\t}\n\t}\n\n\treturn nil\n}\n\n// Notify sends a notification (a request without an ID that doesn't expect a response)\nfunc (c *Client) Notify(ctx context.Context, method string, params any) error {\n\tcnf := config.Get()\n\tif cnf.DebugLSP {\n\t\tlogging.Debug(\"Sending notification\", \"method\", method)\n\t}\n\n\tmsg, err := NewNotification(method, params)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to create notification: %w\", err)\n\t}\n\n\tif err := WriteMessage(c.stdin, msg); err != nil {\n\t\treturn fmt.Errorf(\"failed to send notification: %w\", err)\n\t}\n\n\treturn nil\n}\n\ntype (\n\tNotificationHandler func(params json.RawMessage)\n\tServerRequestHandler func(params json.RawMessage) (any, error)\n)\n"], ["/opencode/internal/llm/prompt/coder.go", "package prompt\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"runtime\"\n\t\"time\"\n\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/llm/models\"\n\t\"github.com/opencode-ai/opencode/internal/llm/tools\"\n)\n\nfunc CoderPrompt(provider models.ModelProvider) string {\n\tbasePrompt := baseAnthropicCoderPrompt\n\tswitch provider {\n\tcase models.ProviderOpenAI:\n\t\tbasePrompt = baseOpenAICoderPrompt\n\t}\n\tenvInfo := getEnvironmentInfo()\n\n\treturn fmt.Sprintf(\"%s\\n\\n%s\\n%s\", basePrompt, envInfo, lspInformation())\n}\n\nconst baseOpenAICoderPrompt = `\nYou are operating as and within the OpenCode CLI, a terminal-based agentic coding assistant built by OpenAI. It wraps OpenAI models to enable natural language interaction with a local codebase. You are expected to be precise, safe, and helpful.\n\nYou can:\n- Receive user prompts, project context, and files.\n- Stream responses and emit function calls (e.g., shell commands, code edits).\n- Apply patches, run commands, and manage user approvals based on policy.\n- Work inside a sandboxed, git-backed workspace with rollback support.\n- Log telemetry so sessions can be replayed or inspected later.\n- More details on your functionality are available at \"opencode --help\"\n\n\nYou are an agent - please keep going until the user's query is completely resolved, before ending your turn and yielding back to the user. Only terminate your turn when you are sure that the problem is solved. If you are not sure about file content or codebase structure pertaining to the user's request, use your tools to read files and gather the relevant information: do NOT guess or make up an answer.\n\nPlease resolve the user's task by editing and testing the code files in your current code execution session. You are a deployed coding agent. Your session allows for you to modify and run code. The repo(s) are already cloned in your working directory, and you must fully solve the problem for your answer to be considered correct.\n\nYou MUST adhere to the following criteria when executing the task:\n- Working on the repo(s) in the current environment is allowed, even if they are proprietary.\n- Analyzing code for vulnerabilities is allowed.\n- Showing user code and tool call details is allowed.\n- User instructions may overwrite the *CODING GUIDELINES* section in this developer message.\n- If completing the user's task requires writing or modifying files:\n - Your code and final answer should follow these *CODING GUIDELINES*:\n - Fix the problem at the root cause rather than applying surface-level patches, when possible.\n - Avoid unneeded complexity in your solution.\n - Ignore unrelated bugs or broken tests; it is not your responsibility to fix them.\n - Update documentation as necessary.\n - Keep changes consistent with the style of the existing codebase. Changes should be minimal and focused on the task.\n - Use \"git log\" and \"git blame\" to search the history of the codebase if additional context is required; internet access is disabled.\n - NEVER add copyright or license headers unless specifically requested.\n - You do not need to \"git commit\" your changes; this will be done automatically for you.\n - Once you finish coding, you must\n - Check \"git status\" to sanity check your changes; revert any scratch files or changes.\n - Remove all inline comments you added as much as possible, even if they look normal. Check using \"git diff\". Inline comments must be generally avoided, unless active maintainers of the repo, after long careful study of the code and the issue, will still misinterpret the code without the comments.\n - Check if you accidentally add copyright or license headers. If so, remove them.\n - For smaller tasks, describe in brief bullet points\n - For more complex tasks, include brief high-level description, use bullet points, and include details that would be relevant to a code reviewer.\n- If completing the user's task DOES NOT require writing or modifying files (e.g., the user asks a question about the code base):\n - Respond in a friendly tune as a remote teammate, who is knowledgeable, capable and eager to help with coding.\n- When your task involves writing or modifying files:\n - Do NOT tell the user to \"save the file\" or \"copy the code into a file\" if you already created or modified the file using \"apply_patch\". Instead, reference the file as already saved.\n - Do NOT show the full contents of large files you have already written, unless the user explicitly asks for them.\n- When doing things with paths, always use use the full path, if the working directory is /abc/xyz and you want to edit the file abc.go in the working dir refer to it as /abc/xyz/abc.go.\n- If you send a path not including the working dir, the working dir will be prepended to it.\n- Remember the user does not see the full output of tools\n`\n\nconst baseAnthropicCoderPrompt = `You are OpenCode, an interactive CLI tool that helps users with software engineering tasks. Use the instructions below and the tools available to you to assist the user.\n\nIMPORTANT: Before you begin work, think about what the code you're editing is supposed to do based on the filenames directory structure.\n\n# Memory\nIf the current working directory contains a file called OpenCode.md, it will be automatically added to your context. This file serves multiple purposes:\n1. Storing frequently used bash commands (build, test, lint, etc.) so you can use them without searching each time\n2. Recording the user's code style preferences (naming conventions, preferred libraries, etc.)\n3. Maintaining useful information about the codebase structure and organization\n\nWhen you spend time searching for commands to typecheck, lint, build, or test, you should ask the user if it's okay to add those commands to OpenCode.md. Similarly, when learning about code style preferences or important codebase information, ask if it's okay to add that to OpenCode.md so you can remember it for next time.\n\n# Tone and style\nYou should be concise, direct, and to the point. When you run a non-trivial bash command, you should explain what the command does and why you are running it, to make sure the user understands what you are doing (this is especially important when you are running a command that will make changes to the user's system).\nRemember that your output will be displayed on a command line interface. Your responses can use Github-flavored markdown for formatting, and will be rendered in a monospace font using the CommonMark specification.\nOutput text to communicate with the user; all text you output outside of tool use is displayed to the user. Only use tools to complete tasks. Never use tools like Bash or code comments as means to communicate with the user during the session.\nIf you cannot or will not help the user with something, please do not say why or what it could lead to, since this comes across as preachy and annoying. Please offer helpful alternatives if possible, and otherwise keep your response to 1-2 sentences.\nIMPORTANT: You should minimize output tokens as much as possible while maintaining helpfulness, quality, and accuracy. Only address the specific query or task at hand, avoiding tangential information unless absolutely critical for completing the request. If you can answer in 1-3 sentences or a short paragraph, please do.\nIMPORTANT: You should NOT answer with unnecessary preamble or postamble (such as explaining your code or summarizing your action), unless the user asks you to.\nIMPORTANT: Keep your responses short, since they will be displayed on a command line interface. You MUST answer concisely with fewer than 4 lines (not including tool use or code generation), unless user asks for detail. Answer the user's question directly, without elaboration, explanation, or details. One word answers are best. Avoid introductions, conclusions, and explanations. You MUST avoid text before/after your response, such as \"The answer is .\", \"Here is the content of the file...\" or \"Based on the information provided, the answer is...\" or \"Here is what I will do next...\". Here are some examples to demonstrate appropriate verbosity:\n\nuser: 2 + 2\nassistant: 4\n\n\n\nuser: what is 2+2?\nassistant: 4\n\n\n\nuser: is 11 a prime number?\nassistant: true\n\n\n\nuser: what command should I run to list files in the current directory?\nassistant: ls\n\n\n\nuser: what command should I run to watch files in the current directory?\nassistant: [use the ls tool to list the files in the current directory, then read docs/commands in the relevant file to find out how to watch files]\nnpm run dev\n\n\n\nuser: How many golf balls fit inside a jetta?\nassistant: 150000\n\n\n\nuser: what files are in the directory src/?\nassistant: [runs ls and sees foo.c, bar.c, baz.c]\nuser: which file contains the implementation of foo?\nassistant: src/foo.c\n\n\n\nuser: write tests for new feature\nassistant: [uses grep and glob search tools to find where similar tests are defined, uses concurrent read file tool use blocks in one tool call to read relevant files at the same time, uses edit/patch file tool to write new tests]\n\n\n# Proactiveness\nYou are allowed to be proactive, but only when the user asks you to do something. You should strive to strike a balance between:\n1. Doing the right thing when asked, including taking actions and follow-up actions\n2. Not surprising the user with actions you take without asking\nFor example, if the user asks you how to approach something, you should do your best to answer their question first, and not immediately jump into taking actions.\n3. Do not add additional code explanation summary unless requested by the user. After working on a file, just stop, rather than providing an explanation of what you did.\n\n# Following conventions\nWhen making changes to files, first understand the file's code conventions. Mimic code style, use existing libraries and utilities, and follow existing patterns.\n- NEVER assume that a given library is available, even if it is well known. Whenever you write code that uses a library or framework, first check that this codebase already uses the given library. For example, you might look at neighboring files, or check the package.json (or cargo.toml, and so on depending on the language).\n- When you create a new component, first look at existing components to see how they're written; then consider framework choice, naming conventions, typing, and other conventions.\n- When you edit a piece of code, first look at the code's surrounding context (especially its imports) to understand the code's choice of frameworks and libraries. Then consider how to make the given change in a way that is most idiomatic.\n- Always follow security best practices. Never introduce code that exposes or logs secrets and keys. Never commit secrets or keys to the repository.\n\n# Code style\n- Do not add comments to the code you write, unless the user asks you to, or the code is complex and requires additional context.\n\n# Doing tasks\nThe user will primarily request you perform software engineering tasks. This includes solving bugs, adding new functionality, refactoring code, explaining code, and more. For these tasks the following steps are recommended:\n1. Use the available search tools to understand the codebase and the user's query. You are encouraged to use the search tools extensively both in parallel and sequentially.\n2. Implement the solution using all tools available to you\n3. Verify the solution if possible with tests. NEVER assume specific test framework or test script. Check the README or search codebase to determine the testing approach.\n4. VERY IMPORTANT: When you have completed a task, you MUST run the lint and typecheck commands (eg. npm run lint, npm run typecheck, ruff, etc.) if they were provided to you to ensure your code is correct. If you are unable to find the correct command, ask the user for the command to run and if they supply it, proactively suggest writing it to opencode.md so that you will know to run it next time.\n\nNEVER commit changes unless the user explicitly asks you to. It is VERY IMPORTANT to only commit when explicitly asked, otherwise the user will feel that you are being too proactive.\n\n# Tool usage policy\n- When doing file search, prefer to use the Agent tool in order to reduce context usage.\n- If you intend to call multiple tools and there are no dependencies between the calls, make all of the independent calls in the same function_calls block.\n- IMPORTANT: The user does not see the full output of the tool responses, so if you need the output of the tool for the response make sure to summarize it for the user.\n\nYou MUST answer concisely with fewer than 4 lines of text (not including tool use or code generation), unless user asks for detail.`\n\nfunc getEnvironmentInfo() string {\n\tcwd := config.WorkingDirectory()\n\tisGit := isGitRepo(cwd)\n\tplatform := runtime.GOOS\n\tdate := time.Now().Format(\"1/2/2006\")\n\tls := tools.NewLsTool()\n\tr, _ := ls.Run(context.Background(), tools.ToolCall{\n\t\tInput: `{\"path\":\".\"}`,\n\t})\n\treturn fmt.Sprintf(`Here is useful information about the environment you are running in:\n\nWorking directory: %s\nIs directory a git repo: %s\nPlatform: %s\nToday's date: %s\n\n\n%s\n\n\t\t`, cwd, boolToYesNo(isGit), platform, date, r.Content)\n}\n\nfunc isGitRepo(dir string) bool {\n\t_, err := os.Stat(filepath.Join(dir, \".git\"))\n\treturn err == nil\n}\n\nfunc lspInformation() string {\n\tcfg := config.Get()\n\thasLSP := false\n\tfor _, v := range cfg.LSP {\n\t\tif !v.Disabled {\n\t\t\thasLSP = true\n\t\t\tbreak\n\t\t}\n\t}\n\tif !hasLSP {\n\t\treturn \"\"\n\t}\n\treturn `# LSP Information\nTools that support it will also include useful diagnostics such as linting and typechecking.\n- These diagnostics will be automatically enabled when you run the tool, and will be displayed in the output at the bottom within the and tags.\n- Take necessary actions to fix the issues.\n- You should ignore diagnostics of files that you did not change or are not related or caused by your changes unless the user explicitly asks you to fix them.\n`\n}\n\nfunc boolToYesNo(b bool) string {\n\tif b {\n\t\treturn \"Yes\"\n\t}\n\treturn \"No\"\n}\n"], ["/opencode/internal/app/app.go", "package app\n\nimport (\n\t\"context\"\n\t\"database/sql\"\n\t\"errors\"\n\t\"fmt\"\n\t\"maps\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/db\"\n\t\"github.com/opencode-ai/opencode/internal/format\"\n\t\"github.com/opencode-ai/opencode/internal/history\"\n\t\"github.com/opencode-ai/opencode/internal/llm/agent\"\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n\t\"github.com/opencode-ai/opencode/internal/lsp\"\n\t\"github.com/opencode-ai/opencode/internal/message\"\n\t\"github.com/opencode-ai/opencode/internal/permission\"\n\t\"github.com/opencode-ai/opencode/internal/session\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n)\n\ntype App struct {\n\tSessions session.Service\n\tMessages message.Service\n\tHistory history.Service\n\tPermissions permission.Service\n\n\tCoderAgent agent.Service\n\n\tLSPClients map[string]*lsp.Client\n\n\tclientsMutex sync.RWMutex\n\n\twatcherCancelFuncs []context.CancelFunc\n\tcancelFuncsMutex sync.Mutex\n\twatcherWG sync.WaitGroup\n}\n\nfunc New(ctx context.Context, conn *sql.DB) (*App, error) {\n\tq := db.New(conn)\n\tsessions := session.NewService(q)\n\tmessages := message.NewService(q)\n\tfiles := history.NewService(q, conn)\n\n\tapp := &App{\n\t\tSessions: sessions,\n\t\tMessages: messages,\n\t\tHistory: files,\n\t\tPermissions: permission.NewPermissionService(),\n\t\tLSPClients: make(map[string]*lsp.Client),\n\t}\n\n\t// Initialize theme based on configuration\n\tapp.initTheme()\n\n\t// Initialize LSP clients in the background\n\tgo app.initLSPClients(ctx)\n\n\tvar err error\n\tapp.CoderAgent, err = agent.NewAgent(\n\t\tconfig.AgentCoder,\n\t\tapp.Sessions,\n\t\tapp.Messages,\n\t\tagent.CoderAgentTools(\n\t\t\tapp.Permissions,\n\t\t\tapp.Sessions,\n\t\t\tapp.Messages,\n\t\t\tapp.History,\n\t\t\tapp.LSPClients,\n\t\t),\n\t)\n\tif err != nil {\n\t\tlogging.Error(\"Failed to create coder agent\", err)\n\t\treturn nil, err\n\t}\n\n\treturn app, nil\n}\n\n// initTheme sets the application theme based on the configuration\nfunc (app *App) initTheme() {\n\tcfg := config.Get()\n\tif cfg == nil || cfg.TUI.Theme == \"\" {\n\t\treturn // Use default theme\n\t}\n\n\t// Try to set the theme from config\n\terr := theme.SetTheme(cfg.TUI.Theme)\n\tif err != nil {\n\t\tlogging.Warn(\"Failed to set theme from config, using default theme\", \"theme\", cfg.TUI.Theme, \"error\", err)\n\t} else {\n\t\tlogging.Debug(\"Set theme from config\", \"theme\", cfg.TUI.Theme)\n\t}\n}\n\n// RunNonInteractive handles the execution flow when a prompt is provided via CLI flag.\nfunc (a *App) RunNonInteractive(ctx context.Context, prompt string, outputFormat string, quiet bool) error {\n\tlogging.Info(\"Running in non-interactive mode\")\n\n\t// Start spinner if not in quiet mode\n\tvar spinner *format.Spinner\n\tif !quiet {\n\t\tspinner = format.NewSpinner(\"Thinking...\")\n\t\tspinner.Start()\n\t\tdefer spinner.Stop()\n\t}\n\n\tconst maxPromptLengthForTitle = 100\n\ttitlePrefix := \"Non-interactive: \"\n\tvar titleSuffix string\n\n\tif len(prompt) > maxPromptLengthForTitle {\n\t\ttitleSuffix = prompt[:maxPromptLengthForTitle] + \"...\"\n\t} else {\n\t\ttitleSuffix = prompt\n\t}\n\ttitle := titlePrefix + titleSuffix\n\n\tsess, err := a.Sessions.Create(ctx, title)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to create session for non-interactive mode: %w\", err)\n\t}\n\tlogging.Info(\"Created session for non-interactive run\", \"session_id\", sess.ID)\n\n\t// Automatically approve all permission requests for this non-interactive session\n\ta.Permissions.AutoApproveSession(sess.ID)\n\n\tdone, err := a.CoderAgent.Run(ctx, sess.ID, prompt)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to start agent processing stream: %w\", err)\n\t}\n\n\tresult := <-done\n\tif result.Error != nil {\n\t\tif errors.Is(result.Error, context.Canceled) || errors.Is(result.Error, agent.ErrRequestCancelled) {\n\t\t\tlogging.Info(\"Agent processing cancelled\", \"session_id\", sess.ID)\n\t\t\treturn nil\n\t\t}\n\t\treturn fmt.Errorf(\"agent processing failed: %w\", result.Error)\n\t}\n\n\t// Stop spinner before printing output\n\tif !quiet && spinner != nil {\n\t\tspinner.Stop()\n\t}\n\n\t// Get the text content from the response\n\tcontent := \"No content available\"\n\tif result.Message.Content().String() != \"\" {\n\t\tcontent = result.Message.Content().String()\n\t}\n\n\tfmt.Println(format.FormatOutput(content, outputFormat))\n\n\tlogging.Info(\"Non-interactive run completed\", \"session_id\", sess.ID)\n\n\treturn nil\n}\n\n// Shutdown performs a clean shutdown of the application\nfunc (app *App) Shutdown() {\n\t// Cancel all watcher goroutines\n\tapp.cancelFuncsMutex.Lock()\n\tfor _, cancel := range app.watcherCancelFuncs {\n\t\tcancel()\n\t}\n\tapp.cancelFuncsMutex.Unlock()\n\tapp.watcherWG.Wait()\n\n\t// Perform additional cleanup for LSP clients\n\tapp.clientsMutex.RLock()\n\tclients := make(map[string]*lsp.Client, len(app.LSPClients))\n\tmaps.Copy(clients, app.LSPClients)\n\tapp.clientsMutex.RUnlock()\n\n\tfor name, client := range clients {\n\t\tshutdownCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)\n\t\tif err := client.Shutdown(shutdownCtx); err != nil {\n\t\t\tlogging.Error(\"Failed to shutdown LSP client\", \"name\", name, \"error\", err)\n\t\t}\n\t\tcancel()\n\t}\n}\n"], ["/opencode/internal/tui/styles/background.go", "package styles\n\nimport (\n\t\"fmt\"\n\t\"regexp\"\n\t\"strings\"\n\n\t\"github.com/charmbracelet/lipgloss\"\n)\n\nvar ansiEscape = regexp.MustCompile(\"\\x1b\\\\[[0-9;]*m\")\n\nfunc getColorRGB(c lipgloss.TerminalColor) (uint8, uint8, uint8) {\n\tr, g, b, a := c.RGBA()\n\n\t// Un-premultiply alpha if needed\n\tif a > 0 && a < 0xffff {\n\t\tr = (r * 0xffff) / a\n\t\tg = (g * 0xffff) / a\n\t\tb = (b * 0xffff) / a\n\t}\n\n\t// Convert from 16-bit to 8-bit color\n\treturn uint8(r >> 8), uint8(g >> 8), uint8(b >> 8)\n}\n\n// ForceReplaceBackgroundWithLipgloss replaces any ANSI background color codes\n// in `input` with a single 24‑bit background (48;2;R;G;B).\nfunc ForceReplaceBackgroundWithLipgloss(input string, newBgColor lipgloss.TerminalColor) string {\n\t// Precompute our new-bg sequence once\n\tr, g, b := getColorRGB(newBgColor)\n\tnewBg := fmt.Sprintf(\"48;2;%d;%d;%d\", r, g, b)\n\n\treturn ansiEscape.ReplaceAllStringFunc(input, func(seq string) string {\n\t\tconst (\n\t\t\tescPrefixLen = 2 // \"\\x1b[\"\n\t\t\tescSuffixLen = 1 // \"m\"\n\t\t)\n\n\t\traw := seq\n\t\tstart := escPrefixLen\n\t\tend := len(raw) - escSuffixLen\n\n\t\tvar sb strings.Builder\n\t\t// reserve enough space: original content minus bg codes + our newBg\n\t\tsb.Grow((end - start) + len(newBg) + 2)\n\n\t\t// scan from start..end, token by token\n\t\tfor i := start; i < end; {\n\t\t\t// find the next ';' or end\n\t\t\tj := i\n\t\t\tfor j < end && raw[j] != ';' {\n\t\t\t\tj++\n\t\t\t}\n\t\t\ttoken := raw[i:j]\n\n\t\t\t// fast‑path: skip \"48;5;N\" or \"48;2;R;G;B\"\n\t\t\tif len(token) == 2 && token[0] == '4' && token[1] == '8' {\n\t\t\t\tk := j + 1\n\t\t\t\tif k < end {\n\t\t\t\t\t// find next token\n\t\t\t\t\tl := k\n\t\t\t\t\tfor l < end && raw[l] != ';' {\n\t\t\t\t\t\tl++\n\t\t\t\t\t}\n\t\t\t\t\tnext := raw[k:l]\n\t\t\t\t\tif next == \"5\" {\n\t\t\t\t\t\t// skip \"48;5;N\"\n\t\t\t\t\t\tm := l + 1\n\t\t\t\t\t\tfor m < end && raw[m] != ';' {\n\t\t\t\t\t\t\tm++\n\t\t\t\t\t\t}\n\t\t\t\t\t\ti = m + 1\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t} else if next == \"2\" {\n\t\t\t\t\t\t// skip \"48;2;R;G;B\"\n\t\t\t\t\t\tm := l + 1\n\t\t\t\t\t\tfor count := 0; count < 3 && m < end; count++ {\n\t\t\t\t\t\t\tfor m < end && raw[m] != ';' {\n\t\t\t\t\t\t\t\tm++\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tm++\n\t\t\t\t\t\t}\n\t\t\t\t\t\ti = m\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// decide whether to keep this token\n\t\t\t// manually parse ASCII digits to int\n\t\t\tisNum := true\n\t\t\tval := 0\n\t\t\tfor p := i; p < j; p++ {\n\t\t\t\tc := raw[p]\n\t\t\t\tif c < '0' || c > '9' {\n\t\t\t\t\tisNum = false\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tval = val*10 + int(c-'0')\n\t\t\t}\n\t\t\tkeep := !isNum ||\n\t\t\t\t((val < 40 || val > 47) && (val < 100 || val > 107) && val != 49)\n\n\t\t\tif keep {\n\t\t\t\tif sb.Len() > 0 {\n\t\t\t\t\tsb.WriteByte(';')\n\t\t\t\t}\n\t\t\t\tsb.WriteString(token)\n\t\t\t}\n\t\t\t// advance past this token (and the semicolon)\n\t\t\ti = j + 1\n\t\t}\n\n\t\t// append our new background\n\t\tif sb.Len() > 0 {\n\t\t\tsb.WriteByte(';')\n\t\t}\n\t\tsb.WriteString(newBg)\n\n\t\treturn \"\\x1b[\" + sb.String() + \"m\"\n\t})\n}\n"], ["/opencode/internal/llm/provider/provider.go", "package provider\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"os\"\n\n\t\"github.com/opencode-ai/opencode/internal/llm/models\"\n\t\"github.com/opencode-ai/opencode/internal/llm/tools\"\n\t\"github.com/opencode-ai/opencode/internal/message\"\n)\n\ntype EventType string\n\nconst maxRetries = 8\n\nconst (\n\tEventContentStart EventType = \"content_start\"\n\tEventToolUseStart EventType = \"tool_use_start\"\n\tEventToolUseDelta EventType = \"tool_use_delta\"\n\tEventToolUseStop EventType = \"tool_use_stop\"\n\tEventContentDelta EventType = \"content_delta\"\n\tEventThinkingDelta EventType = \"thinking_delta\"\n\tEventContentStop EventType = \"content_stop\"\n\tEventComplete EventType = \"complete\"\n\tEventError EventType = \"error\"\n\tEventWarning EventType = \"warning\"\n)\n\ntype TokenUsage struct {\n\tInputTokens int64\n\tOutputTokens int64\n\tCacheCreationTokens int64\n\tCacheReadTokens int64\n}\n\ntype ProviderResponse struct {\n\tContent string\n\tToolCalls []message.ToolCall\n\tUsage TokenUsage\n\tFinishReason message.FinishReason\n}\n\ntype ProviderEvent struct {\n\tType EventType\n\n\tContent string\n\tThinking string\n\tResponse *ProviderResponse\n\tToolCall *message.ToolCall\n\tError error\n}\ntype Provider interface {\n\tSendMessages(ctx context.Context, messages []message.Message, tools []tools.BaseTool) (*ProviderResponse, error)\n\n\tStreamResponse(ctx context.Context, messages []message.Message, tools []tools.BaseTool) <-chan ProviderEvent\n\n\tModel() models.Model\n}\n\ntype providerClientOptions struct {\n\tapiKey string\n\tmodel models.Model\n\tmaxTokens int64\n\tsystemMessage string\n\n\tanthropicOptions []AnthropicOption\n\topenaiOptions []OpenAIOption\n\tgeminiOptions []GeminiOption\n\tbedrockOptions []BedrockOption\n\tcopilotOptions []CopilotOption\n}\n\ntype ProviderClientOption func(*providerClientOptions)\n\ntype ProviderClient interface {\n\tsend(ctx context.Context, messages []message.Message, tools []tools.BaseTool) (*ProviderResponse, error)\n\tstream(ctx context.Context, messages []message.Message, tools []tools.BaseTool) <-chan ProviderEvent\n}\n\ntype baseProvider[C ProviderClient] struct {\n\toptions providerClientOptions\n\tclient C\n}\n\nfunc NewProvider(providerName models.ModelProvider, opts ...ProviderClientOption) (Provider, error) {\n\tclientOptions := providerClientOptions{}\n\tfor _, o := range opts {\n\t\to(&clientOptions)\n\t}\n\tswitch providerName {\n\tcase models.ProviderCopilot:\n\t\treturn &baseProvider[CopilotClient]{\n\t\t\toptions: clientOptions,\n\t\t\tclient: newCopilotClient(clientOptions),\n\t\t}, nil\n\tcase models.ProviderAnthropic:\n\t\treturn &baseProvider[AnthropicClient]{\n\t\t\toptions: clientOptions,\n\t\t\tclient: newAnthropicClient(clientOptions),\n\t\t}, nil\n\tcase models.ProviderOpenAI:\n\t\treturn &baseProvider[OpenAIClient]{\n\t\t\toptions: clientOptions,\n\t\t\tclient: newOpenAIClient(clientOptions),\n\t\t}, nil\n\tcase models.ProviderGemini:\n\t\treturn &baseProvider[GeminiClient]{\n\t\t\toptions: clientOptions,\n\t\t\tclient: newGeminiClient(clientOptions),\n\t\t}, nil\n\tcase models.ProviderBedrock:\n\t\treturn &baseProvider[BedrockClient]{\n\t\t\toptions: clientOptions,\n\t\t\tclient: newBedrockClient(clientOptions),\n\t\t}, nil\n\tcase models.ProviderGROQ:\n\t\tclientOptions.openaiOptions = append(clientOptions.openaiOptions,\n\t\t\tWithOpenAIBaseURL(\"https://api.groq.com/openai/v1\"),\n\t\t)\n\t\treturn &baseProvider[OpenAIClient]{\n\t\t\toptions: clientOptions,\n\t\t\tclient: newOpenAIClient(clientOptions),\n\t\t}, nil\n\tcase models.ProviderAzure:\n\t\treturn &baseProvider[AzureClient]{\n\t\t\toptions: clientOptions,\n\t\t\tclient: newAzureClient(clientOptions),\n\t\t}, nil\n\tcase models.ProviderVertexAI:\n\t\treturn &baseProvider[VertexAIClient]{\n\t\t\toptions: clientOptions,\n\t\t\tclient: newVertexAIClient(clientOptions),\n\t\t}, nil\n\tcase models.ProviderOpenRouter:\n\t\tclientOptions.openaiOptions = append(clientOptions.openaiOptions,\n\t\t\tWithOpenAIBaseURL(\"https://openrouter.ai/api/v1\"),\n\t\t\tWithOpenAIExtraHeaders(map[string]string{\n\t\t\t\t\"HTTP-Referer\": \"opencode.ai\",\n\t\t\t\t\"X-Title\": \"OpenCode\",\n\t\t\t}),\n\t\t)\n\t\treturn &baseProvider[OpenAIClient]{\n\t\t\toptions: clientOptions,\n\t\t\tclient: newOpenAIClient(clientOptions),\n\t\t}, nil\n\tcase models.ProviderXAI:\n\t\tclientOptions.openaiOptions = append(clientOptions.openaiOptions,\n\t\t\tWithOpenAIBaseURL(\"https://api.x.ai/v1\"),\n\t\t)\n\t\treturn &baseProvider[OpenAIClient]{\n\t\t\toptions: clientOptions,\n\t\t\tclient: newOpenAIClient(clientOptions),\n\t\t}, nil\n\tcase models.ProviderLocal:\n\t\tclientOptions.openaiOptions = append(clientOptions.openaiOptions,\n\t\t\tWithOpenAIBaseURL(os.Getenv(\"LOCAL_ENDPOINT\")),\n\t\t)\n\t\treturn &baseProvider[OpenAIClient]{\n\t\t\toptions: clientOptions,\n\t\t\tclient: newOpenAIClient(clientOptions),\n\t\t}, nil\n\tcase models.ProviderMock:\n\t\t// TODO: implement mock client for test\n\t\tpanic(\"not implemented\")\n\t}\n\treturn nil, fmt.Errorf(\"provider not supported: %s\", providerName)\n}\n\nfunc (p *baseProvider[C]) cleanMessages(messages []message.Message) (cleaned []message.Message) {\n\tfor _, msg := range messages {\n\t\t// The message has no content\n\t\tif len(msg.Parts) == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tcleaned = append(cleaned, msg)\n\t}\n\treturn\n}\n\nfunc (p *baseProvider[C]) SendMessages(ctx context.Context, messages []message.Message, tools []tools.BaseTool) (*ProviderResponse, error) {\n\tmessages = p.cleanMessages(messages)\n\treturn p.client.send(ctx, messages, tools)\n}\n\nfunc (p *baseProvider[C]) Model() models.Model {\n\treturn p.options.model\n}\n\nfunc (p *baseProvider[C]) StreamResponse(ctx context.Context, messages []message.Message, tools []tools.BaseTool) <-chan ProviderEvent {\n\tmessages = p.cleanMessages(messages)\n\treturn p.client.stream(ctx, messages, tools)\n}\n\nfunc WithAPIKey(apiKey string) ProviderClientOption {\n\treturn func(options *providerClientOptions) {\n\t\toptions.apiKey = apiKey\n\t}\n}\n\nfunc WithModel(model models.Model) ProviderClientOption {\n\treturn func(options *providerClientOptions) {\n\t\toptions.model = model\n\t}\n}\n\nfunc WithMaxTokens(maxTokens int64) ProviderClientOption {\n\treturn func(options *providerClientOptions) {\n\t\toptions.maxTokens = maxTokens\n\t}\n}\n\nfunc WithSystemMessage(systemMessage string) ProviderClientOption {\n\treturn func(options *providerClientOptions) {\n\t\toptions.systemMessage = systemMessage\n\t}\n}\n\nfunc WithAnthropicOptions(anthropicOptions ...AnthropicOption) ProviderClientOption {\n\treturn func(options *providerClientOptions) {\n\t\toptions.anthropicOptions = anthropicOptions\n\t}\n}\n\nfunc WithOpenAIOptions(openaiOptions ...OpenAIOption) ProviderClientOption {\n\treturn func(options *providerClientOptions) {\n\t\toptions.openaiOptions = openaiOptions\n\t}\n}\n\nfunc WithGeminiOptions(geminiOptions ...GeminiOption) ProviderClientOption {\n\treturn func(options *providerClientOptions) {\n\t\toptions.geminiOptions = geminiOptions\n\t}\n}\n\nfunc WithBedrockOptions(bedrockOptions ...BedrockOption) ProviderClientOption {\n\treturn func(options *providerClientOptions) {\n\t\toptions.bedrockOptions = bedrockOptions\n\t}\n}\n\nfunc WithCopilotOptions(copilotOptions ...CopilotOption) ProviderClientOption {\n\treturn func(options *providerClientOptions) {\n\t\toptions.copilotOptions = copilotOptions\n\t}\n}\n"], ["/opencode/internal/lsp/protocol/tsprotocol.go", "// Copyright 2023 The Go Authors. All rights reserved.\n// Use of this source code is governed by a BSD-style\n// license that can be found in the LICENSE file.\n\n// Code generated for LSP. DO NOT EDIT.\n\npackage protocol\n\n// Code generated from protocol/metaModel.json at ref release/protocol/3.17.6-next.9 (hash c94395b5da53729e6dff931293b051009ccaaaa4).\n// https://github.com/microsoft/vscode-languageserver-node/blob/release/protocol/3.17.6-next.9/protocol/metaModel.json\n// LSP metaData.version = 3.17.0.\n\nimport \"encoding/json\"\n\n// created for And\ntype And_RegOpt_textDocument_colorPresentation struct {\n\tWorkDoneProgressOptions\n\tTextDocumentRegistrationOptions\n}\n\n// A special text edit with an additional change annotation.\n//\n// @since 3.16.0.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#annotatedTextEdit\ntype AnnotatedTextEdit struct {\n\t// The actual identifier of the change annotation\n\tAnnotationID *ChangeAnnotationIdentifier `json:\"annotationId,omitempty\"`\n\tTextEdit\n}\n\n// The parameters passed via an apply workspace edit request.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#applyWorkspaceEditParams\ntype ApplyWorkspaceEditParams struct {\n\t// An optional label of the workspace edit. This label is\n\t// presented in the user interface for example on an undo\n\t// stack to undo the workspace edit.\n\tLabel string `json:\"label,omitempty\"`\n\t// The edits to apply.\n\tEdit WorkspaceEdit `json:\"edit\"`\n\t// Additional data about the edit.\n\t//\n\t// @since 3.18.0\n\t// @proposed\n\tMetadata *WorkspaceEditMetadata `json:\"metadata,omitempty\"`\n}\n\n// The result returned from the apply workspace edit request.\n//\n// @since 3.17 renamed from ApplyWorkspaceEditResponse\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#applyWorkspaceEditResult\ntype ApplyWorkspaceEditResult struct {\n\t// Indicates whether the edit was applied or not.\n\tApplied bool `json:\"applied\"`\n\t// An optional textual description for why the edit was not applied.\n\t// This may be used by the server for diagnostic logging or to provide\n\t// a suitable error for a request that triggered the edit.\n\tFailureReason string `json:\"failureReason,omitempty\"`\n\t// Depending on the client's failure handling strategy `failedChange` might\n\t// contain the index of the change that failed. This property is only available\n\t// if the client signals a `failureHandlingStrategy` in its client capabilities.\n\tFailedChange uint32 `json:\"failedChange,omitempty\"`\n}\n\n// A base for all symbol information.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#baseSymbolInformation\ntype BaseSymbolInformation struct {\n\t// The name of this symbol.\n\tName string `json:\"name\"`\n\t// The kind of this symbol.\n\tKind SymbolKind `json:\"kind\"`\n\t// Tags for this symbol.\n\t//\n\t// @since 3.16.0\n\tTags []SymbolTag `json:\"tags,omitempty\"`\n\t// The name of the symbol containing this symbol. This information is for\n\t// user interface purposes (e.g. to render a qualifier in the user interface\n\t// if necessary). It can't be used to re-infer a hierarchy for the document\n\t// symbols.\n\tContainerName string `json:\"containerName,omitempty\"`\n}\n\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#callHierarchyClientCapabilities\ntype CallHierarchyClientCapabilities struct {\n\t// Whether implementation supports dynamic registration. If this is set to `true`\n\t// the client supports the new `(TextDocumentRegistrationOptions & StaticRegistrationOptions)`\n\t// return value for the corresponding server capability as well.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n}\n\n// Represents an incoming call, e.g. a caller of a method or constructor.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#callHierarchyIncomingCall\ntype CallHierarchyIncomingCall struct {\n\t// The item that makes the call.\n\tFrom CallHierarchyItem `json:\"from\"`\n\t// The ranges at which the calls appear. This is relative to the caller\n\t// denoted by {@link CallHierarchyIncomingCall.from `this.from`}.\n\tFromRanges []Range `json:\"fromRanges\"`\n}\n\n// The parameter of a `callHierarchy/incomingCalls` request.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#callHierarchyIncomingCallsParams\ntype CallHierarchyIncomingCallsParams struct {\n\tItem CallHierarchyItem `json:\"item\"`\n\tWorkDoneProgressParams\n\tPartialResultParams\n}\n\n// Represents programming constructs like functions or constructors in the context\n// of call hierarchy.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#callHierarchyItem\ntype CallHierarchyItem struct {\n\t// The name of this item.\n\tName string `json:\"name\"`\n\t// The kind of this item.\n\tKind SymbolKind `json:\"kind\"`\n\t// Tags for this item.\n\tTags []SymbolTag `json:\"tags,omitempty\"`\n\t// More detail for this item, e.g. the signature of a function.\n\tDetail string `json:\"detail,omitempty\"`\n\t// The resource identifier of this item.\n\tURI DocumentUri `json:\"uri\"`\n\t// The range enclosing this symbol not including leading/trailing whitespace but everything else, e.g. comments and code.\n\tRange Range `json:\"range\"`\n\t// The range that should be selected and revealed when this symbol is being picked, e.g. the name of a function.\n\t// Must be contained by the {@link CallHierarchyItem.range `range`}.\n\tSelectionRange Range `json:\"selectionRange\"`\n\t// A data entry field that is preserved between a call hierarchy prepare and\n\t// incoming calls or outgoing calls requests.\n\tData interface{} `json:\"data,omitempty\"`\n}\n\n// Call hierarchy options used during static registration.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#callHierarchyOptions\ntype CallHierarchyOptions struct {\n\tWorkDoneProgressOptions\n}\n\n// Represents an outgoing call, e.g. calling a getter from a method or a method from a constructor etc.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#callHierarchyOutgoingCall\ntype CallHierarchyOutgoingCall struct {\n\t// The item that is called.\n\tTo CallHierarchyItem `json:\"to\"`\n\t// The range at which this item is called. This is the range relative to the caller, e.g the item\n\t// passed to {@link CallHierarchyItemProvider.provideCallHierarchyOutgoingCalls `provideCallHierarchyOutgoingCalls`}\n\t// and not {@link CallHierarchyOutgoingCall.to `this.to`}.\n\tFromRanges []Range `json:\"fromRanges\"`\n}\n\n// The parameter of a `callHierarchy/outgoingCalls` request.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#callHierarchyOutgoingCallsParams\ntype CallHierarchyOutgoingCallsParams struct {\n\tItem CallHierarchyItem `json:\"item\"`\n\tWorkDoneProgressParams\n\tPartialResultParams\n}\n\n// The parameter of a `textDocument/prepareCallHierarchy` request.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#callHierarchyPrepareParams\ntype CallHierarchyPrepareParams struct {\n\tTextDocumentPositionParams\n\tWorkDoneProgressParams\n}\n\n// Call hierarchy options used during static or dynamic registration.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#callHierarchyRegistrationOptions\ntype CallHierarchyRegistrationOptions struct {\n\tTextDocumentRegistrationOptions\n\tCallHierarchyOptions\n\tStaticRegistrationOptions\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#cancelParams\ntype CancelParams struct {\n\t// The request id to cancel.\n\tID interface{} `json:\"id\"`\n}\n\n// Additional information that describes document changes.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#changeAnnotation\ntype ChangeAnnotation struct {\n\t// A human-readable string describing the actual change. The string\n\t// is rendered prominent in the user interface.\n\tLabel string `json:\"label\"`\n\t// A flag which indicates that user confirmation is needed\n\t// before applying the change.\n\tNeedsConfirmation bool `json:\"needsConfirmation,omitempty\"`\n\t// A human-readable string which is rendered less prominent in\n\t// the user interface.\n\tDescription string `json:\"description,omitempty\"`\n}\n\n// An identifier to refer to a change annotation stored with a workspace edit.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#changeAnnotationIdentifier\ntype ChangeAnnotationIdentifier = string // (alias)\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#changeAnnotationsSupportOptions\ntype ChangeAnnotationsSupportOptions struct {\n\t// Whether the client groups edits with equal labels into tree nodes,\n\t// for instance all edits labelled with \"Changes in Strings\" would\n\t// be a tree node.\n\tGroupsOnLabel bool `json:\"groupsOnLabel,omitempty\"`\n}\n\n// Defines the capabilities provided by the client.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#clientCapabilities\ntype ClientCapabilities struct {\n\t// Workspace specific client capabilities.\n\tWorkspace WorkspaceClientCapabilities `json:\"workspace,omitempty\"`\n\t// Text document specific client capabilities.\n\tTextDocument TextDocumentClientCapabilities `json:\"textDocument,omitempty\"`\n\t// Capabilities specific to the notebook document support.\n\t//\n\t// @since 3.17.0\n\tNotebookDocument *NotebookDocumentClientCapabilities `json:\"notebookDocument,omitempty\"`\n\t// Window specific client capabilities.\n\tWindow WindowClientCapabilities `json:\"window,omitempty\"`\n\t// General client capabilities.\n\t//\n\t// @since 3.16.0\n\tGeneral *GeneralClientCapabilities `json:\"general,omitempty\"`\n\t// Experimental client capabilities.\n\tExperimental interface{} `json:\"experimental,omitempty\"`\n}\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#clientCodeActionKindOptions\ntype ClientCodeActionKindOptions struct {\n\t// The code action kind values the client supports. When this\n\t// property exists the client also guarantees that it will\n\t// handle values outside its set gracefully and falls back\n\t// to a default value when unknown.\n\tValueSet []CodeActionKind `json:\"valueSet\"`\n}\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#clientCodeActionLiteralOptions\ntype ClientCodeActionLiteralOptions struct {\n\t// The code action kind is support with the following value\n\t// set.\n\tCodeActionKind ClientCodeActionKindOptions `json:\"codeActionKind\"`\n}\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#clientCodeActionResolveOptions\ntype ClientCodeActionResolveOptions struct {\n\t// The properties that a client can resolve lazily.\n\tProperties []string `json:\"properties\"`\n}\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#clientCodeLensResolveOptions\ntype ClientCodeLensResolveOptions struct {\n\t// The properties that a client can resolve lazily.\n\tProperties []string `json:\"properties\"`\n}\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#clientCompletionItemInsertTextModeOptions\ntype ClientCompletionItemInsertTextModeOptions struct {\n\tValueSet []InsertTextMode `json:\"valueSet\"`\n}\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#clientCompletionItemOptions\ntype ClientCompletionItemOptions struct {\n\t// Client supports snippets as insert text.\n\t//\n\t// A snippet can define tab stops and placeholders with `$1`, `$2`\n\t// and `${3:foo}`. `$0` defines the final tab stop, it defaults to\n\t// the end of the snippet. Placeholders with equal identifiers are linked,\n\t// that is typing in one will update others too.\n\tSnippetSupport bool `json:\"snippetSupport,omitempty\"`\n\t// Client supports commit characters on a completion item.\n\tCommitCharactersSupport bool `json:\"commitCharactersSupport,omitempty\"`\n\t// Client supports the following content formats for the documentation\n\t// property. The order describes the preferred format of the client.\n\tDocumentationFormat []MarkupKind `json:\"documentationFormat,omitempty\"`\n\t// Client supports the deprecated property on a completion item.\n\tDeprecatedSupport bool `json:\"deprecatedSupport,omitempty\"`\n\t// Client supports the preselect property on a completion item.\n\tPreselectSupport bool `json:\"preselectSupport,omitempty\"`\n\t// Client supports the tag property on a completion item. Clients supporting\n\t// tags have to handle unknown tags gracefully. Clients especially need to\n\t// preserve unknown tags when sending a completion item back to the server in\n\t// a resolve call.\n\t//\n\t// @since 3.15.0\n\tTagSupport *CompletionItemTagOptions `json:\"tagSupport,omitempty\"`\n\t// Client support insert replace edit to control different behavior if a\n\t// completion item is inserted in the text or should replace text.\n\t//\n\t// @since 3.16.0\n\tInsertReplaceSupport bool `json:\"insertReplaceSupport,omitempty\"`\n\t// Indicates which properties a client can resolve lazily on a completion\n\t// item. Before version 3.16.0 only the predefined properties `documentation`\n\t// and `details` could be resolved lazily.\n\t//\n\t// @since 3.16.0\n\tResolveSupport *ClientCompletionItemResolveOptions `json:\"resolveSupport,omitempty\"`\n\t// The client supports the `insertTextMode` property on\n\t// a completion item to override the whitespace handling mode\n\t// as defined by the client (see `insertTextMode`).\n\t//\n\t// @since 3.16.0\n\tInsertTextModeSupport *ClientCompletionItemInsertTextModeOptions `json:\"insertTextModeSupport,omitempty\"`\n\t// The client has support for completion item label\n\t// details (see also `CompletionItemLabelDetails`).\n\t//\n\t// @since 3.17.0\n\tLabelDetailsSupport bool `json:\"labelDetailsSupport,omitempty\"`\n}\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#clientCompletionItemOptionsKind\ntype ClientCompletionItemOptionsKind struct {\n\t// The completion item kind values the client supports. When this\n\t// property exists the client also guarantees that it will\n\t// handle values outside its set gracefully and falls back\n\t// to a default value when unknown.\n\t//\n\t// If this property is not present the client only supports\n\t// the completion items kinds from `Text` to `Reference` as defined in\n\t// the initial version of the protocol.\n\tValueSet []CompletionItemKind `json:\"valueSet,omitempty\"`\n}\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#clientCompletionItemResolveOptions\ntype ClientCompletionItemResolveOptions struct {\n\t// The properties that a client can resolve lazily.\n\tProperties []string `json:\"properties\"`\n}\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#clientDiagnosticsTagOptions\ntype ClientDiagnosticsTagOptions struct {\n\t// The tags supported by the client.\n\tValueSet []DiagnosticTag `json:\"valueSet\"`\n}\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#clientFoldingRangeKindOptions\ntype ClientFoldingRangeKindOptions struct {\n\t// The folding range kind values the client supports. When this\n\t// property exists the client also guarantees that it will\n\t// handle values outside its set gracefully and falls back\n\t// to a default value when unknown.\n\tValueSet []FoldingRangeKind `json:\"valueSet,omitempty\"`\n}\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#clientFoldingRangeOptions\ntype ClientFoldingRangeOptions struct {\n\t// If set, the client signals that it supports setting collapsedText on\n\t// folding ranges to display custom labels instead of the default text.\n\t//\n\t// @since 3.17.0\n\tCollapsedText bool `json:\"collapsedText,omitempty\"`\n}\n\n// Information about the client\n//\n// @since 3.15.0\n// @since 3.18.0 ClientInfo type name added.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#clientInfo\ntype ClientInfo struct {\n\t// The name of the client as defined by the client.\n\tName string `json:\"name\"`\n\t// The client's version as defined by the client.\n\tVersion string `json:\"version,omitempty\"`\n}\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#clientInlayHintResolveOptions\ntype ClientInlayHintResolveOptions struct {\n\t// The properties that a client can resolve lazily.\n\tProperties []string `json:\"properties\"`\n}\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#clientSemanticTokensRequestFullDelta\ntype ClientSemanticTokensRequestFullDelta struct {\n\t// The client will send the `textDocument/semanticTokens/full/delta` request if\n\t// the server provides a corresponding handler.\n\tDelta bool `json:\"delta,omitempty\"`\n}\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#clientSemanticTokensRequestOptions\ntype ClientSemanticTokensRequestOptions struct {\n\t// The client will send the `textDocument/semanticTokens/range` request if\n\t// the server provides a corresponding handler.\n\tRange *Or_ClientSemanticTokensRequestOptions_range `json:\"range,omitempty\"`\n\t// The client will send the `textDocument/semanticTokens/full` request if\n\t// the server provides a corresponding handler.\n\tFull *Or_ClientSemanticTokensRequestOptions_full `json:\"full,omitempty\"`\n}\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#clientShowMessageActionItemOptions\ntype ClientShowMessageActionItemOptions struct {\n\t// Whether the client supports additional attributes which\n\t// are preserved and send back to the server in the\n\t// request's response.\n\tAdditionalPropertiesSupport bool `json:\"additionalPropertiesSupport,omitempty\"`\n}\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#clientSignatureInformationOptions\ntype ClientSignatureInformationOptions struct {\n\t// Client supports the following content formats for the documentation\n\t// property. The order describes the preferred format of the client.\n\tDocumentationFormat []MarkupKind `json:\"documentationFormat,omitempty\"`\n\t// Client capabilities specific to parameter information.\n\tParameterInformation *ClientSignatureParameterInformationOptions `json:\"parameterInformation,omitempty\"`\n\t// The client supports the `activeParameter` property on `SignatureInformation`\n\t// literal.\n\t//\n\t// @since 3.16.0\n\tActiveParameterSupport bool `json:\"activeParameterSupport,omitempty\"`\n\t// The client supports the `activeParameter` property on\n\t// `SignatureHelp`/`SignatureInformation` being set to `null` to\n\t// indicate that no parameter should be active.\n\t//\n\t// @since 3.18.0\n\t// @proposed\n\tNoActiveParameterSupport bool `json:\"noActiveParameterSupport,omitempty\"`\n}\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#clientSignatureParameterInformationOptions\ntype ClientSignatureParameterInformationOptions struct {\n\t// The client supports processing label offsets instead of a\n\t// simple label string.\n\t//\n\t// @since 3.14.0\n\tLabelOffsetSupport bool `json:\"labelOffsetSupport,omitempty\"`\n}\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#clientSymbolKindOptions\ntype ClientSymbolKindOptions struct {\n\t// The symbol kind values the client supports. When this\n\t// property exists the client also guarantees that it will\n\t// handle values outside its set gracefully and falls back\n\t// to a default value when unknown.\n\t//\n\t// If this property is not present the client only supports\n\t// the symbol kinds from `File` to `Array` as defined in\n\t// the initial version of the protocol.\n\tValueSet []SymbolKind `json:\"valueSet,omitempty\"`\n}\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#clientSymbolResolveOptions\ntype ClientSymbolResolveOptions struct {\n\t// The properties that a client can resolve lazily. Usually\n\t// `location.range`\n\tProperties []string `json:\"properties\"`\n}\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#clientSymbolTagOptions\ntype ClientSymbolTagOptions struct {\n\t// The tags supported by the client.\n\tValueSet []SymbolTag `json:\"valueSet\"`\n}\n\n// A code action represents a change that can be performed in code, e.g. to fix a problem or\n// to refactor code.\n//\n// A CodeAction must set either `edit` and/or a `command`. If both are supplied, the `edit` is applied first, then the `command` is executed.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#codeAction\ntype CodeAction struct {\n\t// A short, human-readable, title for this code action.\n\tTitle string `json:\"title\"`\n\t// The kind of the code action.\n\t//\n\t// Used to filter code actions.\n\tKind CodeActionKind `json:\"kind,omitempty\"`\n\t// The diagnostics that this code action resolves.\n\tDiagnostics []Diagnostic `json:\"diagnostics,omitempty\"`\n\t// Marks this as a preferred action. Preferred actions are used by the `auto fix` command and can be targeted\n\t// by keybindings.\n\t//\n\t// A quick fix should be marked preferred if it properly addresses the underlying error.\n\t// A refactoring should be marked preferred if it is the most reasonable choice of actions to take.\n\t//\n\t// @since 3.15.0\n\tIsPreferred bool `json:\"isPreferred,omitempty\"`\n\t// Marks that the code action cannot currently be applied.\n\t//\n\t// Clients should follow the following guidelines regarding disabled code actions:\n\t//\n\t// - Disabled code actions are not shown in automatic [lightbulbs](https://code.visualstudio.com/docs/editor/editingevolved#_code-action)\n\t// code action menus.\n\t//\n\t// - Disabled actions are shown as faded out in the code action menu when the user requests a more specific type\n\t// of code action, such as refactorings.\n\t//\n\t// - If the user has a [keybinding](https://code.visualstudio.com/docs/editor/refactoring#_keybindings-for-code-actions)\n\t// that auto applies a code action and only disabled code actions are returned, the client should show the user an\n\t// error message with `reason` in the editor.\n\t//\n\t// @since 3.16.0\n\tDisabled *CodeActionDisabled `json:\"disabled,omitempty\"`\n\t// The workspace edit this code action performs.\n\tEdit *WorkspaceEdit `json:\"edit,omitempty\"`\n\t// A command this code action executes. If a code action\n\t// provides an edit and a command, first the edit is\n\t// executed and then the command.\n\tCommand *Command `json:\"command,omitempty\"`\n\t// A data entry field that is preserved on a code action between\n\t// a `textDocument/codeAction` and a `codeAction/resolve` request.\n\t//\n\t// @since 3.16.0\n\tData *json.RawMessage `json:\"data,omitempty\"`\n}\n\n// The Client Capabilities of a {@link CodeActionRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#codeActionClientCapabilities\ntype CodeActionClientCapabilities struct {\n\t// Whether code action supports dynamic registration.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n\t// The client support code action literals of type `CodeAction` as a valid\n\t// response of the `textDocument/codeAction` request. If the property is not\n\t// set the request can only return `Command` literals.\n\t//\n\t// @since 3.8.0\n\tCodeActionLiteralSupport ClientCodeActionLiteralOptions `json:\"codeActionLiteralSupport,omitempty\"`\n\t// Whether code action supports the `isPreferred` property.\n\t//\n\t// @since 3.15.0\n\tIsPreferredSupport bool `json:\"isPreferredSupport,omitempty\"`\n\t// Whether code action supports the `disabled` property.\n\t//\n\t// @since 3.16.0\n\tDisabledSupport bool `json:\"disabledSupport,omitempty\"`\n\t// Whether code action supports the `data` property which is\n\t// preserved between a `textDocument/codeAction` and a\n\t// `codeAction/resolve` request.\n\t//\n\t// @since 3.16.0\n\tDataSupport bool `json:\"dataSupport,omitempty\"`\n\t// Whether the client supports resolving additional code action\n\t// properties via a separate `codeAction/resolve` request.\n\t//\n\t// @since 3.16.0\n\tResolveSupport *ClientCodeActionResolveOptions `json:\"resolveSupport,omitempty\"`\n\t// Whether the client honors the change annotations in\n\t// text edits and resource operations returned via the\n\t// `CodeAction#edit` property by for example presenting\n\t// the workspace edit in the user interface and asking\n\t// for confirmation.\n\t//\n\t// @since 3.16.0\n\tHonorsChangeAnnotations bool `json:\"honorsChangeAnnotations,omitempty\"`\n\t// Whether the client supports documentation for a class of\n\t// code actions.\n\t//\n\t// @since 3.18.0\n\t// @proposed\n\tDocumentationSupport bool `json:\"documentationSupport,omitempty\"`\n}\n\n// Contains additional diagnostic information about the context in which\n// a {@link CodeActionProvider.provideCodeActions code action} is run.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#codeActionContext\ntype CodeActionContext struct {\n\t// An array of diagnostics known on the client side overlapping the range provided to the\n\t// `textDocument/codeAction` request. They are provided so that the server knows which\n\t// errors are currently presented to the user for the given range. There is no guarantee\n\t// that these accurately reflect the error state of the resource. The primary parameter\n\t// to compute code actions is the provided range.\n\tDiagnostics []Diagnostic `json:\"diagnostics\"`\n\t// Requested kind of actions to return.\n\t//\n\t// Actions not of this kind are filtered out by the client before being shown. So servers\n\t// can omit computing them.\n\tOnly []CodeActionKind `json:\"only,omitempty\"`\n\t// The reason why code actions were requested.\n\t//\n\t// @since 3.17.0\n\tTriggerKind *CodeActionTriggerKind `json:\"triggerKind,omitempty\"`\n}\n\n// Captures why the code action is currently disabled.\n//\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#codeActionDisabled\ntype CodeActionDisabled struct {\n\t// Human readable description of why the code action is currently disabled.\n\t//\n\t// This is displayed in the code actions UI.\n\tReason string `json:\"reason\"`\n}\n\n// A set of predefined code action kinds\ntype CodeActionKind string\n\n// Documentation for a class of code actions.\n//\n// @since 3.18.0\n// @proposed\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#codeActionKindDocumentation\ntype CodeActionKindDocumentation struct {\n\t// The kind of the code action being documented.\n\t//\n\t// If the kind is generic, such as `CodeActionKind.Refactor`, the documentation will be shown whenever any\n\t// refactorings are returned. If the kind if more specific, such as `CodeActionKind.RefactorExtract`, the\n\t// documentation will only be shown when extract refactoring code actions are returned.\n\tKind CodeActionKind `json:\"kind\"`\n\t// Command that is ued to display the documentation to the user.\n\t//\n\t// The title of this documentation code action is taken from {@linkcode Command.title}\n\tCommand Command `json:\"command\"`\n}\n\n// Provider options for a {@link CodeActionRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#codeActionOptions\ntype CodeActionOptions struct {\n\t// CodeActionKinds that this server may return.\n\t//\n\t// The list of kinds may be generic, such as `CodeActionKind.Refactor`, or the server\n\t// may list out every specific kind they provide.\n\tCodeActionKinds []CodeActionKind `json:\"codeActionKinds,omitempty\"`\n\t// Static documentation for a class of code actions.\n\t//\n\t// Documentation from the provider should be shown in the code actions menu if either:\n\t//\n\t//\n\t// - Code actions of `kind` are requested by the editor. In this case, the editor will show the documentation that\n\t// most closely matches the requested code action kind. For example, if a provider has documentation for\n\t// both `Refactor` and `RefactorExtract`, when the user requests code actions for `RefactorExtract`,\n\t// the editor will use the documentation for `RefactorExtract` instead of the documentation for `Refactor`.\n\t//\n\t//\n\t// - Any code actions of `kind` are returned by the provider.\n\t//\n\t// At most one documentation entry should be shown per provider.\n\t//\n\t// @since 3.18.0\n\t// @proposed\n\tDocumentation []CodeActionKindDocumentation `json:\"documentation,omitempty\"`\n\t// The server provides support to resolve additional\n\t// information for a code action.\n\t//\n\t// @since 3.16.0\n\tResolveProvider bool `json:\"resolveProvider,omitempty\"`\n\tWorkDoneProgressOptions\n}\n\n// The parameters of a {@link CodeActionRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#codeActionParams\ntype CodeActionParams struct {\n\t// The document in which the command was invoked.\n\tTextDocument TextDocumentIdentifier `json:\"textDocument\"`\n\t// The range for which the command was invoked.\n\tRange Range `json:\"range\"`\n\t// Context carrying additional information.\n\tContext CodeActionContext `json:\"context\"`\n\tWorkDoneProgressParams\n\tPartialResultParams\n}\n\n// Registration options for a {@link CodeActionRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#codeActionRegistrationOptions\ntype CodeActionRegistrationOptions struct {\n\tTextDocumentRegistrationOptions\n\tCodeActionOptions\n}\n\n// The reason why code actions were requested.\n//\n// @since 3.17.0\ntype CodeActionTriggerKind uint32\n\n// Structure to capture a description for an error code.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#codeDescription\ntype CodeDescription struct {\n\t// An URI to open with more information about the diagnostic error.\n\tHref URI `json:\"href\"`\n}\n\n// A code lens represents a {@link Command command} that should be shown along with\n// source text, like the number of references, a way to run tests, etc.\n//\n// A code lens is _unresolved_ when no command is associated to it. For performance\n// reasons the creation of a code lens and resolving should be done in two stages.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#codeLens\ntype CodeLens struct {\n\t// The range in which this code lens is valid. Should only span a single line.\n\tRange Range `json:\"range\"`\n\t// The command this code lens represents.\n\tCommand *Command `json:\"command,omitempty\"`\n\t// A data entry field that is preserved on a code lens item between\n\t// a {@link CodeLensRequest} and a {@link CodeLensResolveRequest}\n\tData interface{} `json:\"data,omitempty\"`\n}\n\n// The client capabilities of a {@link CodeLensRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#codeLensClientCapabilities\ntype CodeLensClientCapabilities struct {\n\t// Whether code lens supports dynamic registration.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n\t// Whether the client supports resolving additional code lens\n\t// properties via a separate `codeLens/resolve` request.\n\t//\n\t// @since 3.18.0\n\tResolveSupport *ClientCodeLensResolveOptions `json:\"resolveSupport,omitempty\"`\n}\n\n// Code Lens provider options of a {@link CodeLensRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#codeLensOptions\ntype CodeLensOptions struct {\n\t// Code lens has a resolve provider as well.\n\tResolveProvider bool `json:\"resolveProvider,omitempty\"`\n\tWorkDoneProgressOptions\n}\n\n// The parameters of a {@link CodeLensRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#codeLensParams\ntype CodeLensParams struct {\n\t// The document to request code lens for.\n\tTextDocument TextDocumentIdentifier `json:\"textDocument\"`\n\tWorkDoneProgressParams\n\tPartialResultParams\n}\n\n// Registration options for a {@link CodeLensRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#codeLensRegistrationOptions\ntype CodeLensRegistrationOptions struct {\n\tTextDocumentRegistrationOptions\n\tCodeLensOptions\n}\n\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#codeLensWorkspaceClientCapabilities\ntype CodeLensWorkspaceClientCapabilities struct {\n\t// Whether the client implementation supports a refresh request sent from the\n\t// server to the client.\n\t//\n\t// Note that this event is global and will force the client to refresh all\n\t// code lenses currently shown. It should be used with absolute care and is\n\t// useful for situation where a server for example detect a project wide\n\t// change that requires such a calculation.\n\tRefreshSupport bool `json:\"refreshSupport,omitempty\"`\n}\n\n// Represents a color in RGBA space.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#color\ntype Color struct {\n\t// The red component of this color in the range [0-1].\n\tRed float64 `json:\"red\"`\n\t// The green component of this color in the range [0-1].\n\tGreen float64 `json:\"green\"`\n\t// The blue component of this color in the range [0-1].\n\tBlue float64 `json:\"blue\"`\n\t// The alpha component of this color in the range [0-1].\n\tAlpha float64 `json:\"alpha\"`\n}\n\n// Represents a color range from a document.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#colorInformation\ntype ColorInformation struct {\n\t// The range in the document where this color appears.\n\tRange Range `json:\"range\"`\n\t// The actual color value for this color range.\n\tColor Color `json:\"color\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#colorPresentation\ntype ColorPresentation struct {\n\t// The label of this color presentation. It will be shown on the color\n\t// picker header. By default this is also the text that is inserted when selecting\n\t// this color presentation.\n\tLabel string `json:\"label\"`\n\t// An {@link TextEdit edit} which is applied to a document when selecting\n\t// this presentation for the color. When `falsy` the {@link ColorPresentation.label label}\n\t// is used.\n\tTextEdit *TextEdit `json:\"textEdit,omitempty\"`\n\t// An optional array of additional {@link TextEdit text edits} that are applied when\n\t// selecting this color presentation. Edits must not overlap with the main {@link ColorPresentation.textEdit edit} nor with themselves.\n\tAdditionalTextEdits []TextEdit `json:\"additionalTextEdits,omitempty\"`\n}\n\n// Parameters for a {@link ColorPresentationRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#colorPresentationParams\ntype ColorPresentationParams struct {\n\t// The text document.\n\tTextDocument TextDocumentIdentifier `json:\"textDocument\"`\n\t// The color to request presentations for.\n\tColor Color `json:\"color\"`\n\t// The range where the color would be inserted. Serves as a context.\n\tRange Range `json:\"range\"`\n\tWorkDoneProgressParams\n\tPartialResultParams\n}\n\n// Represents a reference to a command. Provides a title which\n// will be used to represent a command in the UI and, optionally,\n// an array of arguments which will be passed to the command handler\n// function when invoked.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#command\ntype Command struct {\n\t// Title of the command, like `save`.\n\tTitle string `json:\"title\"`\n\t// An optional tooltip.\n\t//\n\t// @since 3.18.0\n\t// @proposed\n\tTooltip string `json:\"tooltip,omitempty\"`\n\t// The identifier of the actual command handler.\n\tCommand string `json:\"command\"`\n\t// Arguments that the command handler should be\n\t// invoked with.\n\tArguments []json.RawMessage `json:\"arguments,omitempty\"`\n}\n\n// Completion client capabilities\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#completionClientCapabilities\ntype CompletionClientCapabilities struct {\n\t// Whether completion supports dynamic registration.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n\t// The client supports the following `CompletionItem` specific\n\t// capabilities.\n\tCompletionItem ClientCompletionItemOptions `json:\"completionItem,omitempty\"`\n\tCompletionItemKind *ClientCompletionItemOptionsKind `json:\"completionItemKind,omitempty\"`\n\t// Defines how the client handles whitespace and indentation\n\t// when accepting a completion item that uses multi line\n\t// text in either `insertText` or `textEdit`.\n\t//\n\t// @since 3.17.0\n\tInsertTextMode InsertTextMode `json:\"insertTextMode,omitempty\"`\n\t// The client supports to send additional context information for a\n\t// `textDocument/completion` request.\n\tContextSupport bool `json:\"contextSupport,omitempty\"`\n\t// The client supports the following `CompletionList` specific\n\t// capabilities.\n\t//\n\t// @since 3.17.0\n\tCompletionList *CompletionListCapabilities `json:\"completionList,omitempty\"`\n}\n\n// Contains additional information about the context in which a completion request is triggered.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#completionContext\ntype CompletionContext struct {\n\t// How the completion was triggered.\n\tTriggerKind CompletionTriggerKind `json:\"triggerKind\"`\n\t// The trigger character (a single character) that has trigger code complete.\n\t// Is undefined if `triggerKind !== CompletionTriggerKind.TriggerCharacter`\n\tTriggerCharacter string `json:\"triggerCharacter,omitempty\"`\n}\n\n// A completion item represents a text snippet that is\n// proposed to complete text that is being typed.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#completionItem\ntype CompletionItem struct {\n\t// The label of this completion item.\n\t//\n\t// The label property is also by default the text that\n\t// is inserted when selecting this completion.\n\t//\n\t// If label details are provided the label itself should\n\t// be an unqualified name of the completion item.\n\tLabel string `json:\"label\"`\n\t// Additional details for the label\n\t//\n\t// @since 3.17.0\n\tLabelDetails *CompletionItemLabelDetails `json:\"labelDetails,omitempty\"`\n\t// The kind of this completion item. Based of the kind\n\t// an icon is chosen by the editor.\n\tKind CompletionItemKind `json:\"kind,omitempty\"`\n\t// Tags for this completion item.\n\t//\n\t// @since 3.15.0\n\tTags []CompletionItemTag `json:\"tags,omitempty\"`\n\t// A human-readable string with additional information\n\t// about this item, like type or symbol information.\n\tDetail string `json:\"detail,omitempty\"`\n\t// A human-readable string that represents a doc-comment.\n\tDocumentation *Or_CompletionItem_documentation `json:\"documentation,omitempty\"`\n\t// Indicates if this item is deprecated.\n\t// @deprecated Use `tags` instead.\n\tDeprecated bool `json:\"deprecated,omitempty\"`\n\t// Select this item when showing.\n\t//\n\t// *Note* that only one completion item can be selected and that the\n\t// tool / client decides which item that is. The rule is that the *first*\n\t// item of those that match best is selected.\n\tPreselect bool `json:\"preselect,omitempty\"`\n\t// A string that should be used when comparing this item\n\t// with other items. When `falsy` the {@link CompletionItem.label label}\n\t// is used.\n\tSortText string `json:\"sortText,omitempty\"`\n\t// A string that should be used when filtering a set of\n\t// completion items. When `falsy` the {@link CompletionItem.label label}\n\t// is used.\n\tFilterText string `json:\"filterText,omitempty\"`\n\t// A string that should be inserted into a document when selecting\n\t// this completion. When `falsy` the {@link CompletionItem.label label}\n\t// is used.\n\t//\n\t// The `insertText` is subject to interpretation by the client side.\n\t// Some tools might not take the string literally. For example\n\t// VS Code when code complete is requested in this example\n\t// `con` and a completion item with an `insertText` of\n\t// `console` is provided it will only insert `sole`. Therefore it is\n\t// recommended to use `textEdit` instead since it avoids additional client\n\t// side interpretation.\n\tInsertText string `json:\"insertText,omitempty\"`\n\t// The format of the insert text. The format applies to both the\n\t// `insertText` property and the `newText` property of a provided\n\t// `textEdit`. If omitted defaults to `InsertTextFormat.PlainText`.\n\t//\n\t// Please note that the insertTextFormat doesn't apply to\n\t// `additionalTextEdits`.\n\tInsertTextFormat *InsertTextFormat `json:\"insertTextFormat,omitempty\"`\n\t// How whitespace and indentation is handled during completion\n\t// item insertion. If not provided the clients default value depends on\n\t// the `textDocument.completion.insertTextMode` client capability.\n\t//\n\t// @since 3.16.0\n\tInsertTextMode *InsertTextMode `json:\"insertTextMode,omitempty\"`\n\t// An {@link TextEdit edit} which is applied to a document when selecting\n\t// this completion. When an edit is provided the value of\n\t// {@link CompletionItem.insertText insertText} is ignored.\n\t//\n\t// Most editors support two different operations when accepting a completion\n\t// item. One is to insert a completion text and the other is to replace an\n\t// existing text with a completion text. Since this can usually not be\n\t// predetermined by a server it can report both ranges. Clients need to\n\t// signal support for `InsertReplaceEdits` via the\n\t// `textDocument.completion.insertReplaceSupport` client capability\n\t// property.\n\t//\n\t// *Note 1:* The text edit's range as well as both ranges from an insert\n\t// replace edit must be a [single line] and they must contain the position\n\t// at which completion has been requested.\n\t// *Note 2:* If an `InsertReplaceEdit` is returned the edit's insert range\n\t// must be a prefix of the edit's replace range, that means it must be\n\t// contained and starting at the same position.\n\t//\n\t// @since 3.16.0 additional type `InsertReplaceEdit`\n\tTextEdit *Or_CompletionItem_textEdit `json:\"textEdit,omitempty\"`\n\t// The edit text used if the completion item is part of a CompletionList and\n\t// CompletionList defines an item default for the text edit range.\n\t//\n\t// Clients will only honor this property if they opt into completion list\n\t// item defaults using the capability `completionList.itemDefaults`.\n\t//\n\t// If not provided and a list's default range is provided the label\n\t// property is used as a text.\n\t//\n\t// @since 3.17.0\n\tTextEditText string `json:\"textEditText,omitempty\"`\n\t// An optional array of additional {@link TextEdit text edits} that are applied when\n\t// selecting this completion. Edits must not overlap (including the same insert position)\n\t// with the main {@link CompletionItem.textEdit edit} nor with themselves.\n\t//\n\t// Additional text edits should be used to change text unrelated to the current cursor position\n\t// (for example adding an import statement at the top of the file if the completion item will\n\t// insert an unqualified type).\n\tAdditionalTextEdits []TextEdit `json:\"additionalTextEdits,omitempty\"`\n\t// An optional set of characters that when pressed while this completion is active will accept it first and\n\t// then type that character. *Note* that all commit characters should have `length=1` and that superfluous\n\t// characters will be ignored.\n\tCommitCharacters []string `json:\"commitCharacters,omitempty\"`\n\t// An optional {@link Command command} that is executed *after* inserting this completion. *Note* that\n\t// additional modifications to the current document should be described with the\n\t// {@link CompletionItem.additionalTextEdits additionalTextEdits}-property.\n\tCommand *Command `json:\"command,omitempty\"`\n\t// A data entry field that is preserved on a completion item between a\n\t// {@link CompletionRequest} and a {@link CompletionResolveRequest}.\n\tData interface{} `json:\"data,omitempty\"`\n}\n\n// In many cases the items of an actual completion result share the same\n// value for properties like `commitCharacters` or the range of a text\n// edit. A completion list can therefore define item defaults which will\n// be used if a completion item itself doesn't specify the value.\n//\n// If a completion list specifies a default value and a completion item\n// also specifies a corresponding value the one from the item is used.\n//\n// Servers are only allowed to return default values if the client\n// signals support for this via the `completionList.itemDefaults`\n// capability.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#completionItemDefaults\ntype CompletionItemDefaults struct {\n\t// A default commit character set.\n\t//\n\t// @since 3.17.0\n\tCommitCharacters []string `json:\"commitCharacters,omitempty\"`\n\t// A default edit range.\n\t//\n\t// @since 3.17.0\n\tEditRange *Or_CompletionItemDefaults_editRange `json:\"editRange,omitempty\"`\n\t// A default insert text format.\n\t//\n\t// @since 3.17.0\n\tInsertTextFormat *InsertTextFormat `json:\"insertTextFormat,omitempty\"`\n\t// A default insert text mode.\n\t//\n\t// @since 3.17.0\n\tInsertTextMode *InsertTextMode `json:\"insertTextMode,omitempty\"`\n\t// A default data value.\n\t//\n\t// @since 3.17.0\n\tData interface{} `json:\"data,omitempty\"`\n}\n\n// The kind of a completion entry.\ntype CompletionItemKind uint32\n\n// Additional details for a completion item label.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#completionItemLabelDetails\ntype CompletionItemLabelDetails struct {\n\t// An optional string which is rendered less prominently directly after {@link CompletionItem.label label},\n\t// without any spacing. Should be used for function signatures and type annotations.\n\tDetail string `json:\"detail,omitempty\"`\n\t// An optional string which is rendered less prominently after {@link CompletionItem.detail}. Should be used\n\t// for fully qualified names and file paths.\n\tDescription string `json:\"description,omitempty\"`\n}\n\n// Completion item tags are extra annotations that tweak the rendering of a completion\n// item.\n//\n// @since 3.15.0\ntype CompletionItemTag uint32\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#completionItemTagOptions\ntype CompletionItemTagOptions struct {\n\t// The tags supported by the client.\n\tValueSet []CompletionItemTag `json:\"valueSet\"`\n}\n\n// Represents a collection of {@link CompletionItem completion items} to be presented\n// in the editor.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#completionList\ntype CompletionList struct {\n\t// This list it not complete. Further typing results in recomputing this list.\n\t//\n\t// Recomputed lists have all their items replaced (not appended) in the\n\t// incomplete completion sessions.\n\tIsIncomplete bool `json:\"isIncomplete\"`\n\t// In many cases the items of an actual completion result share the same\n\t// value for properties like `commitCharacters` or the range of a text\n\t// edit. A completion list can therefore define item defaults which will\n\t// be used if a completion item itself doesn't specify the value.\n\t//\n\t// If a completion list specifies a default value and a completion item\n\t// also specifies a corresponding value the one from the item is used.\n\t//\n\t// Servers are only allowed to return default values if the client\n\t// signals support for this via the `completionList.itemDefaults`\n\t// capability.\n\t//\n\t// @since 3.17.0\n\tItemDefaults *CompletionItemDefaults `json:\"itemDefaults,omitempty\"`\n\t// The completion items.\n\tItems []CompletionItem `json:\"items\"`\n}\n\n// The client supports the following `CompletionList` specific\n// capabilities.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#completionListCapabilities\ntype CompletionListCapabilities struct {\n\t// The client supports the following itemDefaults on\n\t// a completion list.\n\t//\n\t// The value lists the supported property names of the\n\t// `CompletionList.itemDefaults` object. If omitted\n\t// no properties are supported.\n\t//\n\t// @since 3.17.0\n\tItemDefaults []string `json:\"itemDefaults,omitempty\"`\n}\n\n// Completion options.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#completionOptions\ntype CompletionOptions struct {\n\t// Most tools trigger completion request automatically without explicitly requesting\n\t// it using a keyboard shortcut (e.g. Ctrl+Space). Typically they do so when the user\n\t// starts to type an identifier. For example if the user types `c` in a JavaScript file\n\t// code complete will automatically pop up present `console` besides others as a\n\t// completion item. Characters that make up identifiers don't need to be listed here.\n\t//\n\t// If code complete should automatically be trigger on characters not being valid inside\n\t// an identifier (for example `.` in JavaScript) list them in `triggerCharacters`.\n\tTriggerCharacters []string `json:\"triggerCharacters,omitempty\"`\n\t// The list of all possible characters that commit a completion. This field can be used\n\t// if clients don't support individual commit characters per completion item. See\n\t// `ClientCapabilities.textDocument.completion.completionItem.commitCharactersSupport`\n\t//\n\t// If a server provides both `allCommitCharacters` and commit characters on an individual\n\t// completion item the ones on the completion item win.\n\t//\n\t// @since 3.2.0\n\tAllCommitCharacters []string `json:\"allCommitCharacters,omitempty\"`\n\t// The server provides support to resolve additional\n\t// information for a completion item.\n\tResolveProvider bool `json:\"resolveProvider,omitempty\"`\n\t// The server supports the following `CompletionItem` specific\n\t// capabilities.\n\t//\n\t// @since 3.17.0\n\tCompletionItem *ServerCompletionItemOptions `json:\"completionItem,omitempty\"`\n\tWorkDoneProgressOptions\n}\n\n// Completion parameters\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#completionParams\ntype CompletionParams struct {\n\t// The completion context. This is only available it the client specifies\n\t// to send this using the client capability `textDocument.completion.contextSupport === true`\n\tContext CompletionContext `json:\"context,omitempty\"`\n\tTextDocumentPositionParams\n\tWorkDoneProgressParams\n\tPartialResultParams\n}\n\n// Registration options for a {@link CompletionRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#completionRegistrationOptions\ntype CompletionRegistrationOptions struct {\n\tTextDocumentRegistrationOptions\n\tCompletionOptions\n}\n\n// How a completion was triggered\ntype CompletionTriggerKind uint32\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#configurationItem\ntype ConfigurationItem struct {\n\t// The scope to get the configuration section for.\n\tScopeURI *URI `json:\"scopeUri,omitempty\"`\n\t// The configuration section asked for.\n\tSection string `json:\"section,omitempty\"`\n}\n\n// The parameters of a configuration request.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#configurationParams\ntype ConfigurationParams struct {\n\tItems []ConfigurationItem `json:\"items\"`\n}\n\n// Create file operation.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#createFile\ntype CreateFile struct {\n\t// A create\n\tKind string `json:\"kind\"`\n\t// The resource to create.\n\tURI DocumentUri `json:\"uri\"`\n\t// Additional options\n\tOptions *CreateFileOptions `json:\"options,omitempty\"`\n\tResourceOperation\n}\n\n// Options to create a file.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#createFileOptions\ntype CreateFileOptions struct {\n\t// Overwrite existing file. Overwrite wins over `ignoreIfExists`\n\tOverwrite bool `json:\"overwrite,omitempty\"`\n\t// Ignore if exists.\n\tIgnoreIfExists bool `json:\"ignoreIfExists,omitempty\"`\n}\n\n// The parameters sent in notifications/requests for user-initiated creation of\n// files.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#createFilesParams\ntype CreateFilesParams struct {\n\t// An array of all files/folders created in this operation.\n\tFiles []FileCreate `json:\"files\"`\n}\n\n// The declaration of a symbol representation as one or many {@link Location locations}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#declaration\ntype Declaration = Or_Declaration // (alias)\n// @since 3.14.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#declarationClientCapabilities\ntype DeclarationClientCapabilities struct {\n\t// Whether declaration supports dynamic registration. If this is set to `true`\n\t// the client supports the new `DeclarationRegistrationOptions` return value\n\t// for the corresponding server capability as well.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n\t// The client supports additional metadata in the form of declaration links.\n\tLinkSupport bool `json:\"linkSupport,omitempty\"`\n}\n\n// Information about where a symbol is declared.\n//\n// Provides additional metadata over normal {@link Location location} declarations, including the range of\n// the declaring symbol.\n//\n// Servers should prefer returning `DeclarationLink` over `Declaration` if supported\n// by the client.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#declarationLink\ntype DeclarationLink = LocationLink // (alias)\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#declarationOptions\ntype DeclarationOptions struct {\n\tWorkDoneProgressOptions\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#declarationParams\ntype DeclarationParams struct {\n\tTextDocumentPositionParams\n\tWorkDoneProgressParams\n\tPartialResultParams\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#declarationRegistrationOptions\ntype DeclarationRegistrationOptions struct {\n\tDeclarationOptions\n\tTextDocumentRegistrationOptions\n\tStaticRegistrationOptions\n}\n\n// The definition of a symbol represented as one or many {@link Location locations}.\n// For most programming languages there is only one location at which a symbol is\n// defined.\n//\n// Servers should prefer returning `DefinitionLink` over `Definition` if supported\n// by the client.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#definition\ntype Definition = Or_Definition // (alias)\n// Client Capabilities for a {@link DefinitionRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#definitionClientCapabilities\ntype DefinitionClientCapabilities struct {\n\t// Whether definition supports dynamic registration.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n\t// The client supports additional metadata in the form of definition links.\n\t//\n\t// @since 3.14.0\n\tLinkSupport bool `json:\"linkSupport,omitempty\"`\n}\n\n// Information about where a symbol is defined.\n//\n// Provides additional metadata over normal {@link Location location} definitions, including the range of\n// the defining symbol\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#definitionLink\ntype DefinitionLink = LocationLink // (alias)\n// Server Capabilities for a {@link DefinitionRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#definitionOptions\ntype DefinitionOptions struct {\n\tWorkDoneProgressOptions\n}\n\n// Parameters for a {@link DefinitionRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#definitionParams\ntype DefinitionParams struct {\n\tTextDocumentPositionParams\n\tWorkDoneProgressParams\n\tPartialResultParams\n}\n\n// Registration options for a {@link DefinitionRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#definitionRegistrationOptions\ntype DefinitionRegistrationOptions struct {\n\tTextDocumentRegistrationOptions\n\tDefinitionOptions\n}\n\n// Delete file operation\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#deleteFile\ntype DeleteFile struct {\n\t// A delete\n\tKind string `json:\"kind\"`\n\t// The file to delete.\n\tURI DocumentUri `json:\"uri\"`\n\t// Delete options.\n\tOptions *DeleteFileOptions `json:\"options,omitempty\"`\n\tResourceOperation\n}\n\n// Delete file options\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#deleteFileOptions\ntype DeleteFileOptions struct {\n\t// Delete the content recursively if a folder is denoted.\n\tRecursive bool `json:\"recursive,omitempty\"`\n\t// Ignore the operation if the file doesn't exist.\n\tIgnoreIfNotExists bool `json:\"ignoreIfNotExists,omitempty\"`\n}\n\n// The parameters sent in notifications/requests for user-initiated deletes of\n// files.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#deleteFilesParams\ntype DeleteFilesParams struct {\n\t// An array of all files/folders deleted in this operation.\n\tFiles []FileDelete `json:\"files\"`\n}\n\n// Represents a diagnostic, such as a compiler error or warning. Diagnostic objects\n// are only valid in the scope of a resource.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#diagnostic\ntype Diagnostic struct {\n\t// The range at which the message applies\n\tRange Range `json:\"range\"`\n\t// The diagnostic's severity. To avoid interpretation mismatches when a\n\t// server is used with different clients it is highly recommended that servers\n\t// always provide a severity value.\n\tSeverity DiagnosticSeverity `json:\"severity,omitempty\"`\n\t// The diagnostic's code, which usually appear in the user interface.\n\tCode interface{} `json:\"code,omitempty\"`\n\t// An optional property to describe the error code.\n\t// Requires the code field (above) to be present/not null.\n\t//\n\t// @since 3.16.0\n\tCodeDescription *CodeDescription `json:\"codeDescription,omitempty\"`\n\t// A human-readable string describing the source of this\n\t// diagnostic, e.g. 'typescript' or 'super lint'. It usually\n\t// appears in the user interface.\n\tSource string `json:\"source,omitempty\"`\n\t// The diagnostic's message. It usually appears in the user interface\n\tMessage string `json:\"message\"`\n\t// Additional metadata about the diagnostic.\n\t//\n\t// @since 3.15.0\n\tTags []DiagnosticTag `json:\"tags,omitempty\"`\n\t// An array of related diagnostic information, e.g. when symbol-names within\n\t// a scope collide all definitions can be marked via this property.\n\tRelatedInformation []DiagnosticRelatedInformation `json:\"relatedInformation,omitempty\"`\n\t// A data entry field that is preserved between a `textDocument/publishDiagnostics`\n\t// notification and `textDocument/codeAction` request.\n\t//\n\t// @since 3.16.0\n\tData *json.RawMessage `json:\"data,omitempty\"`\n}\n\n// Client capabilities specific to diagnostic pull requests.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#diagnosticClientCapabilities\ntype DiagnosticClientCapabilities struct {\n\t// Whether implementation supports dynamic registration. If this is set to `true`\n\t// the client supports the new `(TextDocumentRegistrationOptions & StaticRegistrationOptions)`\n\t// return value for the corresponding server capability as well.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n\t// Whether the clients supports related documents for document diagnostic pulls.\n\tRelatedDocumentSupport bool `json:\"relatedDocumentSupport,omitempty\"`\n\tDiagnosticsCapabilities\n}\n\n// Diagnostic options.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#diagnosticOptions\ntype DiagnosticOptions struct {\n\t// An optional identifier under which the diagnostics are\n\t// managed by the client.\n\tIdentifier string `json:\"identifier,omitempty\"`\n\t// Whether the language has inter file dependencies meaning that\n\t// editing code in one file can result in a different diagnostic\n\t// set in another file. Inter file dependencies are common for\n\t// most programming languages and typically uncommon for linters.\n\tInterFileDependencies bool `json:\"interFileDependencies\"`\n\t// The server provides support for workspace diagnostics as well.\n\tWorkspaceDiagnostics bool `json:\"workspaceDiagnostics\"`\n\tWorkDoneProgressOptions\n}\n\n// Diagnostic registration options.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#diagnosticRegistrationOptions\ntype DiagnosticRegistrationOptions struct {\n\tTextDocumentRegistrationOptions\n\tDiagnosticOptions\n\tStaticRegistrationOptions\n}\n\n// Represents a related message and source code location for a diagnostic. This should be\n// used to point to code locations that cause or related to a diagnostics, e.g when duplicating\n// a symbol in a scope.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#diagnosticRelatedInformation\ntype DiagnosticRelatedInformation struct {\n\t// The location of this related diagnostic information.\n\tLocation Location `json:\"location\"`\n\t// The message of this related diagnostic information.\n\tMessage string `json:\"message\"`\n}\n\n// Cancellation data returned from a diagnostic request.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#diagnosticServerCancellationData\ntype DiagnosticServerCancellationData struct {\n\tRetriggerRequest bool `json:\"retriggerRequest\"`\n}\n\n// The diagnostic's severity.\ntype DiagnosticSeverity uint32\n\n// The diagnostic tags.\n//\n// @since 3.15.0\ntype DiagnosticTag uint32\n\n// Workspace client capabilities specific to diagnostic pull requests.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#diagnosticWorkspaceClientCapabilities\ntype DiagnosticWorkspaceClientCapabilities struct {\n\t// Whether the client implementation supports a refresh request sent from\n\t// the server to the client.\n\t//\n\t// Note that this event is global and will force the client to refresh all\n\t// pulled diagnostics currently shown. It should be used with absolute care and\n\t// is useful for situation where a server for example detects a project wide\n\t// change that requires such a calculation.\n\tRefreshSupport bool `json:\"refreshSupport,omitempty\"`\n}\n\n// General diagnostics capabilities for pull and push model.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#diagnosticsCapabilities\ntype DiagnosticsCapabilities struct {\n\t// Whether the clients accepts diagnostics with related information.\n\tRelatedInformation bool `json:\"relatedInformation,omitempty\"`\n\t// Client supports the tag property to provide meta data about a diagnostic.\n\t// Clients supporting tags have to handle unknown tags gracefully.\n\t//\n\t// @since 3.15.0\n\tTagSupport *ClientDiagnosticsTagOptions `json:\"tagSupport,omitempty\"`\n\t// Client supports a codeDescription property\n\t//\n\t// @since 3.16.0\n\tCodeDescriptionSupport bool `json:\"codeDescriptionSupport,omitempty\"`\n\t// Whether code action supports the `data` property which is\n\t// preserved between a `textDocument/publishDiagnostics` and\n\t// `textDocument/codeAction` request.\n\t//\n\t// @since 3.16.0\n\tDataSupport bool `json:\"dataSupport,omitempty\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#didChangeConfigurationClientCapabilities\ntype DidChangeConfigurationClientCapabilities struct {\n\t// Did change configuration notification supports dynamic registration.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n}\n\n// The parameters of a change configuration notification.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#didChangeConfigurationParams\ntype DidChangeConfigurationParams struct {\n\t// The actual changed settings\n\tSettings interface{} `json:\"settings\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#didChangeConfigurationRegistrationOptions\ntype DidChangeConfigurationRegistrationOptions struct {\n\tSection *Or_DidChangeConfigurationRegistrationOptions_section `json:\"section,omitempty\"`\n}\n\n// The params sent in a change notebook document notification.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#didChangeNotebookDocumentParams\ntype DidChangeNotebookDocumentParams struct {\n\t// The notebook document that did change. The version number points\n\t// to the version after all provided changes have been applied. If\n\t// only the text document content of a cell changes the notebook version\n\t// doesn't necessarily have to change.\n\tNotebookDocument VersionedNotebookDocumentIdentifier `json:\"notebookDocument\"`\n\t// The actual changes to the notebook document.\n\t//\n\t// The changes describe single state changes to the notebook document.\n\t// So if there are two changes c1 (at array index 0) and c2 (at array\n\t// index 1) for a notebook in state S then c1 moves the notebook from\n\t// S to S' and c2 from S' to S''. So c1 is computed on the state S and\n\t// c2 is computed on the state S'.\n\t//\n\t// To mirror the content of a notebook using change events use the following approach:\n\t//\n\t// - start with the same initial content\n\t// - apply the 'notebookDocument/didChange' notifications in the order you receive them.\n\t// - apply the `NotebookChangeEvent`s in a single notification in the order\n\t// you receive them.\n\tChange NotebookDocumentChangeEvent `json:\"change\"`\n}\n\n// The change text document notification's parameters.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#didChangeTextDocumentParams\ntype DidChangeTextDocumentParams struct {\n\t// The document that did change. The version number points\n\t// to the version after all provided content changes have\n\t// been applied.\n\tTextDocument VersionedTextDocumentIdentifier `json:\"textDocument\"`\n\t// The actual content changes. The content changes describe single state changes\n\t// to the document. So if there are two content changes c1 (at array index 0) and\n\t// c2 (at array index 1) for a document in state S then c1 moves the document from\n\t// S to S' and c2 from S' to S''. So c1 is computed on the state S and c2 is computed\n\t// on the state S'.\n\t//\n\t// To mirror the content of a document using change events use the following approach:\n\t//\n\t// - start with the same initial content\n\t// - apply the 'textDocument/didChange' notifications in the order you receive them.\n\t// - apply the `TextDocumentContentChangeEvent`s in a single notification in the order\n\t// you receive them.\n\tContentChanges []TextDocumentContentChangeEvent `json:\"contentChanges\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#didChangeWatchedFilesClientCapabilities\ntype DidChangeWatchedFilesClientCapabilities struct {\n\t// Did change watched files notification supports dynamic registration. Please note\n\t// that the current protocol doesn't support static configuration for file changes\n\t// from the server side.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n\t// Whether the client has support for {@link RelativePattern relative pattern}\n\t// or not.\n\t//\n\t// @since 3.17.0\n\tRelativePatternSupport bool `json:\"relativePatternSupport,omitempty\"`\n}\n\n// The watched files change notification's parameters.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#didChangeWatchedFilesParams\ntype DidChangeWatchedFilesParams struct {\n\t// The actual file events.\n\tChanges []FileEvent `json:\"changes\"`\n}\n\n// Describe options to be used when registered for text document change events.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#didChangeWatchedFilesRegistrationOptions\ntype DidChangeWatchedFilesRegistrationOptions struct {\n\t// The watchers to register.\n\tWatchers []FileSystemWatcher `json:\"watchers\"`\n}\n\n// The parameters of a `workspace/didChangeWorkspaceFolders` notification.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#didChangeWorkspaceFoldersParams\ntype DidChangeWorkspaceFoldersParams struct {\n\t// The actual workspace folder change event.\n\tEvent WorkspaceFoldersChangeEvent `json:\"event\"`\n}\n\n// The params sent in a close notebook document notification.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#didCloseNotebookDocumentParams\ntype DidCloseNotebookDocumentParams struct {\n\t// The notebook document that got closed.\n\tNotebookDocument NotebookDocumentIdentifier `json:\"notebookDocument\"`\n\t// The text documents that represent the content\n\t// of a notebook cell that got closed.\n\tCellTextDocuments []TextDocumentIdentifier `json:\"cellTextDocuments\"`\n}\n\n// The parameters sent in a close text document notification\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#didCloseTextDocumentParams\ntype DidCloseTextDocumentParams struct {\n\t// The document that was closed.\n\tTextDocument TextDocumentIdentifier `json:\"textDocument\"`\n}\n\n// The params sent in an open notebook document notification.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#didOpenNotebookDocumentParams\ntype DidOpenNotebookDocumentParams struct {\n\t// The notebook document that got opened.\n\tNotebookDocument NotebookDocument `json:\"notebookDocument\"`\n\t// The text documents that represent the content\n\t// of a notebook cell.\n\tCellTextDocuments []TextDocumentItem `json:\"cellTextDocuments\"`\n}\n\n// The parameters sent in an open text document notification\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#didOpenTextDocumentParams\ntype DidOpenTextDocumentParams struct {\n\t// The document that was opened.\n\tTextDocument TextDocumentItem `json:\"textDocument\"`\n}\n\n// The params sent in a save notebook document notification.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#didSaveNotebookDocumentParams\ntype DidSaveNotebookDocumentParams struct {\n\t// The notebook document that got saved.\n\tNotebookDocument NotebookDocumentIdentifier `json:\"notebookDocument\"`\n}\n\n// The parameters sent in a save text document notification\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#didSaveTextDocumentParams\ntype DidSaveTextDocumentParams struct {\n\t// The document that was saved.\n\tTextDocument TextDocumentIdentifier `json:\"textDocument\"`\n\t// Optional the content when saved. Depends on the includeText value\n\t// when the save notification was requested.\n\tText *string `json:\"text,omitempty\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentColorClientCapabilities\ntype DocumentColorClientCapabilities struct {\n\t// Whether implementation supports dynamic registration. If this is set to `true`\n\t// the client supports the new `DocumentColorRegistrationOptions` return value\n\t// for the corresponding server capability as well.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentColorOptions\ntype DocumentColorOptions struct {\n\tWorkDoneProgressOptions\n}\n\n// Parameters for a {@link DocumentColorRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentColorParams\ntype DocumentColorParams struct {\n\t// The text document.\n\tTextDocument TextDocumentIdentifier `json:\"textDocument\"`\n\tWorkDoneProgressParams\n\tPartialResultParams\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentColorRegistrationOptions\ntype DocumentColorRegistrationOptions struct {\n\tTextDocumentRegistrationOptions\n\tDocumentColorOptions\n\tStaticRegistrationOptions\n}\n\n// Parameters of the document diagnostic request.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentDiagnosticParams\ntype DocumentDiagnosticParams struct {\n\t// The text document.\n\tTextDocument TextDocumentIdentifier `json:\"textDocument\"`\n\t// The additional identifier provided during registration.\n\tIdentifier string `json:\"identifier,omitempty\"`\n\t// The result id of a previous response if provided.\n\tPreviousResultID string `json:\"previousResultId,omitempty\"`\n\tWorkDoneProgressParams\n\tPartialResultParams\n}\n\n// The result of a document diagnostic pull request. A report can\n// either be a full report containing all diagnostics for the\n// requested document or an unchanged report indicating that nothing\n// has changed in terms of diagnostics in comparison to the last\n// pull request.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentDiagnosticReport\ntype DocumentDiagnosticReport = Or_DocumentDiagnosticReport // (alias)\n// The document diagnostic report kinds.\n//\n// @since 3.17.0\ntype DocumentDiagnosticReportKind string\n\n// A partial result for a document diagnostic report.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentDiagnosticReportPartialResult\ntype DocumentDiagnosticReportPartialResult struct {\n\tRelatedDocuments map[DocumentUri]interface{} `json:\"relatedDocuments\"`\n}\n\n// A document filter describes a top level text document or\n// a notebook cell document.\n//\n// @since 3.17.0 - proposed support for NotebookCellTextDocumentFilter.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentFilter\ntype DocumentFilter = Or_DocumentFilter // (alias)\n// Client capabilities of a {@link DocumentFormattingRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentFormattingClientCapabilities\ntype DocumentFormattingClientCapabilities struct {\n\t// Whether formatting supports dynamic registration.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n}\n\n// Provider options for a {@link DocumentFormattingRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentFormattingOptions\ntype DocumentFormattingOptions struct {\n\tWorkDoneProgressOptions\n}\n\n// The parameters of a {@link DocumentFormattingRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentFormattingParams\ntype DocumentFormattingParams struct {\n\t// The document to format.\n\tTextDocument TextDocumentIdentifier `json:\"textDocument\"`\n\t// The format options.\n\tOptions FormattingOptions `json:\"options\"`\n\tWorkDoneProgressParams\n}\n\n// Registration options for a {@link DocumentFormattingRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentFormattingRegistrationOptions\ntype DocumentFormattingRegistrationOptions struct {\n\tTextDocumentRegistrationOptions\n\tDocumentFormattingOptions\n}\n\n// A document highlight is a range inside a text document which deserves\n// special attention. Usually a document highlight is visualized by changing\n// the background color of its range.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentHighlight\ntype DocumentHighlight struct {\n\t// The range this highlight applies to.\n\tRange Range `json:\"range\"`\n\t// The highlight kind, default is {@link DocumentHighlightKind.Text text}.\n\tKind DocumentHighlightKind `json:\"kind,omitempty\"`\n}\n\n// Client Capabilities for a {@link DocumentHighlightRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentHighlightClientCapabilities\ntype DocumentHighlightClientCapabilities struct {\n\t// Whether document highlight supports dynamic registration.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n}\n\n// A document highlight kind.\ntype DocumentHighlightKind uint32\n\n// Provider options for a {@link DocumentHighlightRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentHighlightOptions\ntype DocumentHighlightOptions struct {\n\tWorkDoneProgressOptions\n}\n\n// Parameters for a {@link DocumentHighlightRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentHighlightParams\ntype DocumentHighlightParams struct {\n\tTextDocumentPositionParams\n\tWorkDoneProgressParams\n\tPartialResultParams\n}\n\n// Registration options for a {@link DocumentHighlightRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentHighlightRegistrationOptions\ntype DocumentHighlightRegistrationOptions struct {\n\tTextDocumentRegistrationOptions\n\tDocumentHighlightOptions\n}\n\n// A document link is a range in a text document that links to an internal or external resource, like another\n// text document or a web site.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentLink\ntype DocumentLink struct {\n\t// The range this link applies to.\n\tRange Range `json:\"range\"`\n\t// The uri this link points to. If missing a resolve request is sent later.\n\tTarget *URI `json:\"target,omitempty\"`\n\t// The tooltip text when you hover over this link.\n\t//\n\t// If a tooltip is provided, is will be displayed in a string that includes instructions on how to\n\t// trigger the link, such as `{0} (ctrl + click)`. The specific instructions vary depending on OS,\n\t// user settings, and localization.\n\t//\n\t// @since 3.15.0\n\tTooltip string `json:\"tooltip,omitempty\"`\n\t// A data entry field that is preserved on a document link between a\n\t// DocumentLinkRequest and a DocumentLinkResolveRequest.\n\tData interface{} `json:\"data,omitempty\"`\n}\n\n// The client capabilities of a {@link DocumentLinkRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentLinkClientCapabilities\ntype DocumentLinkClientCapabilities struct {\n\t// Whether document link supports dynamic registration.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n\t// Whether the client supports the `tooltip` property on `DocumentLink`.\n\t//\n\t// @since 3.15.0\n\tTooltipSupport bool `json:\"tooltipSupport,omitempty\"`\n}\n\n// Provider options for a {@link DocumentLinkRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentLinkOptions\ntype DocumentLinkOptions struct {\n\t// Document links have a resolve provider as well.\n\tResolveProvider bool `json:\"resolveProvider,omitempty\"`\n\tWorkDoneProgressOptions\n}\n\n// The parameters of a {@link DocumentLinkRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentLinkParams\ntype DocumentLinkParams struct {\n\t// The document to provide document links for.\n\tTextDocument TextDocumentIdentifier `json:\"textDocument\"`\n\tWorkDoneProgressParams\n\tPartialResultParams\n}\n\n// Registration options for a {@link DocumentLinkRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentLinkRegistrationOptions\ntype DocumentLinkRegistrationOptions struct {\n\tTextDocumentRegistrationOptions\n\tDocumentLinkOptions\n}\n\n// Client capabilities of a {@link DocumentOnTypeFormattingRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentOnTypeFormattingClientCapabilities\ntype DocumentOnTypeFormattingClientCapabilities struct {\n\t// Whether on type formatting supports dynamic registration.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n}\n\n// Provider options for a {@link DocumentOnTypeFormattingRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentOnTypeFormattingOptions\ntype DocumentOnTypeFormattingOptions struct {\n\t// A character on which formatting should be triggered, like `{`.\n\tFirstTriggerCharacter string `json:\"firstTriggerCharacter\"`\n\t// More trigger characters.\n\tMoreTriggerCharacter []string `json:\"moreTriggerCharacter,omitempty\"`\n}\n\n// The parameters of a {@link DocumentOnTypeFormattingRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentOnTypeFormattingParams\ntype DocumentOnTypeFormattingParams struct {\n\t// The document to format.\n\tTextDocument TextDocumentIdentifier `json:\"textDocument\"`\n\t// The position around which the on type formatting should happen.\n\t// This is not necessarily the exact position where the character denoted\n\t// by the property `ch` got typed.\n\tPosition Position `json:\"position\"`\n\t// The character that has been typed that triggered the formatting\n\t// on type request. That is not necessarily the last character that\n\t// got inserted into the document since the client could auto insert\n\t// characters as well (e.g. like automatic brace completion).\n\tCh string `json:\"ch\"`\n\t// The formatting options.\n\tOptions FormattingOptions `json:\"options\"`\n}\n\n// Registration options for a {@link DocumentOnTypeFormattingRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentOnTypeFormattingRegistrationOptions\ntype DocumentOnTypeFormattingRegistrationOptions struct {\n\tTextDocumentRegistrationOptions\n\tDocumentOnTypeFormattingOptions\n}\n\n// Client capabilities of a {@link DocumentRangeFormattingRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentRangeFormattingClientCapabilities\ntype DocumentRangeFormattingClientCapabilities struct {\n\t// Whether range formatting supports dynamic registration.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n\t// Whether the client supports formatting multiple ranges at once.\n\t//\n\t// @since 3.18.0\n\t// @proposed\n\tRangesSupport bool `json:\"rangesSupport,omitempty\"`\n}\n\n// Provider options for a {@link DocumentRangeFormattingRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentRangeFormattingOptions\ntype DocumentRangeFormattingOptions struct {\n\t// Whether the server supports formatting multiple ranges at once.\n\t//\n\t// @since 3.18.0\n\t// @proposed\n\tRangesSupport bool `json:\"rangesSupport,omitempty\"`\n\tWorkDoneProgressOptions\n}\n\n// The parameters of a {@link DocumentRangeFormattingRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentRangeFormattingParams\ntype DocumentRangeFormattingParams struct {\n\t// The document to format.\n\tTextDocument TextDocumentIdentifier `json:\"textDocument\"`\n\t// The range to format\n\tRange Range `json:\"range\"`\n\t// The format options\n\tOptions FormattingOptions `json:\"options\"`\n\tWorkDoneProgressParams\n}\n\n// Registration options for a {@link DocumentRangeFormattingRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentRangeFormattingRegistrationOptions\ntype DocumentRangeFormattingRegistrationOptions struct {\n\tTextDocumentRegistrationOptions\n\tDocumentRangeFormattingOptions\n}\n\n// The parameters of a {@link DocumentRangesFormattingRequest}.\n//\n// @since 3.18.0\n// @proposed\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentRangesFormattingParams\ntype DocumentRangesFormattingParams struct {\n\t// The document to format.\n\tTextDocument TextDocumentIdentifier `json:\"textDocument\"`\n\t// The ranges to format\n\tRanges []Range `json:\"ranges\"`\n\t// The format options\n\tOptions FormattingOptions `json:\"options\"`\n\tWorkDoneProgressParams\n}\n\n// A document selector is the combination of one or many document filters.\n//\n// @sample `let sel:DocumentSelector = [{ language: 'typescript' }, { language: 'json', pattern: '**∕tsconfig.json' }]`;\n//\n// The use of a string as a document filter is deprecated @since 3.16.0.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentSelector\ntype DocumentSelector = []DocumentFilter // (alias)\n// Represents programming constructs like variables, classes, interfaces etc.\n// that appear in a document. Document symbols can be hierarchical and they\n// have two ranges: one that encloses its definition and one that points to\n// its most interesting range, e.g. the range of an identifier.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentSymbol\ntype DocumentSymbol struct {\n\t// The name of this symbol. Will be displayed in the user interface and therefore must not be\n\t// an empty string or a string only consisting of white spaces.\n\tName string `json:\"name\"`\n\t// More detail for this symbol, e.g the signature of a function.\n\tDetail string `json:\"detail,omitempty\"`\n\t// The kind of this symbol.\n\tKind SymbolKind `json:\"kind\"`\n\t// Tags for this document symbol.\n\t//\n\t// @since 3.16.0\n\tTags []SymbolTag `json:\"tags,omitempty\"`\n\t// Indicates if this symbol is deprecated.\n\t//\n\t// @deprecated Use tags instead\n\tDeprecated bool `json:\"deprecated,omitempty\"`\n\t// The range enclosing this symbol not including leading/trailing whitespace but everything else\n\t// like comments. This information is typically used to determine if the clients cursor is\n\t// inside the symbol to reveal in the symbol in the UI.\n\tRange Range `json:\"range\"`\n\t// The range that should be selected and revealed when this symbol is being picked, e.g the name of a function.\n\t// Must be contained by the `range`.\n\tSelectionRange Range `json:\"selectionRange\"`\n\t// Children of this symbol, e.g. properties of a class.\n\tChildren []DocumentSymbol `json:\"children,omitempty\"`\n}\n\n// Client Capabilities for a {@link DocumentSymbolRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentSymbolClientCapabilities\ntype DocumentSymbolClientCapabilities struct {\n\t// Whether document symbol supports dynamic registration.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n\t// Specific capabilities for the `SymbolKind` in the\n\t// `textDocument/documentSymbol` request.\n\tSymbolKind *ClientSymbolKindOptions `json:\"symbolKind,omitempty\"`\n\t// The client supports hierarchical document symbols.\n\tHierarchicalDocumentSymbolSupport bool `json:\"hierarchicalDocumentSymbolSupport,omitempty\"`\n\t// The client supports tags on `SymbolInformation`. Tags are supported on\n\t// `DocumentSymbol` if `hierarchicalDocumentSymbolSupport` is set to true.\n\t// Clients supporting tags have to handle unknown tags gracefully.\n\t//\n\t// @since 3.16.0\n\tTagSupport *ClientSymbolTagOptions `json:\"tagSupport,omitempty\"`\n\t// The client supports an additional label presented in the UI when\n\t// registering a document symbol provider.\n\t//\n\t// @since 3.16.0\n\tLabelSupport bool `json:\"labelSupport,omitempty\"`\n}\n\n// Provider options for a {@link DocumentSymbolRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentSymbolOptions\ntype DocumentSymbolOptions struct {\n\t// A human-readable string that is shown when multiple outlines trees\n\t// are shown for the same document.\n\t//\n\t// @since 3.16.0\n\tLabel string `json:\"label,omitempty\"`\n\tWorkDoneProgressOptions\n}\n\n// Parameters for a {@link DocumentSymbolRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentSymbolParams\ntype DocumentSymbolParams struct {\n\t// The text document.\n\tTextDocument TextDocumentIdentifier `json:\"textDocument\"`\n\tWorkDoneProgressParams\n\tPartialResultParams\n}\n\n// Registration options for a {@link DocumentSymbolRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentSymbolRegistrationOptions\ntype DocumentSymbolRegistrationOptions struct {\n\tTextDocumentRegistrationOptions\n\tDocumentSymbolOptions\n}\n\n// Edit range variant that includes ranges for insert and replace operations.\n//\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#editRangeWithInsertReplace\ntype EditRangeWithInsertReplace struct {\n\tInsert Range `json:\"insert\"`\n\tReplace Range `json:\"replace\"`\n}\n\n// Predefined error codes.\ntype ErrorCodes int32\n\n// The client capabilities of a {@link ExecuteCommandRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#executeCommandClientCapabilities\ntype ExecuteCommandClientCapabilities struct {\n\t// Execute command supports dynamic registration.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n}\n\n// The server capabilities of a {@link ExecuteCommandRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#executeCommandOptions\ntype ExecuteCommandOptions struct {\n\t// The commands to be executed on the server\n\tCommands []string `json:\"commands\"`\n\tWorkDoneProgressOptions\n}\n\n// The parameters of a {@link ExecuteCommandRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#executeCommandParams\ntype ExecuteCommandParams struct {\n\t// The identifier of the actual command handler.\n\tCommand string `json:\"command\"`\n\t// Arguments that the command should be invoked with.\n\tArguments []json.RawMessage `json:\"arguments,omitempty\"`\n\tWorkDoneProgressParams\n}\n\n// Registration options for a {@link ExecuteCommandRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#executeCommandRegistrationOptions\ntype ExecuteCommandRegistrationOptions struct {\n\tExecuteCommandOptions\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#executionSummary\ntype ExecutionSummary struct {\n\t// A strict monotonically increasing value\n\t// indicating the execution order of a cell\n\t// inside a notebook.\n\tExecutionOrder uint32 `json:\"executionOrder\"`\n\t// Whether the execution was successful or\n\t// not if known by the client.\n\tSuccess bool `json:\"success,omitempty\"`\n}\ntype FailureHandlingKind string\n\n// The file event type\ntype FileChangeType uint32\n\n// Represents information on a file/folder create.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#fileCreate\ntype FileCreate struct {\n\t// A file:// URI for the location of the file/folder being created.\n\tURI string `json:\"uri\"`\n}\n\n// Represents information on a file/folder delete.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#fileDelete\ntype FileDelete struct {\n\t// A file:// URI for the location of the file/folder being deleted.\n\tURI string `json:\"uri\"`\n}\n\n// An event describing a file change.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#fileEvent\ntype FileEvent struct {\n\t// The file's uri.\n\tURI DocumentUri `json:\"uri\"`\n\t// The change type.\n\tType FileChangeType `json:\"type\"`\n}\n\n// Capabilities relating to events from file operations by the user in the client.\n//\n// These events do not come from the file system, they come from user operations\n// like renaming a file in the UI.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#fileOperationClientCapabilities\ntype FileOperationClientCapabilities struct {\n\t// Whether the client supports dynamic registration for file requests/notifications.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n\t// The client has support for sending didCreateFiles notifications.\n\tDidCreate bool `json:\"didCreate,omitempty\"`\n\t// The client has support for sending willCreateFiles requests.\n\tWillCreate bool `json:\"willCreate,omitempty\"`\n\t// The client has support for sending didRenameFiles notifications.\n\tDidRename bool `json:\"didRename,omitempty\"`\n\t// The client has support for sending willRenameFiles requests.\n\tWillRename bool `json:\"willRename,omitempty\"`\n\t// The client has support for sending didDeleteFiles notifications.\n\tDidDelete bool `json:\"didDelete,omitempty\"`\n\t// The client has support for sending willDeleteFiles requests.\n\tWillDelete bool `json:\"willDelete,omitempty\"`\n}\n\n// A filter to describe in which file operation requests or notifications\n// the server is interested in receiving.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#fileOperationFilter\ntype FileOperationFilter struct {\n\t// A Uri scheme like `file` or `untitled`.\n\tScheme string `json:\"scheme,omitempty\"`\n\t// The actual file operation pattern.\n\tPattern FileOperationPattern `json:\"pattern\"`\n}\n\n// Options for notifications/requests for user operations on files.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#fileOperationOptions\ntype FileOperationOptions struct {\n\t// The server is interested in receiving didCreateFiles notifications.\n\tDidCreate *FileOperationRegistrationOptions `json:\"didCreate,omitempty\"`\n\t// The server is interested in receiving willCreateFiles requests.\n\tWillCreate *FileOperationRegistrationOptions `json:\"willCreate,omitempty\"`\n\t// The server is interested in receiving didRenameFiles notifications.\n\tDidRename *FileOperationRegistrationOptions `json:\"didRename,omitempty\"`\n\t// The server is interested in receiving willRenameFiles requests.\n\tWillRename *FileOperationRegistrationOptions `json:\"willRename,omitempty\"`\n\t// The server is interested in receiving didDeleteFiles file notifications.\n\tDidDelete *FileOperationRegistrationOptions `json:\"didDelete,omitempty\"`\n\t// The server is interested in receiving willDeleteFiles file requests.\n\tWillDelete *FileOperationRegistrationOptions `json:\"willDelete,omitempty\"`\n}\n\n// A pattern to describe in which file operation requests or notifications\n// the server is interested in receiving.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#fileOperationPattern\ntype FileOperationPattern struct {\n\t// The glob pattern to match. Glob patterns can have the following syntax:\n\t//\n\t// - `*` to match one or more characters in a path segment\n\t// - `?` to match on one character in a path segment\n\t// - `**` to match any number of path segments, including none\n\t// - `{}` to group sub patterns into an OR expression. (e.g. `**/*.{ts,js}` matches all TypeScript and JavaScript files)\n\t// - `[]` to declare a range of characters to match in a path segment (e.g., `example.[0-9]` to match on `example.0`, `example.1`, …)\n\t// - `[!...]` to negate a range of characters to match in a path segment (e.g., `example.[!0-9]` to match on `example.a`, `example.b`, but not `example.0`)\n\tGlob string `json:\"glob\"`\n\t// Whether to match files or folders with this pattern.\n\t//\n\t// Matches both if undefined.\n\tMatches *FileOperationPatternKind `json:\"matches,omitempty\"`\n\t// Additional options used during matching.\n\tOptions *FileOperationPatternOptions `json:\"options,omitempty\"`\n}\n\n// A pattern kind describing if a glob pattern matches a file a folder or\n// both.\n//\n// @since 3.16.0\ntype FileOperationPatternKind string\n\n// Matching options for the file operation pattern.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#fileOperationPatternOptions\ntype FileOperationPatternOptions struct {\n\t// The pattern should be matched ignoring casing.\n\tIgnoreCase bool `json:\"ignoreCase,omitempty\"`\n}\n\n// The options to register for file operations.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#fileOperationRegistrationOptions\ntype FileOperationRegistrationOptions struct {\n\t// The actual filters.\n\tFilters []FileOperationFilter `json:\"filters\"`\n}\n\n// Represents information on a file/folder rename.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#fileRename\ntype FileRename struct {\n\t// A file:// URI for the original location of the file/folder being renamed.\n\tOldURI string `json:\"oldUri\"`\n\t// A file:// URI for the new location of the file/folder being renamed.\n\tNewURI string `json:\"newUri\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#fileSystemWatcher\ntype FileSystemWatcher struct {\n\t// The glob pattern to watch. See {@link GlobPattern glob pattern} for more detail.\n\t//\n\t// @since 3.17.0 support for relative patterns.\n\tGlobPattern GlobPattern `json:\"globPattern\"`\n\t// The kind of events of interest. If omitted it defaults\n\t// to WatchKind.Create | WatchKind.Change | WatchKind.Delete\n\t// which is 7.\n\tKind *WatchKind `json:\"kind,omitempty\"`\n}\n\n// Represents a folding range. To be valid, start and end line must be bigger than zero and smaller\n// than the number of lines in the document. Clients are free to ignore invalid ranges.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#foldingRange\ntype FoldingRange struct {\n\t// The zero-based start line of the range to fold. The folded area starts after the line's last character.\n\t// To be valid, the end must be zero or larger and smaller than the number of lines in the document.\n\tStartLine uint32 `json:\"startLine\"`\n\t// The zero-based character offset from where the folded range starts. If not defined, defaults to the length of the start line.\n\tStartCharacter uint32 `json:\"startCharacter,omitempty\"`\n\t// The zero-based end line of the range to fold. The folded area ends with the line's last character.\n\t// To be valid, the end must be zero or larger and smaller than the number of lines in the document.\n\tEndLine uint32 `json:\"endLine\"`\n\t// The zero-based character offset before the folded range ends. If not defined, defaults to the length of the end line.\n\tEndCharacter uint32 `json:\"endCharacter,omitempty\"`\n\t// Describes the kind of the folding range such as 'comment' or 'region'. The kind\n\t// is used to categorize folding ranges and used by commands like 'Fold all comments'.\n\t// See {@link FoldingRangeKind} for an enumeration of standardized kinds.\n\tKind string `json:\"kind,omitempty\"`\n\t// The text that the client should show when the specified range is\n\t// collapsed. If not defined or not supported by the client, a default\n\t// will be chosen by the client.\n\t//\n\t// @since 3.17.0\n\tCollapsedText string `json:\"collapsedText,omitempty\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#foldingRangeClientCapabilities\ntype FoldingRangeClientCapabilities struct {\n\t// Whether implementation supports dynamic registration for folding range\n\t// providers. If this is set to `true` the client supports the new\n\t// `FoldingRangeRegistrationOptions` return value for the corresponding\n\t// server capability as well.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n\t// The maximum number of folding ranges that the client prefers to receive\n\t// per document. The value serves as a hint, servers are free to follow the\n\t// limit.\n\tRangeLimit uint32 `json:\"rangeLimit,omitempty\"`\n\t// If set, the client signals that it only supports folding complete lines.\n\t// If set, client will ignore specified `startCharacter` and `endCharacter`\n\t// properties in a FoldingRange.\n\tLineFoldingOnly bool `json:\"lineFoldingOnly,omitempty\"`\n\t// Specific options for the folding range kind.\n\t//\n\t// @since 3.17.0\n\tFoldingRangeKind *ClientFoldingRangeKindOptions `json:\"foldingRangeKind,omitempty\"`\n\t// Specific options for the folding range.\n\t//\n\t// @since 3.17.0\n\tFoldingRange *ClientFoldingRangeOptions `json:\"foldingRange,omitempty\"`\n}\n\n// A set of predefined range kinds.\ntype FoldingRangeKind string\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#foldingRangeOptions\ntype FoldingRangeOptions struct {\n\tWorkDoneProgressOptions\n}\n\n// Parameters for a {@link FoldingRangeRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#foldingRangeParams\ntype FoldingRangeParams struct {\n\t// The text document.\n\tTextDocument TextDocumentIdentifier `json:\"textDocument\"`\n\tWorkDoneProgressParams\n\tPartialResultParams\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#foldingRangeRegistrationOptions\ntype FoldingRangeRegistrationOptions struct {\n\tTextDocumentRegistrationOptions\n\tFoldingRangeOptions\n\tStaticRegistrationOptions\n}\n\n// Client workspace capabilities specific to folding ranges\n//\n// @since 3.18.0\n// @proposed\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#foldingRangeWorkspaceClientCapabilities\ntype FoldingRangeWorkspaceClientCapabilities struct {\n\t// Whether the client implementation supports a refresh request sent from the\n\t// server to the client.\n\t//\n\t// Note that this event is global and will force the client to refresh all\n\t// folding ranges currently shown. It should be used with absolute care and is\n\t// useful for situation where a server for example detects a project wide\n\t// change that requires such a calculation.\n\t//\n\t// @since 3.18.0\n\t// @proposed\n\tRefreshSupport bool `json:\"refreshSupport,omitempty\"`\n}\n\n// Value-object describing what options formatting should use.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#formattingOptions\ntype FormattingOptions struct {\n\t// Size of a tab in spaces.\n\tTabSize uint32 `json:\"tabSize\"`\n\t// Prefer spaces over tabs.\n\tInsertSpaces bool `json:\"insertSpaces\"`\n\t// Trim trailing whitespace on a line.\n\t//\n\t// @since 3.15.0\n\tTrimTrailingWhitespace bool `json:\"trimTrailingWhitespace,omitempty\"`\n\t// Insert a newline character at the end of the file if one does not exist.\n\t//\n\t// @since 3.15.0\n\tInsertFinalNewline bool `json:\"insertFinalNewline,omitempty\"`\n\t// Trim all newlines after the final newline at the end of the file.\n\t//\n\t// @since 3.15.0\n\tTrimFinalNewlines bool `json:\"trimFinalNewlines,omitempty\"`\n}\n\n// A diagnostic report with a full set of problems.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#fullDocumentDiagnosticReport\ntype FullDocumentDiagnosticReport struct {\n\t// A full document diagnostic report.\n\tKind string `json:\"kind\"`\n\t// An optional result id. If provided it will\n\t// be sent on the next diagnostic request for the\n\t// same document.\n\tResultID string `json:\"resultId,omitempty\"`\n\t// The actual items.\n\tItems []Diagnostic `json:\"items\"`\n}\n\n// General client capabilities.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#generalClientCapabilities\ntype GeneralClientCapabilities struct {\n\t// Client capability that signals how the client\n\t// handles stale requests (e.g. a request\n\t// for which the client will not process the response\n\t// anymore since the information is outdated).\n\t//\n\t// @since 3.17.0\n\tStaleRequestSupport *StaleRequestSupportOptions `json:\"staleRequestSupport,omitempty\"`\n\t// Client capabilities specific to regular expressions.\n\t//\n\t// @since 3.16.0\n\tRegularExpressions *RegularExpressionsClientCapabilities `json:\"regularExpressions,omitempty\"`\n\t// Client capabilities specific to the client's markdown parser.\n\t//\n\t// @since 3.16.0\n\tMarkdown *MarkdownClientCapabilities `json:\"markdown,omitempty\"`\n\t// The position encodings supported by the client. Client and server\n\t// have to agree on the same position encoding to ensure that offsets\n\t// (e.g. character position in a line) are interpreted the same on both\n\t// sides.\n\t//\n\t// To keep the protocol backwards compatible the following applies: if\n\t// the value 'utf-16' is missing from the array of position encodings\n\t// servers can assume that the client supports UTF-16. UTF-16 is\n\t// therefore a mandatory encoding.\n\t//\n\t// If omitted it defaults to ['utf-16'].\n\t//\n\t// Implementation considerations: since the conversion from one encoding\n\t// into another requires the content of the file / line the conversion\n\t// is best done where the file is read which is usually on the server\n\t// side.\n\t//\n\t// @since 3.17.0\n\tPositionEncodings []PositionEncodingKind `json:\"positionEncodings,omitempty\"`\n}\n\n// The glob pattern. Either a string pattern or a relative pattern.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#globPattern\ntype GlobPattern = Or_GlobPattern // (alias)\n// The result of a hover request.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#hover\ntype Hover struct {\n\t// The hover's content\n\tContents MarkupContent `json:\"contents\"`\n\t// An optional range inside the text document that is used to\n\t// visualize the hover, e.g. by changing the background color.\n\tRange Range `json:\"range,omitempty\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#hoverClientCapabilities\ntype HoverClientCapabilities struct {\n\t// Whether hover supports dynamic registration.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n\t// Client supports the following content formats for the content\n\t// property. The order describes the preferred format of the client.\n\tContentFormat []MarkupKind `json:\"contentFormat,omitempty\"`\n}\n\n// Hover options.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#hoverOptions\ntype HoverOptions struct {\n\tWorkDoneProgressOptions\n}\n\n// Parameters for a {@link HoverRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#hoverParams\ntype HoverParams struct {\n\tTextDocumentPositionParams\n\tWorkDoneProgressParams\n}\n\n// Registration options for a {@link HoverRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#hoverRegistrationOptions\ntype HoverRegistrationOptions struct {\n\tTextDocumentRegistrationOptions\n\tHoverOptions\n}\n\n// @since 3.6.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#implementationClientCapabilities\ntype ImplementationClientCapabilities struct {\n\t// Whether implementation supports dynamic registration. If this is set to `true`\n\t// the client supports the new `ImplementationRegistrationOptions` return value\n\t// for the corresponding server capability as well.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n\t// The client supports additional metadata in the form of definition links.\n\t//\n\t// @since 3.14.0\n\tLinkSupport bool `json:\"linkSupport,omitempty\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#implementationOptions\ntype ImplementationOptions struct {\n\tWorkDoneProgressOptions\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#implementationParams\ntype ImplementationParams struct {\n\tTextDocumentPositionParams\n\tWorkDoneProgressParams\n\tPartialResultParams\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#implementationRegistrationOptions\ntype ImplementationRegistrationOptions struct {\n\tTextDocumentRegistrationOptions\n\tImplementationOptions\n\tStaticRegistrationOptions\n}\n\n// The data type of the ResponseError if the\n// initialize request fails.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#initializeError\ntype InitializeError struct {\n\t// Indicates whether the client execute the following retry logic:\n\t// (1) show the message provided by the ResponseError to the user\n\t// (2) user selects retry or cancel\n\t// (3) if user selected retry the initialize method is sent again.\n\tRetry bool `json:\"retry\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#initializeParams\ntype InitializeParams struct {\n\tXInitializeParams\n\tWorkspaceFoldersInitializeParams\n}\n\n// The result returned from an initialize request.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#initializeResult\ntype InitializeResult struct {\n\t// The capabilities the language server provides.\n\tCapabilities ServerCapabilities `json:\"capabilities\"`\n\t// Information about the server.\n\t//\n\t// @since 3.15.0\n\tServerInfo *ServerInfo `json:\"serverInfo,omitempty\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#initializedParams\ntype InitializedParams struct {\n}\n\n// Inlay hint information.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#inlayHint\ntype InlayHint struct {\n\t// The position of this hint.\n\t//\n\t// If multiple hints have the same position, they will be shown in the order\n\t// they appear in the response.\n\tPosition Position `json:\"position\"`\n\t// The label of this hint. A human readable string or an array of\n\t// InlayHintLabelPart label parts.\n\t//\n\t// *Note* that neither the string nor the label part can be empty.\n\tLabel []InlayHintLabelPart `json:\"label\"`\n\t// The kind of this hint. Can be omitted in which case the client\n\t// should fall back to a reasonable default.\n\tKind InlayHintKind `json:\"kind,omitempty\"`\n\t// Optional text edits that are performed when accepting this inlay hint.\n\t//\n\t// *Note* that edits are expected to change the document so that the inlay\n\t// hint (or its nearest variant) is now part of the document and the inlay\n\t// hint itself is now obsolete.\n\tTextEdits []TextEdit `json:\"textEdits,omitempty\"`\n\t// The tooltip text when you hover over this item.\n\tTooltip *Or_InlayHint_tooltip `json:\"tooltip,omitempty\"`\n\t// Render padding before the hint.\n\t//\n\t// Note: Padding should use the editor's background color, not the\n\t// background color of the hint itself. That means padding can be used\n\t// to visually align/separate an inlay hint.\n\tPaddingLeft bool `json:\"paddingLeft,omitempty\"`\n\t// Render padding after the hint.\n\t//\n\t// Note: Padding should use the editor's background color, not the\n\t// background color of the hint itself. That means padding can be used\n\t// to visually align/separate an inlay hint.\n\tPaddingRight bool `json:\"paddingRight,omitempty\"`\n\t// A data entry field that is preserved on an inlay hint between\n\t// a `textDocument/inlayHint` and a `inlayHint/resolve` request.\n\tData interface{} `json:\"data,omitempty\"`\n}\n\n// Inlay hint client capabilities.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#inlayHintClientCapabilities\ntype InlayHintClientCapabilities struct {\n\t// Whether inlay hints support dynamic registration.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n\t// Indicates which properties a client can resolve lazily on an inlay\n\t// hint.\n\tResolveSupport *ClientInlayHintResolveOptions `json:\"resolveSupport,omitempty\"`\n}\n\n// Inlay hint kinds.\n//\n// @since 3.17.0\ntype InlayHintKind uint32\n\n// An inlay hint label part allows for interactive and composite labels\n// of inlay hints.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#inlayHintLabelPart\ntype InlayHintLabelPart struct {\n\t// The value of this label part.\n\tValue string `json:\"value\"`\n\t// The tooltip text when you hover over this label part. Depending on\n\t// the client capability `inlayHint.resolveSupport` clients might resolve\n\t// this property late using the resolve request.\n\tTooltip *Or_InlayHintLabelPart_tooltip `json:\"tooltip,omitempty\"`\n\t// An optional source code location that represents this\n\t// label part.\n\t//\n\t// The editor will use this location for the hover and for code navigation\n\t// features: This part will become a clickable link that resolves to the\n\t// definition of the symbol at the given location (not necessarily the\n\t// location itself), it shows the hover that shows at the given location,\n\t// and it shows a context menu with further code navigation commands.\n\t//\n\t// Depending on the client capability `inlayHint.resolveSupport` clients\n\t// might resolve this property late using the resolve request.\n\tLocation *Location `json:\"location,omitempty\"`\n\t// An optional command for this label part.\n\t//\n\t// Depending on the client capability `inlayHint.resolveSupport` clients\n\t// might resolve this property late using the resolve request.\n\tCommand *Command `json:\"command,omitempty\"`\n}\n\n// Inlay hint options used during static registration.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#inlayHintOptions\ntype InlayHintOptions struct {\n\t// The server provides support to resolve additional\n\t// information for an inlay hint item.\n\tResolveProvider bool `json:\"resolveProvider,omitempty\"`\n\tWorkDoneProgressOptions\n}\n\n// A parameter literal used in inlay hint requests.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#inlayHintParams\ntype InlayHintParams struct {\n\t// The text document.\n\tTextDocument TextDocumentIdentifier `json:\"textDocument\"`\n\t// The document range for which inlay hints should be computed.\n\tRange Range `json:\"range\"`\n\tWorkDoneProgressParams\n}\n\n// Inlay hint options used during static or dynamic registration.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#inlayHintRegistrationOptions\ntype InlayHintRegistrationOptions struct {\n\tInlayHintOptions\n\tTextDocumentRegistrationOptions\n\tStaticRegistrationOptions\n}\n\n// Client workspace capabilities specific to inlay hints.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#inlayHintWorkspaceClientCapabilities\ntype InlayHintWorkspaceClientCapabilities struct {\n\t// Whether the client implementation supports a refresh request sent from\n\t// the server to the client.\n\t//\n\t// Note that this event is global and will force the client to refresh all\n\t// inlay hints currently shown. It should be used with absolute care and\n\t// is useful for situation where a server for example detects a project wide\n\t// change that requires such a calculation.\n\tRefreshSupport bool `json:\"refreshSupport,omitempty\"`\n}\n\n// Client capabilities specific to inline completions.\n//\n// @since 3.18.0\n// @proposed\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#inlineCompletionClientCapabilities\ntype InlineCompletionClientCapabilities struct {\n\t// Whether implementation supports dynamic registration for inline completion providers.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n}\n\n// Provides information about the context in which an inline completion was requested.\n//\n// @since 3.18.0\n// @proposed\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#inlineCompletionContext\ntype InlineCompletionContext struct {\n\t// Describes how the inline completion was triggered.\n\tTriggerKind InlineCompletionTriggerKind `json:\"triggerKind\"`\n\t// Provides information about the currently selected item in the autocomplete widget if it is visible.\n\tSelectedCompletionInfo *SelectedCompletionInfo `json:\"selectedCompletionInfo,omitempty\"`\n}\n\n// An inline completion item represents a text snippet that is proposed inline to complete text that is being typed.\n//\n// @since 3.18.0\n// @proposed\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#inlineCompletionItem\ntype InlineCompletionItem struct {\n\t// The text to replace the range with. Must be set.\n\tInsertText Or_InlineCompletionItem_insertText `json:\"insertText\"`\n\t// A text that is used to decide if this inline completion should be shown. When `falsy` the {@link InlineCompletionItem.insertText} is used.\n\tFilterText string `json:\"filterText,omitempty\"`\n\t// The range to replace. Must begin and end on the same line.\n\tRange *Range `json:\"range,omitempty\"`\n\t// An optional {@link Command} that is executed *after* inserting this completion.\n\tCommand *Command `json:\"command,omitempty\"`\n}\n\n// Represents a collection of {@link InlineCompletionItem inline completion items} to be presented in the editor.\n//\n// @since 3.18.0\n// @proposed\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#inlineCompletionList\ntype InlineCompletionList struct {\n\t// The inline completion items\n\tItems []InlineCompletionItem `json:\"items\"`\n}\n\n// Inline completion options used during static registration.\n//\n// @since 3.18.0\n// @proposed\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#inlineCompletionOptions\ntype InlineCompletionOptions struct {\n\tWorkDoneProgressOptions\n}\n\n// A parameter literal used in inline completion requests.\n//\n// @since 3.18.0\n// @proposed\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#inlineCompletionParams\ntype InlineCompletionParams struct {\n\t// Additional information about the context in which inline completions were\n\t// requested.\n\tContext InlineCompletionContext `json:\"context\"`\n\tTextDocumentPositionParams\n\tWorkDoneProgressParams\n}\n\n// Inline completion options used during static or dynamic registration.\n//\n// @since 3.18.0\n// @proposed\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#inlineCompletionRegistrationOptions\ntype InlineCompletionRegistrationOptions struct {\n\tInlineCompletionOptions\n\tTextDocumentRegistrationOptions\n\tStaticRegistrationOptions\n}\n\n// Describes how an {@link InlineCompletionItemProvider inline completion provider} was triggered.\n//\n// @since 3.18.0\n// @proposed\ntype InlineCompletionTriggerKind uint32\n\n// Inline value information can be provided by different means:\n//\n// - directly as a text value (class InlineValueText).\n// - as a name to use for a variable lookup (class InlineValueVariableLookup)\n// - as an evaluatable expression (class InlineValueEvaluatableExpression)\n//\n// The InlineValue types combines all inline value types into one type.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#inlineValue\ntype InlineValue = Or_InlineValue // (alias)\n// Client capabilities specific to inline values.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#inlineValueClientCapabilities\ntype InlineValueClientCapabilities struct {\n\t// Whether implementation supports dynamic registration for inline value providers.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n}\n\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#inlineValueContext\ntype InlineValueContext struct {\n\t// The stack frame (as a DAP Id) where the execution has stopped.\n\tFrameID int32 `json:\"frameId\"`\n\t// The document range where execution has stopped.\n\t// Typically the end position of the range denotes the line where the inline values are shown.\n\tStoppedLocation Range `json:\"stoppedLocation\"`\n}\n\n// Provide an inline value through an expression evaluation.\n// If only a range is specified, the expression will be extracted from the underlying document.\n// An optional expression can be used to override the extracted expression.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#inlineValueEvaluatableExpression\ntype InlineValueEvaluatableExpression struct {\n\t// The document range for which the inline value applies.\n\t// The range is used to extract the evaluatable expression from the underlying document.\n\tRange Range `json:\"range\"`\n\t// If specified the expression overrides the extracted expression.\n\tExpression string `json:\"expression,omitempty\"`\n}\n\n// Inline value options used during static registration.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#inlineValueOptions\ntype InlineValueOptions struct {\n\tWorkDoneProgressOptions\n}\n\n// A parameter literal used in inline value requests.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#inlineValueParams\ntype InlineValueParams struct {\n\t// The text document.\n\tTextDocument TextDocumentIdentifier `json:\"textDocument\"`\n\t// The document range for which inline values should be computed.\n\tRange Range `json:\"range\"`\n\t// Additional information about the context in which inline values were\n\t// requested.\n\tContext InlineValueContext `json:\"context\"`\n\tWorkDoneProgressParams\n}\n\n// Inline value options used during static or dynamic registration.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#inlineValueRegistrationOptions\ntype InlineValueRegistrationOptions struct {\n\tInlineValueOptions\n\tTextDocumentRegistrationOptions\n\tStaticRegistrationOptions\n}\n\n// Provide inline value as text.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#inlineValueText\ntype InlineValueText struct {\n\t// The document range for which the inline value applies.\n\tRange Range `json:\"range\"`\n\t// The text of the inline value.\n\tText string `json:\"text\"`\n}\n\n// Provide inline value through a variable lookup.\n// If only a range is specified, the variable name will be extracted from the underlying document.\n// An optional variable name can be used to override the extracted name.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#inlineValueVariableLookup\ntype InlineValueVariableLookup struct {\n\t// The document range for which the inline value applies.\n\t// The range is used to extract the variable name from the underlying document.\n\tRange Range `json:\"range\"`\n\t// If specified the name of the variable to look up.\n\tVariableName string `json:\"variableName,omitempty\"`\n\t// How to perform the lookup.\n\tCaseSensitiveLookup bool `json:\"caseSensitiveLookup\"`\n}\n\n// Client workspace capabilities specific to inline values.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#inlineValueWorkspaceClientCapabilities\ntype InlineValueWorkspaceClientCapabilities struct {\n\t// Whether the client implementation supports a refresh request sent from the\n\t// server to the client.\n\t//\n\t// Note that this event is global and will force the client to refresh all\n\t// inline values currently shown. It should be used with absolute care and is\n\t// useful for situation where a server for example detects a project wide\n\t// change that requires such a calculation.\n\tRefreshSupport bool `json:\"refreshSupport,omitempty\"`\n}\n\n// A special text edit to provide an insert and a replace operation.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#insertReplaceEdit\ntype InsertReplaceEdit struct {\n\t// The string to be inserted.\n\tNewText string `json:\"newText\"`\n\t// The range if the insert is requested\n\tInsert Range `json:\"insert\"`\n\t// The range if the replace is requested.\n\tReplace Range `json:\"replace\"`\n}\n\n// Defines whether the insert text in a completion item should be interpreted as\n// plain text or a snippet.\ntype InsertTextFormat uint32\n\n// How whitespace and indentation is handled during completion\n// item insertion.\n//\n// @since 3.16.0\ntype InsertTextMode uint32\ntype LSPAny = interface{}\n\n// LSP arrays.\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#lSPArray\ntype LSPArray = []interface{} // (alias)\ntype LSPErrorCodes int32\n\n// LSP object definition.\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#lSPObject\ntype LSPObject = map[string]LSPAny // (alias)\n// Predefined Language kinds\n// @since 3.18.0\n// @proposed\ntype LanguageKind string\n\n// Client capabilities for the linked editing range request.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#linkedEditingRangeClientCapabilities\ntype LinkedEditingRangeClientCapabilities struct {\n\t// Whether implementation supports dynamic registration. If this is set to `true`\n\t// the client supports the new `(TextDocumentRegistrationOptions & StaticRegistrationOptions)`\n\t// return value for the corresponding server capability as well.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#linkedEditingRangeOptions\ntype LinkedEditingRangeOptions struct {\n\tWorkDoneProgressOptions\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#linkedEditingRangeParams\ntype LinkedEditingRangeParams struct {\n\tTextDocumentPositionParams\n\tWorkDoneProgressParams\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#linkedEditingRangeRegistrationOptions\ntype LinkedEditingRangeRegistrationOptions struct {\n\tTextDocumentRegistrationOptions\n\tLinkedEditingRangeOptions\n\tStaticRegistrationOptions\n}\n\n// The result of a linked editing range request.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#linkedEditingRanges\ntype LinkedEditingRanges struct {\n\t// A list of ranges that can be edited together. The ranges must have\n\t// identical length and contain identical text content. The ranges cannot overlap.\n\tRanges []Range `json:\"ranges\"`\n\t// An optional word pattern (regular expression) that describes valid contents for\n\t// the given ranges. If no pattern is provided, the client configuration's word\n\t// pattern will be used.\n\tWordPattern string `json:\"wordPattern,omitempty\"`\n}\n\n// created for Literal (Lit_ClientSemanticTokensRequestOptions_range_Item1)\ntype Lit_ClientSemanticTokensRequestOptions_range_Item1 struct {\n}\n\n// created for Literal (Lit_SemanticTokensOptions_range_Item1)\ntype Lit_SemanticTokensOptions_range_Item1 struct {\n}\n\n// Represents a location inside a resource, such as a line\n// inside a text file.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#location\ntype Location struct {\n\tURI DocumentUri `json:\"uri\"`\n\tRange Range `json:\"range\"`\n}\n\n// Represents the connection of two locations. Provides additional metadata over normal {@link Location locations},\n// including an origin range.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#locationLink\ntype LocationLink struct {\n\t// Span of the origin of this link.\n\t//\n\t// Used as the underlined span for mouse interaction. Defaults to the word range at\n\t// the definition position.\n\tOriginSelectionRange *Range `json:\"originSelectionRange,omitempty\"`\n\t// The target resource identifier of this link.\n\tTargetURI DocumentUri `json:\"targetUri\"`\n\t// The full target range of this link. If the target for example is a symbol then target range is the\n\t// range enclosing this symbol not including leading/trailing whitespace but everything else\n\t// like comments. This information is typically used to highlight the range in the editor.\n\tTargetRange Range `json:\"targetRange\"`\n\t// The range that should be selected and revealed when this link is being followed, e.g the name of a function.\n\t// Must be contained by the `targetRange`. See also `DocumentSymbol#range`\n\tTargetSelectionRange Range `json:\"targetSelectionRange\"`\n}\n\n// Location with only uri and does not include range.\n//\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#locationUriOnly\ntype LocationUriOnly struct {\n\tURI DocumentUri `json:\"uri\"`\n}\n\n// The log message parameters.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#logMessageParams\ntype LogMessageParams struct {\n\t// The message type. See {@link MessageType}\n\tType MessageType `json:\"type\"`\n\t// The actual message.\n\tMessage string `json:\"message\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#logTraceParams\ntype LogTraceParams struct {\n\tMessage string `json:\"message\"`\n\tVerbose string `json:\"verbose,omitempty\"`\n}\n\n// Client capabilities specific to the used markdown parser.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#markdownClientCapabilities\ntype MarkdownClientCapabilities struct {\n\t// The name of the parser.\n\tParser string `json:\"parser\"`\n\t// The version of the parser.\n\tVersion string `json:\"version,omitempty\"`\n\t// A list of HTML tags that the client allows / supports in\n\t// Markdown.\n\t//\n\t// @since 3.17.0\n\tAllowedTags []string `json:\"allowedTags,omitempty\"`\n}\n\n// MarkedString can be used to render human readable text. It is either a markdown string\n// or a code-block that provides a language and a code snippet. The language identifier\n// is semantically equal to the optional language identifier in fenced code blocks in GitHub\n// issues. See https://help.github.com/articles/creating-and-highlighting-code-blocks/#syntax-highlighting\n//\n// The pair of a language and a value is an equivalent to markdown:\n// ```${language}\n// ${value}\n// ```\n//\n// Note that markdown strings will be sanitized - that means html will be escaped.\n// @deprecated use MarkupContent instead.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#markedString\ntype MarkedString = Or_MarkedString // (alias)\n// @since 3.18.0\n// @deprecated use MarkupContent instead.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#markedStringWithLanguage\ntype MarkedStringWithLanguage struct {\n\tLanguage string `json:\"language\"`\n\tValue string `json:\"value\"`\n}\n\n// A `MarkupContent` literal represents a string value which content is interpreted base on its\n// kind flag. Currently the protocol supports `plaintext` and `markdown` as markup kinds.\n//\n// If the kind is `markdown` then the value can contain fenced code blocks like in GitHub issues.\n// See https://help.github.com/articles/creating-and-highlighting-code-blocks/#syntax-highlighting\n//\n// Here is an example how such a string can be constructed using JavaScript / TypeScript:\n// ```ts\n//\n//\tlet markdown: MarkdownContent = {\n//\t kind: MarkupKind.Markdown,\n//\t value: [\n//\t '# Header',\n//\t 'Some text',\n//\t '```typescript',\n//\t 'someCode();',\n//\t '```'\n//\t ].join('\\n')\n//\t};\n//\n// ```\n//\n// *Please Note* that clients might sanitize the return markdown. A client could decide to\n// remove HTML from the markdown to avoid script execution.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#markupContent\ntype MarkupContent struct {\n\t// The type of the Markup\n\tKind MarkupKind `json:\"kind\"`\n\t// The content itself\n\tValue string `json:\"value\"`\n}\n\n// Describes the content type that a client supports in various\n// result literals like `Hover`, `ParameterInfo` or `CompletionItem`.\n//\n// Please note that `MarkupKinds` must not start with a `$`. This kinds\n// are reserved for internal usage.\ntype MarkupKind string\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#messageActionItem\ntype MessageActionItem struct {\n\t// A short title like 'Retry', 'Open Log' etc.\n\tTitle string `json:\"title\"`\n}\n\n// The message type\ntype MessageType uint32\n\n// Moniker definition to match LSIF 0.5 moniker definition.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#moniker\ntype Moniker struct {\n\t// The scheme of the moniker. For example tsc or .Net\n\tScheme string `json:\"scheme\"`\n\t// The identifier of the moniker. The value is opaque in LSIF however\n\t// schema owners are allowed to define the structure if they want.\n\tIdentifier string `json:\"identifier\"`\n\t// The scope in which the moniker is unique\n\tUnique UniquenessLevel `json:\"unique\"`\n\t// The moniker kind if known.\n\tKind *MonikerKind `json:\"kind,omitempty\"`\n}\n\n// Client capabilities specific to the moniker request.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#monikerClientCapabilities\ntype MonikerClientCapabilities struct {\n\t// Whether moniker supports dynamic registration. If this is set to `true`\n\t// the client supports the new `MonikerRegistrationOptions` return value\n\t// for the corresponding server capability as well.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n}\n\n// The moniker kind.\n//\n// @since 3.16.0\ntype MonikerKind string\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#monikerOptions\ntype MonikerOptions struct {\n\tWorkDoneProgressOptions\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#monikerParams\ntype MonikerParams struct {\n\tTextDocumentPositionParams\n\tWorkDoneProgressParams\n\tPartialResultParams\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#monikerRegistrationOptions\ntype MonikerRegistrationOptions struct {\n\tTextDocumentRegistrationOptions\n\tMonikerOptions\n}\n\n// A notebook cell.\n//\n// A cell's document URI must be unique across ALL notebook\n// cells and can therefore be used to uniquely identify a\n// notebook cell or the cell's text document.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#notebookCell\ntype NotebookCell struct {\n\t// The cell's kind\n\tKind NotebookCellKind `json:\"kind\"`\n\t// The URI of the cell's text document\n\t// content.\n\tDocument DocumentUri `json:\"document\"`\n\t// Additional metadata stored with the cell.\n\t//\n\t// Note: should always be an object literal (e.g. LSPObject)\n\tMetadata *LSPObject `json:\"metadata,omitempty\"`\n\t// Additional execution summary information\n\t// if supported by the client.\n\tExecutionSummary *ExecutionSummary `json:\"executionSummary,omitempty\"`\n}\n\n// A change describing how to move a `NotebookCell`\n// array from state S to S'.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#notebookCellArrayChange\ntype NotebookCellArrayChange struct {\n\t// The start oftest of the cell that changed.\n\tStart uint32 `json:\"start\"`\n\t// The deleted cells\n\tDeleteCount uint32 `json:\"deleteCount\"`\n\t// The new cells, if any\n\tCells []NotebookCell `json:\"cells,omitempty\"`\n}\n\n// A notebook cell kind.\n//\n// @since 3.17.0\ntype NotebookCellKind uint32\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#notebookCellLanguage\ntype NotebookCellLanguage struct {\n\tLanguage string `json:\"language\"`\n}\n\n// A notebook cell text document filter denotes a cell text\n// document by different properties.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#notebookCellTextDocumentFilter\ntype NotebookCellTextDocumentFilter struct {\n\t// A filter that matches against the notebook\n\t// containing the notebook cell. If a string\n\t// value is provided it matches against the\n\t// notebook type. '*' matches every notebook.\n\tNotebook Or_NotebookCellTextDocumentFilter_notebook `json:\"notebook\"`\n\t// A language id like `python`.\n\t//\n\t// Will be matched against the language id of the\n\t// notebook cell document. '*' matches every language.\n\tLanguage string `json:\"language,omitempty\"`\n}\n\n// A notebook document.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#notebookDocument\ntype NotebookDocument struct {\n\t// The notebook document's uri.\n\tURI URI `json:\"uri\"`\n\t// The type of the notebook.\n\tNotebookType string `json:\"notebookType\"`\n\t// The version number of this document (it will increase after each\n\t// change, including undo/redo).\n\tVersion int32 `json:\"version\"`\n\t// Additional metadata stored with the notebook\n\t// document.\n\t//\n\t// Note: should always be an object literal (e.g. LSPObject)\n\tMetadata *LSPObject `json:\"metadata,omitempty\"`\n\t// The cells of a notebook.\n\tCells []NotebookCell `json:\"cells\"`\n}\n\n// Structural changes to cells in a notebook document.\n//\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#notebookDocumentCellChangeStructure\ntype NotebookDocumentCellChangeStructure struct {\n\t// The change to the cell array.\n\tArray NotebookCellArrayChange `json:\"array\"`\n\t// Additional opened cell text documents.\n\tDidOpen []TextDocumentItem `json:\"didOpen,omitempty\"`\n\t// Additional closed cell text documents.\n\tDidClose []TextDocumentIdentifier `json:\"didClose,omitempty\"`\n}\n\n// Cell changes to a notebook document.\n//\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#notebookDocumentCellChanges\ntype NotebookDocumentCellChanges struct {\n\t// Changes to the cell structure to add or\n\t// remove cells.\n\tStructure *NotebookDocumentCellChangeStructure `json:\"structure,omitempty\"`\n\t// Changes to notebook cells properties like its\n\t// kind, execution summary or metadata.\n\tData []NotebookCell `json:\"data,omitempty\"`\n\t// Changes to the text content of notebook cells.\n\tTextContent []NotebookDocumentCellContentChanges `json:\"textContent,omitempty\"`\n}\n\n// Content changes to a cell in a notebook document.\n//\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#notebookDocumentCellContentChanges\ntype NotebookDocumentCellContentChanges struct {\n\tDocument VersionedTextDocumentIdentifier `json:\"document\"`\n\tChanges []TextDocumentContentChangeEvent `json:\"changes\"`\n}\n\n// A change event for a notebook document.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#notebookDocumentChangeEvent\ntype NotebookDocumentChangeEvent struct {\n\t// The changed meta data if any.\n\t//\n\t// Note: should always be an object literal (e.g. LSPObject)\n\tMetadata *LSPObject `json:\"metadata,omitempty\"`\n\t// Changes to cells\n\tCells *NotebookDocumentCellChanges `json:\"cells,omitempty\"`\n}\n\n// Capabilities specific to the notebook document support.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#notebookDocumentClientCapabilities\ntype NotebookDocumentClientCapabilities struct {\n\t// Capabilities specific to notebook document synchronization\n\t//\n\t// @since 3.17.0\n\tSynchronization NotebookDocumentSyncClientCapabilities `json:\"synchronization\"`\n}\n\n// A notebook document filter denotes a notebook document by\n// different properties. The properties will be match\n// against the notebook's URI (same as with documents)\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#notebookDocumentFilter\ntype NotebookDocumentFilter = Or_NotebookDocumentFilter // (alias)\n// A notebook document filter where `notebookType` is required field.\n//\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#notebookDocumentFilterNotebookType\ntype NotebookDocumentFilterNotebookType struct {\n\t// The type of the enclosing notebook.\n\tNotebookType string `json:\"notebookType\"`\n\t// A Uri {@link Uri.scheme scheme}, like `file` or `untitled`.\n\tScheme string `json:\"scheme,omitempty\"`\n\t// A glob pattern.\n\tPattern *GlobPattern `json:\"pattern,omitempty\"`\n}\n\n// A notebook document filter where `pattern` is required field.\n//\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#notebookDocumentFilterPattern\ntype NotebookDocumentFilterPattern struct {\n\t// The type of the enclosing notebook.\n\tNotebookType string `json:\"notebookType,omitempty\"`\n\t// A Uri {@link Uri.scheme scheme}, like `file` or `untitled`.\n\tScheme string `json:\"scheme,omitempty\"`\n\t// A glob pattern.\n\tPattern GlobPattern `json:\"pattern\"`\n}\n\n// A notebook document filter where `scheme` is required field.\n//\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#notebookDocumentFilterScheme\ntype NotebookDocumentFilterScheme struct {\n\t// The type of the enclosing notebook.\n\tNotebookType string `json:\"notebookType,omitempty\"`\n\t// A Uri {@link Uri.scheme scheme}, like `file` or `untitled`.\n\tScheme string `json:\"scheme\"`\n\t// A glob pattern.\n\tPattern *GlobPattern `json:\"pattern,omitempty\"`\n}\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#notebookDocumentFilterWithCells\ntype NotebookDocumentFilterWithCells struct {\n\t// The notebook to be synced If a string\n\t// value is provided it matches against the\n\t// notebook type. '*' matches every notebook.\n\tNotebook *Or_NotebookDocumentFilterWithCells_notebook `json:\"notebook,omitempty\"`\n\t// The cells of the matching notebook to be synced.\n\tCells []NotebookCellLanguage `json:\"cells\"`\n}\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#notebookDocumentFilterWithNotebook\ntype NotebookDocumentFilterWithNotebook struct {\n\t// The notebook to be synced If a string\n\t// value is provided it matches against the\n\t// notebook type. '*' matches every notebook.\n\tNotebook Or_NotebookDocumentFilterWithNotebook_notebook `json:\"notebook\"`\n\t// The cells of the matching notebook to be synced.\n\tCells []NotebookCellLanguage `json:\"cells,omitempty\"`\n}\n\n// A literal to identify a notebook document in the client.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#notebookDocumentIdentifier\ntype NotebookDocumentIdentifier struct {\n\t// The notebook document's uri.\n\tURI URI `json:\"uri\"`\n}\n\n// Notebook specific client capabilities.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#notebookDocumentSyncClientCapabilities\ntype NotebookDocumentSyncClientCapabilities struct {\n\t// Whether implementation supports dynamic registration. If this is\n\t// set to `true` the client supports the new\n\t// `(TextDocumentRegistrationOptions & StaticRegistrationOptions)`\n\t// return value for the corresponding server capability as well.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n\t// The client supports sending execution summary data per cell.\n\tExecutionSummarySupport bool `json:\"executionSummarySupport,omitempty\"`\n}\n\n// Options specific to a notebook plus its cells\n// to be synced to the server.\n//\n// If a selector provides a notebook document\n// filter but no cell selector all cells of a\n// matching notebook document will be synced.\n//\n// If a selector provides no notebook document\n// filter but only a cell selector all notebook\n// document that contain at least one matching\n// cell will be synced.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#notebookDocumentSyncOptions\ntype NotebookDocumentSyncOptions struct {\n\t// The notebooks to be synced\n\tNotebookSelector []Or_NotebookDocumentSyncOptions_notebookSelector_Elem `json:\"notebookSelector\"`\n\t// Whether save notification should be forwarded to\n\t// the server. Will only be honored if mode === `notebook`.\n\tSave bool `json:\"save,omitempty\"`\n}\n\n// Registration options specific to a notebook.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#notebookDocumentSyncRegistrationOptions\ntype NotebookDocumentSyncRegistrationOptions struct {\n\tNotebookDocumentSyncOptions\n\tStaticRegistrationOptions\n}\n\n// A text document identifier to optionally denote a specific version of a text document.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#optionalVersionedTextDocumentIdentifier\ntype OptionalVersionedTextDocumentIdentifier struct {\n\t// The version number of this document. If a versioned text document identifier\n\t// is sent from the server to the client and the file is not open in the editor\n\t// (the server has not received an open notification before) the server can send\n\t// `null` to indicate that the version is unknown and the content on disk is the\n\t// truth (as specified with document content ownership).\n\tVersion int32 `json:\"version\"`\n\tTextDocumentIdentifier\n}\n\n// created for Or [int32 string]\ntype Or_CancelParams_id struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [ClientSemanticTokensRequestFullDelta bool]\ntype Or_ClientSemanticTokensRequestOptions_full struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [Lit_ClientSemanticTokensRequestOptions_range_Item1 bool]\ntype Or_ClientSemanticTokensRequestOptions_range struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [EditRangeWithInsertReplace Range]\ntype Or_CompletionItemDefaults_editRange struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [MarkupContent string]\ntype Or_CompletionItem_documentation struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [InsertReplaceEdit TextEdit]\ntype Or_CompletionItem_textEdit struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [Location []Location]\ntype Or_Declaration struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [Location []Location]\ntype Or_Definition struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [int32 string]\ntype Or_Diagnostic_code struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [[]string string]\ntype Or_DidChangeConfigurationRegistrationOptions_section struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [RelatedFullDocumentDiagnosticReport RelatedUnchangedDocumentDiagnosticReport]\ntype Or_DocumentDiagnosticReport struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [FullDocumentDiagnosticReport UnchangedDocumentDiagnosticReport]\ntype Or_DocumentDiagnosticReportPartialResult_relatedDocuments_Value struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [NotebookCellTextDocumentFilter TextDocumentFilter]\ntype Or_DocumentFilter struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [Pattern RelativePattern]\ntype Or_GlobPattern struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [MarkedString MarkupContent []MarkedString]\ntype Or_Hover_contents struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [MarkupContent string]\ntype Or_InlayHintLabelPart_tooltip struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [[]InlayHintLabelPart string]\ntype Or_InlayHint_label struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [MarkupContent string]\ntype Or_InlayHint_tooltip struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [StringValue string]\ntype Or_InlineCompletionItem_insertText struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [InlineValueEvaluatableExpression InlineValueText InlineValueVariableLookup]\ntype Or_InlineValue struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [LSPArray LSPObject bool float64 int32 string uint32]\ntype Or_LSPAny struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [MarkedStringWithLanguage string]\ntype Or_MarkedString struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [NotebookDocumentFilter string]\ntype Or_NotebookCellTextDocumentFilter_notebook struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [NotebookDocumentFilterNotebookType NotebookDocumentFilterPattern NotebookDocumentFilterScheme]\ntype Or_NotebookDocumentFilter struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [NotebookDocumentFilter string]\ntype Or_NotebookDocumentFilterWithCells_notebook struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [NotebookDocumentFilter string]\ntype Or_NotebookDocumentFilterWithNotebook_notebook struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [NotebookDocumentFilterWithCells NotebookDocumentFilterWithNotebook]\ntype Or_NotebookDocumentSyncOptions_notebookSelector_Elem struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [MarkupContent string]\ntype Or_ParameterInformation_documentation struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [Tuple_ParameterInformation_label_Item1 string]\ntype Or_ParameterInformation_label struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [PrepareRenameDefaultBehavior PrepareRenamePlaceholder Range]\ntype Or_PrepareRenameResult struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [int32 string]\ntype Or_ProgressToken struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [FullDocumentDiagnosticReport UnchangedDocumentDiagnosticReport]\ntype Or_RelatedFullDocumentDiagnosticReport_relatedDocuments_Value struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [FullDocumentDiagnosticReport UnchangedDocumentDiagnosticReport]\ntype Or_RelatedUnchangedDocumentDiagnosticReport_relatedDocuments_Value struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [URI WorkspaceFolder]\ntype Or_RelativePattern_baseUri struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [CodeAction Command]\ntype Or_Result_textDocument_codeAction_Item0_Elem struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [CompletionList []CompletionItem]\ntype Or_Result_textDocument_completion struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [Declaration []DeclarationLink]\ntype Or_Result_textDocument_declaration struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [Definition []DefinitionLink]\ntype Or_Result_textDocument_definition struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [[]DocumentSymbol []SymbolInformation]\ntype Or_Result_textDocument_documentSymbol struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [Definition []DefinitionLink]\ntype Or_Result_textDocument_implementation struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [InlineCompletionList []InlineCompletionItem]\ntype Or_Result_textDocument_inlineCompletion struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [SemanticTokens SemanticTokensDelta]\ntype Or_Result_textDocument_semanticTokens_full_delta struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [Definition []DefinitionLink]\ntype Or_Result_textDocument_typeDefinition struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [[]SymbolInformation []WorkspaceSymbol]\ntype Or_Result_workspace_symbol struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [SemanticTokensFullDelta bool]\ntype Or_SemanticTokensOptions_full struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [Lit_SemanticTokensOptions_range_Item1 bool]\ntype Or_SemanticTokensOptions_range struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [CallHierarchyOptions CallHierarchyRegistrationOptions bool]\ntype Or_ServerCapabilities_callHierarchyProvider struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [CodeActionOptions bool]\ntype Or_ServerCapabilities_codeActionProvider struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [DocumentColorOptions DocumentColorRegistrationOptions bool]\ntype Or_ServerCapabilities_colorProvider struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [DeclarationOptions DeclarationRegistrationOptions bool]\ntype Or_ServerCapabilities_declarationProvider struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [DefinitionOptions bool]\ntype Or_ServerCapabilities_definitionProvider struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [DiagnosticOptions DiagnosticRegistrationOptions]\ntype Or_ServerCapabilities_diagnosticProvider struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [DocumentFormattingOptions bool]\ntype Or_ServerCapabilities_documentFormattingProvider struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [DocumentHighlightOptions bool]\ntype Or_ServerCapabilities_documentHighlightProvider struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [DocumentRangeFormattingOptions bool]\ntype Or_ServerCapabilities_documentRangeFormattingProvider struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [DocumentSymbolOptions bool]\ntype Or_ServerCapabilities_documentSymbolProvider struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [FoldingRangeOptions FoldingRangeRegistrationOptions bool]\ntype Or_ServerCapabilities_foldingRangeProvider struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [HoverOptions bool]\ntype Or_ServerCapabilities_hoverProvider struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [ImplementationOptions ImplementationRegistrationOptions bool]\ntype Or_ServerCapabilities_implementationProvider struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [InlayHintOptions InlayHintRegistrationOptions bool]\ntype Or_ServerCapabilities_inlayHintProvider struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [InlineCompletionOptions bool]\ntype Or_ServerCapabilities_inlineCompletionProvider struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [InlineValueOptions InlineValueRegistrationOptions bool]\ntype Or_ServerCapabilities_inlineValueProvider struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [LinkedEditingRangeOptions LinkedEditingRangeRegistrationOptions bool]\ntype Or_ServerCapabilities_linkedEditingRangeProvider struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [MonikerOptions MonikerRegistrationOptions bool]\ntype Or_ServerCapabilities_monikerProvider struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [NotebookDocumentSyncOptions NotebookDocumentSyncRegistrationOptions]\ntype Or_ServerCapabilities_notebookDocumentSync struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [ReferenceOptions bool]\ntype Or_ServerCapabilities_referencesProvider struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [RenameOptions bool]\ntype Or_ServerCapabilities_renameProvider struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [SelectionRangeOptions SelectionRangeRegistrationOptions bool]\ntype Or_ServerCapabilities_selectionRangeProvider struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [SemanticTokensOptions SemanticTokensRegistrationOptions]\ntype Or_ServerCapabilities_semanticTokensProvider struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [TextDocumentSyncKind TextDocumentSyncOptions]\ntype Or_ServerCapabilities_textDocumentSync struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [TypeDefinitionOptions TypeDefinitionRegistrationOptions bool]\ntype Or_ServerCapabilities_typeDefinitionProvider struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [TypeHierarchyOptions TypeHierarchyRegistrationOptions bool]\ntype Or_ServerCapabilities_typeHierarchyProvider struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [WorkspaceSymbolOptions bool]\ntype Or_ServerCapabilities_workspaceSymbolProvider struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [MarkupContent string]\ntype Or_SignatureInformation_documentation struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [TextDocumentContentChangePartial TextDocumentContentChangeWholeDocument]\ntype Or_TextDocumentContentChangeEvent struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [AnnotatedTextEdit SnippetTextEdit TextEdit]\ntype Or_TextDocumentEdit_edits_Elem struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [TextDocumentFilterLanguage TextDocumentFilterPattern TextDocumentFilterScheme]\ntype Or_TextDocumentFilter struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [SaveOptions bool]\ntype Or_TextDocumentSyncOptions_save struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [WorkspaceFullDocumentDiagnosticReport WorkspaceUnchangedDocumentDiagnosticReport]\ntype Or_WorkspaceDocumentDiagnosticReport struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [CreateFile DeleteFile RenameFile TextDocumentEdit]\ntype Or_WorkspaceEdit_documentChanges_Elem struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [bool string]\ntype Or_WorkspaceFoldersServerCapabilities_changeNotifications struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [TextDocumentContentOptions TextDocumentContentRegistrationOptions]\ntype Or_WorkspaceOptions_textDocumentContent struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [Location LocationUriOnly]\ntype Or_WorkspaceSymbol_location struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// The parameters of a configuration request.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#configurationParams\ntype ParamConfiguration struct {\n\tItems []ConfigurationItem `json:\"items\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#initializeParams\ntype ParamInitialize struct {\n\tXInitializeParams\n\tWorkspaceFoldersInitializeParams\n}\n\n// Represents a parameter of a callable-signature. A parameter can\n// have a label and a doc-comment.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#parameterInformation\ntype ParameterInformation struct {\n\t// The label of this parameter information.\n\t//\n\t// Either a string or an inclusive start and exclusive end offsets within its containing\n\t// signature label. (see SignatureInformation.label). The offsets are based on a UTF-16\n\t// string representation as `Position` and `Range` does.\n\t//\n\t// To avoid ambiguities a server should use the [start, end] offset value instead of using\n\t// a substring. Whether a client support this is controlled via `labelOffsetSupport` client\n\t// capability.\n\t//\n\t// *Note*: a label of type string should be a substring of its containing signature label.\n\t// Its intended use case is to highlight the parameter label part in the `SignatureInformation.label`.\n\tLabel Or_ParameterInformation_label `json:\"label\"`\n\t// The human-readable doc-comment of this parameter. Will be shown\n\t// in the UI but can be omitted.\n\tDocumentation *Or_ParameterInformation_documentation `json:\"documentation,omitempty\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#partialResultParams\ntype PartialResultParams struct {\n\t// An optional token that a server can use to report partial results (e.g. streaming) to\n\t// the client.\n\tPartialResultToken *ProgressToken `json:\"partialResultToken,omitempty\"`\n}\n\n// The glob pattern to watch relative to the base path. Glob patterns can have the following syntax:\n//\n// - `*` to match one or more characters in a path segment\n// - `?` to match on one character in a path segment\n// - `**` to match any number of path segments, including none\n// - `{}` to group conditions (e.g. `**/*.{ts,js}` matches all TypeScript and JavaScript files)\n// - `[]` to declare a range of characters to match in a path segment (e.g., `example.[0-9]` to match on `example.0`, `example.1`, …)\n// - `[!...]` to negate a range of characters to match in a path segment (e.g., `example.[!0-9]` to match on `example.a`, `example.b`, but not `example.0`)\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#pattern\ntype Pattern = string // (alias)\n// Position in a text document expressed as zero-based line and character\n// offset. Prior to 3.17 the offsets were always based on a UTF-16 string\n// representation. So a string of the form `a𐐀b` the character offset of the\n// character `a` is 0, the character offset of `𐐀` is 1 and the character\n// offset of b is 3 since `𐐀` is represented using two code units in UTF-16.\n// Since 3.17 clients and servers can agree on a different string encoding\n// representation (e.g. UTF-8). The client announces it's supported encoding\n// via the client capability [`general.positionEncodings`](https://microsoft.github.io/language-server-protocol/specifications/specification-current/#clientCapabilities).\n// The value is an array of position encodings the client supports, with\n// decreasing preference (e.g. the encoding at index `0` is the most preferred\n// one). To stay backwards compatible the only mandatory encoding is UTF-16\n// represented via the string `utf-16`. The server can pick one of the\n// encodings offered by the client and signals that encoding back to the\n// client via the initialize result's property\n// [`capabilities.positionEncoding`](https://microsoft.github.io/language-server-protocol/specifications/specification-current/#serverCapabilities). If the string value\n// `utf-16` is missing from the client's capability `general.positionEncodings`\n// servers can safely assume that the client supports UTF-16. If the server\n// omits the position encoding in its initialize result the encoding defaults\n// to the string value `utf-16`. Implementation considerations: since the\n// conversion from one encoding into another requires the content of the\n// file / line the conversion is best done where the file is read which is\n// usually on the server side.\n//\n// Positions are line end character agnostic. So you can not specify a position\n// that denotes `\\r|\\n` or `\\n|` where `|` represents the character offset.\n//\n// @since 3.17.0 - support for negotiated position encoding.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#position\ntype Position struct {\n\t// Line position in a document (zero-based).\n\t//\n\t// If a line number is greater than the number of lines in a document, it defaults back to the number of lines in the document.\n\t// If a line number is negative, it defaults to 0.\n\tLine uint32 `json:\"line\"`\n\t// Character offset on a line in a document (zero-based).\n\t//\n\t// The meaning of this offset is determined by the negotiated\n\t// `PositionEncodingKind`.\n\t//\n\t// If the character value is greater than the line length it defaults back to the\n\t// line length.\n\tCharacter uint32 `json:\"character\"`\n}\n\n// A set of predefined position encoding kinds.\n//\n// @since 3.17.0\ntype PositionEncodingKind string\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#prepareRenameDefaultBehavior\ntype PrepareRenameDefaultBehavior struct {\n\tDefaultBehavior bool `json:\"defaultBehavior\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#prepareRenameParams\ntype PrepareRenameParams struct {\n\tTextDocumentPositionParams\n\tWorkDoneProgressParams\n}\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#prepareRenamePlaceholder\ntype PrepareRenamePlaceholder struct {\n\tRange Range `json:\"range\"`\n\tPlaceholder string `json:\"placeholder\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#prepareRenameResult\ntype PrepareRenameResult = Or_PrepareRenameResult // (alias)\ntype PrepareSupportDefaultBehavior uint32\n\n// A previous result id in a workspace pull request.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#previousResultId\ntype PreviousResultID struct {\n\t// The URI for which the client knowns a\n\t// result id.\n\tURI DocumentUri `json:\"uri\"`\n\t// The value of the previous result id.\n\tValue string `json:\"value\"`\n}\n\n// A previous result id in a workspace pull request.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#previousResultId\ntype PreviousResultId struct {\n\t// The URI for which the client knowns a\n\t// result id.\n\tURI DocumentUri `json:\"uri\"`\n\t// The value of the previous result id.\n\tValue string `json:\"value\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#progressParams\ntype ProgressParams struct {\n\t// The progress token provided by the client or server.\n\tToken ProgressToken `json:\"token\"`\n\t// The progress data.\n\tValue interface{} `json:\"value\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#progressToken\ntype ProgressToken = Or_ProgressToken // (alias)\n// The publish diagnostic client capabilities.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#publishDiagnosticsClientCapabilities\ntype PublishDiagnosticsClientCapabilities struct {\n\t// Whether the client interprets the version property of the\n\t// `textDocument/publishDiagnostics` notification's parameter.\n\t//\n\t// @since 3.15.0\n\tVersionSupport bool `json:\"versionSupport,omitempty\"`\n\tDiagnosticsCapabilities\n}\n\n// The publish diagnostic notification's parameters.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#publishDiagnosticsParams\ntype PublishDiagnosticsParams struct {\n\t// The URI for which diagnostic information is reported.\n\tURI DocumentUri `json:\"uri\"`\n\t// Optional the version number of the document the diagnostics are published for.\n\t//\n\t// @since 3.15.0\n\tVersion int32 `json:\"version,omitempty\"`\n\t// An array of diagnostic information items.\n\tDiagnostics []Diagnostic `json:\"diagnostics\"`\n}\n\n// A range in a text document expressed as (zero-based) start and end positions.\n//\n// If you want to specify a range that contains a line including the line ending\n// character(s) then use an end position denoting the start of the next line.\n// For example:\n// ```ts\n//\n//\t{\n//\t start: { line: 5, character: 23 }\n//\t end : { line 6, character : 0 }\n//\t}\n//\n// ```\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#range\ntype Range struct {\n\t// The range's start position.\n\tStart Position `json:\"start\"`\n\t// The range's end position.\n\tEnd Position `json:\"end\"`\n}\n\n// Client Capabilities for a {@link ReferencesRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#referenceClientCapabilities\ntype ReferenceClientCapabilities struct {\n\t// Whether references supports dynamic registration.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n}\n\n// Value-object that contains additional information when\n// requesting references.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#referenceContext\ntype ReferenceContext struct {\n\t// Include the declaration of the current symbol.\n\tIncludeDeclaration bool `json:\"includeDeclaration\"`\n}\n\n// Reference options.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#referenceOptions\ntype ReferenceOptions struct {\n\tWorkDoneProgressOptions\n}\n\n// Parameters for a {@link ReferencesRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#referenceParams\ntype ReferenceParams struct {\n\tContext ReferenceContext `json:\"context\"`\n\tTextDocumentPositionParams\n\tWorkDoneProgressParams\n\tPartialResultParams\n}\n\n// Registration options for a {@link ReferencesRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#referenceRegistrationOptions\ntype ReferenceRegistrationOptions struct {\n\tTextDocumentRegistrationOptions\n\tReferenceOptions\n}\n\n// General parameters to register for a notification or to register a provider.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#registration\ntype Registration struct {\n\t// The id used to register the request. The id can be used to deregister\n\t// the request again.\n\tID string `json:\"id\"`\n\t// The method / capability to register for.\n\tMethod string `json:\"method\"`\n\t// Options necessary for the registration.\n\tRegisterOptions interface{} `json:\"registerOptions,omitempty\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#registrationParams\ntype RegistrationParams struct {\n\tRegistrations []Registration `json:\"registrations\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#regularExpressionEngineKind\ntype RegularExpressionEngineKind = string // (alias)\n// Client capabilities specific to regular expressions.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#regularExpressionsClientCapabilities\ntype RegularExpressionsClientCapabilities struct {\n\t// The engine's name.\n\tEngine RegularExpressionEngineKind `json:\"engine\"`\n\t// The engine's version.\n\tVersion string `json:\"version,omitempty\"`\n}\n\n// A full diagnostic report with a set of related documents.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#relatedFullDocumentDiagnosticReport\ntype RelatedFullDocumentDiagnosticReport struct {\n\t// Diagnostics of related documents. This information is useful\n\t// in programming languages where code in a file A can generate\n\t// diagnostics in a file B which A depends on. An example of\n\t// such a language is C/C++ where marco definitions in a file\n\t// a.cpp and result in errors in a header file b.hpp.\n\t//\n\t// @since 3.17.0\n\tRelatedDocuments map[DocumentUri]interface{} `json:\"relatedDocuments,omitempty\"`\n\tFullDocumentDiagnosticReport\n}\n\n// An unchanged diagnostic report with a set of related documents.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#relatedUnchangedDocumentDiagnosticReport\ntype RelatedUnchangedDocumentDiagnosticReport struct {\n\t// Diagnostics of related documents. This information is useful\n\t// in programming languages where code in a file A can generate\n\t// diagnostics in a file B which A depends on. An example of\n\t// such a language is C/C++ where marco definitions in a file\n\t// a.cpp and result in errors in a header file b.hpp.\n\t//\n\t// @since 3.17.0\n\tRelatedDocuments map[DocumentUri]interface{} `json:\"relatedDocuments,omitempty\"`\n\tUnchangedDocumentDiagnosticReport\n}\n\n// A relative pattern is a helper to construct glob patterns that are matched\n// relatively to a base URI. The common value for a `baseUri` is a workspace\n// folder root, but it can be another absolute URI as well.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#relativePattern\ntype RelativePattern struct {\n\t// A workspace folder or a base URI to which this pattern will be matched\n\t// against relatively.\n\tBaseURI Or_RelativePattern_baseUri `json:\"baseUri\"`\n\t// The actual glob pattern;\n\tPattern Pattern `json:\"pattern\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#renameClientCapabilities\ntype RenameClientCapabilities struct {\n\t// Whether rename supports dynamic registration.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n\t// Client supports testing for validity of rename operations\n\t// before execution.\n\t//\n\t// @since 3.12.0\n\tPrepareSupport bool `json:\"prepareSupport,omitempty\"`\n\t// Client supports the default behavior result.\n\t//\n\t// The value indicates the default behavior used by the\n\t// client.\n\t//\n\t// @since 3.16.0\n\tPrepareSupportDefaultBehavior *PrepareSupportDefaultBehavior `json:\"prepareSupportDefaultBehavior,omitempty\"`\n\t// Whether the client honors the change annotations in\n\t// text edits and resource operations returned via the\n\t// rename request's workspace edit by for example presenting\n\t// the workspace edit in the user interface and asking\n\t// for confirmation.\n\t//\n\t// @since 3.16.0\n\tHonorsChangeAnnotations bool `json:\"honorsChangeAnnotations,omitempty\"`\n}\n\n// Rename file operation\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#renameFile\ntype RenameFile struct {\n\t// A rename\n\tKind string `json:\"kind\"`\n\t// The old (existing) location.\n\tOldURI DocumentUri `json:\"oldUri\"`\n\t// The new location.\n\tNewURI DocumentUri `json:\"newUri\"`\n\t// Rename options.\n\tOptions *RenameFileOptions `json:\"options,omitempty\"`\n\tResourceOperation\n}\n\n// Rename file options\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#renameFileOptions\ntype RenameFileOptions struct {\n\t// Overwrite target if existing. Overwrite wins over `ignoreIfExists`\n\tOverwrite bool `json:\"overwrite,omitempty\"`\n\t// Ignores if target exists.\n\tIgnoreIfExists bool `json:\"ignoreIfExists,omitempty\"`\n}\n\n// The parameters sent in notifications/requests for user-initiated renames of\n// files.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#renameFilesParams\ntype RenameFilesParams struct {\n\t// An array of all files/folders renamed in this operation. When a folder is renamed, only\n\t// the folder will be included, and not its children.\n\tFiles []FileRename `json:\"files\"`\n}\n\n// Provider options for a {@link RenameRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#renameOptions\ntype RenameOptions struct {\n\t// Renames should be checked and tested before being executed.\n\t//\n\t// @since version 3.12.0\n\tPrepareProvider bool `json:\"prepareProvider,omitempty\"`\n\tWorkDoneProgressOptions\n}\n\n// The parameters of a {@link RenameRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#renameParams\ntype RenameParams struct {\n\t// The document to rename.\n\tTextDocument TextDocumentIdentifier `json:\"textDocument\"`\n\t// The position at which this request was sent.\n\tPosition Position `json:\"position\"`\n\t// The new name of the symbol. If the given name is not valid the\n\t// request must return a {@link ResponseError} with an\n\t// appropriate message set.\n\tNewName string `json:\"newName\"`\n\tWorkDoneProgressParams\n}\n\n// Registration options for a {@link RenameRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#renameRegistrationOptions\ntype RenameRegistrationOptions struct {\n\tTextDocumentRegistrationOptions\n\tRenameOptions\n}\n\n// A generic resource operation.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#resourceOperation\ntype ResourceOperation struct {\n\t// The resource operation kind.\n\tKind string `json:\"kind\"`\n\t// An optional annotation identifier describing the operation.\n\t//\n\t// @since 3.16.0\n\tAnnotationID *ChangeAnnotationIdentifier `json:\"annotationId,omitempty\"`\n}\ntype ResourceOperationKind string\n\n// Save options.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#saveOptions\ntype SaveOptions struct {\n\t// The client is supposed to include the content on save.\n\tIncludeText bool `json:\"includeText,omitempty\"`\n}\n\n// Describes the currently selected completion item.\n//\n// @since 3.18.0\n// @proposed\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#selectedCompletionInfo\ntype SelectedCompletionInfo struct {\n\t// The range that will be replaced if this completion item is accepted.\n\tRange Range `json:\"range\"`\n\t// The text the range will be replaced with if this completion is accepted.\n\tText string `json:\"text\"`\n}\n\n// A selection range represents a part of a selection hierarchy. A selection range\n// may have a parent selection range that contains it.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#selectionRange\ntype SelectionRange struct {\n\t// The {@link Range range} of this selection range.\n\tRange Range `json:\"range\"`\n\t// The parent selection range containing this range. Therefore `parent.range` must contain `this.range`.\n\tParent *SelectionRange `json:\"parent,omitempty\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#selectionRangeClientCapabilities\ntype SelectionRangeClientCapabilities struct {\n\t// Whether implementation supports dynamic registration for selection range providers. If this is set to `true`\n\t// the client supports the new `SelectionRangeRegistrationOptions` return value for the corresponding server\n\t// capability as well.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#selectionRangeOptions\ntype SelectionRangeOptions struct {\n\tWorkDoneProgressOptions\n}\n\n// A parameter literal used in selection range requests.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#selectionRangeParams\ntype SelectionRangeParams struct {\n\t// The text document.\n\tTextDocument TextDocumentIdentifier `json:\"textDocument\"`\n\t// The positions inside the text document.\n\tPositions []Position `json:\"positions\"`\n\tWorkDoneProgressParams\n\tPartialResultParams\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#selectionRangeRegistrationOptions\ntype SelectionRangeRegistrationOptions struct {\n\tSelectionRangeOptions\n\tTextDocumentRegistrationOptions\n\tStaticRegistrationOptions\n}\n\n// A set of predefined token modifiers. This set is not fixed\n// an clients can specify additional token types via the\n// corresponding client capabilities.\n//\n// @since 3.16.0\ntype SemanticTokenModifiers string\n\n// A set of predefined token types. This set is not fixed\n// an clients can specify additional token types via the\n// corresponding client capabilities.\n//\n// @since 3.16.0\ntype SemanticTokenTypes string\n\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#semanticTokens\ntype SemanticTokens struct {\n\t// An optional result id. If provided and clients support delta updating\n\t// the client will include the result id in the next semantic token request.\n\t// A server can then instead of computing all semantic tokens again simply\n\t// send a delta.\n\tResultID string `json:\"resultId,omitempty\"`\n\t// The actual tokens.\n\tData []uint32 `json:\"data\"`\n}\n\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#semanticTokensClientCapabilities\ntype SemanticTokensClientCapabilities struct {\n\t// Whether implementation supports dynamic registration. If this is set to `true`\n\t// the client supports the new `(TextDocumentRegistrationOptions & StaticRegistrationOptions)`\n\t// return value for the corresponding server capability as well.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n\t// Which requests the client supports and might send to the server\n\t// depending on the server's capability. Please note that clients might not\n\t// show semantic tokens or degrade some of the user experience if a range\n\t// or full request is advertised by the client but not provided by the\n\t// server. If for example the client capability `requests.full` and\n\t// `request.range` are both set to true but the server only provides a\n\t// range provider the client might not render a minimap correctly or might\n\t// even decide to not show any semantic tokens at all.\n\tRequests ClientSemanticTokensRequestOptions `json:\"requests\"`\n\t// The token types that the client supports.\n\tTokenTypes []string `json:\"tokenTypes\"`\n\t// The token modifiers that the client supports.\n\tTokenModifiers []string `json:\"tokenModifiers\"`\n\t// The token formats the clients supports.\n\tFormats []TokenFormat `json:\"formats\"`\n\t// Whether the client supports tokens that can overlap each other.\n\tOverlappingTokenSupport bool `json:\"overlappingTokenSupport,omitempty\"`\n\t// Whether the client supports tokens that can span multiple lines.\n\tMultilineTokenSupport bool `json:\"multilineTokenSupport,omitempty\"`\n\t// Whether the client allows the server to actively cancel a\n\t// semantic token request, e.g. supports returning\n\t// LSPErrorCodes.ServerCancelled. If a server does the client\n\t// needs to retrigger the request.\n\t//\n\t// @since 3.17.0\n\tServerCancelSupport bool `json:\"serverCancelSupport,omitempty\"`\n\t// Whether the client uses semantic tokens to augment existing\n\t// syntax tokens. If set to `true` client side created syntax\n\t// tokens and semantic tokens are both used for colorization. If\n\t// set to `false` the client only uses the returned semantic tokens\n\t// for colorization.\n\t//\n\t// If the value is `undefined` then the client behavior is not\n\t// specified.\n\t//\n\t// @since 3.17.0\n\tAugmentsSyntaxTokens bool `json:\"augmentsSyntaxTokens,omitempty\"`\n}\n\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#semanticTokensDelta\ntype SemanticTokensDelta struct {\n\tResultID string `json:\"resultId,omitempty\"`\n\t// The semantic token edits to transform a previous result into a new result.\n\tEdits []SemanticTokensEdit `json:\"edits\"`\n}\n\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#semanticTokensDeltaParams\ntype SemanticTokensDeltaParams struct {\n\t// The text document.\n\tTextDocument TextDocumentIdentifier `json:\"textDocument\"`\n\t// The result id of a previous response. The result Id can either point to a full response\n\t// or a delta response depending on what was received last.\n\tPreviousResultID string `json:\"previousResultId\"`\n\tWorkDoneProgressParams\n\tPartialResultParams\n}\n\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#semanticTokensDeltaPartialResult\ntype SemanticTokensDeltaPartialResult struct {\n\tEdits []SemanticTokensEdit `json:\"edits\"`\n}\n\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#semanticTokensEdit\ntype SemanticTokensEdit struct {\n\t// The start offset of the edit.\n\tStart uint32 `json:\"start\"`\n\t// The count of elements to remove.\n\tDeleteCount uint32 `json:\"deleteCount\"`\n\t// The elements to insert.\n\tData []uint32 `json:\"data,omitempty\"`\n}\n\n// Semantic tokens options to support deltas for full documents\n//\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#semanticTokensFullDelta\ntype SemanticTokensFullDelta struct {\n\t// The server supports deltas for full documents.\n\tDelta bool `json:\"delta,omitempty\"`\n}\n\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#semanticTokensLegend\ntype SemanticTokensLegend struct {\n\t// The token types a server uses.\n\tTokenTypes []string `json:\"tokenTypes\"`\n\t// The token modifiers a server uses.\n\tTokenModifiers []string `json:\"tokenModifiers\"`\n}\n\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#semanticTokensOptions\ntype SemanticTokensOptions struct {\n\t// The legend used by the server\n\tLegend SemanticTokensLegend `json:\"legend\"`\n\t// Server supports providing semantic tokens for a specific range\n\t// of a document.\n\tRange *Or_SemanticTokensOptions_range `json:\"range,omitempty\"`\n\t// Server supports providing semantic tokens for a full document.\n\tFull *Or_SemanticTokensOptions_full `json:\"full,omitempty\"`\n\tWorkDoneProgressOptions\n}\n\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#semanticTokensParams\ntype SemanticTokensParams struct {\n\t// The text document.\n\tTextDocument TextDocumentIdentifier `json:\"textDocument\"`\n\tWorkDoneProgressParams\n\tPartialResultParams\n}\n\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#semanticTokensPartialResult\ntype SemanticTokensPartialResult struct {\n\tData []uint32 `json:\"data\"`\n}\n\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#semanticTokensRangeParams\ntype SemanticTokensRangeParams struct {\n\t// The text document.\n\tTextDocument TextDocumentIdentifier `json:\"textDocument\"`\n\t// The range the semantic tokens are requested for.\n\tRange Range `json:\"range\"`\n\tWorkDoneProgressParams\n\tPartialResultParams\n}\n\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#semanticTokensRegistrationOptions\ntype SemanticTokensRegistrationOptions struct {\n\tTextDocumentRegistrationOptions\n\tSemanticTokensOptions\n\tStaticRegistrationOptions\n}\n\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#semanticTokensWorkspaceClientCapabilities\ntype SemanticTokensWorkspaceClientCapabilities struct {\n\t// Whether the client implementation supports a refresh request sent from\n\t// the server to the client.\n\t//\n\t// Note that this event is global and will force the client to refresh all\n\t// semantic tokens currently shown. It should be used with absolute care\n\t// and is useful for situation where a server for example detects a project\n\t// wide change that requires such a calculation.\n\tRefreshSupport bool `json:\"refreshSupport,omitempty\"`\n}\n\n// Defines the capabilities provided by a language\n// server.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#serverCapabilities\ntype ServerCapabilities struct {\n\t// The position encoding the server picked from the encodings offered\n\t// by the client via the client capability `general.positionEncodings`.\n\t//\n\t// If the client didn't provide any position encodings the only valid\n\t// value that a server can return is 'utf-16'.\n\t//\n\t// If omitted it defaults to 'utf-16'.\n\t//\n\t// @since 3.17.0\n\tPositionEncoding *PositionEncodingKind `json:\"positionEncoding,omitempty\"`\n\t// Defines how text documents are synced. Is either a detailed structure\n\t// defining each notification or for backwards compatibility the\n\t// TextDocumentSyncKind number.\n\tTextDocumentSync interface{} `json:\"textDocumentSync,omitempty\"`\n\t// Defines how notebook documents are synced.\n\t//\n\t// @since 3.17.0\n\tNotebookDocumentSync *Or_ServerCapabilities_notebookDocumentSync `json:\"notebookDocumentSync,omitempty\"`\n\t// The server provides completion support.\n\tCompletionProvider *CompletionOptions `json:\"completionProvider,omitempty\"`\n\t// The server provides hover support.\n\tHoverProvider *Or_ServerCapabilities_hoverProvider `json:\"hoverProvider,omitempty\"`\n\t// The server provides signature help support.\n\tSignatureHelpProvider *SignatureHelpOptions `json:\"signatureHelpProvider,omitempty\"`\n\t// The server provides Goto Declaration support.\n\tDeclarationProvider *Or_ServerCapabilities_declarationProvider `json:\"declarationProvider,omitempty\"`\n\t// The server provides goto definition support.\n\tDefinitionProvider *Or_ServerCapabilities_definitionProvider `json:\"definitionProvider,omitempty\"`\n\t// The server provides Goto Type Definition support.\n\tTypeDefinitionProvider *Or_ServerCapabilities_typeDefinitionProvider `json:\"typeDefinitionProvider,omitempty\"`\n\t// The server provides Goto Implementation support.\n\tImplementationProvider *Or_ServerCapabilities_implementationProvider `json:\"implementationProvider,omitempty\"`\n\t// The server provides find references support.\n\tReferencesProvider *Or_ServerCapabilities_referencesProvider `json:\"referencesProvider,omitempty\"`\n\t// The server provides document highlight support.\n\tDocumentHighlightProvider *Or_ServerCapabilities_documentHighlightProvider `json:\"documentHighlightProvider,omitempty\"`\n\t// The server provides document symbol support.\n\tDocumentSymbolProvider *Or_ServerCapabilities_documentSymbolProvider `json:\"documentSymbolProvider,omitempty\"`\n\t// The server provides code actions. CodeActionOptions may only be\n\t// specified if the client states that it supports\n\t// `codeActionLiteralSupport` in its initial `initialize` request.\n\tCodeActionProvider interface{} `json:\"codeActionProvider,omitempty\"`\n\t// The server provides code lens.\n\tCodeLensProvider *CodeLensOptions `json:\"codeLensProvider,omitempty\"`\n\t// The server provides document link support.\n\tDocumentLinkProvider *DocumentLinkOptions `json:\"documentLinkProvider,omitempty\"`\n\t// The server provides color provider support.\n\tColorProvider *Or_ServerCapabilities_colorProvider `json:\"colorProvider,omitempty\"`\n\t// The server provides workspace symbol support.\n\tWorkspaceSymbolProvider *Or_ServerCapabilities_workspaceSymbolProvider `json:\"workspaceSymbolProvider,omitempty\"`\n\t// The server provides document formatting.\n\tDocumentFormattingProvider *Or_ServerCapabilities_documentFormattingProvider `json:\"documentFormattingProvider,omitempty\"`\n\t// The server provides document range formatting.\n\tDocumentRangeFormattingProvider *Or_ServerCapabilities_documentRangeFormattingProvider `json:\"documentRangeFormattingProvider,omitempty\"`\n\t// The server provides document formatting on typing.\n\tDocumentOnTypeFormattingProvider *DocumentOnTypeFormattingOptions `json:\"documentOnTypeFormattingProvider,omitempty\"`\n\t// The server provides rename support. RenameOptions may only be\n\t// specified if the client states that it supports\n\t// `prepareSupport` in its initial `initialize` request.\n\tRenameProvider interface{} `json:\"renameProvider,omitempty\"`\n\t// The server provides folding provider support.\n\tFoldingRangeProvider *Or_ServerCapabilities_foldingRangeProvider `json:\"foldingRangeProvider,omitempty\"`\n\t// The server provides selection range support.\n\tSelectionRangeProvider *Or_ServerCapabilities_selectionRangeProvider `json:\"selectionRangeProvider,omitempty\"`\n\t// The server provides execute command support.\n\tExecuteCommandProvider *ExecuteCommandOptions `json:\"executeCommandProvider,omitempty\"`\n\t// The server provides call hierarchy support.\n\t//\n\t// @since 3.16.0\n\tCallHierarchyProvider *Or_ServerCapabilities_callHierarchyProvider `json:\"callHierarchyProvider,omitempty\"`\n\t// The server provides linked editing range support.\n\t//\n\t// @since 3.16.0\n\tLinkedEditingRangeProvider *Or_ServerCapabilities_linkedEditingRangeProvider `json:\"linkedEditingRangeProvider,omitempty\"`\n\t// The server provides semantic tokens support.\n\t//\n\t// @since 3.16.0\n\tSemanticTokensProvider interface{} `json:\"semanticTokensProvider,omitempty\"`\n\t// The server provides moniker support.\n\t//\n\t// @since 3.16.0\n\tMonikerProvider *Or_ServerCapabilities_monikerProvider `json:\"monikerProvider,omitempty\"`\n\t// The server provides type hierarchy support.\n\t//\n\t// @since 3.17.0\n\tTypeHierarchyProvider *Or_ServerCapabilities_typeHierarchyProvider `json:\"typeHierarchyProvider,omitempty\"`\n\t// The server provides inline values.\n\t//\n\t// @since 3.17.0\n\tInlineValueProvider *Or_ServerCapabilities_inlineValueProvider `json:\"inlineValueProvider,omitempty\"`\n\t// The server provides inlay hints.\n\t//\n\t// @since 3.17.0\n\tInlayHintProvider interface{} `json:\"inlayHintProvider,omitempty\"`\n\t// The server has support for pull model diagnostics.\n\t//\n\t// @since 3.17.0\n\tDiagnosticProvider *Or_ServerCapabilities_diagnosticProvider `json:\"diagnosticProvider,omitempty\"`\n\t// Inline completion options used during static registration.\n\t//\n\t// @since 3.18.0\n\t// @proposed\n\tInlineCompletionProvider *Or_ServerCapabilities_inlineCompletionProvider `json:\"inlineCompletionProvider,omitempty\"`\n\t// Workspace specific server capabilities.\n\tWorkspace *WorkspaceOptions `json:\"workspace,omitempty\"`\n\t// Experimental server capabilities.\n\tExperimental interface{} `json:\"experimental,omitempty\"`\n}\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#serverCompletionItemOptions\ntype ServerCompletionItemOptions struct {\n\t// The server has support for completion item label\n\t// details (see also `CompletionItemLabelDetails`) when\n\t// receiving a completion item in a resolve call.\n\t//\n\t// @since 3.17.0\n\tLabelDetailsSupport bool `json:\"labelDetailsSupport,omitempty\"`\n}\n\n// Information about the server\n//\n// @since 3.15.0\n// @since 3.18.0 ServerInfo type name added.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#serverInfo\ntype ServerInfo struct {\n\t// The name of the server as defined by the server.\n\tName string `json:\"name\"`\n\t// The server's version as defined by the server.\n\tVersion string `json:\"version,omitempty\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#setTraceParams\ntype SetTraceParams struct {\n\tValue TraceValue `json:\"value\"`\n}\n\n// Client capabilities for the showDocument request.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#showDocumentClientCapabilities\ntype ShowDocumentClientCapabilities struct {\n\t// The client has support for the showDocument\n\t// request.\n\tSupport bool `json:\"support\"`\n}\n\n// Params to show a resource in the UI.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#showDocumentParams\ntype ShowDocumentParams struct {\n\t// The uri to show.\n\tURI URI `json:\"uri\"`\n\t// Indicates to show the resource in an external program.\n\t// To show, for example, `https://code.visualstudio.com/`\n\t// in the default WEB browser set `external` to `true`.\n\tExternal bool `json:\"external,omitempty\"`\n\t// An optional property to indicate whether the editor\n\t// showing the document should take focus or not.\n\t// Clients might ignore this property if an external\n\t// program is started.\n\tTakeFocus bool `json:\"takeFocus,omitempty\"`\n\t// An optional selection range if the document is a text\n\t// document. Clients might ignore the property if an\n\t// external program is started or the file is not a text\n\t// file.\n\tSelection *Range `json:\"selection,omitempty\"`\n}\n\n// The result of a showDocument request.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#showDocumentResult\ntype ShowDocumentResult struct {\n\t// A boolean indicating if the show was successful.\n\tSuccess bool `json:\"success\"`\n}\n\n// The parameters of a notification message.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#showMessageParams\ntype ShowMessageParams struct {\n\t// The message type. See {@link MessageType}\n\tType MessageType `json:\"type\"`\n\t// The actual message.\n\tMessage string `json:\"message\"`\n}\n\n// Show message request client capabilities\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#showMessageRequestClientCapabilities\ntype ShowMessageRequestClientCapabilities struct {\n\t// Capabilities specific to the `MessageActionItem` type.\n\tMessageActionItem *ClientShowMessageActionItemOptions `json:\"messageActionItem,omitempty\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#showMessageRequestParams\ntype ShowMessageRequestParams struct {\n\t// The message type. See {@link MessageType}\n\tType MessageType `json:\"type\"`\n\t// The actual message.\n\tMessage string `json:\"message\"`\n\t// The message action items to present.\n\tActions []MessageActionItem `json:\"actions,omitempty\"`\n}\n\n// Signature help represents the signature of something\n// callable. There can be multiple signature but only one\n// active and only one active parameter.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#signatureHelp\ntype SignatureHelp struct {\n\t// One or more signatures.\n\tSignatures []SignatureInformation `json:\"signatures\"`\n\t// The active signature. If omitted or the value lies outside the\n\t// range of `signatures` the value defaults to zero or is ignored if\n\t// the `SignatureHelp` has no signatures.\n\t//\n\t// Whenever possible implementors should make an active decision about\n\t// the active signature and shouldn't rely on a default value.\n\t//\n\t// In future version of the protocol this property might become\n\t// mandatory to better express this.\n\tActiveSignature uint32 `json:\"activeSignature,omitempty\"`\n\t// The active parameter of the active signature.\n\t//\n\t// If `null`, no parameter of the signature is active (for example a named\n\t// argument that does not match any declared parameters). This is only valid\n\t// if the client specifies the client capability\n\t// `textDocument.signatureHelp.noActiveParameterSupport === true`\n\t//\n\t// If omitted or the value lies outside the range of\n\t// `signatures[activeSignature].parameters` defaults to 0 if the active\n\t// signature has parameters.\n\t//\n\t// If the active signature has no parameters it is ignored.\n\t//\n\t// In future version of the protocol this property might become\n\t// mandatory (but still nullable) to better express the active parameter if\n\t// the active signature does have any.\n\tActiveParameter uint32 `json:\"activeParameter,omitempty\"`\n}\n\n// Client Capabilities for a {@link SignatureHelpRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#signatureHelpClientCapabilities\ntype SignatureHelpClientCapabilities struct {\n\t// Whether signature help supports dynamic registration.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n\t// The client supports the following `SignatureInformation`\n\t// specific properties.\n\tSignatureInformation *ClientSignatureInformationOptions `json:\"signatureInformation,omitempty\"`\n\t// The client supports to send additional context information for a\n\t// `textDocument/signatureHelp` request. A client that opts into\n\t// contextSupport will also support the `retriggerCharacters` on\n\t// `SignatureHelpOptions`.\n\t//\n\t// @since 3.15.0\n\tContextSupport bool `json:\"contextSupport,omitempty\"`\n}\n\n// Additional information about the context in which a signature help request was triggered.\n//\n// @since 3.15.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#signatureHelpContext\ntype SignatureHelpContext struct {\n\t// Action that caused signature help to be triggered.\n\tTriggerKind SignatureHelpTriggerKind `json:\"triggerKind\"`\n\t// Character that caused signature help to be triggered.\n\t//\n\t// This is undefined when `triggerKind !== SignatureHelpTriggerKind.TriggerCharacter`\n\tTriggerCharacter string `json:\"triggerCharacter,omitempty\"`\n\t// `true` if signature help was already showing when it was triggered.\n\t//\n\t// Retriggers occurs when the signature help is already active and can be caused by actions such as\n\t// typing a trigger character, a cursor move, or document content changes.\n\tIsRetrigger bool `json:\"isRetrigger\"`\n\t// The currently active `SignatureHelp`.\n\t//\n\t// The `activeSignatureHelp` has its `SignatureHelp.activeSignature` field updated based on\n\t// the user navigating through available signatures.\n\tActiveSignatureHelp *SignatureHelp `json:\"activeSignatureHelp,omitempty\"`\n}\n\n// Server Capabilities for a {@link SignatureHelpRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#signatureHelpOptions\ntype SignatureHelpOptions struct {\n\t// List of characters that trigger signature help automatically.\n\tTriggerCharacters []string `json:\"triggerCharacters,omitempty\"`\n\t// List of characters that re-trigger signature help.\n\t//\n\t// These trigger characters are only active when signature help is already showing. All trigger characters\n\t// are also counted as re-trigger characters.\n\t//\n\t// @since 3.15.0\n\tRetriggerCharacters []string `json:\"retriggerCharacters,omitempty\"`\n\tWorkDoneProgressOptions\n}\n\n// Parameters for a {@link SignatureHelpRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#signatureHelpParams\ntype SignatureHelpParams struct {\n\t// The signature help context. This is only available if the client specifies\n\t// to send this using the client capability `textDocument.signatureHelp.contextSupport === true`\n\t//\n\t// @since 3.15.0\n\tContext *SignatureHelpContext `json:\"context,omitempty\"`\n\tTextDocumentPositionParams\n\tWorkDoneProgressParams\n}\n\n// Registration options for a {@link SignatureHelpRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#signatureHelpRegistrationOptions\ntype SignatureHelpRegistrationOptions struct {\n\tTextDocumentRegistrationOptions\n\tSignatureHelpOptions\n}\n\n// How a signature help was triggered.\n//\n// @since 3.15.0\ntype SignatureHelpTriggerKind uint32\n\n// Represents the signature of something callable. A signature\n// can have a label, like a function-name, a doc-comment, and\n// a set of parameters.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#signatureInformation\ntype SignatureInformation struct {\n\t// The label of this signature. Will be shown in\n\t// the UI.\n\tLabel string `json:\"label\"`\n\t// The human-readable doc-comment of this signature. Will be shown\n\t// in the UI but can be omitted.\n\tDocumentation *Or_SignatureInformation_documentation `json:\"documentation,omitempty\"`\n\t// The parameters of this signature.\n\tParameters []ParameterInformation `json:\"parameters,omitempty\"`\n\t// The index of the active parameter.\n\t//\n\t// If `null`, no parameter of the signature is active (for example a named\n\t// argument that does not match any declared parameters). This is only valid\n\t// if the client specifies the client capability\n\t// `textDocument.signatureHelp.noActiveParameterSupport === true`\n\t//\n\t// If provided (or `null`), this is used in place of\n\t// `SignatureHelp.activeParameter`.\n\t//\n\t// @since 3.16.0\n\tActiveParameter uint32 `json:\"activeParameter,omitempty\"`\n}\n\n// An interactive text edit.\n//\n// @since 3.18.0\n// @proposed\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#snippetTextEdit\ntype SnippetTextEdit struct {\n\t// The range of the text document to be manipulated.\n\tRange Range `json:\"range\"`\n\t// The snippet to be inserted.\n\tSnippet StringValue `json:\"snippet\"`\n\t// The actual identifier of the snippet edit.\n\tAnnotationID *ChangeAnnotationIdentifier `json:\"annotationId,omitempty\"`\n}\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#staleRequestSupportOptions\ntype StaleRequestSupportOptions struct {\n\t// The client will actively cancel the request.\n\tCancel bool `json:\"cancel\"`\n\t// The list of requests for which the client\n\t// will retry the request if it receives a\n\t// response with error code `ContentModified`\n\tRetryOnContentModified []string `json:\"retryOnContentModified\"`\n}\n\n// Static registration options to be returned in the initialize\n// request.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#staticRegistrationOptions\ntype StaticRegistrationOptions struct {\n\t// The id used to register the request. The id can be used to deregister\n\t// the request again. See also Registration#id.\n\tID string `json:\"id,omitempty\"`\n}\n\n// A string value used as a snippet is a template which allows to insert text\n// and to control the editor cursor when insertion happens.\n//\n// A snippet can define tab stops and placeholders with `$1`, `$2`\n// and `${3:foo}`. `$0` defines the final tab stop, it defaults to\n// the end of the snippet. Variables are defined with `$name` and\n// `${name:default value}`.\n//\n// @since 3.18.0\n// @proposed\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#stringValue\ntype StringValue struct {\n\t// The kind of string value.\n\tKind string `json:\"kind\"`\n\t// The snippet string.\n\tValue string `json:\"value\"`\n}\n\n// Represents information about programming constructs like variables, classes,\n// interfaces etc.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#symbolInformation\ntype SymbolInformation struct {\n\t// extends BaseSymbolInformation\n\t// Indicates if this symbol is deprecated.\n\t//\n\t// @deprecated Use tags instead\n\tDeprecated bool `json:\"deprecated,omitempty\"`\n\t// The location of this symbol. The location's range is used by a tool\n\t// to reveal the location in the editor. If the symbol is selected in the\n\t// tool the range's start information is used to position the cursor. So\n\t// the range usually spans more than the actual symbol's name and does\n\t// normally include things like visibility modifiers.\n\t//\n\t// The range doesn't have to denote a node range in the sense of an abstract\n\t// syntax tree. It can therefore not be used to re-construct a hierarchy of\n\t// the symbols.\n\tLocation Location `json:\"location\"`\n\t// The name of this symbol.\n\tName string `json:\"name\"`\n\t// The kind of this symbol.\n\tKind SymbolKind `json:\"kind\"`\n\t// Tags for this symbol.\n\t//\n\t// @since 3.16.0\n\tTags []SymbolTag `json:\"tags,omitempty\"`\n\t// The name of the symbol containing this symbol. This information is for\n\t// user interface purposes (e.g. to render a qualifier in the user interface\n\t// if necessary). It can't be used to re-infer a hierarchy for the document\n\t// symbols.\n\tContainerName string `json:\"containerName,omitempty\"`\n}\n\n// A symbol kind.\ntype SymbolKind uint32\n\n// Symbol tags are extra annotations that tweak the rendering of a symbol.\n//\n// @since 3.16\ntype SymbolTag uint32\n\n// Describe options to be used when registered for text document change events.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#textDocumentChangeRegistrationOptions\ntype TextDocumentChangeRegistrationOptions struct {\n\t// How documents are synced to the server.\n\tSyncKind TextDocumentSyncKind `json:\"syncKind\"`\n\tTextDocumentRegistrationOptions\n}\n\n// Text document specific client capabilities.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#textDocumentClientCapabilities\ntype TextDocumentClientCapabilities struct {\n\t// Defines which synchronization capabilities the client supports.\n\tSynchronization *TextDocumentSyncClientCapabilities `json:\"synchronization,omitempty\"`\n\t// Capabilities specific to the `textDocument/completion` request.\n\tCompletion CompletionClientCapabilities `json:\"completion,omitempty\"`\n\t// Capabilities specific to the `textDocument/hover` request.\n\tHover *HoverClientCapabilities `json:\"hover,omitempty\"`\n\t// Capabilities specific to the `textDocument/signatureHelp` request.\n\tSignatureHelp *SignatureHelpClientCapabilities `json:\"signatureHelp,omitempty\"`\n\t// Capabilities specific to the `textDocument/declaration` request.\n\t//\n\t// @since 3.14.0\n\tDeclaration *DeclarationClientCapabilities `json:\"declaration,omitempty\"`\n\t// Capabilities specific to the `textDocument/definition` request.\n\tDefinition *DefinitionClientCapabilities `json:\"definition,omitempty\"`\n\t// Capabilities specific to the `textDocument/typeDefinition` request.\n\t//\n\t// @since 3.6.0\n\tTypeDefinition *TypeDefinitionClientCapabilities `json:\"typeDefinition,omitempty\"`\n\t// Capabilities specific to the `textDocument/implementation` request.\n\t//\n\t// @since 3.6.0\n\tImplementation *ImplementationClientCapabilities `json:\"implementation,omitempty\"`\n\t// Capabilities specific to the `textDocument/references` request.\n\tReferences *ReferenceClientCapabilities `json:\"references,omitempty\"`\n\t// Capabilities specific to the `textDocument/documentHighlight` request.\n\tDocumentHighlight *DocumentHighlightClientCapabilities `json:\"documentHighlight,omitempty\"`\n\t// Capabilities specific to the `textDocument/documentSymbol` request.\n\tDocumentSymbol DocumentSymbolClientCapabilities `json:\"documentSymbol,omitempty\"`\n\t// Capabilities specific to the `textDocument/codeAction` request.\n\tCodeAction CodeActionClientCapabilities `json:\"codeAction,omitempty\"`\n\t// Capabilities specific to the `textDocument/codeLens` request.\n\tCodeLens *CodeLensClientCapabilities `json:\"codeLens,omitempty\"`\n\t// Capabilities specific to the `textDocument/documentLink` request.\n\tDocumentLink *DocumentLinkClientCapabilities `json:\"documentLink,omitempty\"`\n\t// Capabilities specific to the `textDocument/documentColor` and the\n\t// `textDocument/colorPresentation` request.\n\t//\n\t// @since 3.6.0\n\tColorProvider *DocumentColorClientCapabilities `json:\"colorProvider,omitempty\"`\n\t// Capabilities specific to the `textDocument/formatting` request.\n\tFormatting *DocumentFormattingClientCapabilities `json:\"formatting,omitempty\"`\n\t// Capabilities specific to the `textDocument/rangeFormatting` request.\n\tRangeFormatting *DocumentRangeFormattingClientCapabilities `json:\"rangeFormatting,omitempty\"`\n\t// Capabilities specific to the `textDocument/onTypeFormatting` request.\n\tOnTypeFormatting *DocumentOnTypeFormattingClientCapabilities `json:\"onTypeFormatting,omitempty\"`\n\t// Capabilities specific to the `textDocument/rename` request.\n\tRename *RenameClientCapabilities `json:\"rename,omitempty\"`\n\t// Capabilities specific to the `textDocument/foldingRange` request.\n\t//\n\t// @since 3.10.0\n\tFoldingRange *FoldingRangeClientCapabilities `json:\"foldingRange,omitempty\"`\n\t// Capabilities specific to the `textDocument/selectionRange` request.\n\t//\n\t// @since 3.15.0\n\tSelectionRange *SelectionRangeClientCapabilities `json:\"selectionRange,omitempty\"`\n\t// Capabilities specific to the `textDocument/publishDiagnostics` notification.\n\tPublishDiagnostics PublishDiagnosticsClientCapabilities `json:\"publishDiagnostics,omitempty\"`\n\t// Capabilities specific to the various call hierarchy requests.\n\t//\n\t// @since 3.16.0\n\tCallHierarchy *CallHierarchyClientCapabilities `json:\"callHierarchy,omitempty\"`\n\t// Capabilities specific to the various semantic token request.\n\t//\n\t// @since 3.16.0\n\tSemanticTokens SemanticTokensClientCapabilities `json:\"semanticTokens,omitempty\"`\n\t// Capabilities specific to the `textDocument/linkedEditingRange` request.\n\t//\n\t// @since 3.16.0\n\tLinkedEditingRange *LinkedEditingRangeClientCapabilities `json:\"linkedEditingRange,omitempty\"`\n\t// Client capabilities specific to the `textDocument/moniker` request.\n\t//\n\t// @since 3.16.0\n\tMoniker *MonikerClientCapabilities `json:\"moniker,omitempty\"`\n\t// Capabilities specific to the various type hierarchy requests.\n\t//\n\t// @since 3.17.0\n\tTypeHierarchy *TypeHierarchyClientCapabilities `json:\"typeHierarchy,omitempty\"`\n\t// Capabilities specific to the `textDocument/inlineValue` request.\n\t//\n\t// @since 3.17.0\n\tInlineValue *InlineValueClientCapabilities `json:\"inlineValue,omitempty\"`\n\t// Capabilities specific to the `textDocument/inlayHint` request.\n\t//\n\t// @since 3.17.0\n\tInlayHint *InlayHintClientCapabilities `json:\"inlayHint,omitempty\"`\n\t// Capabilities specific to the diagnostic pull model.\n\t//\n\t// @since 3.17.0\n\tDiagnostic *DiagnosticClientCapabilities `json:\"diagnostic,omitempty\"`\n\t// Client capabilities specific to inline completions.\n\t//\n\t// @since 3.18.0\n\t// @proposed\n\tInlineCompletion *InlineCompletionClientCapabilities `json:\"inlineCompletion,omitempty\"`\n}\n\n// An event describing a change to a text document. If only a text is provided\n// it is considered to be the full content of the document.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#textDocumentContentChangeEvent\ntype TextDocumentContentChangeEvent = Or_TextDocumentContentChangeEvent // (alias)\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#textDocumentContentChangePartial\ntype TextDocumentContentChangePartial struct {\n\t// The range of the document that changed.\n\tRange *Range `json:\"range,omitempty\"`\n\t// The optional length of the range that got replaced.\n\t//\n\t// @deprecated use range instead.\n\tRangeLength uint32 `json:\"rangeLength,omitempty\"`\n\t// The new text for the provided range.\n\tText string `json:\"text\"`\n}\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#textDocumentContentChangeWholeDocument\ntype TextDocumentContentChangeWholeDocument struct {\n\t// The new text of the whole document.\n\tText string `json:\"text\"`\n}\n\n// Client capabilities for a text document content provider.\n//\n// @since 3.18.0\n// @proposed\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#textDocumentContentClientCapabilities\ntype TextDocumentContentClientCapabilities struct {\n\t// Text document content provider supports dynamic registration.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n}\n\n// Text document content provider options.\n//\n// @since 3.18.0\n// @proposed\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#textDocumentContentOptions\ntype TextDocumentContentOptions struct {\n\t// The scheme for which the server provides content.\n\tScheme string `json:\"scheme\"`\n}\n\n// Parameters for the `workspace/textDocumentContent` request.\n//\n// @since 3.18.0\n// @proposed\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#textDocumentContentParams\ntype TextDocumentContentParams struct {\n\t// The uri of the text document.\n\tURI DocumentUri `json:\"uri\"`\n}\n\n// Parameters for the `workspace/textDocumentContent/refresh` request.\n//\n// @since 3.18.0\n// @proposed\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#textDocumentContentRefreshParams\ntype TextDocumentContentRefreshParams struct {\n\t// The uri of the text document to refresh.\n\tURI DocumentUri `json:\"uri\"`\n}\n\n// Text document content provider registration options.\n//\n// @since 3.18.0\n// @proposed\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#textDocumentContentRegistrationOptions\ntype TextDocumentContentRegistrationOptions struct {\n\tTextDocumentContentOptions\n\tStaticRegistrationOptions\n}\n\n// Describes textual changes on a text document. A TextDocumentEdit describes all changes\n// on a document version Si and after they are applied move the document to version Si+1.\n// So the creator of a TextDocumentEdit doesn't need to sort the array of edits or do any\n// kind of ordering. However the edits must be non overlapping.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#textDocumentEdit\ntype TextDocumentEdit struct {\n\t// The text document to change.\n\tTextDocument OptionalVersionedTextDocumentIdentifier `json:\"textDocument\"`\n\t// The edits to be applied.\n\t//\n\t// @since 3.16.0 - support for AnnotatedTextEdit. This is guarded using a\n\t// client capability.\n\t//\n\t// @since 3.18.0 - support for SnippetTextEdit. This is guarded using a\n\t// client capability.\n\tEdits []Or_TextDocumentEdit_edits_Elem `json:\"edits\"`\n}\n\n// A document filter denotes a document by different properties like\n// the {@link TextDocument.languageId language}, the {@link Uri.scheme scheme} of\n// its resource, or a glob-pattern that is applied to the {@link TextDocument.fileName path}.\n//\n// Glob patterns can have the following syntax:\n//\n// - `*` to match one or more characters in a path segment\n// - `?` to match on one character in a path segment\n// - `**` to match any number of path segments, including none\n// - `{}` to group sub patterns into an OR expression. (e.g. `**/*.{ts,js}` matches all TypeScript and JavaScript files)\n// - `[]` to declare a range of characters to match in a path segment (e.g., `example.[0-9]` to match on `example.0`, `example.1`, …)\n// - `[!...]` to negate a range of characters to match in a path segment (e.g., `example.[!0-9]` to match on `example.a`, `example.b`, but not `example.0`)\n//\n// @sample A language filter that applies to typescript files on disk: `{ language: 'typescript', scheme: 'file' }`\n// @sample A language filter that applies to all package.json paths: `{ language: 'json', pattern: '**package.json' }`\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#textDocumentFilter\ntype TextDocumentFilter = Or_TextDocumentFilter // (alias)\n// A document filter where `language` is required field.\n//\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#textDocumentFilterLanguage\ntype TextDocumentFilterLanguage struct {\n\t// A language id, like `typescript`.\n\tLanguage string `json:\"language\"`\n\t// A Uri {@link Uri.scheme scheme}, like `file` or `untitled`.\n\tScheme string `json:\"scheme,omitempty\"`\n\t// A glob pattern, like **/*.{ts,js}. See TextDocumentFilter for examples.\n\t//\n\t// @since 3.18.0 - support for relative patterns.\n\tPattern *GlobPattern `json:\"pattern,omitempty\"`\n}\n\n// A document filter where `pattern` is required field.\n//\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#textDocumentFilterPattern\ntype TextDocumentFilterPattern struct {\n\t// A language id, like `typescript`.\n\tLanguage string `json:\"language,omitempty\"`\n\t// A Uri {@link Uri.scheme scheme}, like `file` or `untitled`.\n\tScheme string `json:\"scheme,omitempty\"`\n\t// A glob pattern, like **/*.{ts,js}. See TextDocumentFilter for examples.\n\t//\n\t// @since 3.18.0 - support for relative patterns.\n\tPattern GlobPattern `json:\"pattern\"`\n}\n\n// A document filter where `scheme` is required field.\n//\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#textDocumentFilterScheme\ntype TextDocumentFilterScheme struct {\n\t// A language id, like `typescript`.\n\tLanguage string `json:\"language,omitempty\"`\n\t// A Uri {@link Uri.scheme scheme}, like `file` or `untitled`.\n\tScheme string `json:\"scheme\"`\n\t// A glob pattern, like **/*.{ts,js}. See TextDocumentFilter for examples.\n\t//\n\t// @since 3.18.0 - support for relative patterns.\n\tPattern *GlobPattern `json:\"pattern,omitempty\"`\n}\n\n// A literal to identify a text document in the client.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#textDocumentIdentifier\ntype TextDocumentIdentifier struct {\n\t// The text document's uri.\n\tURI DocumentUri `json:\"uri\"`\n}\n\n// An item to transfer a text document from the client to the\n// server.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#textDocumentItem\ntype TextDocumentItem struct {\n\t// The text document's uri.\n\tURI DocumentUri `json:\"uri\"`\n\t// The text document's language identifier.\n\tLanguageID LanguageKind `json:\"languageId\"`\n\t// The version number of this document (it will increase after each\n\t// change, including undo/redo).\n\tVersion int32 `json:\"version\"`\n\t// The content of the opened text document.\n\tText string `json:\"text\"`\n}\n\n// A parameter literal used in requests to pass a text document and a position inside that\n// document.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#textDocumentPositionParams\ntype TextDocumentPositionParams struct {\n\t// The text document.\n\tTextDocument TextDocumentIdentifier `json:\"textDocument\"`\n\t// The position inside the text document.\n\tPosition Position `json:\"position\"`\n}\n\n// General text document registration options.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#textDocumentRegistrationOptions\ntype TextDocumentRegistrationOptions struct {\n\t// A document selector to identify the scope of the registration. If set to null\n\t// the document selector provided on the client side will be used.\n\tDocumentSelector DocumentSelector `json:\"documentSelector\"`\n}\n\n// Represents reasons why a text document is saved.\ntype TextDocumentSaveReason uint32\n\n// Save registration options.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#textDocumentSaveRegistrationOptions\ntype TextDocumentSaveRegistrationOptions struct {\n\tTextDocumentRegistrationOptions\n\tSaveOptions\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#textDocumentSyncClientCapabilities\ntype TextDocumentSyncClientCapabilities struct {\n\t// Whether text document synchronization supports dynamic registration.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n\t// The client supports sending will save notifications.\n\tWillSave bool `json:\"willSave,omitempty\"`\n\t// The client supports sending a will save request and\n\t// waits for a response providing text edits which will\n\t// be applied to the document before it is saved.\n\tWillSaveWaitUntil bool `json:\"willSaveWaitUntil,omitempty\"`\n\t// The client supports did save notifications.\n\tDidSave bool `json:\"didSave,omitempty\"`\n}\n\n// Defines how the host (editor) should sync\n// document changes to the language server.\ntype TextDocumentSyncKind uint32\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#textDocumentSyncOptions\ntype TextDocumentSyncOptions struct {\n\t// Open and close notifications are sent to the server. If omitted open close notification should not\n\t// be sent.\n\tOpenClose bool `json:\"openClose,omitempty\"`\n\t// Change notifications are sent to the server. See TextDocumentSyncKind.None, TextDocumentSyncKind.Full\n\t// and TextDocumentSyncKind.Incremental. If omitted it defaults to TextDocumentSyncKind.None.\n\tChange TextDocumentSyncKind `json:\"change,omitempty\"`\n\t// If present will save notifications are sent to the server. If omitted the notification should not be\n\t// sent.\n\tWillSave bool `json:\"willSave,omitempty\"`\n\t// If present will save wait until requests are sent to the server. If omitted the request should not be\n\t// sent.\n\tWillSaveWaitUntil bool `json:\"willSaveWaitUntil,omitempty\"`\n\t// If present save notifications are sent to the server. If omitted the notification should not be\n\t// sent.\n\tSave *SaveOptions `json:\"save,omitempty\"`\n}\n\n// A text edit applicable to a text document.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#textEdit\ntype TextEdit struct {\n\t// The range of the text document to be manipulated. To insert\n\t// text into a document create a range where start === end.\n\tRange Range `json:\"range\"`\n\t// The string to be inserted. For delete operations use an\n\t// empty string.\n\tNewText string `json:\"newText\"`\n}\ntype TokenFormat string\ntype TraceValue string\n\n// created for Tuple\ntype Tuple_ParameterInformation_label_Item1 struct {\n\tFld0 uint32 `json:\"fld0\"`\n\tFld1 uint32 `json:\"fld1\"`\n}\n\n// Since 3.6.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#typeDefinitionClientCapabilities\ntype TypeDefinitionClientCapabilities struct {\n\t// Whether implementation supports dynamic registration. If this is set to `true`\n\t// the client supports the new `TypeDefinitionRegistrationOptions` return value\n\t// for the corresponding server capability as well.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n\t// The client supports additional metadata in the form of definition links.\n\t//\n\t// Since 3.14.0\n\tLinkSupport bool `json:\"linkSupport,omitempty\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#typeDefinitionOptions\ntype TypeDefinitionOptions struct {\n\tWorkDoneProgressOptions\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#typeDefinitionParams\ntype TypeDefinitionParams struct {\n\tTextDocumentPositionParams\n\tWorkDoneProgressParams\n\tPartialResultParams\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#typeDefinitionRegistrationOptions\ntype TypeDefinitionRegistrationOptions struct {\n\tTextDocumentRegistrationOptions\n\tTypeDefinitionOptions\n\tStaticRegistrationOptions\n}\n\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#typeHierarchyClientCapabilities\ntype TypeHierarchyClientCapabilities struct {\n\t// Whether implementation supports dynamic registration. If this is set to `true`\n\t// the client supports the new `(TextDocumentRegistrationOptions & StaticRegistrationOptions)`\n\t// return value for the corresponding server capability as well.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n}\n\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#typeHierarchyItem\ntype TypeHierarchyItem struct {\n\t// The name of this item.\n\tName string `json:\"name\"`\n\t// The kind of this item.\n\tKind SymbolKind `json:\"kind\"`\n\t// Tags for this item.\n\tTags []SymbolTag `json:\"tags,omitempty\"`\n\t// More detail for this item, e.g. the signature of a function.\n\tDetail string `json:\"detail,omitempty\"`\n\t// The resource identifier of this item.\n\tURI DocumentUri `json:\"uri\"`\n\t// The range enclosing this symbol not including leading/trailing whitespace\n\t// but everything else, e.g. comments and code.\n\tRange Range `json:\"range\"`\n\t// The range that should be selected and revealed when this symbol is being\n\t// picked, e.g. the name of a function. Must be contained by the\n\t// {@link TypeHierarchyItem.range `range`}.\n\tSelectionRange Range `json:\"selectionRange\"`\n\t// A data entry field that is preserved between a type hierarchy prepare and\n\t// supertypes or subtypes requests. It could also be used to identify the\n\t// type hierarchy in the server, helping improve the performance on\n\t// resolving supertypes and subtypes.\n\tData interface{} `json:\"data,omitempty\"`\n}\n\n// Type hierarchy options used during static registration.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#typeHierarchyOptions\ntype TypeHierarchyOptions struct {\n\tWorkDoneProgressOptions\n}\n\n// The parameter of a `textDocument/prepareTypeHierarchy` request.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#typeHierarchyPrepareParams\ntype TypeHierarchyPrepareParams struct {\n\tTextDocumentPositionParams\n\tWorkDoneProgressParams\n}\n\n// Type hierarchy options used during static or dynamic registration.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#typeHierarchyRegistrationOptions\ntype TypeHierarchyRegistrationOptions struct {\n\tTextDocumentRegistrationOptions\n\tTypeHierarchyOptions\n\tStaticRegistrationOptions\n}\n\n// The parameter of a `typeHierarchy/subtypes` request.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#typeHierarchySubtypesParams\ntype TypeHierarchySubtypesParams struct {\n\tItem TypeHierarchyItem `json:\"item\"`\n\tWorkDoneProgressParams\n\tPartialResultParams\n}\n\n// The parameter of a `typeHierarchy/supertypes` request.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#typeHierarchySupertypesParams\ntype TypeHierarchySupertypesParams struct {\n\tItem TypeHierarchyItem `json:\"item\"`\n\tWorkDoneProgressParams\n\tPartialResultParams\n}\n\n// A diagnostic report indicating that the last returned\n// report is still accurate.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#unchangedDocumentDiagnosticReport\ntype UnchangedDocumentDiagnosticReport struct {\n\t// A document diagnostic report indicating\n\t// no changes to the last result. A server can\n\t// only return `unchanged` if result ids are\n\t// provided.\n\tKind string `json:\"kind\"`\n\t// A result id which will be sent on the next\n\t// diagnostic request for the same document.\n\tResultID string `json:\"resultId\"`\n}\n\n// Moniker uniqueness level to define scope of the moniker.\n//\n// @since 3.16.0\ntype UniquenessLevel string\n\n// General parameters to unregister a request or notification.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#unregistration\ntype Unregistration struct {\n\t// The id used to unregister the request or notification. Usually an id\n\t// provided during the register request.\n\tID string `json:\"id\"`\n\t// The method to unregister for.\n\tMethod string `json:\"method\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#unregistrationParams\ntype UnregistrationParams struct {\n\tUnregisterations []Unregistration `json:\"unregisterations\"`\n}\n\n// A versioned notebook document identifier.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#versionedNotebookDocumentIdentifier\ntype VersionedNotebookDocumentIdentifier struct {\n\t// The version number of this notebook document.\n\tVersion int32 `json:\"version\"`\n\t// The notebook document's uri.\n\tURI URI `json:\"uri\"`\n}\n\n// A text document identifier to denote a specific version of a text document.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#versionedTextDocumentIdentifier\ntype VersionedTextDocumentIdentifier struct {\n\t// The version number of this document.\n\tVersion int32 `json:\"version\"`\n\tTextDocumentIdentifier\n}\ntype WatchKind = uint32 // The parameters sent in a will save text document notification.\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#willSaveTextDocumentParams\ntype WillSaveTextDocumentParams struct {\n\t// The document that will be saved.\n\tTextDocument TextDocumentIdentifier `json:\"textDocument\"`\n\t// The 'TextDocumentSaveReason'.\n\tReason TextDocumentSaveReason `json:\"reason\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#windowClientCapabilities\ntype WindowClientCapabilities struct {\n\t// It indicates whether the client supports server initiated\n\t// progress using the `window/workDoneProgress/create` request.\n\t//\n\t// The capability also controls Whether client supports handling\n\t// of progress notifications. If set servers are allowed to report a\n\t// `workDoneProgress` property in the request specific server\n\t// capabilities.\n\t//\n\t// @since 3.15.0\n\tWorkDoneProgress bool `json:\"workDoneProgress,omitempty\"`\n\t// Capabilities specific to the showMessage request.\n\t//\n\t// @since 3.16.0\n\tShowMessage *ShowMessageRequestClientCapabilities `json:\"showMessage,omitempty\"`\n\t// Capabilities specific to the showDocument request.\n\t//\n\t// @since 3.16.0\n\tShowDocument *ShowDocumentClientCapabilities `json:\"showDocument,omitempty\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#workDoneProgressBegin\ntype WorkDoneProgressBegin struct {\n\tKind string `json:\"kind\"`\n\t// Mandatory title of the progress operation. Used to briefly inform about\n\t// the kind of operation being performed.\n\t//\n\t// Examples: \"Indexing\" or \"Linking dependencies\".\n\tTitle string `json:\"title\"`\n\t// Controls if a cancel button should show to allow the user to cancel the\n\t// long running operation. Clients that don't support cancellation are allowed\n\t// to ignore the setting.\n\tCancellable bool `json:\"cancellable,omitempty\"`\n\t// Optional, more detailed associated progress message. Contains\n\t// complementary information to the `title`.\n\t//\n\t// Examples: \"3/25 files\", \"project/src/module2\", \"node_modules/some_dep\".\n\t// If unset, the previous progress message (if any) is still valid.\n\tMessage string `json:\"message,omitempty\"`\n\t// Optional progress percentage to display (value 100 is considered 100%).\n\t// If not provided infinite progress is assumed and clients are allowed\n\t// to ignore the `percentage` value in subsequent in report notifications.\n\t//\n\t// The value should be steadily rising. Clients are free to ignore values\n\t// that are not following this rule. The value range is [0, 100].\n\tPercentage uint32 `json:\"percentage,omitempty\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#workDoneProgressCancelParams\ntype WorkDoneProgressCancelParams struct {\n\t// The token to be used to report progress.\n\tToken ProgressToken `json:\"token\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#workDoneProgressCreateParams\ntype WorkDoneProgressCreateParams struct {\n\t// The token to be used to report progress.\n\tToken ProgressToken `json:\"token\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#workDoneProgressEnd\ntype WorkDoneProgressEnd struct {\n\tKind string `json:\"kind\"`\n\t// Optional, a final message indicating to for example indicate the outcome\n\t// of the operation.\n\tMessage string `json:\"message,omitempty\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#workDoneProgressOptions\ntype WorkDoneProgressOptions struct {\n\tWorkDoneProgress bool `json:\"workDoneProgress,omitempty\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#workDoneProgressParams\ntype WorkDoneProgressParams struct {\n\t// An optional token that a server can use to report work done progress.\n\tWorkDoneToken ProgressToken `json:\"workDoneToken,omitempty\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#workDoneProgressReport\ntype WorkDoneProgressReport struct {\n\tKind string `json:\"kind\"`\n\t// Controls enablement state of a cancel button.\n\t//\n\t// Clients that don't support cancellation or don't support controlling the button's\n\t// enablement state are allowed to ignore the property.\n\tCancellable bool `json:\"cancellable,omitempty\"`\n\t// Optional, more detailed associated progress message. Contains\n\t// complementary information to the `title`.\n\t//\n\t// Examples: \"3/25 files\", \"project/src/module2\", \"node_modules/some_dep\".\n\t// If unset, the previous progress message (if any) is still valid.\n\tMessage string `json:\"message,omitempty\"`\n\t// Optional progress percentage to display (value 100 is considered 100%).\n\t// If not provided infinite progress is assumed and clients are allowed\n\t// to ignore the `percentage` value in subsequent in report notifications.\n\t//\n\t// The value should be steadily rising. Clients are free to ignore values\n\t// that are not following this rule. The value range is [0, 100]\n\tPercentage uint32 `json:\"percentage,omitempty\"`\n}\n\n// Workspace specific client capabilities.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#workspaceClientCapabilities\ntype WorkspaceClientCapabilities struct {\n\t// The client supports applying batch edits\n\t// to the workspace by supporting the request\n\t// 'workspace/applyEdit'\n\tApplyEdit bool `json:\"applyEdit,omitempty\"`\n\t// Capabilities specific to `WorkspaceEdit`s.\n\tWorkspaceEdit *WorkspaceEditClientCapabilities `json:\"workspaceEdit,omitempty\"`\n\t// Capabilities specific to the `workspace/didChangeConfiguration` notification.\n\tDidChangeConfiguration DidChangeConfigurationClientCapabilities `json:\"didChangeConfiguration,omitempty\"`\n\t// Capabilities specific to the `workspace/didChangeWatchedFiles` notification.\n\tDidChangeWatchedFiles DidChangeWatchedFilesClientCapabilities `json:\"didChangeWatchedFiles,omitempty\"`\n\t// Capabilities specific to the `workspace/symbol` request.\n\tSymbol *WorkspaceSymbolClientCapabilities `json:\"symbol,omitempty\"`\n\t// Capabilities specific to the `workspace/executeCommand` request.\n\tExecuteCommand *ExecuteCommandClientCapabilities `json:\"executeCommand,omitempty\"`\n\t// The client has support for workspace folders.\n\t//\n\t// @since 3.6.0\n\tWorkspaceFolders bool `json:\"workspaceFolders,omitempty\"`\n\t// The client supports `workspace/configuration` requests.\n\t//\n\t// @since 3.6.0\n\tConfiguration bool `json:\"configuration,omitempty\"`\n\t// Capabilities specific to the semantic token requests scoped to the\n\t// workspace.\n\t//\n\t// @since 3.16.0.\n\tSemanticTokens *SemanticTokensWorkspaceClientCapabilities `json:\"semanticTokens,omitempty\"`\n\t// Capabilities specific to the code lens requests scoped to the\n\t// workspace.\n\t//\n\t// @since 3.16.0.\n\tCodeLens *CodeLensWorkspaceClientCapabilities `json:\"codeLens,omitempty\"`\n\t// The client has support for file notifications/requests for user operations on files.\n\t//\n\t// Since 3.16.0\n\tFileOperations *FileOperationClientCapabilities `json:\"fileOperations,omitempty\"`\n\t// Capabilities specific to the inline values requests scoped to the\n\t// workspace.\n\t//\n\t// @since 3.17.0.\n\tInlineValue *InlineValueWorkspaceClientCapabilities `json:\"inlineValue,omitempty\"`\n\t// Capabilities specific to the inlay hint requests scoped to the\n\t// workspace.\n\t//\n\t// @since 3.17.0.\n\tInlayHint *InlayHintWorkspaceClientCapabilities `json:\"inlayHint,omitempty\"`\n\t// Capabilities specific to the diagnostic requests scoped to the\n\t// workspace.\n\t//\n\t// @since 3.17.0.\n\tDiagnostics *DiagnosticWorkspaceClientCapabilities `json:\"diagnostics,omitempty\"`\n\t// Capabilities specific to the folding range requests scoped to the workspace.\n\t//\n\t// @since 3.18.0\n\t// @proposed\n\tFoldingRange *FoldingRangeWorkspaceClientCapabilities `json:\"foldingRange,omitempty\"`\n\t// Capabilities specific to the `workspace/textDocumentContent` request.\n\t//\n\t// @since 3.18.0\n\t// @proposed\n\tTextDocumentContent *TextDocumentContentClientCapabilities `json:\"textDocumentContent,omitempty\"`\n}\n\n// Parameters of the workspace diagnostic request.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#workspaceDiagnosticParams\ntype WorkspaceDiagnosticParams struct {\n\t// The additional identifier provided during registration.\n\tIdentifier string `json:\"identifier,omitempty\"`\n\t// The currently known diagnostic reports with their\n\t// previous result ids.\n\tPreviousResultIds []PreviousResultId `json:\"previousResultIds\"`\n\tWorkDoneProgressParams\n\tPartialResultParams\n}\n\n// A workspace diagnostic report.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#workspaceDiagnosticReport\ntype WorkspaceDiagnosticReport struct {\n\tItems []WorkspaceDocumentDiagnosticReport `json:\"items\"`\n}\n\n// A partial result for a workspace diagnostic report.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#workspaceDiagnosticReportPartialResult\ntype WorkspaceDiagnosticReportPartialResult struct {\n\tItems []WorkspaceDocumentDiagnosticReport `json:\"items\"`\n}\n\n// A workspace diagnostic document report.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#workspaceDocumentDiagnosticReport\ntype WorkspaceDocumentDiagnosticReport = Or_WorkspaceDocumentDiagnosticReport // (alias)\n// A workspace edit represents changes to many resources managed in the workspace. The edit\n// should either provide `changes` or `documentChanges`. If documentChanges are present\n// they are preferred over `changes` if the client can handle versioned document edits.\n//\n// Since version 3.13.0 a workspace edit can contain resource operations as well. If resource\n// operations are present clients need to execute the operations in the order in which they\n// are provided. So a workspace edit for example can consist of the following two changes:\n// (1) a create file a.txt and (2) a text document edit which insert text into file a.txt.\n//\n// An invalid sequence (e.g. (1) delete file a.txt and (2) insert text into file a.txt) will\n// cause failure of the operation. How the client recovers from the failure is described by\n// the client capability: `workspace.workspaceEdit.failureHandling`\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#workspaceEdit\ntype WorkspaceEdit struct {\n\t// Holds changes to existing resources.\n\tChanges map[DocumentUri][]TextEdit `json:\"changes,omitempty\"`\n\t// Depending on the client capability `workspace.workspaceEdit.resourceOperations` document changes\n\t// are either an array of `TextDocumentEdit`s to express changes to n different text documents\n\t// where each text document edit addresses a specific version of a text document. Or it can contain\n\t// above `TextDocumentEdit`s mixed with create, rename and delete file / folder operations.\n\t//\n\t// Whether a client supports versioned document edits is expressed via\n\t// `workspace.workspaceEdit.documentChanges` client capability.\n\t//\n\t// If a client neither supports `documentChanges` nor `workspace.workspaceEdit.resourceOperations` then\n\t// only plain `TextEdit`s using the `changes` property are supported.\n\tDocumentChanges []DocumentChange `json:\"documentChanges,omitempty\"`\n\t// A map of change annotations that can be referenced in `AnnotatedTextEdit`s or create, rename and\n\t// delete file / folder operations.\n\t//\n\t// Whether clients honor this property depends on the client capability `workspace.changeAnnotationSupport`.\n\t//\n\t// @since 3.16.0\n\tChangeAnnotations map[ChangeAnnotationIdentifier]ChangeAnnotation `json:\"changeAnnotations,omitempty\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#workspaceEditClientCapabilities\ntype WorkspaceEditClientCapabilities struct {\n\t// The client supports versioned document changes in `WorkspaceEdit`s\n\tDocumentChanges bool `json:\"documentChanges,omitempty\"`\n\t// The resource operations the client supports. Clients should at least\n\t// support 'create', 'rename' and 'delete' files and folders.\n\t//\n\t// @since 3.13.0\n\tResourceOperations []ResourceOperationKind `json:\"resourceOperations,omitempty\"`\n\t// The failure handling strategy of a client if applying the workspace edit\n\t// fails.\n\t//\n\t// @since 3.13.0\n\tFailureHandling *FailureHandlingKind `json:\"failureHandling,omitempty\"`\n\t// Whether the client normalizes line endings to the client specific\n\t// setting.\n\t// If set to `true` the client will normalize line ending characters\n\t// in a workspace edit to the client-specified new line\n\t// character.\n\t//\n\t// @since 3.16.0\n\tNormalizesLineEndings bool `json:\"normalizesLineEndings,omitempty\"`\n\t// Whether the client in general supports change annotations on text edits,\n\t// create file, rename file and delete file changes.\n\t//\n\t// @since 3.16.0\n\tChangeAnnotationSupport *ChangeAnnotationsSupportOptions `json:\"changeAnnotationSupport,omitempty\"`\n\t// Whether the client supports `WorkspaceEditMetadata` in `WorkspaceEdit`s.\n\t//\n\t// @since 3.18.0\n\t// @proposed\n\tMetadataSupport bool `json:\"metadataSupport,omitempty\"`\n\t// Whether the client supports snippets as text edits.\n\t//\n\t// @since 3.18.0\n\t// @proposed\n\tSnippetEditSupport bool `json:\"snippetEditSupport,omitempty\"`\n}\n\n// Additional data about a workspace edit.\n//\n// @since 3.18.0\n// @proposed\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#workspaceEditMetadata\ntype WorkspaceEditMetadata struct {\n\t// Signal to the editor that this edit is a refactoring.\n\tIsRefactoring bool `json:\"isRefactoring,omitempty\"`\n}\n\n// A workspace folder inside a client.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#workspaceFolder\ntype WorkspaceFolder struct {\n\t// The associated URI for this workspace folder.\n\tURI URI `json:\"uri\"`\n\t// The name of the workspace folder. Used to refer to this\n\t// workspace folder in the user interface.\n\tName string `json:\"name\"`\n}\n\n// The workspace folder change event.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#workspaceFoldersChangeEvent\ntype WorkspaceFoldersChangeEvent struct {\n\t// The array of added workspace folders\n\tAdded []WorkspaceFolder `json:\"added\"`\n\t// The array of the removed workspace folders\n\tRemoved []WorkspaceFolder `json:\"removed\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#workspaceFoldersInitializeParams\ntype WorkspaceFoldersInitializeParams struct {\n\t// The workspace folders configured in the client when the server starts.\n\t//\n\t// This property is only available if the client supports workspace folders.\n\t// It can be `null` if the client supports workspace folders but none are\n\t// configured.\n\t//\n\t// @since 3.6.0\n\tWorkspaceFolders []WorkspaceFolder `json:\"workspaceFolders,omitempty\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#workspaceFoldersServerCapabilities\ntype WorkspaceFoldersServerCapabilities struct {\n\t// The server has support for workspace folders\n\tSupported bool `json:\"supported,omitempty\"`\n\t// Whether the server wants to receive workspace folder\n\t// change notifications.\n\t//\n\t// If a string is provided the string is treated as an ID\n\t// under which the notification is registered on the client\n\t// side. The ID can be used to unregister for these events\n\t// using the `client/unregisterCapability` request.\n\tChangeNotifications *Or_WorkspaceFoldersServerCapabilities_changeNotifications `json:\"changeNotifications,omitempty\"`\n}\n\n// A full document diagnostic report for a workspace diagnostic result.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#workspaceFullDocumentDiagnosticReport\ntype WorkspaceFullDocumentDiagnosticReport struct {\n\t// The URI for which diagnostic information is reported.\n\tURI DocumentUri `json:\"uri\"`\n\t// The version number for which the diagnostics are reported.\n\t// If the document is not marked as open `null` can be provided.\n\tVersion int32 `json:\"version\"`\n\tFullDocumentDiagnosticReport\n}\n\n// Defines workspace specific capabilities of the server.\n//\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#workspaceOptions\ntype WorkspaceOptions struct {\n\t// The server supports workspace folder.\n\t//\n\t// @since 3.6.0\n\tWorkspaceFolders *WorkspaceFoldersServerCapabilities `json:\"workspaceFolders,omitempty\"`\n\t// The server is interested in notifications/requests for operations on files.\n\t//\n\t// @since 3.16.0\n\tFileOperations *FileOperationOptions `json:\"fileOperations,omitempty\"`\n\t// The server supports the `workspace/textDocumentContent` request.\n\t//\n\t// @since 3.18.0\n\t// @proposed\n\tTextDocumentContent *Or_WorkspaceOptions_textDocumentContent `json:\"textDocumentContent,omitempty\"`\n}\n\n// A special workspace symbol that supports locations without a range.\n//\n// See also SymbolInformation.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#workspaceSymbol\ntype WorkspaceSymbol struct {\n\t// The location of the symbol. Whether a server is allowed to\n\t// return a location without a range depends on the client\n\t// capability `workspace.symbol.resolveSupport`.\n\t//\n\t// See SymbolInformation#location for more details.\n\tLocation Or_WorkspaceSymbol_location `json:\"location\"`\n\t// A data entry field that is preserved on a workspace symbol between a\n\t// workspace symbol request and a workspace symbol resolve request.\n\tData interface{} `json:\"data,omitempty\"`\n\tBaseSymbolInformation\n}\n\n// Client capabilities for a {@link WorkspaceSymbolRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#workspaceSymbolClientCapabilities\ntype WorkspaceSymbolClientCapabilities struct {\n\t// Symbol request supports dynamic registration.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n\t// Specific capabilities for the `SymbolKind` in the `workspace/symbol` request.\n\tSymbolKind *ClientSymbolKindOptions `json:\"symbolKind,omitempty\"`\n\t// The client supports tags on `SymbolInformation`.\n\t// Clients supporting tags have to handle unknown tags gracefully.\n\t//\n\t// @since 3.16.0\n\tTagSupport *ClientSymbolTagOptions `json:\"tagSupport,omitempty\"`\n\t// The client support partial workspace symbols. The client will send the\n\t// request `workspaceSymbol/resolve` to the server to resolve additional\n\t// properties.\n\t//\n\t// @since 3.17.0\n\tResolveSupport *ClientSymbolResolveOptions `json:\"resolveSupport,omitempty\"`\n}\n\n// Server capabilities for a {@link WorkspaceSymbolRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#workspaceSymbolOptions\ntype WorkspaceSymbolOptions struct {\n\t// The server provides support to resolve additional\n\t// information for a workspace symbol.\n\t//\n\t// @since 3.17.0\n\tResolveProvider bool `json:\"resolveProvider,omitempty\"`\n\tWorkDoneProgressOptions\n}\n\n// The parameters of a {@link WorkspaceSymbolRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#workspaceSymbolParams\ntype WorkspaceSymbolParams struct {\n\t// A query string to filter symbols by. Clients may send an empty\n\t// string here to request all symbols.\n\t//\n\t// The `query`-parameter should be interpreted in a *relaxed way* as editors\n\t// will apply their own highlighting and scoring on the results. A good rule\n\t// of thumb is to match case-insensitive and to simply check that the\n\t// characters of *query* appear in their order in a candidate symbol.\n\t// Servers shouldn't use prefix, substring, or similar strict matching.\n\tQuery string `json:\"query\"`\n\tWorkDoneProgressParams\n\tPartialResultParams\n}\n\n// Registration options for a {@link WorkspaceSymbolRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#workspaceSymbolRegistrationOptions\ntype WorkspaceSymbolRegistrationOptions struct {\n\tWorkspaceSymbolOptions\n}\n\n// An unchanged document diagnostic report for a workspace diagnostic result.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#workspaceUnchangedDocumentDiagnosticReport\ntype WorkspaceUnchangedDocumentDiagnosticReport struct {\n\t// The URI for which diagnostic information is reported.\n\tURI DocumentUri `json:\"uri\"`\n\t// The version number for which the diagnostics are reported.\n\t// If the document is not marked as open `null` can be provided.\n\tVersion int32 `json:\"version\"`\n\tUnchangedDocumentDiagnosticReport\n}\n\n// The initialize parameters\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#_InitializeParams\ntype XInitializeParams struct {\n\t// The process Id of the parent process that started\n\t// the server.\n\t//\n\t// Is `null` if the process has not been started by another process.\n\t// If the parent process is not alive then the server should exit.\n\tProcessID int32 `json:\"processId\"`\n\t// Information about the client\n\t//\n\t// @since 3.15.0\n\tClientInfo *ClientInfo `json:\"clientInfo,omitempty\"`\n\t// The locale the client is currently showing the user interface\n\t// in. This must not necessarily be the locale of the operating\n\t// system.\n\t//\n\t// Uses IETF language tags as the value's syntax\n\t// (See https://en.wikipedia.org/wiki/IETF_language_tag)\n\t//\n\t// @since 3.16.0\n\tLocale string `json:\"locale,omitempty\"`\n\t// The rootPath of the workspace. Is null\n\t// if no folder is open.\n\t//\n\t// @deprecated in favour of rootUri.\n\tRootPath string `json:\"rootPath,omitempty\"`\n\t// The rootUri of the workspace. Is null if no\n\t// folder is open. If both `rootPath` and `rootUri` are set\n\t// `rootUri` wins.\n\t//\n\t// @deprecated in favour of workspaceFolders.\n\tRootURI DocumentUri `json:\"rootUri\"`\n\t// The capabilities provided by the client (editor or tool)\n\tCapabilities ClientCapabilities `json:\"capabilities\"`\n\t// User provided initialization options.\n\tInitializationOptions interface{} `json:\"initializationOptions,omitempty\"`\n\t// The initial trace setting. If omitted trace is disabled ('off').\n\tTrace *TraceValue `json:\"trace,omitempty\"`\n\tWorkDoneProgressParams\n}\n\n// The initialize parameters\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#_InitializeParams\ntype _InitializeParams struct {\n\t// The process Id of the parent process that started\n\t// the server.\n\t//\n\t// Is `null` if the process has not been started by another process.\n\t// If the parent process is not alive then the server should exit.\n\tProcessID int32 `json:\"processId\"`\n\t// Information about the client\n\t//\n\t// @since 3.15.0\n\tClientInfo *ClientInfo `json:\"clientInfo,omitempty\"`\n\t// The locale the client is currently showing the user interface\n\t// in. This must not necessarily be the locale of the operating\n\t// system.\n\t//\n\t// Uses IETF language tags as the value's syntax\n\t// (See https://en.wikipedia.org/wiki/IETF_language_tag)\n\t//\n\t// @since 3.16.0\n\tLocale string `json:\"locale,omitempty\"`\n\t// The rootPath of the workspace. Is null\n\t// if no folder is open.\n\t//\n\t// @deprecated in favour of rootUri.\n\tRootPath string `json:\"rootPath,omitempty\"`\n\t// The rootUri of the workspace. Is null if no\n\t// folder is open. If both `rootPath` and `rootUri` are set\n\t// `rootUri` wins.\n\t//\n\t// @deprecated in favour of workspaceFolders.\n\tRootURI DocumentUri `json:\"rootUri\"`\n\t// The capabilities provided by the client (editor or tool)\n\tCapabilities ClientCapabilities `json:\"capabilities\"`\n\t// User provided initialization options.\n\tInitializationOptions interface{} `json:\"initializationOptions,omitempty\"`\n\t// The initial trace setting. If omitted trace is disabled ('off').\n\tTrace *TraceValue `json:\"trace,omitempty\"`\n\tWorkDoneProgressParams\n}\n\nconst (\n\t// A set of predefined code action kinds\n\t// Empty kind.\n\tEmpty CodeActionKind = \"\"\n\t// Base kind for quickfix actions: 'quickfix'\n\tQuickFix CodeActionKind = \"quickfix\"\n\t// Base kind for refactoring actions: 'refactor'\n\tRefactor CodeActionKind = \"refactor\"\n\t// Base kind for refactoring extraction actions: 'refactor.extract'\n\t//\n\t// Example extract actions:\n\t//\n\t//\n\t// - Extract method\n\t// - Extract function\n\t// - Extract variable\n\t// - Extract interface from class\n\t// - ...\n\tRefactorExtract CodeActionKind = \"refactor.extract\"\n\t// Base kind for refactoring inline actions: 'refactor.inline'\n\t//\n\t// Example inline actions:\n\t//\n\t//\n\t// - Inline function\n\t// - Inline variable\n\t// - Inline constant\n\t// - ...\n\tRefactorInline CodeActionKind = \"refactor.inline\"\n\t// Base kind for refactoring move actions: `refactor.move`\n\t//\n\t// Example move actions:\n\t//\n\t//\n\t// - Move a function to a new file\n\t// - Move a property between classes\n\t// - Move method to base class\n\t// - ...\n\t//\n\t// @since 3.18.0\n\t// @proposed\n\tRefactorMove CodeActionKind = \"refactor.move\"\n\t// Base kind for refactoring rewrite actions: 'refactor.rewrite'\n\t//\n\t// Example rewrite actions:\n\t//\n\t//\n\t// - Convert JavaScript function to class\n\t// - Add or remove parameter\n\t// - Encapsulate field\n\t// - Make method static\n\t// - Move method to base class\n\t// - ...\n\tRefactorRewrite CodeActionKind = \"refactor.rewrite\"\n\t// Base kind for source actions: `source`\n\t//\n\t// Source code actions apply to the entire file.\n\tSource CodeActionKind = \"source\"\n\t// Base kind for an organize imports source action: `source.organizeImports`\n\tSourceOrganizeImports CodeActionKind = \"source.organizeImports\"\n\t// Base kind for auto-fix source actions: `source.fixAll`.\n\t//\n\t// Fix all actions automatically fix errors that have a clear fix that do not require user input.\n\t// They should not suppress errors or perform unsafe fixes such as generating new types or classes.\n\t//\n\t// @since 3.15.0\n\tSourceFixAll CodeActionKind = \"source.fixAll\"\n\t// Base kind for all code actions applying to the entire notebook's scope. CodeActionKinds using\n\t// this should always begin with `notebook.`\n\t//\n\t// @since 3.18.0\n\tNotebook CodeActionKind = \"notebook\"\n\t// The reason why code actions were requested.\n\t//\n\t// @since 3.17.0\n\t// Code actions were explicitly requested by the user or by an extension.\n\tCodeActionInvoked CodeActionTriggerKind = 1\n\t// Code actions were requested automatically.\n\t//\n\t// This typically happens when current selection in a file changes, but can\n\t// also be triggered when file content changes.\n\tCodeActionAutomatic CodeActionTriggerKind = 2\n\t// The kind of a completion entry.\n\tTextCompletion CompletionItemKind = 1\n\tMethodCompletion CompletionItemKind = 2\n\tFunctionCompletion CompletionItemKind = 3\n\tConstructorCompletion CompletionItemKind = 4\n\tFieldCompletion CompletionItemKind = 5\n\tVariableCompletion CompletionItemKind = 6\n\tClassCompletion CompletionItemKind = 7\n\tInterfaceCompletion CompletionItemKind = 8\n\tModuleCompletion CompletionItemKind = 9\n\tPropertyCompletion CompletionItemKind = 10\n\tUnitCompletion CompletionItemKind = 11\n\tValueCompletion CompletionItemKind = 12\n\tEnumCompletion CompletionItemKind = 13\n\tKeywordCompletion CompletionItemKind = 14\n\tSnippetCompletion CompletionItemKind = 15\n\tColorCompletion CompletionItemKind = 16\n\tFileCompletion CompletionItemKind = 17\n\tReferenceCompletion CompletionItemKind = 18\n\tFolderCompletion CompletionItemKind = 19\n\tEnumMemberCompletion CompletionItemKind = 20\n\tConstantCompletion CompletionItemKind = 21\n\tStructCompletion CompletionItemKind = 22\n\tEventCompletion CompletionItemKind = 23\n\tOperatorCompletion CompletionItemKind = 24\n\tTypeParameterCompletion CompletionItemKind = 25\n\t// Completion item tags are extra annotations that tweak the rendering of a completion\n\t// item.\n\t//\n\t// @since 3.15.0\n\t// Render a completion as obsolete, usually using a strike-out.\n\tComplDeprecated CompletionItemTag = 1\n\t// How a completion was triggered\n\t// Completion was triggered by typing an identifier (24x7 code\n\t// complete), manual invocation (e.g Ctrl+Space) or via API.\n\tInvoked CompletionTriggerKind = 1\n\t// Completion was triggered by a trigger character specified by\n\t// the `triggerCharacters` properties of the `CompletionRegistrationOptions`.\n\tTriggerCharacter CompletionTriggerKind = 2\n\t// Completion was re-triggered as current completion list is incomplete\n\tTriggerForIncompleteCompletions CompletionTriggerKind = 3\n\t// The diagnostic's severity.\n\t// Reports an error.\n\tSeverityError DiagnosticSeverity = 1\n\t// Reports a warning.\n\tSeverityWarning DiagnosticSeverity = 2\n\t// Reports an information.\n\tSeverityInformation DiagnosticSeverity = 3\n\t// Reports a hint.\n\tSeverityHint DiagnosticSeverity = 4\n\t// The diagnostic tags.\n\t//\n\t// @since 3.15.0\n\t// Unused or unnecessary code.\n\t//\n\t// Clients are allowed to render diagnostics with this tag faded out instead of having\n\t// an error squiggle.\n\tUnnecessary DiagnosticTag = 1\n\t// Deprecated or obsolete code.\n\t//\n\t// Clients are allowed to rendered diagnostics with this tag strike through.\n\tDeprecated DiagnosticTag = 2\n\t// The document diagnostic report kinds.\n\t//\n\t// @since 3.17.0\n\t// A diagnostic report with a full\n\t// set of problems.\n\tDiagnosticFull DocumentDiagnosticReportKind = \"full\"\n\t// A report indicating that the last\n\t// returned report is still accurate.\n\tDiagnosticUnchanged DocumentDiagnosticReportKind = \"unchanged\"\n\t// A document highlight kind.\n\t// A textual occurrence.\n\tText DocumentHighlightKind = 1\n\t// Read-access of a symbol, like reading a variable.\n\tRead DocumentHighlightKind = 2\n\t// Write-access of a symbol, like writing to a variable.\n\tWrite DocumentHighlightKind = 3\n\t// Predefined error codes.\n\tParseError ErrorCodes = -32700\n\tInvalidRequest ErrorCodes = -32600\n\tMethodNotFound ErrorCodes = -32601\n\tInvalidParams ErrorCodes = -32602\n\tInternalError ErrorCodes = -32603\n\t// Error code indicating that a server received a notification or\n\t// request before the server has received the `initialize` request.\n\tServerNotInitialized ErrorCodes = -32002\n\tUnknownErrorCode ErrorCodes = -32001\n\t// Applying the workspace change is simply aborted if one of the changes provided\n\t// fails. All operations executed before the failing operation stay executed.\n\tAbort FailureHandlingKind = \"abort\"\n\t// All operations are executed transactional. That means they either all\n\t// succeed or no changes at all are applied to the workspace.\n\tTransactional FailureHandlingKind = \"transactional\"\n\t// If the workspace edit contains only textual file changes they are executed transactional.\n\t// If resource changes (create, rename or delete file) are part of the change the failure\n\t// handling strategy is abort.\n\tTextOnlyTransactional FailureHandlingKind = \"textOnlyTransactional\"\n\t// The client tries to undo the operations already executed. But there is no\n\t// guarantee that this is succeeding.\n\tUndo FailureHandlingKind = \"undo\"\n\t// The file event type\n\t// The file got created.\n\tCreated FileChangeType = 1\n\t// The file got changed.\n\tChanged FileChangeType = 2\n\t// The file got deleted.\n\tDeleted FileChangeType = 3\n\t// A pattern kind describing if a glob pattern matches a file a folder or\n\t// both.\n\t//\n\t// @since 3.16.0\n\t// The pattern matches a file only.\n\tFilePattern FileOperationPatternKind = \"file\"\n\t// The pattern matches a folder only.\n\tFolderPattern FileOperationPatternKind = \"folder\"\n\t// A set of predefined range kinds.\n\t// Folding range for a comment\n\tComment FoldingRangeKind = \"comment\"\n\t// Folding range for an import or include\n\tImports FoldingRangeKind = \"imports\"\n\t// Folding range for a region (e.g. `#region`)\n\tRegion FoldingRangeKind = \"region\"\n\t// Inlay hint kinds.\n\t//\n\t// @since 3.17.0\n\t// An inlay hint that for a type annotation.\n\tType InlayHintKind = 1\n\t// An inlay hint that is for a parameter.\n\tParameter InlayHintKind = 2\n\t// Describes how an {@link InlineCompletionItemProvider inline completion provider} was triggered.\n\t//\n\t// @since 3.18.0\n\t// @proposed\n\t// Completion was triggered explicitly by a user gesture.\n\tInlineInvoked InlineCompletionTriggerKind = 1\n\t// Completion was triggered automatically while editing.\n\tInlineAutomatic InlineCompletionTriggerKind = 2\n\t// Defines whether the insert text in a completion item should be interpreted as\n\t// plain text or a snippet.\n\t// The primary text to be inserted is treated as a plain string.\n\tPlainTextTextFormat InsertTextFormat = 1\n\t// The primary text to be inserted is treated as a snippet.\n\t//\n\t// A snippet can define tab stops and placeholders with `$1`, `$2`\n\t// and `${3:foo}`. `$0` defines the final tab stop, it defaults to\n\t// the end of the snippet. Placeholders with equal identifiers are linked,\n\t// that is typing in one will update others too.\n\t//\n\t// See also: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#snippet_syntax\n\tSnippetTextFormat InsertTextFormat = 2\n\t// How whitespace and indentation is handled during completion\n\t// item insertion.\n\t//\n\t// @since 3.16.0\n\t// The insertion or replace strings is taken as it is. If the\n\t// value is multi line the lines below the cursor will be\n\t// inserted using the indentation defined in the string value.\n\t// The client will not apply any kind of adjustments to the\n\t// string.\n\tAsIs InsertTextMode = 1\n\t// The editor adjusts leading whitespace of new lines so that\n\t// they match the indentation up to the cursor of the line for\n\t// which the item is accepted.\n\t//\n\t// Consider a line like this: <2tabs><3tabs>foo. Accepting a\n\t// multi line completion item is indented using 2 tabs and all\n\t// following lines inserted will be indented using 2 tabs as well.\n\tAdjustIndentation InsertTextMode = 2\n\t// A request failed but it was syntactically correct, e.g the\n\t// method name was known and the parameters were valid. The error\n\t// message should contain human readable information about why\n\t// the request failed.\n\t//\n\t// @since 3.17.0\n\tRequestFailed LSPErrorCodes = -32803\n\t// The server cancelled the request. This error code should\n\t// only be used for requests that explicitly support being\n\t// server cancellable.\n\t//\n\t// @since 3.17.0\n\tServerCancelled LSPErrorCodes = -32802\n\t// The server detected that the content of a document got\n\t// modified outside normal conditions. A server should\n\t// NOT send this error code if it detects a content change\n\t// in it unprocessed messages. The result even computed\n\t// on an older state might still be useful for the client.\n\t//\n\t// If a client decides that a result is not of any use anymore\n\t// the client should cancel the request.\n\tContentModified LSPErrorCodes = -32801\n\t// The client has canceled a request and a server has detected\n\t// the cancel.\n\tRequestCancelled LSPErrorCodes = -32800\n\t// Predefined Language kinds\n\t// @since 3.18.0\n\t// @proposed\n\tLangABAP LanguageKind = \"abap\"\n\tLangWindowsBat LanguageKind = \"bat\"\n\tLangBibTeX LanguageKind = \"bibtex\"\n\tLangClojure LanguageKind = \"clojure\"\n\tLangCoffeescript LanguageKind = \"coffeescript\"\n\tLangC LanguageKind = \"c\"\n\tLangCPP LanguageKind = \"cpp\"\n\tLangCSharp LanguageKind = \"csharp\"\n\tLangCSS LanguageKind = \"css\"\n\t// @since 3.18.0\n\t// @proposed\n\tLangD LanguageKind = \"d\"\n\t// @since 3.18.0\n\t// @proposed\n\tLangDelphi LanguageKind = \"pascal\"\n\tLangDiff LanguageKind = \"diff\"\n\tLangDart LanguageKind = \"dart\"\n\tLangDockerfile LanguageKind = \"dockerfile\"\n\tLangElixir LanguageKind = \"elixir\"\n\tLangErlang LanguageKind = \"erlang\"\n\tLangFSharp LanguageKind = \"fsharp\"\n\tLangGitCommit LanguageKind = \"git-commit\"\n\tLangGitRebase LanguageKind = \"rebase\"\n\tLangGo LanguageKind = \"go\"\n\tLangGroovy LanguageKind = \"groovy\"\n\tLangHandlebars LanguageKind = \"handlebars\"\n\tLangHaskell LanguageKind = \"haskell\"\n\tLangHTML LanguageKind = \"html\"\n\tLangIni LanguageKind = \"ini\"\n\tLangJava LanguageKind = \"java\"\n\tLangJavaScript LanguageKind = \"javascript\"\n\tLangJavaScriptReact LanguageKind = \"javascriptreact\"\n\tLangJSON LanguageKind = \"json\"\n\tLangLaTeX LanguageKind = \"latex\"\n\tLangLess LanguageKind = \"less\"\n\tLangLua LanguageKind = \"lua\"\n\tLangMakefile LanguageKind = \"makefile\"\n\tLangMarkdown LanguageKind = \"markdown\"\n\tLangObjectiveC LanguageKind = \"objective-c\"\n\tLangObjectiveCPP LanguageKind = \"objective-cpp\"\n\t// @since 3.18.0\n\t// @proposed\n\tLangPascal LanguageKind = \"pascal\"\n\tLangPerl LanguageKind = \"perl\"\n\tLangPerl6 LanguageKind = \"perl6\"\n\tLangPHP LanguageKind = \"php\"\n\tLangPowershell LanguageKind = \"powershell\"\n\tLangPug LanguageKind = \"jade\"\n\tLangPython LanguageKind = \"python\"\n\tLangR LanguageKind = \"r\"\n\tLangRazor LanguageKind = \"razor\"\n\tLangRuby LanguageKind = \"ruby\"\n\tLangRust LanguageKind = \"rust\"\n\tLangSCSS LanguageKind = \"scss\"\n\tLangSASS LanguageKind = \"sass\"\n\tLangScala LanguageKind = \"scala\"\n\tLangShaderLab LanguageKind = \"shaderlab\"\n\tLangShellScript LanguageKind = \"shellscript\"\n\tLangSQL LanguageKind = \"sql\"\n\tLangSwift LanguageKind = \"swift\"\n\tLangTypeScript LanguageKind = \"typescript\"\n\tLangTypeScriptReact LanguageKind = \"typescriptreact\"\n\tLangTeX LanguageKind = \"tex\"\n\tLangVisualBasic LanguageKind = \"vb\"\n\tLangXML LanguageKind = \"xml\"\n\tLangXSL LanguageKind = \"xsl\"\n\tLangYAML LanguageKind = \"yaml\"\n\t// Describes the content type that a client supports in various\n\t// result literals like `Hover`, `ParameterInfo` or `CompletionItem`.\n\t//\n\t// Please note that `MarkupKinds` must not start with a `$`. This kinds\n\t// are reserved for internal usage.\n\t// Plain text is supported as a content format\n\tPlainText MarkupKind = \"plaintext\"\n\t// Markdown is supported as a content format\n\tMarkdown MarkupKind = \"markdown\"\n\t// The message type\n\t// An error message.\n\tError MessageType = 1\n\t// A warning message.\n\tWarning MessageType = 2\n\t// An information message.\n\tInfo MessageType = 3\n\t// A log message.\n\tLog MessageType = 4\n\t// A debug message.\n\t//\n\t// @since 3.18.0\n\t// @proposed\n\tDebug MessageType = 5\n\t// The moniker kind.\n\t//\n\t// @since 3.16.0\n\t// The moniker represent a symbol that is imported into a project\n\tImport MonikerKind = \"import\"\n\t// The moniker represents a symbol that is exported from a project\n\tExport MonikerKind = \"export\"\n\t// The moniker represents a symbol that is local to a project (e.g. a local\n\t// variable of a function, a class not visible outside the project, ...)\n\tLocal MonikerKind = \"local\"\n\t// A notebook cell kind.\n\t//\n\t// @since 3.17.0\n\t// A markup-cell is formatted source that is used for display.\n\tMarkup NotebookCellKind = 1\n\t// A code-cell is source code.\n\tCode NotebookCellKind = 2\n\t// A set of predefined position encoding kinds.\n\t//\n\t// @since 3.17.0\n\t// Character offsets count UTF-8 code units (e.g. bytes).\n\tUTF8 PositionEncodingKind = \"utf-8\"\n\t// Character offsets count UTF-16 code units.\n\t//\n\t// This is the default and must always be supported\n\t// by servers\n\tUTF16 PositionEncodingKind = \"utf-16\"\n\t// Character offsets count UTF-32 code units.\n\t//\n\t// Implementation note: these are the same as Unicode codepoints,\n\t// so this `PositionEncodingKind` may also be used for an\n\t// encoding-agnostic representation of character offsets.\n\tUTF32 PositionEncodingKind = \"utf-32\"\n\t// The client's default behavior is to select the identifier\n\t// according the to language's syntax rule.\n\tIdentifier PrepareSupportDefaultBehavior = 1\n\t// Supports creating new files and folders.\n\tCreate ResourceOperationKind = \"create\"\n\t// Supports renaming existing files and folders.\n\tRename ResourceOperationKind = \"rename\"\n\t// Supports deleting existing files and folders.\n\tDelete ResourceOperationKind = \"delete\"\n\t// A set of predefined token modifiers. This set is not fixed\n\t// an clients can specify additional token types via the\n\t// corresponding client capabilities.\n\t//\n\t// @since 3.16.0\n\tModDeclaration SemanticTokenModifiers = \"declaration\"\n\tModDefinition SemanticTokenModifiers = \"definition\"\n\tModReadonly SemanticTokenModifiers = \"readonly\"\n\tModStatic SemanticTokenModifiers = \"static\"\n\tModDeprecated SemanticTokenModifiers = \"deprecated\"\n\tModAbstract SemanticTokenModifiers = \"abstract\"\n\tModAsync SemanticTokenModifiers = \"async\"\n\tModModification SemanticTokenModifiers = \"modification\"\n\tModDocumentation SemanticTokenModifiers = \"documentation\"\n\tModDefaultLibrary SemanticTokenModifiers = \"defaultLibrary\"\n\t// A set of predefined token types. This set is not fixed\n\t// an clients can specify additional token types via the\n\t// corresponding client capabilities.\n\t//\n\t// @since 3.16.0\n\tNamespaceType SemanticTokenTypes = \"namespace\"\n\t// Represents a generic type. Acts as a fallback for types which can't be mapped to\n\t// a specific type like class or enum.\n\tTypeType SemanticTokenTypes = \"type\"\n\tClassType SemanticTokenTypes = \"class\"\n\tEnumType SemanticTokenTypes = \"enum\"\n\tInterfaceType SemanticTokenTypes = \"interface\"\n\tStructType SemanticTokenTypes = \"struct\"\n\tTypeParameterType SemanticTokenTypes = \"typeParameter\"\n\tParameterType SemanticTokenTypes = \"parameter\"\n\tVariableType SemanticTokenTypes = \"variable\"\n\tPropertyType SemanticTokenTypes = \"property\"\n\tEnumMemberType SemanticTokenTypes = \"enumMember\"\n\tEventType SemanticTokenTypes = \"event\"\n\tFunctionType SemanticTokenTypes = \"function\"\n\tMethodType SemanticTokenTypes = \"method\"\n\tMacroType SemanticTokenTypes = \"macro\"\n\tKeywordType SemanticTokenTypes = \"keyword\"\n\tModifierType SemanticTokenTypes = \"modifier\"\n\tCommentType SemanticTokenTypes = \"comment\"\n\tStringType SemanticTokenTypes = \"string\"\n\tNumberType SemanticTokenTypes = \"number\"\n\tRegexpType SemanticTokenTypes = \"regexp\"\n\tOperatorType SemanticTokenTypes = \"operator\"\n\t// @since 3.17.0\n\tDecoratorType SemanticTokenTypes = \"decorator\"\n\t// @since 3.18.0\n\tLabelType SemanticTokenTypes = \"label\"\n\t// How a signature help was triggered.\n\t//\n\t// @since 3.15.0\n\t// Signature help was invoked manually by the user or by a command.\n\tSigInvoked SignatureHelpTriggerKind = 1\n\t// Signature help was triggered by a trigger character.\n\tSigTriggerCharacter SignatureHelpTriggerKind = 2\n\t// Signature help was triggered by the cursor moving or by the document content changing.\n\tSigContentChange SignatureHelpTriggerKind = 3\n\t// A symbol kind.\n\tFile SymbolKind = 1\n\tModule SymbolKind = 2\n\tNamespace SymbolKind = 3\n\tPackage SymbolKind = 4\n\tClass SymbolKind = 5\n\tMethod SymbolKind = 6\n\tProperty SymbolKind = 7\n\tField SymbolKind = 8\n\tConstructor SymbolKind = 9\n\tEnum SymbolKind = 10\n\tInterface SymbolKind = 11\n\tFunction SymbolKind = 12\n\tVariable SymbolKind = 13\n\tConstant SymbolKind = 14\n\tString SymbolKind = 15\n\tNumber SymbolKind = 16\n\tBoolean SymbolKind = 17\n\tArray SymbolKind = 18\n\tObject SymbolKind = 19\n\tKey SymbolKind = 20\n\tNull SymbolKind = 21\n\tEnumMember SymbolKind = 22\n\tStruct SymbolKind = 23\n\tEvent SymbolKind = 24\n\tOperator SymbolKind = 25\n\tTypeParameter SymbolKind = 26\n\t// Symbol tags are extra annotations that tweak the rendering of a symbol.\n\t//\n\t// @since 3.16\n\t// Render a symbol as obsolete, usually using a strike-out.\n\tDeprecatedSymbol SymbolTag = 1\n\t// Represents reasons why a text document is saved.\n\t// Manually triggered, e.g. by the user pressing save, by starting debugging,\n\t// or by an API call.\n\tManual TextDocumentSaveReason = 1\n\t// Automatic after a delay.\n\tAfterDelay TextDocumentSaveReason = 2\n\t// When the editor lost focus.\n\tFocusOut TextDocumentSaveReason = 3\n\t// Defines how the host (editor) should sync\n\t// document changes to the language server.\n\t// Documents should not be synced at all.\n\tNone TextDocumentSyncKind = 0\n\t// Documents are synced by always sending the full content\n\t// of the document.\n\tFull TextDocumentSyncKind = 1\n\t// Documents are synced by sending the full content on open.\n\t// After that only incremental updates to the document are\n\t// send.\n\tIncremental TextDocumentSyncKind = 2\n\tRelative TokenFormat = \"relative\"\n\t// Turn tracing off.\n\tOff TraceValue = \"off\"\n\t// Trace messages only.\n\tMessages TraceValue = \"messages\"\n\t// Verbose message tracing.\n\tVerbose TraceValue = \"verbose\"\n\t// Moniker uniqueness level to define scope of the moniker.\n\t//\n\t// @since 3.16.0\n\t// The moniker is only unique inside a document\n\tDocument UniquenessLevel = \"document\"\n\t// The moniker is unique inside a project for which a dump got created\n\tProject UniquenessLevel = \"project\"\n\t// The moniker is unique inside the group to which a project belongs\n\tGroup UniquenessLevel = \"group\"\n\t// The moniker is unique inside the moniker scheme.\n\tScheme UniquenessLevel = \"scheme\"\n\t// The moniker is globally unique\n\tGlobal UniquenessLevel = \"global\"\n\t// Interested in create events.\n\tWatchCreate WatchKind = 1\n\t// Interested in change events\n\tWatchChange WatchKind = 2\n\t// Interested in delete events\n\tWatchDelete WatchKind = 4\n)\n"], ["/opencode/internal/fileutil/fileutil.go", "package fileutil\n\nimport (\n\t\"fmt\"\n\t\"io/fs\"\n\t\"os\"\n\t\"os/exec\"\n\t\"path/filepath\"\n\t\"sort\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/bmatcuk/doublestar/v4\"\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n)\n\nvar (\n\trgPath string\n\tfzfPath string\n)\n\nfunc init() {\n\tvar err error\n\trgPath, err = exec.LookPath(\"rg\")\n\tif err != nil {\n\t\tlogging.Warn(\"Ripgrep (rg) not found in $PATH. Some features might be limited or slower.\")\n\t\trgPath = \"\"\n\t}\n\tfzfPath, err = exec.LookPath(\"fzf\")\n\tif err != nil {\n\t\tlogging.Warn(\"FZF not found in $PATH. Some features might be limited or slower.\")\n\t\tfzfPath = \"\"\n\t}\n}\n\nfunc GetRgCmd(globPattern string) *exec.Cmd {\n\tif rgPath == \"\" {\n\t\treturn nil\n\t}\n\trgArgs := []string{\n\t\t\"--files\",\n\t\t\"-L\",\n\t\t\"--null\",\n\t}\n\tif globPattern != \"\" {\n\t\tif !filepath.IsAbs(globPattern) && !strings.HasPrefix(globPattern, \"/\") {\n\t\t\tglobPattern = \"/\" + globPattern\n\t\t}\n\t\trgArgs = append(rgArgs, \"--glob\", globPattern)\n\t}\n\tcmd := exec.Command(rgPath, rgArgs...)\n\tcmd.Dir = \".\"\n\treturn cmd\n}\n\nfunc GetFzfCmd(query string) *exec.Cmd {\n\tif fzfPath == \"\" {\n\t\treturn nil\n\t}\n\tfzfArgs := []string{\n\t\t\"--filter\",\n\t\tquery,\n\t\t\"--read0\",\n\t\t\"--print0\",\n\t}\n\tcmd := exec.Command(fzfPath, fzfArgs...)\n\tcmd.Dir = \".\"\n\treturn cmd\n}\n\ntype FileInfo struct {\n\tPath string\n\tModTime time.Time\n}\n\nfunc SkipHidden(path string) bool {\n\t// Check for hidden files (starting with a dot)\n\tbase := filepath.Base(path)\n\tif base != \".\" && strings.HasPrefix(base, \".\") {\n\t\treturn true\n\t}\n\n\tcommonIgnoredDirs := map[string]bool{\n\t\t\".opencode\": true,\n\t\t\"node_modules\": true,\n\t\t\"vendor\": true,\n\t\t\"dist\": true,\n\t\t\"build\": true,\n\t\t\"target\": true,\n\t\t\".git\": true,\n\t\t\".idea\": true,\n\t\t\".vscode\": true,\n\t\t\"__pycache__\": true,\n\t\t\"bin\": true,\n\t\t\"obj\": true,\n\t\t\"out\": true,\n\t\t\"coverage\": true,\n\t\t\"tmp\": true,\n\t\t\"temp\": true,\n\t\t\"logs\": true,\n\t\t\"generated\": true,\n\t\t\"bower_components\": true,\n\t\t\"jspm_packages\": true,\n\t}\n\n\tparts := strings.Split(path, string(os.PathSeparator))\n\tfor _, part := range parts {\n\t\tif commonIgnoredDirs[part] {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc GlobWithDoublestar(pattern, searchPath string, limit int) ([]string, bool, error) {\n\tfsys := os.DirFS(searchPath)\n\trelPattern := strings.TrimPrefix(pattern, \"/\")\n\tvar matches []FileInfo\n\n\terr := doublestar.GlobWalk(fsys, relPattern, func(path string, d fs.DirEntry) error {\n\t\tif d.IsDir() {\n\t\t\treturn nil\n\t\t}\n\t\tif SkipHidden(path) {\n\t\t\treturn nil\n\t\t}\n\t\tinfo, err := d.Info()\n\t\tif err != nil {\n\t\t\treturn nil\n\t\t}\n\t\tabsPath := path\n\t\tif !strings.HasPrefix(absPath, searchPath) && searchPath != \".\" {\n\t\t\tabsPath = filepath.Join(searchPath, absPath)\n\t\t} else if !strings.HasPrefix(absPath, \"/\") && searchPath == \".\" {\n\t\t\tabsPath = filepath.Join(searchPath, absPath) // Ensure relative paths are joined correctly\n\t\t}\n\n\t\tmatches = append(matches, FileInfo{Path: absPath, ModTime: info.ModTime()})\n\t\tif limit > 0 && len(matches) >= limit*2 {\n\t\t\treturn fs.SkipAll\n\t\t}\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\treturn nil, false, fmt.Errorf(\"glob walk error: %w\", err)\n\t}\n\n\tsort.Slice(matches, func(i, j int) bool {\n\t\treturn matches[i].ModTime.After(matches[j].ModTime)\n\t})\n\n\ttruncated := false\n\tif limit > 0 && len(matches) > limit {\n\t\tmatches = matches[:limit]\n\t\ttruncated = true\n\t}\n\n\tresults := make([]string, len(matches))\n\tfor i, m := range matches {\n\t\tresults[i] = m.Path\n\t}\n\treturn results, truncated, nil\n}\n"], ["/opencode/internal/tui/layout/layout.go", "package layout\n\nimport (\n\t\"reflect\"\n\n\t\"github.com/charmbracelet/bubbles/key\"\n\ttea \"github.com/charmbracelet/bubbletea\"\n)\n\ntype Focusable interface {\n\tFocus() tea.Cmd\n\tBlur() tea.Cmd\n\tIsFocused() bool\n}\n\ntype Sizeable interface {\n\tSetSize(width, height int) tea.Cmd\n\tGetSize() (int, int)\n}\n\ntype Bindings interface {\n\tBindingKeys() []key.Binding\n}\n\nfunc KeyMapToSlice(t any) (bindings []key.Binding) {\n\ttyp := reflect.TypeOf(t)\n\tif typ.Kind() != reflect.Struct {\n\t\treturn nil\n\t}\n\tfor i := range typ.NumField() {\n\t\tv := reflect.ValueOf(t).Field(i)\n\t\tbindings = append(bindings, v.Interface().(key.Binding))\n\t}\n\treturn\n}\n"], ["/opencode/internal/app/lsp.go", "package app\n\nimport (\n\t\"context\"\n\t\"time\"\n\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n\t\"github.com/opencode-ai/opencode/internal/lsp\"\n\t\"github.com/opencode-ai/opencode/internal/lsp/watcher\"\n)\n\nfunc (app *App) initLSPClients(ctx context.Context) {\n\tcfg := config.Get()\n\n\t// Initialize LSP clients\n\tfor name, clientConfig := range cfg.LSP {\n\t\t// Start each client initialization in its own goroutine\n\t\tgo app.createAndStartLSPClient(ctx, name, clientConfig.Command, clientConfig.Args...)\n\t}\n\tlogging.Info(\"LSP clients initialization started in background\")\n}\n\n// createAndStartLSPClient creates a new LSP client, initializes it, and starts its workspace watcher\nfunc (app *App) createAndStartLSPClient(ctx context.Context, name string, command string, args ...string) {\n\t// Create a specific context for initialization with a timeout\n\tlogging.Info(\"Creating LSP client\", \"name\", name, \"command\", command, \"args\", args)\n\t\n\t// Create the LSP client\n\tlspClient, err := lsp.NewClient(ctx, command, args...)\n\tif err != nil {\n\t\tlogging.Error(\"Failed to create LSP client for\", name, err)\n\t\treturn\n\t}\n\n\t// Create a longer timeout for initialization (some servers take time to start)\n\tinitCtx, cancel := context.WithTimeout(ctx, 30*time.Second)\n\tdefer cancel()\n\t\n\t// Initialize with the initialization context\n\t_, err = lspClient.InitializeLSPClient(initCtx, config.WorkingDirectory())\n\tif err != nil {\n\t\tlogging.Error(\"Initialize failed\", \"name\", name, \"error\", err)\n\t\t// Clean up the client to prevent resource leaks\n\t\tlspClient.Close()\n\t\treturn\n\t}\n\n\t// Wait for the server to be ready\n\tif err := lspClient.WaitForServerReady(initCtx); err != nil {\n\t\tlogging.Error(\"Server failed to become ready\", \"name\", name, \"error\", err)\n\t\t// We'll continue anyway, as some functionality might still work\n\t\tlspClient.SetServerState(lsp.StateError)\n\t} else {\n\t\tlogging.Info(\"LSP server is ready\", \"name\", name)\n\t\tlspClient.SetServerState(lsp.StateReady)\n\t}\n\n\tlogging.Info(\"LSP client initialized\", \"name\", name)\n\t\n\t// Create a child context that can be canceled when the app is shutting down\n\twatchCtx, cancelFunc := context.WithCancel(ctx)\n\t\n\t// Create a context with the server name for better identification\n\twatchCtx = context.WithValue(watchCtx, \"serverName\", name)\n\t\n\t// Create the workspace watcher\n\tworkspaceWatcher := watcher.NewWorkspaceWatcher(lspClient)\n\n\t// Store the cancel function to be called during cleanup\n\tapp.cancelFuncsMutex.Lock()\n\tapp.watcherCancelFuncs = append(app.watcherCancelFuncs, cancelFunc)\n\tapp.cancelFuncsMutex.Unlock()\n\n\t// Add the watcher to a WaitGroup to track active goroutines\n\tapp.watcherWG.Add(1)\n\n\t// Add to map with mutex protection before starting goroutine\n\tapp.clientsMutex.Lock()\n\tapp.LSPClients[name] = lspClient\n\tapp.clientsMutex.Unlock()\n\n\tgo app.runWorkspaceWatcher(watchCtx, name, workspaceWatcher)\n}\n\n// runWorkspaceWatcher executes the workspace watcher for an LSP client\nfunc (app *App) runWorkspaceWatcher(ctx context.Context, name string, workspaceWatcher *watcher.WorkspaceWatcher) {\n\tdefer app.watcherWG.Done()\n\tdefer logging.RecoverPanic(\"LSP-\"+name, func() {\n\t\t// Try to restart the client\n\t\tapp.restartLSPClient(ctx, name)\n\t})\n\n\tworkspaceWatcher.WatchWorkspace(ctx, config.WorkingDirectory())\n\tlogging.Info(\"Workspace watcher stopped\", \"client\", name)\n}\n\n// restartLSPClient attempts to restart a crashed or failed LSP client\nfunc (app *App) restartLSPClient(ctx context.Context, name string) {\n\t// Get the original configuration\n\tcfg := config.Get()\n\tclientConfig, exists := cfg.LSP[name]\n\tif !exists {\n\t\tlogging.Error(\"Cannot restart client, configuration not found\", \"client\", name)\n\t\treturn\n\t}\n\n\t// Clean up the old client if it exists\n\tapp.clientsMutex.Lock()\n\toldClient, exists := app.LSPClients[name]\n\tif exists {\n\t\tdelete(app.LSPClients, name) // Remove from map before potentially slow shutdown\n\t}\n\tapp.clientsMutex.Unlock()\n\n\tif exists && oldClient != nil {\n\t\t// Try to shut it down gracefully, but don't block on errors\n\t\tshutdownCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)\n\t\t_ = oldClient.Shutdown(shutdownCtx)\n\t\tcancel()\n\t}\n\n\t// Create a new client using the shared function\n\tapp.createAndStartLSPClient(ctx, name, clientConfig.Command, clientConfig.Args...)\n\tlogging.Info(\"Successfully restarted LSP client\", \"client\", name)\n}\n"], ["/opencode/cmd/schema/main.go", "package main\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"os\"\n\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/llm/models\"\n)\n\n// JSONSchemaType represents a JSON Schema type\ntype JSONSchemaType struct {\n\tType string `json:\"type,omitempty\"`\n\tDescription string `json:\"description,omitempty\"`\n\tProperties map[string]any `json:\"properties,omitempty\"`\n\tRequired []string `json:\"required,omitempty\"`\n\tAdditionalProperties any `json:\"additionalProperties,omitempty\"`\n\tEnum []any `json:\"enum,omitempty\"`\n\tItems map[string]any `json:\"items,omitempty\"`\n\tOneOf []map[string]any `json:\"oneOf,omitempty\"`\n\tAnyOf []map[string]any `json:\"anyOf,omitempty\"`\n\tDefault any `json:\"default,omitempty\"`\n}\n\nfunc main() {\n\tschema := generateSchema()\n\n\t// Pretty print the schema\n\tencoder := json.NewEncoder(os.Stdout)\n\tencoder.SetIndent(\"\", \" \")\n\tif err := encoder.Encode(schema); err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"Error encoding schema: %v\\n\", err)\n\t\tos.Exit(1)\n\t}\n}\n\nfunc generateSchema() map[string]any {\n\tschema := map[string]any{\n\t\t\"$schema\": \"http://json-schema.org/draft-07/schema#\",\n\t\t\"title\": \"OpenCode Configuration\",\n\t\t\"description\": \"Configuration schema for the OpenCode application\",\n\t\t\"type\": \"object\",\n\t\t\"properties\": map[string]any{},\n\t}\n\n\t// Add Data configuration\n\tschema[\"properties\"].(map[string]any)[\"data\"] = map[string]any{\n\t\t\"type\": \"object\",\n\t\t\"description\": \"Storage configuration\",\n\t\t\"properties\": map[string]any{\n\t\t\t\"directory\": map[string]any{\n\t\t\t\t\"type\": \"string\",\n\t\t\t\t\"description\": \"Directory where application data is stored\",\n\t\t\t\t\"default\": \".opencode\",\n\t\t\t},\n\t\t},\n\t\t\"required\": []string{\"directory\"},\n\t}\n\n\t// Add working directory\n\tschema[\"properties\"].(map[string]any)[\"wd\"] = map[string]any{\n\t\t\"type\": \"string\",\n\t\t\"description\": \"Working directory for the application\",\n\t}\n\n\t// Add debug flags\n\tschema[\"properties\"].(map[string]any)[\"debug\"] = map[string]any{\n\t\t\"type\": \"boolean\",\n\t\t\"description\": \"Enable debug mode\",\n\t\t\"default\": false,\n\t}\n\n\tschema[\"properties\"].(map[string]any)[\"debugLSP\"] = map[string]any{\n\t\t\"type\": \"boolean\",\n\t\t\"description\": \"Enable LSP debug mode\",\n\t\t\"default\": false,\n\t}\n\n\tschema[\"properties\"].(map[string]any)[\"contextPaths\"] = map[string]any{\n\t\t\"type\": \"array\",\n\t\t\"description\": \"Context paths for the application\",\n\t\t\"items\": map[string]any{\n\t\t\t\"type\": \"string\",\n\t\t},\n\t\t\"default\": []string{\n\t\t\t\".github/copilot-instructions.md\",\n\t\t\t\".cursorrules\",\n\t\t\t\".cursor/rules/\",\n\t\t\t\"CLAUDE.md\",\n\t\t\t\"CLAUDE.local.md\",\n\t\t\t\"opencode.md\",\n\t\t\t\"opencode.local.md\",\n\t\t\t\"OpenCode.md\",\n\t\t\t\"OpenCode.local.md\",\n\t\t\t\"OPENCODE.md\",\n\t\t\t\"OPENCODE.local.md\",\n\t\t},\n\t}\n\n\tschema[\"properties\"].(map[string]any)[\"tui\"] = map[string]any{\n\t\t\"type\": \"object\",\n\t\t\"description\": \"Terminal User Interface configuration\",\n\t\t\"properties\": map[string]any{\n\t\t\t\"theme\": map[string]any{\n\t\t\t\t\"type\": \"string\",\n\t\t\t\t\"description\": \"TUI theme name\",\n\t\t\t\t\"default\": \"opencode\",\n\t\t\t\t\"enum\": []string{\n\t\t\t\t\t\"opencode\",\n\t\t\t\t\t\"catppuccin\",\n\t\t\t\t\t\"dracula\",\n\t\t\t\t\t\"flexoki\",\n\t\t\t\t\t\"gruvbox\",\n\t\t\t\t\t\"monokai\",\n\t\t\t\t\t\"onedark\",\n\t\t\t\t\t\"tokyonight\",\n\t\t\t\t\t\"tron\",\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\t// Add MCP servers\n\tschema[\"properties\"].(map[string]any)[\"mcpServers\"] = map[string]any{\n\t\t\"type\": \"object\",\n\t\t\"description\": \"Model Control Protocol server configurations\",\n\t\t\"additionalProperties\": map[string]any{\n\t\t\t\"type\": \"object\",\n\t\t\t\"description\": \"MCP server configuration\",\n\t\t\t\"properties\": map[string]any{\n\t\t\t\t\"command\": map[string]any{\n\t\t\t\t\t\"type\": \"string\",\n\t\t\t\t\t\"description\": \"Command to execute for the MCP server\",\n\t\t\t\t},\n\t\t\t\t\"env\": map[string]any{\n\t\t\t\t\t\"type\": \"array\",\n\t\t\t\t\t\"description\": \"Environment variables for the MCP server\",\n\t\t\t\t\t\"items\": map[string]any{\n\t\t\t\t\t\t\"type\": \"string\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t\"args\": map[string]any{\n\t\t\t\t\t\"type\": \"array\",\n\t\t\t\t\t\"description\": \"Command arguments for the MCP server\",\n\t\t\t\t\t\"items\": map[string]any{\n\t\t\t\t\t\t\"type\": \"string\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t\"type\": map[string]any{\n\t\t\t\t\t\"type\": \"string\",\n\t\t\t\t\t\"description\": \"Type of MCP server\",\n\t\t\t\t\t\"enum\": []string{\"stdio\", \"sse\"},\n\t\t\t\t\t\"default\": \"stdio\",\n\t\t\t\t},\n\t\t\t\t\"url\": map[string]any{\n\t\t\t\t\t\"type\": \"string\",\n\t\t\t\t\t\"description\": \"URL for SSE type MCP servers\",\n\t\t\t\t},\n\t\t\t\t\"headers\": map[string]any{\n\t\t\t\t\t\"type\": \"object\",\n\t\t\t\t\t\"description\": \"HTTP headers for SSE type MCP servers\",\n\t\t\t\t\t\"additionalProperties\": map[string]any{\n\t\t\t\t\t\t\"type\": \"string\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\t\"required\": []string{\"command\"},\n\t\t},\n\t}\n\n\t// Add providers\n\tproviderSchema := map[string]any{\n\t\t\"type\": \"object\",\n\t\t\"description\": \"LLM provider configurations\",\n\t\t\"additionalProperties\": map[string]any{\n\t\t\t\"type\": \"object\",\n\t\t\t\"description\": \"Provider configuration\",\n\t\t\t\"properties\": map[string]any{\n\t\t\t\t\"apiKey\": map[string]any{\n\t\t\t\t\t\"type\": \"string\",\n\t\t\t\t\t\"description\": \"API key for the provider\",\n\t\t\t\t},\n\t\t\t\t\"disabled\": map[string]any{\n\t\t\t\t\t\"type\": \"boolean\",\n\t\t\t\t\t\"description\": \"Whether the provider is disabled\",\n\t\t\t\t\t\"default\": false,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\t// Add known providers\n\tknownProviders := []string{\n\t\tstring(models.ProviderAnthropic),\n\t\tstring(models.ProviderOpenAI),\n\t\tstring(models.ProviderGemini),\n\t\tstring(models.ProviderGROQ),\n\t\tstring(models.ProviderOpenRouter),\n\t\tstring(models.ProviderBedrock),\n\t\tstring(models.ProviderAzure),\n\t\tstring(models.ProviderVertexAI),\n\t}\n\n\tproviderSchema[\"additionalProperties\"].(map[string]any)[\"properties\"].(map[string]any)[\"provider\"] = map[string]any{\n\t\t\"type\": \"string\",\n\t\t\"description\": \"Provider type\",\n\t\t\"enum\": knownProviders,\n\t}\n\n\tschema[\"properties\"].(map[string]any)[\"providers\"] = providerSchema\n\n\t// Add agents\n\tagentSchema := map[string]any{\n\t\t\"type\": \"object\",\n\t\t\"description\": \"Agent configurations\",\n\t\t\"additionalProperties\": map[string]any{\n\t\t\t\"type\": \"object\",\n\t\t\t\"description\": \"Agent configuration\",\n\t\t\t\"properties\": map[string]any{\n\t\t\t\t\"model\": map[string]any{\n\t\t\t\t\t\"type\": \"string\",\n\t\t\t\t\t\"description\": \"Model ID for the agent\",\n\t\t\t\t},\n\t\t\t\t\"maxTokens\": map[string]any{\n\t\t\t\t\t\"type\": \"integer\",\n\t\t\t\t\t\"description\": \"Maximum tokens for the agent\",\n\t\t\t\t\t\"minimum\": 1,\n\t\t\t\t},\n\t\t\t\t\"reasoningEffort\": map[string]any{\n\t\t\t\t\t\"type\": \"string\",\n\t\t\t\t\t\"description\": \"Reasoning effort for models that support it (OpenAI, Anthropic)\",\n\t\t\t\t\t\"enum\": []string{\"low\", \"medium\", \"high\"},\n\t\t\t\t},\n\t\t\t},\n\t\t\t\"required\": []string{\"model\"},\n\t\t},\n\t}\n\n\t// Add model enum\n\tmodelEnum := []string{}\n\tfor modelID := range models.SupportedModels {\n\t\tmodelEnum = append(modelEnum, string(modelID))\n\t}\n\tagentSchema[\"additionalProperties\"].(map[string]any)[\"properties\"].(map[string]any)[\"model\"].(map[string]any)[\"enum\"] = modelEnum\n\n\t// Add specific agent properties\n\tagentProperties := map[string]any{}\n\tknownAgents := []string{\n\t\tstring(config.AgentCoder),\n\t\tstring(config.AgentTask),\n\t\tstring(config.AgentTitle),\n\t}\n\n\tfor _, agentName := range knownAgents {\n\t\tagentProperties[agentName] = map[string]any{\n\t\t\t\"$ref\": \"#/definitions/agent\",\n\t\t}\n\t}\n\n\t// Create a combined schema that allows both specific agents and additional ones\n\tcombinedAgentSchema := map[string]any{\n\t\t\"type\": \"object\",\n\t\t\"description\": \"Agent configurations\",\n\t\t\"properties\": agentProperties,\n\t\t\"additionalProperties\": agentSchema[\"additionalProperties\"],\n\t}\n\n\tschema[\"properties\"].(map[string]any)[\"agents\"] = combinedAgentSchema\n\tschema[\"definitions\"] = map[string]any{\n\t\t\"agent\": agentSchema[\"additionalProperties\"],\n\t}\n\n\t// Add LSP configuration\n\tschema[\"properties\"].(map[string]any)[\"lsp\"] = map[string]any{\n\t\t\"type\": \"object\",\n\t\t\"description\": \"Language Server Protocol configurations\",\n\t\t\"additionalProperties\": map[string]any{\n\t\t\t\"type\": \"object\",\n\t\t\t\"description\": \"LSP configuration for a language\",\n\t\t\t\"properties\": map[string]any{\n\t\t\t\t\"disabled\": map[string]any{\n\t\t\t\t\t\"type\": \"boolean\",\n\t\t\t\t\t\"description\": \"Whether the LSP is disabled\",\n\t\t\t\t\t\"default\": false,\n\t\t\t\t},\n\t\t\t\t\"command\": map[string]any{\n\t\t\t\t\t\"type\": \"string\",\n\t\t\t\t\t\"description\": \"Command to execute for the LSP server\",\n\t\t\t\t},\n\t\t\t\t\"args\": map[string]any{\n\t\t\t\t\t\"type\": \"array\",\n\t\t\t\t\t\"description\": \"Command arguments for the LSP server\",\n\t\t\t\t\t\"items\": map[string]any{\n\t\t\t\t\t\t\"type\": \"string\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t\"options\": map[string]any{\n\t\t\t\t\t\"type\": \"object\",\n\t\t\t\t\t\"description\": \"Additional options for the LSP server\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t\"required\": []string{\"command\"},\n\t\t},\n\t}\n\n\treturn schema\n}\n"], ["/opencode/internal/message/content.go", "package message\n\nimport (\n\t\"encoding/base64\"\n\t\"slices\"\n\t\"time\"\n\n\t\"github.com/opencode-ai/opencode/internal/llm/models\"\n)\n\ntype MessageRole string\n\nconst (\n\tAssistant MessageRole = \"assistant\"\n\tUser MessageRole = \"user\"\n\tSystem MessageRole = \"system\"\n\tTool MessageRole = \"tool\"\n)\n\ntype FinishReason string\n\nconst (\n\tFinishReasonEndTurn FinishReason = \"end_turn\"\n\tFinishReasonMaxTokens FinishReason = \"max_tokens\"\n\tFinishReasonToolUse FinishReason = \"tool_use\"\n\tFinishReasonCanceled FinishReason = \"canceled\"\n\tFinishReasonError FinishReason = \"error\"\n\tFinishReasonPermissionDenied FinishReason = \"permission_denied\"\n\n\t// Should never happen\n\tFinishReasonUnknown FinishReason = \"unknown\"\n)\n\ntype ContentPart interface {\n\tisPart()\n}\n\ntype ReasoningContent struct {\n\tThinking string `json:\"thinking\"`\n}\n\nfunc (tc ReasoningContent) String() string {\n\treturn tc.Thinking\n}\nfunc (ReasoningContent) isPart() {}\n\ntype TextContent struct {\n\tText string `json:\"text\"`\n}\n\nfunc (tc TextContent) String() string {\n\treturn tc.Text\n}\n\nfunc (TextContent) isPart() {}\n\ntype ImageURLContent struct {\n\tURL string `json:\"url\"`\n\tDetail string `json:\"detail,omitempty\"`\n}\n\nfunc (iuc ImageURLContent) String() string {\n\treturn iuc.URL\n}\n\nfunc (ImageURLContent) isPart() {}\n\ntype BinaryContent struct {\n\tPath string\n\tMIMEType string\n\tData []byte\n}\n\nfunc (bc BinaryContent) String(provider models.ModelProvider) string {\n\tbase64Encoded := base64.StdEncoding.EncodeToString(bc.Data)\n\tif provider == models.ProviderOpenAI {\n\t\treturn \"data:\" + bc.MIMEType + \";base64,\" + base64Encoded\n\t}\n\treturn base64Encoded\n}\n\nfunc (BinaryContent) isPart() {}\n\ntype ToolCall struct {\n\tID string `json:\"id\"`\n\tName string `json:\"name\"`\n\tInput string `json:\"input\"`\n\tType string `json:\"type\"`\n\tFinished bool `json:\"finished\"`\n}\n\nfunc (ToolCall) isPart() {}\n\ntype ToolResult struct {\n\tToolCallID string `json:\"tool_call_id\"`\n\tName string `json:\"name\"`\n\tContent string `json:\"content\"`\n\tMetadata string `json:\"metadata\"`\n\tIsError bool `json:\"is_error\"`\n}\n\nfunc (ToolResult) isPart() {}\n\ntype Finish struct {\n\tReason FinishReason `json:\"reason\"`\n\tTime int64 `json:\"time\"`\n}\n\nfunc (Finish) isPart() {}\n\ntype Message struct {\n\tID string\n\tRole MessageRole\n\tSessionID string\n\tParts []ContentPart\n\tModel models.ModelID\n\tCreatedAt int64\n\tUpdatedAt int64\n}\n\nfunc (m *Message) Content() TextContent {\n\tfor _, part := range m.Parts {\n\t\tif c, ok := part.(TextContent); ok {\n\t\t\treturn c\n\t\t}\n\t}\n\treturn TextContent{}\n}\n\nfunc (m *Message) ReasoningContent() ReasoningContent {\n\tfor _, part := range m.Parts {\n\t\tif c, ok := part.(ReasoningContent); ok {\n\t\t\treturn c\n\t\t}\n\t}\n\treturn ReasoningContent{}\n}\n\nfunc (m *Message) ImageURLContent() []ImageURLContent {\n\timageURLContents := make([]ImageURLContent, 0)\n\tfor _, part := range m.Parts {\n\t\tif c, ok := part.(ImageURLContent); ok {\n\t\t\timageURLContents = append(imageURLContents, c)\n\t\t}\n\t}\n\treturn imageURLContents\n}\n\nfunc (m *Message) BinaryContent() []BinaryContent {\n\tbinaryContents := make([]BinaryContent, 0)\n\tfor _, part := range m.Parts {\n\t\tif c, ok := part.(BinaryContent); ok {\n\t\t\tbinaryContents = append(binaryContents, c)\n\t\t}\n\t}\n\treturn binaryContents\n}\n\nfunc (m *Message) ToolCalls() []ToolCall {\n\ttoolCalls := make([]ToolCall, 0)\n\tfor _, part := range m.Parts {\n\t\tif c, ok := part.(ToolCall); ok {\n\t\t\ttoolCalls = append(toolCalls, c)\n\t\t}\n\t}\n\treturn toolCalls\n}\n\nfunc (m *Message) ToolResults() []ToolResult {\n\ttoolResults := make([]ToolResult, 0)\n\tfor _, part := range m.Parts {\n\t\tif c, ok := part.(ToolResult); ok {\n\t\t\ttoolResults = append(toolResults, c)\n\t\t}\n\t}\n\treturn toolResults\n}\n\nfunc (m *Message) IsFinished() bool {\n\tfor _, part := range m.Parts {\n\t\tif _, ok := part.(Finish); ok {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc (m *Message) FinishPart() *Finish {\n\tfor _, part := range m.Parts {\n\t\tif c, ok := part.(Finish); ok {\n\t\t\treturn &c\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (m *Message) FinishReason() FinishReason {\n\tfor _, part := range m.Parts {\n\t\tif c, ok := part.(Finish); ok {\n\t\t\treturn c.Reason\n\t\t}\n\t}\n\treturn \"\"\n}\n\nfunc (m *Message) IsThinking() bool {\n\tif m.ReasoningContent().Thinking != \"\" && m.Content().Text == \"\" && !m.IsFinished() {\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc (m *Message) AppendContent(delta string) {\n\tfound := false\n\tfor i, part := range m.Parts {\n\t\tif c, ok := part.(TextContent); ok {\n\t\t\tm.Parts[i] = TextContent{Text: c.Text + delta}\n\t\t\tfound = true\n\t\t}\n\t}\n\tif !found {\n\t\tm.Parts = append(m.Parts, TextContent{Text: delta})\n\t}\n}\n\nfunc (m *Message) AppendReasoningContent(delta string) {\n\tfound := false\n\tfor i, part := range m.Parts {\n\t\tif c, ok := part.(ReasoningContent); ok {\n\t\t\tm.Parts[i] = ReasoningContent{Thinking: c.Thinking + delta}\n\t\t\tfound = true\n\t\t}\n\t}\n\tif !found {\n\t\tm.Parts = append(m.Parts, ReasoningContent{Thinking: delta})\n\t}\n}\n\nfunc (m *Message) FinishToolCall(toolCallID string) {\n\tfor i, part := range m.Parts {\n\t\tif c, ok := part.(ToolCall); ok {\n\t\t\tif c.ID == toolCallID {\n\t\t\t\tm.Parts[i] = ToolCall{\n\t\t\t\t\tID: c.ID,\n\t\t\t\t\tName: c.Name,\n\t\t\t\t\tInput: c.Input,\n\t\t\t\t\tType: c.Type,\n\t\t\t\t\tFinished: true,\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc (m *Message) AppendToolCallInput(toolCallID string, inputDelta string) {\n\tfor i, part := range m.Parts {\n\t\tif c, ok := part.(ToolCall); ok {\n\t\t\tif c.ID == toolCallID {\n\t\t\t\tm.Parts[i] = ToolCall{\n\t\t\t\t\tID: c.ID,\n\t\t\t\t\tName: c.Name,\n\t\t\t\t\tInput: c.Input + inputDelta,\n\t\t\t\t\tType: c.Type,\n\t\t\t\t\tFinished: c.Finished,\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc (m *Message) AddToolCall(tc ToolCall) {\n\tfor i, part := range m.Parts {\n\t\tif c, ok := part.(ToolCall); ok {\n\t\t\tif c.ID == tc.ID {\n\t\t\t\tm.Parts[i] = tc\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\tm.Parts = append(m.Parts, tc)\n}\n\nfunc (m *Message) SetToolCalls(tc []ToolCall) {\n\t// remove any existing tool call part it could have multiple\n\tparts := make([]ContentPart, 0)\n\tfor _, part := range m.Parts {\n\t\tif _, ok := part.(ToolCall); ok {\n\t\t\tcontinue\n\t\t}\n\t\tparts = append(parts, part)\n\t}\n\tm.Parts = parts\n\tfor _, toolCall := range tc {\n\t\tm.Parts = append(m.Parts, toolCall)\n\t}\n}\n\nfunc (m *Message) AddToolResult(tr ToolResult) {\n\tm.Parts = append(m.Parts, tr)\n}\n\nfunc (m *Message) SetToolResults(tr []ToolResult) {\n\tfor _, toolResult := range tr {\n\t\tm.Parts = append(m.Parts, toolResult)\n\t}\n}\n\nfunc (m *Message) AddFinish(reason FinishReason) {\n\t// remove any existing finish part\n\tfor i, part := range m.Parts {\n\t\tif _, ok := part.(Finish); ok {\n\t\t\tm.Parts = slices.Delete(m.Parts, i, i+1)\n\t\t\tbreak\n\t\t}\n\t}\n\tm.Parts = append(m.Parts, Finish{Reason: reason, Time: time.Now().Unix()})\n}\n\nfunc (m *Message) AddImageURL(url, detail string) {\n\tm.Parts = append(m.Parts, ImageURLContent{URL: url, Detail: detail})\n}\n\nfunc (m *Message) AddBinary(mimeType string, data []byte) {\n\tm.Parts = append(m.Parts, BinaryContent{MIMEType: mimeType, Data: data})\n}\n"], ["/opencode/internal/llm/models/local.go", "package models\n\nimport (\n\t\"cmp\"\n\t\"encoding/json\"\n\t\"net/http\"\n\t\"net/url\"\n\t\"os\"\n\t\"regexp\"\n\t\"strings\"\n\t\"unicode\"\n\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n\t\"github.com/spf13/viper\"\n)\n\nconst (\n\tProviderLocal ModelProvider = \"local\"\n\n\tlocalModelsPath = \"v1/models\"\n\tlmStudioBetaModelsPath = \"api/v0/models\"\n)\n\nfunc init() {\n\tif endpoint := os.Getenv(\"LOCAL_ENDPOINT\"); endpoint != \"\" {\n\t\tlocalEndpoint, err := url.Parse(endpoint)\n\t\tif err != nil {\n\t\t\tlogging.Debug(\"Failed to parse local endpoint\",\n\t\t\t\t\"error\", err,\n\t\t\t\t\"endpoint\", endpoint,\n\t\t\t)\n\t\t\treturn\n\t\t}\n\n\t\tload := func(url *url.URL, path string) []localModel {\n\t\t\turl.Path = path\n\t\t\treturn listLocalModels(url.String())\n\t\t}\n\n\t\tmodels := load(localEndpoint, lmStudioBetaModelsPath)\n\n\t\tif len(models) == 0 {\n\t\t\tmodels = load(localEndpoint, localModelsPath)\n\t\t}\n\n\t\tif len(models) == 0 {\n\t\t\tlogging.Debug(\"No local models found\",\n\t\t\t\t\"endpoint\", endpoint,\n\t\t\t)\n\t\t\treturn\n\t\t}\n\n\t\tloadLocalModels(models)\n\n\t\tviper.SetDefault(\"providers.local.apiKey\", \"dummy\")\n\t\tProviderPopularity[ProviderLocal] = 0\n\t}\n}\n\ntype localModelList struct {\n\tData []localModel `json:\"data\"`\n}\n\ntype localModel struct {\n\tID string `json:\"id\"`\n\tObject string `json:\"object\"`\n\tType string `json:\"type\"`\n\tPublisher string `json:\"publisher\"`\n\tArch string `json:\"arch\"`\n\tCompatibilityType string `json:\"compatibility_type\"`\n\tQuantization string `json:\"quantization\"`\n\tState string `json:\"state\"`\n\tMaxContextLength int64 `json:\"max_context_length\"`\n\tLoadedContextLength int64 `json:\"loaded_context_length\"`\n}\n\nfunc listLocalModels(modelsEndpoint string) []localModel {\n\tres, err := http.Get(modelsEndpoint)\n\tif err != nil {\n\t\tlogging.Debug(\"Failed to list local models\",\n\t\t\t\"error\", err,\n\t\t\t\"endpoint\", modelsEndpoint,\n\t\t)\n\t\treturn []localModel{}\n\t}\n\tdefer res.Body.Close()\n\n\tif res.StatusCode != http.StatusOK {\n\t\tlogging.Debug(\"Failed to list local models\",\n\t\t\t\"status\", res.StatusCode,\n\t\t\t\"endpoint\", modelsEndpoint,\n\t\t)\n\t\treturn []localModel{}\n\t}\n\n\tvar modelList localModelList\n\tif err = json.NewDecoder(res.Body).Decode(&modelList); err != nil {\n\t\tlogging.Debug(\"Failed to list local models\",\n\t\t\t\"error\", err,\n\t\t\t\"endpoint\", modelsEndpoint,\n\t\t)\n\t\treturn []localModel{}\n\t}\n\n\tvar supportedModels []localModel\n\tfor _, model := range modelList.Data {\n\t\tif strings.HasSuffix(modelsEndpoint, lmStudioBetaModelsPath) {\n\t\t\tif model.Object != \"model\" || model.Type != \"llm\" {\n\t\t\t\tlogging.Debug(\"Skipping unsupported LMStudio model\",\n\t\t\t\t\t\"endpoint\", modelsEndpoint,\n\t\t\t\t\t\"id\", model.ID,\n\t\t\t\t\t\"object\", model.Object,\n\t\t\t\t\t\"type\", model.Type,\n\t\t\t\t)\n\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\n\t\tsupportedModels = append(supportedModels, model)\n\t}\n\n\treturn supportedModels\n}\n\nfunc loadLocalModels(models []localModel) {\n\tfor i, m := range models {\n\t\tmodel := convertLocalModel(m)\n\t\tSupportedModels[model.ID] = model\n\n\t\tif i == 0 || m.State == \"loaded\" {\n\t\t\tviper.SetDefault(\"agents.coder.model\", model.ID)\n\t\t\tviper.SetDefault(\"agents.summarizer.model\", model.ID)\n\t\t\tviper.SetDefault(\"agents.task.model\", model.ID)\n\t\t\tviper.SetDefault(\"agents.title.model\", model.ID)\n\t\t}\n\t}\n}\n\nfunc convertLocalModel(model localModel) Model {\n\treturn Model{\n\t\tID: ModelID(\"local.\" + model.ID),\n\t\tName: friendlyModelName(model.ID),\n\t\tProvider: ProviderLocal,\n\t\tAPIModel: model.ID,\n\t\tContextWindow: cmp.Or(model.LoadedContextLength, 4096),\n\t\tDefaultMaxTokens: cmp.Or(model.LoadedContextLength, 4096),\n\t\tCanReason: true,\n\t\tSupportsAttachments: true,\n\t}\n}\n\nvar modelInfoRegex = regexp.MustCompile(`(?i)^([a-z0-9]+)(?:[-_]?([rv]?\\d[\\.\\d]*))?(?:[-_]?([a-z]+))?.*`)\n\nfunc friendlyModelName(modelID string) string {\n\tmainID := modelID\n\ttag := \"\"\n\n\tif slash := strings.LastIndex(mainID, \"/\"); slash != -1 {\n\t\tmainID = mainID[slash+1:]\n\t}\n\n\tif at := strings.Index(modelID, \"@\"); at != -1 {\n\t\tmainID = modelID[:at]\n\t\ttag = modelID[at+1:]\n\t}\n\n\tmatch := modelInfoRegex.FindStringSubmatch(mainID)\n\tif match == nil {\n\t\treturn modelID\n\t}\n\n\tcapitalize := func(s string) string {\n\t\tif s == \"\" {\n\t\t\treturn \"\"\n\t\t}\n\t\trunes := []rune(s)\n\t\trunes[0] = unicode.ToUpper(runes[0])\n\t\treturn string(runes)\n\t}\n\n\tfamily := capitalize(match[1])\n\tversion := \"\"\n\tlabel := \"\"\n\n\tif len(match) > 2 && match[2] != \"\" {\n\t\tversion = strings.ToUpper(match[2])\n\t}\n\n\tif len(match) > 3 && match[3] != \"\" {\n\t\tlabel = capitalize(match[3])\n\t}\n\n\tvar parts []string\n\tif family != \"\" {\n\t\tparts = append(parts, family)\n\t}\n\tif version != \"\" {\n\t\tparts = append(parts, version)\n\t}\n\tif label != \"\" {\n\t\tparts = append(parts, label)\n\t}\n\tif tag != \"\" {\n\t\tparts = append(parts, tag)\n\t}\n\n\treturn strings.Join(parts, \" \")\n}\n"], ["/opencode/internal/lsp/methods.go", "// Generated code. Do not edit\npackage lsp\n\nimport (\n\t\"context\"\n\n\t\"github.com/opencode-ai/opencode/internal/lsp/protocol\"\n)\n\n// Implementation sends a textDocument/implementation request to the LSP server.\n// A request to resolve the implementation locations of a symbol at a given text document position. The request's parameter is of type TextDocumentPositionParams the response is of type Definition or a Thenable that resolves to such.\nfunc (c *Client) Implementation(ctx context.Context, params protocol.ImplementationParams) (protocol.Or_Result_textDocument_implementation, error) {\n\tvar result protocol.Or_Result_textDocument_implementation\n\terr := c.Call(ctx, \"textDocument/implementation\", params, &result)\n\treturn result, err\n}\n\n// TypeDefinition sends a textDocument/typeDefinition request to the LSP server.\n// A request to resolve the type definition locations of a symbol at a given text document position. The request's parameter is of type TextDocumentPositionParams the response is of type Definition or a Thenable that resolves to such.\nfunc (c *Client) TypeDefinition(ctx context.Context, params protocol.TypeDefinitionParams) (protocol.Or_Result_textDocument_typeDefinition, error) {\n\tvar result protocol.Or_Result_textDocument_typeDefinition\n\terr := c.Call(ctx, \"textDocument/typeDefinition\", params, &result)\n\treturn result, err\n}\n\n// DocumentColor sends a textDocument/documentColor request to the LSP server.\n// A request to list all color symbols found in a given text document. The request's parameter is of type DocumentColorParams the response is of type ColorInformation ColorInformation[] or a Thenable that resolves to such.\nfunc (c *Client) DocumentColor(ctx context.Context, params protocol.DocumentColorParams) ([]protocol.ColorInformation, error) {\n\tvar result []protocol.ColorInformation\n\terr := c.Call(ctx, \"textDocument/documentColor\", params, &result)\n\treturn result, err\n}\n\n// ColorPresentation sends a textDocument/colorPresentation request to the LSP server.\n// A request to list all presentation for a color. The request's parameter is of type ColorPresentationParams the response is of type ColorInformation ColorInformation[] or a Thenable that resolves to such.\nfunc (c *Client) ColorPresentation(ctx context.Context, params protocol.ColorPresentationParams) ([]protocol.ColorPresentation, error) {\n\tvar result []protocol.ColorPresentation\n\terr := c.Call(ctx, \"textDocument/colorPresentation\", params, &result)\n\treturn result, err\n}\n\n// FoldingRange sends a textDocument/foldingRange request to the LSP server.\n// A request to provide folding ranges in a document. The request's parameter is of type FoldingRangeParams, the response is of type FoldingRangeList or a Thenable that resolves to such.\nfunc (c *Client) FoldingRange(ctx context.Context, params protocol.FoldingRangeParams) ([]protocol.FoldingRange, error) {\n\tvar result []protocol.FoldingRange\n\terr := c.Call(ctx, \"textDocument/foldingRange\", params, &result)\n\treturn result, err\n}\n\n// Declaration sends a textDocument/declaration request to the LSP server.\n// A request to resolve the type definition locations of a symbol at a given text document position. The request's parameter is of type TextDocumentPositionParams the response is of type Declaration or a typed array of DeclarationLink or a Thenable that resolves to such.\nfunc (c *Client) Declaration(ctx context.Context, params protocol.DeclarationParams) (protocol.Or_Result_textDocument_declaration, error) {\n\tvar result protocol.Or_Result_textDocument_declaration\n\terr := c.Call(ctx, \"textDocument/declaration\", params, &result)\n\treturn result, err\n}\n\n// SelectionRange sends a textDocument/selectionRange request to the LSP server.\n// A request to provide selection ranges in a document. The request's parameter is of type SelectionRangeParams, the response is of type SelectionRange SelectionRange[] or a Thenable that resolves to such.\nfunc (c *Client) SelectionRange(ctx context.Context, params protocol.SelectionRangeParams) ([]protocol.SelectionRange, error) {\n\tvar result []protocol.SelectionRange\n\terr := c.Call(ctx, \"textDocument/selectionRange\", params, &result)\n\treturn result, err\n}\n\n// PrepareCallHierarchy sends a textDocument/prepareCallHierarchy request to the LSP server.\n// A request to result a CallHierarchyItem in a document at a given position. Can be used as an input to an incoming or outgoing call hierarchy. Since 3.16.0\nfunc (c *Client) PrepareCallHierarchy(ctx context.Context, params protocol.CallHierarchyPrepareParams) ([]protocol.CallHierarchyItem, error) {\n\tvar result []protocol.CallHierarchyItem\n\terr := c.Call(ctx, \"textDocument/prepareCallHierarchy\", params, &result)\n\treturn result, err\n}\n\n// IncomingCalls sends a callHierarchy/incomingCalls request to the LSP server.\n// A request to resolve the incoming calls for a given CallHierarchyItem. Since 3.16.0\nfunc (c *Client) IncomingCalls(ctx context.Context, params protocol.CallHierarchyIncomingCallsParams) ([]protocol.CallHierarchyIncomingCall, error) {\n\tvar result []protocol.CallHierarchyIncomingCall\n\terr := c.Call(ctx, \"callHierarchy/incomingCalls\", params, &result)\n\treturn result, err\n}\n\n// OutgoingCalls sends a callHierarchy/outgoingCalls request to the LSP server.\n// A request to resolve the outgoing calls for a given CallHierarchyItem. Since 3.16.0\nfunc (c *Client) OutgoingCalls(ctx context.Context, params protocol.CallHierarchyOutgoingCallsParams) ([]protocol.CallHierarchyOutgoingCall, error) {\n\tvar result []protocol.CallHierarchyOutgoingCall\n\terr := c.Call(ctx, \"callHierarchy/outgoingCalls\", params, &result)\n\treturn result, err\n}\n\n// SemanticTokensFull sends a textDocument/semanticTokens/full request to the LSP server.\n// Since 3.16.0\nfunc (c *Client) SemanticTokensFull(ctx context.Context, params protocol.SemanticTokensParams) (protocol.SemanticTokens, error) {\n\tvar result protocol.SemanticTokens\n\terr := c.Call(ctx, \"textDocument/semanticTokens/full\", params, &result)\n\treturn result, err\n}\n\n// SemanticTokensFullDelta sends a textDocument/semanticTokens/full/delta request to the LSP server.\n// Since 3.16.0\nfunc (c *Client) SemanticTokensFullDelta(ctx context.Context, params protocol.SemanticTokensDeltaParams) (protocol.Or_Result_textDocument_semanticTokens_full_delta, error) {\n\tvar result protocol.Or_Result_textDocument_semanticTokens_full_delta\n\terr := c.Call(ctx, \"textDocument/semanticTokens/full/delta\", params, &result)\n\treturn result, err\n}\n\n// SemanticTokensRange sends a textDocument/semanticTokens/range request to the LSP server.\n// Since 3.16.0\nfunc (c *Client) SemanticTokensRange(ctx context.Context, params protocol.SemanticTokensRangeParams) (protocol.SemanticTokens, error) {\n\tvar result protocol.SemanticTokens\n\terr := c.Call(ctx, \"textDocument/semanticTokens/range\", params, &result)\n\treturn result, err\n}\n\n// LinkedEditingRange sends a textDocument/linkedEditingRange request to the LSP server.\n// A request to provide ranges that can be edited together. Since 3.16.0\nfunc (c *Client) LinkedEditingRange(ctx context.Context, params protocol.LinkedEditingRangeParams) (protocol.LinkedEditingRanges, error) {\n\tvar result protocol.LinkedEditingRanges\n\terr := c.Call(ctx, \"textDocument/linkedEditingRange\", params, &result)\n\treturn result, err\n}\n\n// WillCreateFiles sends a workspace/willCreateFiles request to the LSP server.\n// The will create files request is sent from the client to the server before files are actually created as long as the creation is triggered from within the client. The request can return a WorkspaceEdit which will be applied to workspace before the files are created. Hence the WorkspaceEdit can not manipulate the content of the file to be created. Since 3.16.0\nfunc (c *Client) WillCreateFiles(ctx context.Context, params protocol.CreateFilesParams) (protocol.WorkspaceEdit, error) {\n\tvar result protocol.WorkspaceEdit\n\terr := c.Call(ctx, \"workspace/willCreateFiles\", params, &result)\n\treturn result, err\n}\n\n// WillRenameFiles sends a workspace/willRenameFiles request to the LSP server.\n// The will rename files request is sent from the client to the server before files are actually renamed as long as the rename is triggered from within the client. Since 3.16.0\nfunc (c *Client) WillRenameFiles(ctx context.Context, params protocol.RenameFilesParams) (protocol.WorkspaceEdit, error) {\n\tvar result protocol.WorkspaceEdit\n\terr := c.Call(ctx, \"workspace/willRenameFiles\", params, &result)\n\treturn result, err\n}\n\n// WillDeleteFiles sends a workspace/willDeleteFiles request to the LSP server.\n// The did delete files notification is sent from the client to the server when files were deleted from within the client. Since 3.16.0\nfunc (c *Client) WillDeleteFiles(ctx context.Context, params protocol.DeleteFilesParams) (protocol.WorkspaceEdit, error) {\n\tvar result protocol.WorkspaceEdit\n\terr := c.Call(ctx, \"workspace/willDeleteFiles\", params, &result)\n\treturn result, err\n}\n\n// Moniker sends a textDocument/moniker request to the LSP server.\n// A request to get the moniker of a symbol at a given text document position. The request parameter is of type TextDocumentPositionParams. The response is of type Moniker Moniker[] or null.\nfunc (c *Client) Moniker(ctx context.Context, params protocol.MonikerParams) ([]protocol.Moniker, error) {\n\tvar result []protocol.Moniker\n\terr := c.Call(ctx, \"textDocument/moniker\", params, &result)\n\treturn result, err\n}\n\n// PrepareTypeHierarchy sends a textDocument/prepareTypeHierarchy request to the LSP server.\n// A request to result a TypeHierarchyItem in a document at a given position. Can be used as an input to a subtypes or supertypes type hierarchy. Since 3.17.0\nfunc (c *Client) PrepareTypeHierarchy(ctx context.Context, params protocol.TypeHierarchyPrepareParams) ([]protocol.TypeHierarchyItem, error) {\n\tvar result []protocol.TypeHierarchyItem\n\terr := c.Call(ctx, \"textDocument/prepareTypeHierarchy\", params, &result)\n\treturn result, err\n}\n\n// Supertypes sends a typeHierarchy/supertypes request to the LSP server.\n// A request to resolve the supertypes for a given TypeHierarchyItem. Since 3.17.0\nfunc (c *Client) Supertypes(ctx context.Context, params protocol.TypeHierarchySupertypesParams) ([]protocol.TypeHierarchyItem, error) {\n\tvar result []protocol.TypeHierarchyItem\n\terr := c.Call(ctx, \"typeHierarchy/supertypes\", params, &result)\n\treturn result, err\n}\n\n// Subtypes sends a typeHierarchy/subtypes request to the LSP server.\n// A request to resolve the subtypes for a given TypeHierarchyItem. Since 3.17.0\nfunc (c *Client) Subtypes(ctx context.Context, params protocol.TypeHierarchySubtypesParams) ([]protocol.TypeHierarchyItem, error) {\n\tvar result []protocol.TypeHierarchyItem\n\terr := c.Call(ctx, \"typeHierarchy/subtypes\", params, &result)\n\treturn result, err\n}\n\n// InlineValue sends a textDocument/inlineValue request to the LSP server.\n// A request to provide inline values in a document. The request's parameter is of type InlineValueParams, the response is of type InlineValue InlineValue[] or a Thenable that resolves to such. Since 3.17.0\nfunc (c *Client) InlineValue(ctx context.Context, params protocol.InlineValueParams) ([]protocol.InlineValue, error) {\n\tvar result []protocol.InlineValue\n\terr := c.Call(ctx, \"textDocument/inlineValue\", params, &result)\n\treturn result, err\n}\n\n// InlayHint sends a textDocument/inlayHint request to the LSP server.\n// A request to provide inlay hints in a document. The request's parameter is of type InlayHintsParams, the response is of type InlayHint InlayHint[] or a Thenable that resolves to such. Since 3.17.0\nfunc (c *Client) InlayHint(ctx context.Context, params protocol.InlayHintParams) ([]protocol.InlayHint, error) {\n\tvar result []protocol.InlayHint\n\terr := c.Call(ctx, \"textDocument/inlayHint\", params, &result)\n\treturn result, err\n}\n\n// Resolve sends a inlayHint/resolve request to the LSP server.\n// A request to resolve additional properties for an inlay hint. The request's parameter is of type InlayHint, the response is of type InlayHint or a Thenable that resolves to such. Since 3.17.0\nfunc (c *Client) Resolve(ctx context.Context, params protocol.InlayHint) (protocol.InlayHint, error) {\n\tvar result protocol.InlayHint\n\terr := c.Call(ctx, \"inlayHint/resolve\", params, &result)\n\treturn result, err\n}\n\n// Diagnostic sends a textDocument/diagnostic request to the LSP server.\n// The document diagnostic request definition. Since 3.17.0\nfunc (c *Client) Diagnostic(ctx context.Context, params protocol.DocumentDiagnosticParams) (protocol.DocumentDiagnosticReport, error) {\n\tvar result protocol.DocumentDiagnosticReport\n\terr := c.Call(ctx, \"textDocument/diagnostic\", params, &result)\n\treturn result, err\n}\n\n// DiagnosticWorkspace sends a workspace/diagnostic request to the LSP server.\n// The workspace diagnostic request definition. Since 3.17.0\nfunc (c *Client) DiagnosticWorkspace(ctx context.Context, params protocol.WorkspaceDiagnosticParams) (protocol.WorkspaceDiagnosticReport, error) {\n\tvar result protocol.WorkspaceDiagnosticReport\n\terr := c.Call(ctx, \"workspace/diagnostic\", params, &result)\n\treturn result, err\n}\n\n// InlineCompletion sends a textDocument/inlineCompletion request to the LSP server.\n// A request to provide inline completions in a document. The request's parameter is of type InlineCompletionParams, the response is of type InlineCompletion InlineCompletion[] or a Thenable that resolves to such. Since 3.18.0 PROPOSED\nfunc (c *Client) InlineCompletion(ctx context.Context, params protocol.InlineCompletionParams) (protocol.Or_Result_textDocument_inlineCompletion, error) {\n\tvar result protocol.Or_Result_textDocument_inlineCompletion\n\terr := c.Call(ctx, \"textDocument/inlineCompletion\", params, &result)\n\treturn result, err\n}\n\n// TextDocumentContent sends a workspace/textDocumentContent request to the LSP server.\n// The workspace/textDocumentContent request is sent from the client to the server to request the content of a text document. Since 3.18.0 PROPOSED\nfunc (c *Client) TextDocumentContent(ctx context.Context, params protocol.TextDocumentContentParams) (string, error) {\n\tvar result string\n\terr := c.Call(ctx, \"workspace/textDocumentContent\", params, &result)\n\treturn result, err\n}\n\n// Initialize sends a initialize request to the LSP server.\n// The initialize request is sent from the client to the server. It is sent once as the request after starting up the server. The requests parameter is of type InitializeParams the response if of type InitializeResult of a Thenable that resolves to such.\nfunc (c *Client) Initialize(ctx context.Context, params protocol.ParamInitialize) (protocol.InitializeResult, error) {\n\tvar result protocol.InitializeResult\n\terr := c.Call(ctx, \"initialize\", params, &result)\n\treturn result, err\n}\n\n// Shutdown sends a shutdown request to the LSP server.\n// A shutdown request is sent from the client to the server. It is sent once when the client decides to shutdown the server. The only notification that is sent after a shutdown request is the exit event.\nfunc (c *Client) Shutdown(ctx context.Context) error {\n\treturn c.Call(ctx, \"shutdown\", nil, nil)\n}\n\n// WillSaveWaitUntil sends a textDocument/willSaveWaitUntil request to the LSP server.\n// A document will save request is sent from the client to the server before the document is actually saved. The request can return an array of TextEdits which will be applied to the text document before it is saved. Please note that clients might drop results if computing the text edits took too long or if a server constantly fails on this request. This is done to keep the save fast and reliable.\nfunc (c *Client) WillSaveWaitUntil(ctx context.Context, params protocol.WillSaveTextDocumentParams) ([]protocol.TextEdit, error) {\n\tvar result []protocol.TextEdit\n\terr := c.Call(ctx, \"textDocument/willSaveWaitUntil\", params, &result)\n\treturn result, err\n}\n\n// Completion sends a textDocument/completion request to the LSP server.\n// Request to request completion at a given text document position. The request's parameter is of type TextDocumentPosition the response is of type CompletionItem CompletionItem[] or CompletionList or a Thenable that resolves to such. The request can delay the computation of the CompletionItem.detail detail and CompletionItem.documentation documentation properties to the completionItem/resolve request. However, properties that are needed for the initial sorting and filtering, like sortText, filterText, insertText, and textEdit, must not be changed during resolve.\nfunc (c *Client) Completion(ctx context.Context, params protocol.CompletionParams) (protocol.Or_Result_textDocument_completion, error) {\n\tvar result protocol.Or_Result_textDocument_completion\n\terr := c.Call(ctx, \"textDocument/completion\", params, &result)\n\treturn result, err\n}\n\n// ResolveCompletionItem sends a completionItem/resolve request to the LSP server.\n// Request to resolve additional information for a given completion item.The request's parameter is of type CompletionItem the response is of type CompletionItem or a Thenable that resolves to such.\nfunc (c *Client) ResolveCompletionItem(ctx context.Context, params protocol.CompletionItem) (protocol.CompletionItem, error) {\n\tvar result protocol.CompletionItem\n\terr := c.Call(ctx, \"completionItem/resolve\", params, &result)\n\treturn result, err\n}\n\n// Hover sends a textDocument/hover request to the LSP server.\n// Request to request hover information at a given text document position. The request's parameter is of type TextDocumentPosition the response is of type Hover or a Thenable that resolves to such.\nfunc (c *Client) Hover(ctx context.Context, params protocol.HoverParams) (protocol.Hover, error) {\n\tvar result protocol.Hover\n\terr := c.Call(ctx, \"textDocument/hover\", params, &result)\n\treturn result, err\n}\n\n// SignatureHelp sends a textDocument/signatureHelp request to the LSP server.\nfunc (c *Client) SignatureHelp(ctx context.Context, params protocol.SignatureHelpParams) (protocol.SignatureHelp, error) {\n\tvar result protocol.SignatureHelp\n\terr := c.Call(ctx, \"textDocument/signatureHelp\", params, &result)\n\treturn result, err\n}\n\n// Definition sends a textDocument/definition request to the LSP server.\n// A request to resolve the definition location of a symbol at a given text document position. The request's parameter is of type TextDocumentPosition the response is of either type Definition or a typed array of DefinitionLink or a Thenable that resolves to such.\nfunc (c *Client) Definition(ctx context.Context, params protocol.DefinitionParams) (protocol.Or_Result_textDocument_definition, error) {\n\tvar result protocol.Or_Result_textDocument_definition\n\terr := c.Call(ctx, \"textDocument/definition\", params, &result)\n\treturn result, err\n}\n\n// References sends a textDocument/references request to the LSP server.\n// A request to resolve project-wide references for the symbol denoted by the given text document position. The request's parameter is of type ReferenceParams the response is of type Location Location[] or a Thenable that resolves to such.\nfunc (c *Client) References(ctx context.Context, params protocol.ReferenceParams) ([]protocol.Location, error) {\n\tvar result []protocol.Location\n\terr := c.Call(ctx, \"textDocument/references\", params, &result)\n\treturn result, err\n}\n\n// DocumentHighlight sends a textDocument/documentHighlight request to the LSP server.\n// Request to resolve a DocumentHighlight for a given text document position. The request's parameter is of type TextDocumentPosition the request response is an array of type DocumentHighlight or a Thenable that resolves to such.\nfunc (c *Client) DocumentHighlight(ctx context.Context, params protocol.DocumentHighlightParams) ([]protocol.DocumentHighlight, error) {\n\tvar result []protocol.DocumentHighlight\n\terr := c.Call(ctx, \"textDocument/documentHighlight\", params, &result)\n\treturn result, err\n}\n\n// DocumentSymbol sends a textDocument/documentSymbol request to the LSP server.\n// A request to list all symbols found in a given text document. The request's parameter is of type TextDocumentIdentifier the response is of type SymbolInformation SymbolInformation[] or a Thenable that resolves to such.\nfunc (c *Client) DocumentSymbol(ctx context.Context, params protocol.DocumentSymbolParams) (protocol.Or_Result_textDocument_documentSymbol, error) {\n\tvar result protocol.Or_Result_textDocument_documentSymbol\n\terr := c.Call(ctx, \"textDocument/documentSymbol\", params, &result)\n\treturn result, err\n}\n\n// CodeAction sends a textDocument/codeAction request to the LSP server.\n// A request to provide commands for the given text document and range.\nfunc (c *Client) CodeAction(ctx context.Context, params protocol.CodeActionParams) ([]protocol.Or_Result_textDocument_codeAction_Item0_Elem, error) {\n\tvar result []protocol.Or_Result_textDocument_codeAction_Item0_Elem\n\terr := c.Call(ctx, \"textDocument/codeAction\", params, &result)\n\treturn result, err\n}\n\n// ResolveCodeAction sends a codeAction/resolve request to the LSP server.\n// Request to resolve additional information for a given code action.The request's parameter is of type CodeAction the response is of type CodeAction or a Thenable that resolves to such.\nfunc (c *Client) ResolveCodeAction(ctx context.Context, params protocol.CodeAction) (protocol.CodeAction, error) {\n\tvar result protocol.CodeAction\n\terr := c.Call(ctx, \"codeAction/resolve\", params, &result)\n\treturn result, err\n}\n\n// Symbol sends a workspace/symbol request to the LSP server.\n// A request to list project-wide symbols matching the query string given by the WorkspaceSymbolParams. The response is of type SymbolInformation SymbolInformation[] or a Thenable that resolves to such. Since 3.17.0 - support for WorkspaceSymbol in the returned data. Clients need to advertise support for WorkspaceSymbols via the client capability workspace.symbol.resolveSupport.\nfunc (c *Client) Symbol(ctx context.Context, params protocol.WorkspaceSymbolParams) (protocol.Or_Result_workspace_symbol, error) {\n\tvar result protocol.Or_Result_workspace_symbol\n\terr := c.Call(ctx, \"workspace/symbol\", params, &result)\n\treturn result, err\n}\n\n// ResolveWorkspaceSymbol sends a workspaceSymbol/resolve request to the LSP server.\n// A request to resolve the range inside the workspace symbol's location. Since 3.17.0\nfunc (c *Client) ResolveWorkspaceSymbol(ctx context.Context, params protocol.WorkspaceSymbol) (protocol.WorkspaceSymbol, error) {\n\tvar result protocol.WorkspaceSymbol\n\terr := c.Call(ctx, \"workspaceSymbol/resolve\", params, &result)\n\treturn result, err\n}\n\n// CodeLens sends a textDocument/codeLens request to the LSP server.\n// A request to provide code lens for the given text document.\nfunc (c *Client) CodeLens(ctx context.Context, params protocol.CodeLensParams) ([]protocol.CodeLens, error) {\n\tvar result []protocol.CodeLens\n\terr := c.Call(ctx, \"textDocument/codeLens\", params, &result)\n\treturn result, err\n}\n\n// ResolveCodeLens sends a codeLens/resolve request to the LSP server.\n// A request to resolve a command for a given code lens.\nfunc (c *Client) ResolveCodeLens(ctx context.Context, params protocol.CodeLens) (protocol.CodeLens, error) {\n\tvar result protocol.CodeLens\n\terr := c.Call(ctx, \"codeLens/resolve\", params, &result)\n\treturn result, err\n}\n\n// DocumentLink sends a textDocument/documentLink request to the LSP server.\n// A request to provide document links\nfunc (c *Client) DocumentLink(ctx context.Context, params protocol.DocumentLinkParams) ([]protocol.DocumentLink, error) {\n\tvar result []protocol.DocumentLink\n\terr := c.Call(ctx, \"textDocument/documentLink\", params, &result)\n\treturn result, err\n}\n\n// ResolveDocumentLink sends a documentLink/resolve request to the LSP server.\n// Request to resolve additional information for a given document link. The request's parameter is of type DocumentLink the response is of type DocumentLink or a Thenable that resolves to such.\nfunc (c *Client) ResolveDocumentLink(ctx context.Context, params protocol.DocumentLink) (protocol.DocumentLink, error) {\n\tvar result protocol.DocumentLink\n\terr := c.Call(ctx, \"documentLink/resolve\", params, &result)\n\treturn result, err\n}\n\n// Formatting sends a textDocument/formatting request to the LSP server.\n// A request to format a whole document.\nfunc (c *Client) Formatting(ctx context.Context, params protocol.DocumentFormattingParams) ([]protocol.TextEdit, error) {\n\tvar result []protocol.TextEdit\n\terr := c.Call(ctx, \"textDocument/formatting\", params, &result)\n\treturn result, err\n}\n\n// RangeFormatting sends a textDocument/rangeFormatting request to the LSP server.\n// A request to format a range in a document.\nfunc (c *Client) RangeFormatting(ctx context.Context, params protocol.DocumentRangeFormattingParams) ([]protocol.TextEdit, error) {\n\tvar result []protocol.TextEdit\n\terr := c.Call(ctx, \"textDocument/rangeFormatting\", params, &result)\n\treturn result, err\n}\n\n// RangesFormatting sends a textDocument/rangesFormatting request to the LSP server.\n// A request to format ranges in a document. Since 3.18.0 PROPOSED\nfunc (c *Client) RangesFormatting(ctx context.Context, params protocol.DocumentRangesFormattingParams) ([]protocol.TextEdit, error) {\n\tvar result []protocol.TextEdit\n\terr := c.Call(ctx, \"textDocument/rangesFormatting\", params, &result)\n\treturn result, err\n}\n\n// OnTypeFormatting sends a textDocument/onTypeFormatting request to the LSP server.\n// A request to format a document on type.\nfunc (c *Client) OnTypeFormatting(ctx context.Context, params protocol.DocumentOnTypeFormattingParams) ([]protocol.TextEdit, error) {\n\tvar result []protocol.TextEdit\n\terr := c.Call(ctx, \"textDocument/onTypeFormatting\", params, &result)\n\treturn result, err\n}\n\n// Rename sends a textDocument/rename request to the LSP server.\n// A request to rename a symbol.\nfunc (c *Client) Rename(ctx context.Context, params protocol.RenameParams) (protocol.WorkspaceEdit, error) {\n\tvar result protocol.WorkspaceEdit\n\terr := c.Call(ctx, \"textDocument/rename\", params, &result)\n\treturn result, err\n}\n\n// PrepareRename sends a textDocument/prepareRename request to the LSP server.\n// A request to test and perform the setup necessary for a rename. Since 3.16 - support for default behavior\nfunc (c *Client) PrepareRename(ctx context.Context, params protocol.PrepareRenameParams) (protocol.PrepareRenameResult, error) {\n\tvar result protocol.PrepareRenameResult\n\terr := c.Call(ctx, \"textDocument/prepareRename\", params, &result)\n\treturn result, err\n}\n\n// ExecuteCommand sends a workspace/executeCommand request to the LSP server.\n// A request send from the client to the server to execute a command. The request might return a workspace edit which the client will apply to the workspace.\nfunc (c *Client) ExecuteCommand(ctx context.Context, params protocol.ExecuteCommandParams) (any, error) {\n\tvar result any\n\terr := c.Call(ctx, \"workspace/executeCommand\", params, &result)\n\treturn result, err\n}\n\n// DidChangeWorkspaceFolders sends a workspace/didChangeWorkspaceFolders notification to the LSP server.\n// The workspace/didChangeWorkspaceFolders notification is sent from the client to the server when the workspace folder configuration changes.\nfunc (c *Client) DidChangeWorkspaceFolders(ctx context.Context, params protocol.DidChangeWorkspaceFoldersParams) error {\n\treturn c.Notify(ctx, \"workspace/didChangeWorkspaceFolders\", params)\n}\n\n// WorkDoneProgressCancel sends a window/workDoneProgress/cancel notification to the LSP server.\n// The window/workDoneProgress/cancel notification is sent from the client to the server to cancel a progress initiated on the server side.\nfunc (c *Client) WorkDoneProgressCancel(ctx context.Context, params protocol.WorkDoneProgressCancelParams) error {\n\treturn c.Notify(ctx, \"window/workDoneProgress/cancel\", params)\n}\n\n// DidCreateFiles sends a workspace/didCreateFiles notification to the LSP server.\n// The did create files notification is sent from the client to the server when files were created from within the client. Since 3.16.0\nfunc (c *Client) DidCreateFiles(ctx context.Context, params protocol.CreateFilesParams) error {\n\treturn c.Notify(ctx, \"workspace/didCreateFiles\", params)\n}\n\n// DidRenameFiles sends a workspace/didRenameFiles notification to the LSP server.\n// The did rename files notification is sent from the client to the server when files were renamed from within the client. Since 3.16.0\nfunc (c *Client) DidRenameFiles(ctx context.Context, params protocol.RenameFilesParams) error {\n\treturn c.Notify(ctx, \"workspace/didRenameFiles\", params)\n}\n\n// DidDeleteFiles sends a workspace/didDeleteFiles notification to the LSP server.\n// The will delete files request is sent from the client to the server before files are actually deleted as long as the deletion is triggered from within the client. Since 3.16.0\nfunc (c *Client) DidDeleteFiles(ctx context.Context, params protocol.DeleteFilesParams) error {\n\treturn c.Notify(ctx, \"workspace/didDeleteFiles\", params)\n}\n\n// DidOpenNotebookDocument sends a notebookDocument/didOpen notification to the LSP server.\n// A notification sent when a notebook opens. Since 3.17.0\nfunc (c *Client) DidOpenNotebookDocument(ctx context.Context, params protocol.DidOpenNotebookDocumentParams) error {\n\treturn c.Notify(ctx, \"notebookDocument/didOpen\", params)\n}\n\n// DidChangeNotebookDocument sends a notebookDocument/didChange notification to the LSP server.\nfunc (c *Client) DidChangeNotebookDocument(ctx context.Context, params protocol.DidChangeNotebookDocumentParams) error {\n\treturn c.Notify(ctx, \"notebookDocument/didChange\", params)\n}\n\n// DidSaveNotebookDocument sends a notebookDocument/didSave notification to the LSP server.\n// A notification sent when a notebook document is saved. Since 3.17.0\nfunc (c *Client) DidSaveNotebookDocument(ctx context.Context, params protocol.DidSaveNotebookDocumentParams) error {\n\treturn c.Notify(ctx, \"notebookDocument/didSave\", params)\n}\n\n// DidCloseNotebookDocument sends a notebookDocument/didClose notification to the LSP server.\n// A notification sent when a notebook closes. Since 3.17.0\nfunc (c *Client) DidCloseNotebookDocument(ctx context.Context, params protocol.DidCloseNotebookDocumentParams) error {\n\treturn c.Notify(ctx, \"notebookDocument/didClose\", params)\n}\n\n// Initialized sends a initialized notification to the LSP server.\n// The initialized notification is sent from the client to the server after the client is fully initialized and the server is allowed to send requests from the server to the client.\nfunc (c *Client) Initialized(ctx context.Context, params protocol.InitializedParams) error {\n\treturn c.Notify(ctx, \"initialized\", params)\n}\n\n// Exit sends a exit notification to the LSP server.\n// The exit event is sent from the client to the server to ask the server to exit its process.\nfunc (c *Client) Exit(ctx context.Context) error {\n\treturn c.Notify(ctx, \"exit\", nil)\n}\n\n// DidChangeConfiguration sends a workspace/didChangeConfiguration notification to the LSP server.\n// The configuration change notification is sent from the client to the server when the client's configuration has changed. The notification contains the changed configuration as defined by the language client.\nfunc (c *Client) DidChangeConfiguration(ctx context.Context, params protocol.DidChangeConfigurationParams) error {\n\treturn c.Notify(ctx, \"workspace/didChangeConfiguration\", params)\n}\n\n// DidOpen sends a textDocument/didOpen notification to the LSP server.\n// The document open notification is sent from the client to the server to signal newly opened text documents. The document's truth is now managed by the client and the server must not try to read the document's truth using the document's uri. Open in this sense means it is managed by the client. It doesn't necessarily mean that its content is presented in an editor. An open notification must not be sent more than once without a corresponding close notification send before. This means open and close notification must be balanced and the max open count is one.\nfunc (c *Client) DidOpen(ctx context.Context, params protocol.DidOpenTextDocumentParams) error {\n\treturn c.Notify(ctx, \"textDocument/didOpen\", params)\n}\n\n// DidChange sends a textDocument/didChange notification to the LSP server.\n// The document change notification is sent from the client to the server to signal changes to a text document.\nfunc (c *Client) DidChange(ctx context.Context, params protocol.DidChangeTextDocumentParams) error {\n\treturn c.Notify(ctx, \"textDocument/didChange\", params)\n}\n\n// DidClose sends a textDocument/didClose notification to the LSP server.\n// The document close notification is sent from the client to the server when the document got closed in the client. The document's truth now exists where the document's uri points to (e.g. if the document's uri is a file uri the truth now exists on disk). As with the open notification the close notification is about managing the document's content. Receiving a close notification doesn't mean that the document was open in an editor before. A close notification requires a previous open notification to be sent.\nfunc (c *Client) DidClose(ctx context.Context, params protocol.DidCloseTextDocumentParams) error {\n\treturn c.Notify(ctx, \"textDocument/didClose\", params)\n}\n\n// DidSave sends a textDocument/didSave notification to the LSP server.\n// The document save notification is sent from the client to the server when the document got saved in the client.\nfunc (c *Client) DidSave(ctx context.Context, params protocol.DidSaveTextDocumentParams) error {\n\treturn c.Notify(ctx, \"textDocument/didSave\", params)\n}\n\n// WillSave sends a textDocument/willSave notification to the LSP server.\n// A document will save notification is sent from the client to the server before the document is actually saved.\nfunc (c *Client) WillSave(ctx context.Context, params protocol.WillSaveTextDocumentParams) error {\n\treturn c.Notify(ctx, \"textDocument/willSave\", params)\n}\n\n// DidChangeWatchedFiles sends a workspace/didChangeWatchedFiles notification to the LSP server.\n// The watched files notification is sent from the client to the server when the client detects changes to file watched by the language client.\nfunc (c *Client) DidChangeWatchedFiles(ctx context.Context, params protocol.DidChangeWatchedFilesParams) error {\n\treturn c.Notify(ctx, \"workspace/didChangeWatchedFiles\", params)\n}\n\n// SetTrace sends a $/setTrace notification to the LSP server.\nfunc (c *Client) SetTrace(ctx context.Context, params protocol.SetTraceParams) error {\n\treturn c.Notify(ctx, \"$/setTrace\", params)\n}\n\n// Progress sends a $/progress notification to the LSP server.\nfunc (c *Client) Progress(ctx context.Context, params protocol.ProgressParams) error {\n\treturn c.Notify(ctx, \"$/progress\", params)\n}\n"], ["/opencode/internal/diff/patch.go", "package diff\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"strings\"\n)\n\ntype ActionType string\n\nconst (\n\tActionAdd ActionType = \"add\"\n\tActionDelete ActionType = \"delete\"\n\tActionUpdate ActionType = \"update\"\n)\n\ntype FileChange struct {\n\tType ActionType\n\tOldContent *string\n\tNewContent *string\n\tMovePath *string\n}\n\ntype Commit struct {\n\tChanges map[string]FileChange\n}\n\ntype Chunk struct {\n\tOrigIndex int // line index of the first line in the original file\n\tDelLines []string // lines to delete\n\tInsLines []string // lines to insert\n}\n\ntype PatchAction struct {\n\tType ActionType\n\tNewFile *string\n\tChunks []Chunk\n\tMovePath *string\n}\n\ntype Patch struct {\n\tActions map[string]PatchAction\n}\n\ntype DiffError struct {\n\tmessage string\n}\n\nfunc (e DiffError) Error() string {\n\treturn e.message\n}\n\n// Helper functions for error handling\nfunc NewDiffError(message string) DiffError {\n\treturn DiffError{message: message}\n}\n\nfunc fileError(action, reason, path string) DiffError {\n\treturn NewDiffError(fmt.Sprintf(\"%s File Error: %s: %s\", action, reason, path))\n}\n\nfunc contextError(index int, context string, isEOF bool) DiffError {\n\tprefix := \"Invalid Context\"\n\tif isEOF {\n\t\tprefix = \"Invalid EOF Context\"\n\t}\n\treturn NewDiffError(fmt.Sprintf(\"%s %d:\\n%s\", prefix, index, context))\n}\n\ntype Parser struct {\n\tcurrentFiles map[string]string\n\tlines []string\n\tindex int\n\tpatch Patch\n\tfuzz int\n}\n\nfunc NewParser(currentFiles map[string]string, lines []string) *Parser {\n\treturn &Parser{\n\t\tcurrentFiles: currentFiles,\n\t\tlines: lines,\n\t\tindex: 0,\n\t\tpatch: Patch{Actions: make(map[string]PatchAction, len(currentFiles))},\n\t\tfuzz: 0,\n\t}\n}\n\nfunc (p *Parser) isDone(prefixes []string) bool {\n\tif p.index >= len(p.lines) {\n\t\treturn true\n\t}\n\tfor _, prefix := range prefixes {\n\t\tif strings.HasPrefix(p.lines[p.index], prefix) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc (p *Parser) startsWith(prefix any) bool {\n\tvar prefixes []string\n\tswitch v := prefix.(type) {\n\tcase string:\n\t\tprefixes = []string{v}\n\tcase []string:\n\t\tprefixes = v\n\t}\n\n\tfor _, pfx := range prefixes {\n\t\tif strings.HasPrefix(p.lines[p.index], pfx) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc (p *Parser) readStr(prefix string, returnEverything bool) string {\n\tif p.index >= len(p.lines) {\n\t\treturn \"\" // Changed from panic to return empty string for safer operation\n\t}\n\tif strings.HasPrefix(p.lines[p.index], prefix) {\n\t\tvar text string\n\t\tif returnEverything {\n\t\t\ttext = p.lines[p.index]\n\t\t} else {\n\t\t\ttext = p.lines[p.index][len(prefix):]\n\t\t}\n\t\tp.index++\n\t\treturn text\n\t}\n\treturn \"\"\n}\n\nfunc (p *Parser) Parse() error {\n\tendPatchPrefixes := []string{\"*** End Patch\"}\n\n\tfor !p.isDone(endPatchPrefixes) {\n\t\tpath := p.readStr(\"*** Update File: \", false)\n\t\tif path != \"\" {\n\t\t\tif _, exists := p.patch.Actions[path]; exists {\n\t\t\t\treturn fileError(\"Update\", \"Duplicate Path\", path)\n\t\t\t}\n\t\t\tmoveTo := p.readStr(\"*** Move to: \", false)\n\t\t\tif _, exists := p.currentFiles[path]; !exists {\n\t\t\t\treturn fileError(\"Update\", \"Missing File\", path)\n\t\t\t}\n\t\t\ttext := p.currentFiles[path]\n\t\t\taction, err := p.parseUpdateFile(text)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif moveTo != \"\" {\n\t\t\t\taction.MovePath = &moveTo\n\t\t\t}\n\t\t\tp.patch.Actions[path] = action\n\t\t\tcontinue\n\t\t}\n\n\t\tpath = p.readStr(\"*** Delete File: \", false)\n\t\tif path != \"\" {\n\t\t\tif _, exists := p.patch.Actions[path]; exists {\n\t\t\t\treturn fileError(\"Delete\", \"Duplicate Path\", path)\n\t\t\t}\n\t\t\tif _, exists := p.currentFiles[path]; !exists {\n\t\t\t\treturn fileError(\"Delete\", \"Missing File\", path)\n\t\t\t}\n\t\t\tp.patch.Actions[path] = PatchAction{Type: ActionDelete, Chunks: []Chunk{}}\n\t\t\tcontinue\n\t\t}\n\n\t\tpath = p.readStr(\"*** Add File: \", false)\n\t\tif path != \"\" {\n\t\t\tif _, exists := p.patch.Actions[path]; exists {\n\t\t\t\treturn fileError(\"Add\", \"Duplicate Path\", path)\n\t\t\t}\n\t\t\tif _, exists := p.currentFiles[path]; exists {\n\t\t\t\treturn fileError(\"Add\", \"File already exists\", path)\n\t\t\t}\n\t\t\taction, err := p.parseAddFile()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tp.patch.Actions[path] = action\n\t\t\tcontinue\n\t\t}\n\n\t\treturn NewDiffError(fmt.Sprintf(\"Unknown Line: %s\", p.lines[p.index]))\n\t}\n\n\tif !p.startsWith(\"*** End Patch\") {\n\t\treturn NewDiffError(\"Missing End Patch\")\n\t}\n\tp.index++\n\n\treturn nil\n}\n\nfunc (p *Parser) parseUpdateFile(text string) (PatchAction, error) {\n\taction := PatchAction{Type: ActionUpdate, Chunks: []Chunk{}}\n\tfileLines := strings.Split(text, \"\\n\")\n\tindex := 0\n\n\tendPrefixes := []string{\n\t\t\"*** End Patch\",\n\t\t\"*** Update File:\",\n\t\t\"*** Delete File:\",\n\t\t\"*** Add File:\",\n\t\t\"*** End of File\",\n\t}\n\n\tfor !p.isDone(endPrefixes) {\n\t\tdefStr := p.readStr(\"@@ \", false)\n\t\tsectionStr := \"\"\n\t\tif defStr == \"\" && p.index < len(p.lines) && p.lines[p.index] == \"@@\" {\n\t\t\tsectionStr = p.lines[p.index]\n\t\t\tp.index++\n\t\t}\n\t\tif defStr == \"\" && sectionStr == \"\" && index != 0 {\n\t\t\treturn action, NewDiffError(fmt.Sprintf(\"Invalid Line:\\n%s\", p.lines[p.index]))\n\t\t}\n\t\tif strings.TrimSpace(defStr) != \"\" {\n\t\t\tfound := false\n\t\t\tfor i := range fileLines[:index] {\n\t\t\t\tif fileLines[i] == defStr {\n\t\t\t\t\tfound = true\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif !found {\n\t\t\t\tfor i := index; i < len(fileLines); i++ {\n\t\t\t\t\tif fileLines[i] == defStr {\n\t\t\t\t\t\tindex = i + 1\n\t\t\t\t\t\tfound = true\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif !found {\n\t\t\t\tfor i := range fileLines[:index] {\n\t\t\t\t\tif strings.TrimSpace(fileLines[i]) == strings.TrimSpace(defStr) {\n\t\t\t\t\t\tfound = true\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif !found {\n\t\t\t\tfor i := index; i < len(fileLines); i++ {\n\t\t\t\t\tif strings.TrimSpace(fileLines[i]) == strings.TrimSpace(defStr) {\n\t\t\t\t\t\tindex = i + 1\n\t\t\t\t\t\tp.fuzz++\n\t\t\t\t\t\tfound = true\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tnextChunkContext, chunks, endPatchIndex, eof := peekNextSection(p.lines, p.index)\n\t\tnewIndex, fuzz := findContext(fileLines, nextChunkContext, index, eof)\n\t\tif newIndex == -1 {\n\t\t\tctxText := strings.Join(nextChunkContext, \"\\n\")\n\t\t\treturn action, contextError(index, ctxText, eof)\n\t\t}\n\t\tp.fuzz += fuzz\n\n\t\tfor _, ch := range chunks {\n\t\t\tch.OrigIndex += newIndex\n\t\t\taction.Chunks = append(action.Chunks, ch)\n\t\t}\n\t\tindex = newIndex + len(nextChunkContext)\n\t\tp.index = endPatchIndex\n\t}\n\treturn action, nil\n}\n\nfunc (p *Parser) parseAddFile() (PatchAction, error) {\n\tlines := make([]string, 0, 16) // Preallocate space for better performance\n\tendPrefixes := []string{\n\t\t\"*** End Patch\",\n\t\t\"*** Update File:\",\n\t\t\"*** Delete File:\",\n\t\t\"*** Add File:\",\n\t}\n\n\tfor !p.isDone(endPrefixes) {\n\t\ts := p.readStr(\"\", true)\n\t\tif !strings.HasPrefix(s, \"+\") {\n\t\t\treturn PatchAction{}, NewDiffError(fmt.Sprintf(\"Invalid Add File Line: %s\", s))\n\t\t}\n\t\tlines = append(lines, s[1:])\n\t}\n\n\tnewFile := strings.Join(lines, \"\\n\")\n\treturn PatchAction{\n\t\tType: ActionAdd,\n\t\tNewFile: &newFile,\n\t\tChunks: []Chunk{},\n\t}, nil\n}\n\n// Refactored to use a matcher function for each comparison type\nfunc findContextCore(lines []string, context []string, start int) (int, int) {\n\tif len(context) == 0 {\n\t\treturn start, 0\n\t}\n\n\t// Try exact match\n\tif idx, fuzz := tryFindMatch(lines, context, start, func(a, b string) bool {\n\t\treturn a == b\n\t}); idx >= 0 {\n\t\treturn idx, fuzz\n\t}\n\n\t// Try trimming right whitespace\n\tif idx, fuzz := tryFindMatch(lines, context, start, func(a, b string) bool {\n\t\treturn strings.TrimRight(a, \" \\t\") == strings.TrimRight(b, \" \\t\")\n\t}); idx >= 0 {\n\t\treturn idx, fuzz\n\t}\n\n\t// Try trimming all whitespace\n\tif idx, fuzz := tryFindMatch(lines, context, start, func(a, b string) bool {\n\t\treturn strings.TrimSpace(a) == strings.TrimSpace(b)\n\t}); idx >= 0 {\n\t\treturn idx, fuzz\n\t}\n\n\treturn -1, 0\n}\n\n// Helper function to DRY up the match logic\nfunc tryFindMatch(lines []string, context []string, start int,\n\tcompareFunc func(string, string) bool,\n) (int, int) {\n\tfor i := start; i < len(lines); i++ {\n\t\tif i+len(context) <= len(lines) {\n\t\t\tmatch := true\n\t\t\tfor j := range context {\n\t\t\t\tif !compareFunc(lines[i+j], context[j]) {\n\t\t\t\t\tmatch = false\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\tif match {\n\t\t\t\t// Return fuzz level: 0 for exact, 1 for trimRight, 100 for trimSpace\n\t\t\t\tvar fuzz int\n\t\t\t\tif compareFunc(\"a \", \"a\") && !compareFunc(\"a\", \"b\") {\n\t\t\t\t\tfuzz = 1\n\t\t\t\t} else if compareFunc(\"a \", \"a\") {\n\t\t\t\t\tfuzz = 100\n\t\t\t\t}\n\t\t\t\treturn i, fuzz\n\t\t\t}\n\t\t}\n\t}\n\treturn -1, 0\n}\n\nfunc findContext(lines []string, context []string, start int, eof bool) (int, int) {\n\tif eof {\n\t\tnewIndex, fuzz := findContextCore(lines, context, len(lines)-len(context))\n\t\tif newIndex != -1 {\n\t\t\treturn newIndex, fuzz\n\t\t}\n\t\tnewIndex, fuzz = findContextCore(lines, context, start)\n\t\treturn newIndex, fuzz + 10000\n\t}\n\treturn findContextCore(lines, context, start)\n}\n\nfunc peekNextSection(lines []string, initialIndex int) ([]string, []Chunk, int, bool) {\n\tindex := initialIndex\n\told := make([]string, 0, 32) // Preallocate for better performance\n\tdelLines := make([]string, 0, 8)\n\tinsLines := make([]string, 0, 8)\n\tchunks := make([]Chunk, 0, 4)\n\tmode := \"keep\"\n\n\t// End conditions for the section\n\tendSectionConditions := func(s string) bool {\n\t\treturn strings.HasPrefix(s, \"@@\") ||\n\t\t\tstrings.HasPrefix(s, \"*** End Patch\") ||\n\t\t\tstrings.HasPrefix(s, \"*** Update File:\") ||\n\t\t\tstrings.HasPrefix(s, \"*** Delete File:\") ||\n\t\t\tstrings.HasPrefix(s, \"*** Add File:\") ||\n\t\t\tstrings.HasPrefix(s, \"*** End of File\") ||\n\t\t\ts == \"***\" ||\n\t\t\tstrings.HasPrefix(s, \"***\")\n\t}\n\n\tfor index < len(lines) {\n\t\ts := lines[index]\n\t\tif endSectionConditions(s) {\n\t\t\tbreak\n\t\t}\n\t\tindex++\n\t\tlastMode := mode\n\t\tline := s\n\n\t\tif len(line) > 0 {\n\t\t\tswitch line[0] {\n\t\t\tcase '+':\n\t\t\t\tmode = \"add\"\n\t\t\tcase '-':\n\t\t\t\tmode = \"delete\"\n\t\t\tcase ' ':\n\t\t\t\tmode = \"keep\"\n\t\t\tdefault:\n\t\t\t\tmode = \"keep\"\n\t\t\t\tline = \" \" + line\n\t\t\t}\n\t\t} else {\n\t\t\tmode = \"keep\"\n\t\t\tline = \" \"\n\t\t}\n\n\t\tline = line[1:]\n\t\tif mode == \"keep\" && lastMode != mode {\n\t\t\tif len(insLines) > 0 || len(delLines) > 0 {\n\t\t\t\tchunks = append(chunks, Chunk{\n\t\t\t\t\tOrigIndex: len(old) - len(delLines),\n\t\t\t\t\tDelLines: delLines,\n\t\t\t\t\tInsLines: insLines,\n\t\t\t\t})\n\t\t\t}\n\t\t\tdelLines = make([]string, 0, 8)\n\t\t\tinsLines = make([]string, 0, 8)\n\t\t}\n\t\tswitch mode {\n\t\tcase \"delete\":\n\t\t\tdelLines = append(delLines, line)\n\t\t\told = append(old, line)\n\t\tcase \"add\":\n\t\t\tinsLines = append(insLines, line)\n\t\tdefault:\n\t\t\told = append(old, line)\n\t\t}\n\t}\n\n\tif len(insLines) > 0 || len(delLines) > 0 {\n\t\tchunks = append(chunks, Chunk{\n\t\t\tOrigIndex: len(old) - len(delLines),\n\t\t\tDelLines: delLines,\n\t\t\tInsLines: insLines,\n\t\t})\n\t}\n\n\tif index < len(lines) && lines[index] == \"*** End of File\" {\n\t\tindex++\n\t\treturn old, chunks, index, true\n\t}\n\treturn old, chunks, index, false\n}\n\nfunc TextToPatch(text string, orig map[string]string) (Patch, int, error) {\n\ttext = strings.TrimSpace(text)\n\tlines := strings.Split(text, \"\\n\")\n\tif len(lines) < 2 || !strings.HasPrefix(lines[0], \"*** Begin Patch\") || lines[len(lines)-1] != \"*** End Patch\" {\n\t\treturn Patch{}, 0, NewDiffError(\"Invalid patch text\")\n\t}\n\tparser := NewParser(orig, lines)\n\tparser.index = 1\n\tif err := parser.Parse(); err != nil {\n\t\treturn Patch{}, 0, err\n\t}\n\treturn parser.patch, parser.fuzz, nil\n}\n\nfunc IdentifyFilesNeeded(text string) []string {\n\ttext = strings.TrimSpace(text)\n\tlines := strings.Split(text, \"\\n\")\n\tresult := make(map[string]bool)\n\n\tfor _, line := range lines {\n\t\tif strings.HasPrefix(line, \"*** Update File: \") {\n\t\t\tresult[line[len(\"*** Update File: \"):]] = true\n\t\t}\n\t\tif strings.HasPrefix(line, \"*** Delete File: \") {\n\t\t\tresult[line[len(\"*** Delete File: \"):]] = true\n\t\t}\n\t}\n\n\tfiles := make([]string, 0, len(result))\n\tfor file := range result {\n\t\tfiles = append(files, file)\n\t}\n\treturn files\n}\n\nfunc IdentifyFilesAdded(text string) []string {\n\ttext = strings.TrimSpace(text)\n\tlines := strings.Split(text, \"\\n\")\n\tresult := make(map[string]bool)\n\n\tfor _, line := range lines {\n\t\tif strings.HasPrefix(line, \"*** Add File: \") {\n\t\t\tresult[line[len(\"*** Add File: \"):]] = true\n\t\t}\n\t}\n\n\tfiles := make([]string, 0, len(result))\n\tfor file := range result {\n\t\tfiles = append(files, file)\n\t}\n\treturn files\n}\n\nfunc getUpdatedFile(text string, action PatchAction, path string) (string, error) {\n\tif action.Type != ActionUpdate {\n\t\treturn \"\", errors.New(\"expected UPDATE action\")\n\t}\n\torigLines := strings.Split(text, \"\\n\")\n\tdestLines := make([]string, 0, len(origLines)) // Preallocate with capacity\n\torigIndex := 0\n\n\tfor _, chunk := range action.Chunks {\n\t\tif chunk.OrigIndex > len(origLines) {\n\t\t\treturn \"\", NewDiffError(fmt.Sprintf(\"%s: chunk.orig_index %d > len(lines) %d\", path, chunk.OrigIndex, len(origLines)))\n\t\t}\n\t\tif origIndex > chunk.OrigIndex {\n\t\t\treturn \"\", NewDiffError(fmt.Sprintf(\"%s: orig_index %d > chunk.orig_index %d\", path, origIndex, chunk.OrigIndex))\n\t\t}\n\t\tdestLines = append(destLines, origLines[origIndex:chunk.OrigIndex]...)\n\t\tdelta := chunk.OrigIndex - origIndex\n\t\torigIndex += delta\n\n\t\tif len(chunk.InsLines) > 0 {\n\t\t\tdestLines = append(destLines, chunk.InsLines...)\n\t\t}\n\t\torigIndex += len(chunk.DelLines)\n\t}\n\n\tdestLines = append(destLines, origLines[origIndex:]...)\n\treturn strings.Join(destLines, \"\\n\"), nil\n}\n\nfunc PatchToCommit(patch Patch, orig map[string]string) (Commit, error) {\n\tcommit := Commit{Changes: make(map[string]FileChange, len(patch.Actions))}\n\tfor pathKey, action := range patch.Actions {\n\t\tswitch action.Type {\n\t\tcase ActionDelete:\n\t\t\toldContent := orig[pathKey]\n\t\t\tcommit.Changes[pathKey] = FileChange{\n\t\t\t\tType: ActionDelete,\n\t\t\t\tOldContent: &oldContent,\n\t\t\t}\n\t\tcase ActionAdd:\n\t\t\tcommit.Changes[pathKey] = FileChange{\n\t\t\t\tType: ActionAdd,\n\t\t\t\tNewContent: action.NewFile,\n\t\t\t}\n\t\tcase ActionUpdate:\n\t\t\tnewContent, err := getUpdatedFile(orig[pathKey], action, pathKey)\n\t\t\tif err != nil {\n\t\t\t\treturn Commit{}, err\n\t\t\t}\n\t\t\toldContent := orig[pathKey]\n\t\t\tfileChange := FileChange{\n\t\t\t\tType: ActionUpdate,\n\t\t\t\tOldContent: &oldContent,\n\t\t\t\tNewContent: &newContent,\n\t\t\t}\n\t\t\tif action.MovePath != nil {\n\t\t\t\tfileChange.MovePath = action.MovePath\n\t\t\t}\n\t\t\tcommit.Changes[pathKey] = fileChange\n\t\t}\n\t}\n\treturn commit, nil\n}\n\nfunc AssembleChanges(orig map[string]string, updatedFiles map[string]string) Commit {\n\tcommit := Commit{Changes: make(map[string]FileChange, len(updatedFiles))}\n\tfor p, newContent := range updatedFiles {\n\t\toldContent, exists := orig[p]\n\t\tif exists && oldContent == newContent {\n\t\t\tcontinue\n\t\t}\n\n\t\tif exists && newContent != \"\" {\n\t\t\tcommit.Changes[p] = FileChange{\n\t\t\t\tType: ActionUpdate,\n\t\t\t\tOldContent: &oldContent,\n\t\t\t\tNewContent: &newContent,\n\t\t\t}\n\t\t} else if newContent != \"\" {\n\t\t\tcommit.Changes[p] = FileChange{\n\t\t\t\tType: ActionAdd,\n\t\t\t\tNewContent: &newContent,\n\t\t\t}\n\t\t} else if exists {\n\t\t\tcommit.Changes[p] = FileChange{\n\t\t\t\tType: ActionDelete,\n\t\t\t\tOldContent: &oldContent,\n\t\t\t}\n\t\t} else {\n\t\t\treturn commit // Changed from panic to simply return current commit\n\t\t}\n\t}\n\treturn commit\n}\n\nfunc LoadFiles(paths []string, openFn func(string) (string, error)) (map[string]string, error) {\n\torig := make(map[string]string, len(paths))\n\tfor _, p := range paths {\n\t\tcontent, err := openFn(p)\n\t\tif err != nil {\n\t\t\treturn nil, fileError(\"Open\", \"File not found\", p)\n\t\t}\n\t\torig[p] = content\n\t}\n\treturn orig, nil\n}\n\nfunc ApplyCommit(commit Commit, writeFn func(string, string) error, removeFn func(string) error) error {\n\tfor p, change := range commit.Changes {\n\t\tswitch change.Type {\n\t\tcase ActionDelete:\n\t\t\tif err := removeFn(p); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\tcase ActionAdd:\n\t\t\tif change.NewContent == nil {\n\t\t\t\treturn NewDiffError(fmt.Sprintf(\"Add action for %s has nil new_content\", p))\n\t\t\t}\n\t\t\tif err := writeFn(p, *change.NewContent); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\tcase ActionUpdate:\n\t\t\tif change.NewContent == nil {\n\t\t\t\treturn NewDiffError(fmt.Sprintf(\"Update action for %s has nil new_content\", p))\n\t\t\t}\n\t\t\tif change.MovePath != nil {\n\t\t\t\tif err := writeFn(*change.MovePath, *change.NewContent); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tif err := removeFn(p); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif err := writeFn(p, *change.NewContent); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc ProcessPatch(text string, openFn func(string) (string, error), writeFn func(string, string) error, removeFn func(string) error) (string, error) {\n\tif !strings.HasPrefix(text, \"*** Begin Patch\") {\n\t\treturn \"\", NewDiffError(\"Patch must start with *** Begin Patch\")\n\t}\n\tpaths := IdentifyFilesNeeded(text)\n\torig, err := LoadFiles(paths, openFn)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tpatch, fuzz, err := TextToPatch(text, orig)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif fuzz > 0 {\n\t\treturn \"\", NewDiffError(fmt.Sprintf(\"Patch contains fuzzy matches (fuzz level: %d)\", fuzz))\n\t}\n\n\tcommit, err := PatchToCommit(patch, orig)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif err := ApplyCommit(commit, writeFn, removeFn); err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn \"Patch applied successfully\", nil\n}\n\nfunc OpenFile(p string) (string, error) {\n\tdata, err := os.ReadFile(p)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn string(data), nil\n}\n\nfunc WriteFile(p string, content string) error {\n\tif filepath.IsAbs(p) {\n\t\treturn NewDiffError(\"We do not support absolute paths.\")\n\t}\n\n\tdir := filepath.Dir(p)\n\tif dir != \".\" {\n\t\tif err := os.MkdirAll(dir, 0o755); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn os.WriteFile(p, []byte(content), 0o644)\n}\n\nfunc RemoveFile(p string) error {\n\treturn os.Remove(p)\n}\n\nfunc ValidatePatch(patchText string, files map[string]string) (bool, string, error) {\n\tif !strings.HasPrefix(patchText, \"*** Begin Patch\") {\n\t\treturn false, \"Patch must start with *** Begin Patch\", nil\n\t}\n\n\tneededFiles := IdentifyFilesNeeded(patchText)\n\tfor _, filePath := range neededFiles {\n\t\tif _, exists := files[filePath]; !exists {\n\t\t\treturn false, fmt.Sprintf(\"File not found: %s\", filePath), nil\n\t\t}\n\t}\n\n\tpatch, fuzz, err := TextToPatch(patchText, files)\n\tif err != nil {\n\t\treturn false, err.Error(), nil\n\t}\n\n\tif fuzz > 0 {\n\t\treturn false, fmt.Sprintf(\"Patch contains fuzzy matches (fuzz level: %d)\", fuzz), nil\n\t}\n\n\t_, err = PatchToCommit(patch, files)\n\tif err != nil {\n\t\treturn false, err.Error(), nil\n\t}\n\n\treturn true, \"Patch is valid\", nil\n}\n"], ["/opencode/internal/lsp/protocol/uri.go", "// Copyright 2023 The Go Authors. All rights reserved.\n// Use of this source code is governed by a BSD-style\n// license that can be found in the LICENSE file.\n\npackage protocol\n\n// This file declares URI, DocumentUri, and its methods.\n//\n// For the LSP definition of these types, see\n// https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#uri\n\nimport (\n\t\"fmt\"\n\t\"net/url\"\n\t\"path/filepath\"\n\t\"strings\"\n\t\"unicode\"\n)\n\n// A DocumentUri is the URI of a client editor document.\n//\n// According to the LSP specification:\n//\n//\tCare should be taken to handle encoding in URIs. For\n//\texample, some clients (such as VS Code) may encode colons\n//\tin drive letters while others do not. The URIs below are\n//\tboth valid, but clients and servers should be consistent\n//\twith the form they use themselves to ensure the other party\n//\tdoesn’t interpret them as distinct URIs. Clients and\n//\tservers should not assume that each other are encoding the\n//\tsame way (for example a client encoding colons in drive\n//\tletters cannot assume server responses will have encoded\n//\tcolons). The same applies to casing of drive letters - one\n//\tparty should not assume the other party will return paths\n//\twith drive letters cased the same as it.\n//\n//\tfile:///c:/project/readme.md\n//\tfile:///C%3A/project/readme.md\n//\n// This is done during JSON unmarshalling;\n// see [DocumentUri.UnmarshalText] for details.\ntype DocumentUri string\n\n// A URI is an arbitrary URL (e.g. https), not necessarily a file.\ntype URI = string\n\n// UnmarshalText implements decoding of DocumentUri values.\n//\n// In particular, it implements a systematic correction of various odd\n// features of the definition of DocumentUri in the LSP spec that\n// appear to be workarounds for bugs in VS Code. For example, it may\n// URI-encode the URI itself, so that colon becomes %3A, and it may\n// send file://foo.go URIs that have two slashes (not three) and no\n// hostname.\n//\n// We use UnmarshalText, not UnmarshalJSON, because it is called even\n// for non-addressable values such as keys and values of map[K]V,\n// where there is no pointer of type *K or *V on which to call\n// UnmarshalJSON. (See Go issue #28189 for more detail.)\n//\n// Non-empty DocumentUris are valid \"file\"-scheme URIs.\n// The empty DocumentUri is valid.\nfunc (uri *DocumentUri) UnmarshalText(data []byte) (err error) {\n\t*uri, err = ParseDocumentUri(string(data))\n\treturn\n}\n\n// Path returns the file path for the given URI.\n//\n// DocumentUri(\"\").Path() returns the empty string.\n//\n// Path panics if called on a URI that is not a valid filename.\nfunc (uri DocumentUri) Path() string {\n\tfilename, err := filename(uri)\n\tif err != nil {\n\t\t// e.g. ParseRequestURI failed.\n\t\t//\n\t\t// This can only affect DocumentUris created by\n\t\t// direct string manipulation; all DocumentUris\n\t\t// received from the client pass through\n\t\t// ParseRequestURI, which ensures validity.\n\t\tpanic(err)\n\t}\n\treturn filepath.FromSlash(filename)\n}\n\n// Dir returns the URI for the directory containing the receiver.\nfunc (uri DocumentUri) Dir() DocumentUri {\n\t// This function could be more efficiently implemented by avoiding any call\n\t// to Path(), but at least consolidates URI manipulation.\n\treturn URIFromPath(uri.DirPath())\n}\n\n// DirPath returns the file path to the directory containing this URI, which\n// must be a file URI.\nfunc (uri DocumentUri) DirPath() string {\n\treturn filepath.Dir(uri.Path())\n}\n\nfunc filename(uri DocumentUri) (string, error) {\n\tif uri == \"\" {\n\t\treturn \"\", nil\n\t}\n\n\t// This conservative check for the common case\n\t// of a simple non-empty absolute POSIX filename\n\t// avoids the allocation of a net.URL.\n\tif strings.HasPrefix(string(uri), \"file:///\") {\n\t\trest := string(uri)[len(\"file://\"):] // leave one slash\n\t\tfor i := range len(rest) {\n\t\t\tb := rest[i]\n\t\t\t// Reject these cases:\n\t\t\tif b < ' ' || b == 0x7f || // control character\n\t\t\t\tb == '%' || b == '+' || // URI escape\n\t\t\t\tb == ':' || // Windows drive letter\n\t\t\t\tb == '@' || b == '&' || b == '?' { // authority or query\n\t\t\t\tgoto slow\n\t\t\t}\n\t\t}\n\t\treturn rest, nil\n\t}\nslow:\n\n\tu, err := url.ParseRequestURI(string(uri))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tif u.Scheme != fileScheme {\n\t\treturn \"\", fmt.Errorf(\"only file URIs are supported, got %q from %q\", u.Scheme, uri)\n\t}\n\t// If the URI is a Windows URI, we trim the leading \"/\" and uppercase\n\t// the drive letter, which will never be case sensitive.\n\tif isWindowsDriveURIPath(u.Path) {\n\t\tu.Path = strings.ToUpper(string(u.Path[1])) + u.Path[2:]\n\t}\n\n\treturn u.Path, nil\n}\n\n// ParseDocumentUri interprets a string as a DocumentUri, applying VS\n// Code workarounds; see [DocumentUri.UnmarshalText] for details.\nfunc ParseDocumentUri(s string) (DocumentUri, error) {\n\tif s == \"\" {\n\t\treturn \"\", nil\n\t}\n\n\tif !strings.HasPrefix(s, \"file://\") {\n\t\treturn \"\", fmt.Errorf(\"DocumentUri scheme is not 'file': %s\", s)\n\t}\n\n\t// VS Code sends URLs with only two slashes,\n\t// which are invalid. golang/go#39789.\n\tif !strings.HasPrefix(s, \"file:///\") {\n\t\ts = \"file:///\" + s[len(\"file://\"):]\n\t}\n\n\t// Even though the input is a URI, it may not be in canonical form. VS Code\n\t// in particular over-escapes :, @, etc. Unescape and re-encode to canonicalize.\n\tpath, err := url.PathUnescape(s[len(\"file://\"):])\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t// File URIs from Windows may have lowercase drive letters.\n\t// Since drive letters are guaranteed to be case insensitive,\n\t// we change them to uppercase to remain consistent.\n\t// For example, file:///c:/x/y/z becomes file:///C:/x/y/z.\n\tif isWindowsDriveURIPath(path) {\n\t\tpath = path[:1] + strings.ToUpper(string(path[1])) + path[2:]\n\t}\n\tu := url.URL{Scheme: fileScheme, Path: path}\n\treturn DocumentUri(u.String()), nil\n}\n\n// URIFromPath returns DocumentUri for the supplied file path.\n// Given \"\", it returns \"\".\nfunc URIFromPath(path string) DocumentUri {\n\tif path == \"\" {\n\t\treturn \"\"\n\t}\n\tif !isWindowsDrivePath(path) {\n\t\tif abs, err := filepath.Abs(path); err == nil {\n\t\t\tpath = abs\n\t\t}\n\t}\n\t// Check the file path again, in case it became absolute.\n\tif isWindowsDrivePath(path) {\n\t\tpath = \"/\" + strings.ToUpper(string(path[0])) + path[1:]\n\t}\n\tpath = filepath.ToSlash(path)\n\tu := url.URL{\n\t\tScheme: fileScheme,\n\t\tPath: path,\n\t}\n\treturn DocumentUri(u.String())\n}\n\nconst fileScheme = \"file\"\n\n// isWindowsDrivePath returns true if the file path is of the form used by\n// Windows. We check if the path begins with a drive letter, followed by a \":\".\n// For example: C:/x/y/z.\nfunc isWindowsDrivePath(path string) bool {\n\tif len(path) < 3 {\n\t\treturn false\n\t}\n\treturn unicode.IsLetter(rune(path[0])) && path[1] == ':'\n}\n\n// isWindowsDriveURIPath returns true if the file URI is of the format used by\n// Windows URIs. The url.Parse package does not specially handle Windows paths\n// (see golang/go#6027), so we check if the URI path has a drive prefix (e.g. \"/C:\").\nfunc isWindowsDriveURIPath(uri string) bool {\n\tif len(uri) < 4 {\n\t\treturn false\n\t}\n\treturn uri[0] == '/' && unicode.IsLetter(rune(uri[1])) && uri[2] == ':'\n}\n"], ["/opencode/internal/logging/writer.go", "package logging\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"fmt\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com/go-logfmt/logfmt\"\n\t\"github.com/opencode-ai/opencode/internal/pubsub\"\n)\n\nconst (\n\tpersistKeyArg = \"$_persist\"\n\tPersistTimeArg = \"$_persist_time\"\n)\n\ntype LogData struct {\n\tmessages []LogMessage\n\t*pubsub.Broker[LogMessage]\n\tlock sync.Mutex\n}\n\nfunc (l *LogData) Add(msg LogMessage) {\n\tl.lock.Lock()\n\tdefer l.lock.Unlock()\n\tl.messages = append(l.messages, msg)\n\tl.Publish(pubsub.CreatedEvent, msg)\n}\n\nfunc (l *LogData) List() []LogMessage {\n\tl.lock.Lock()\n\tdefer l.lock.Unlock()\n\treturn l.messages\n}\n\nvar defaultLogData = &LogData{\n\tmessages: make([]LogMessage, 0),\n\tBroker: pubsub.NewBroker[LogMessage](),\n}\n\ntype writer struct{}\n\nfunc (w *writer) Write(p []byte) (int, error) {\n\td := logfmt.NewDecoder(bytes.NewReader(p))\n\n\tfor d.ScanRecord() {\n\t\tmsg := LogMessage{\n\t\t\tID: fmt.Sprintf(\"%d\", time.Now().UnixNano()),\n\t\t\tTime: time.Now(),\n\t\t}\n\t\tfor d.ScanKeyval() {\n\t\t\tswitch string(d.Key()) {\n\t\t\tcase \"time\":\n\t\t\t\tparsed, err := time.Parse(time.RFC3339, string(d.Value()))\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn 0, fmt.Errorf(\"parsing time: %w\", err)\n\t\t\t\t}\n\t\t\t\tmsg.Time = parsed\n\t\t\tcase \"level\":\n\t\t\t\tmsg.Level = strings.ToLower(string(d.Value()))\n\t\t\tcase \"msg\":\n\t\t\t\tmsg.Message = string(d.Value())\n\t\t\tdefault:\n\t\t\t\tif string(d.Key()) == persistKeyArg {\n\t\t\t\t\tmsg.Persist = true\n\t\t\t\t} else if string(d.Key()) == PersistTimeArg {\n\t\t\t\t\tparsed, err := time.ParseDuration(string(d.Value()))\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tmsg.PersistTime = parsed\n\t\t\t\t} else {\n\t\t\t\t\tmsg.Attributes = append(msg.Attributes, Attr{\n\t\t\t\t\t\tKey: string(d.Key()),\n\t\t\t\t\t\tValue: string(d.Value()),\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tdefaultLogData.Add(msg)\n\t}\n\tif d.Err() != nil {\n\t\treturn 0, d.Err()\n\t}\n\treturn len(p), nil\n}\n\nfunc NewWriter() *writer {\n\tw := &writer{}\n\treturn w\n}\n\nfunc Subscribe(ctx context.Context) <-chan pubsub.Event[LogMessage] {\n\treturn defaultLogData.Subscribe(ctx)\n}\n\nfunc List() []LogMessage {\n\treturn defaultLogData.List()\n}\n"], ["/opencode/internal/history/file.go", "package history\n\nimport (\n\t\"context\"\n\t\"database/sql\"\n\t\"fmt\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/google/uuid\"\n\t\"github.com/opencode-ai/opencode/internal/db\"\n\t\"github.com/opencode-ai/opencode/internal/pubsub\"\n)\n\nconst (\n\tInitialVersion = \"initial\"\n)\n\ntype File struct {\n\tID string\n\tSessionID string\n\tPath string\n\tContent string\n\tVersion string\n\tCreatedAt int64\n\tUpdatedAt int64\n}\n\ntype Service interface {\n\tpubsub.Suscriber[File]\n\tCreate(ctx context.Context, sessionID, path, content string) (File, error)\n\tCreateVersion(ctx context.Context, sessionID, path, content string) (File, error)\n\tGet(ctx context.Context, id string) (File, error)\n\tGetByPathAndSession(ctx context.Context, path, sessionID string) (File, error)\n\tListBySession(ctx context.Context, sessionID string) ([]File, error)\n\tListLatestSessionFiles(ctx context.Context, sessionID string) ([]File, error)\n\tUpdate(ctx context.Context, file File) (File, error)\n\tDelete(ctx context.Context, id string) error\n\tDeleteSessionFiles(ctx context.Context, sessionID string) error\n}\n\ntype service struct {\n\t*pubsub.Broker[File]\n\tdb *sql.DB\n\tq *db.Queries\n}\n\nfunc NewService(q *db.Queries, db *sql.DB) Service {\n\treturn &service{\n\t\tBroker: pubsub.NewBroker[File](),\n\t\tq: q,\n\t\tdb: db,\n\t}\n}\n\nfunc (s *service) Create(ctx context.Context, sessionID, path, content string) (File, error) {\n\treturn s.createWithVersion(ctx, sessionID, path, content, InitialVersion)\n}\n\nfunc (s *service) CreateVersion(ctx context.Context, sessionID, path, content string) (File, error) {\n\t// Get the latest version for this path\n\tfiles, err := s.q.ListFilesByPath(ctx, path)\n\tif err != nil {\n\t\treturn File{}, err\n\t}\n\n\tif len(files) == 0 {\n\t\t// No previous versions, create initial\n\t\treturn s.Create(ctx, sessionID, path, content)\n\t}\n\n\t// Get the latest version\n\tlatestFile := files[0] // Files are ordered by created_at DESC\n\tlatestVersion := latestFile.Version\n\n\t// Generate the next version\n\tvar nextVersion string\n\tif latestVersion == InitialVersion {\n\t\tnextVersion = \"v1\"\n\t} else if strings.HasPrefix(latestVersion, \"v\") {\n\t\tversionNum, err := strconv.Atoi(latestVersion[1:])\n\t\tif err != nil {\n\t\t\t// If we can't parse the version, just use a timestamp-based version\n\t\t\tnextVersion = fmt.Sprintf(\"v%d\", latestFile.CreatedAt)\n\t\t} else {\n\t\t\tnextVersion = fmt.Sprintf(\"v%d\", versionNum+1)\n\t\t}\n\t} else {\n\t\t// If the version format is unexpected, use a timestamp-based version\n\t\tnextVersion = fmt.Sprintf(\"v%d\", latestFile.CreatedAt)\n\t}\n\n\treturn s.createWithVersion(ctx, sessionID, path, content, nextVersion)\n}\n\nfunc (s *service) createWithVersion(ctx context.Context, sessionID, path, content, version string) (File, error) {\n\t// Maximum number of retries for transaction conflicts\n\tconst maxRetries = 3\n\tvar file File\n\tvar err error\n\n\t// Retry loop for transaction conflicts\n\tfor attempt := range maxRetries {\n\t\t// Start a transaction\n\t\ttx, txErr := s.db.Begin()\n\t\tif txErr != nil {\n\t\t\treturn File{}, fmt.Errorf(\"failed to begin transaction: %w\", txErr)\n\t\t}\n\n\t\t// Create a new queries instance with the transaction\n\t\tqtx := s.q.WithTx(tx)\n\n\t\t// Try to create the file within the transaction\n\t\tdbFile, txErr := qtx.CreateFile(ctx, db.CreateFileParams{\n\t\t\tID: uuid.New().String(),\n\t\t\tSessionID: sessionID,\n\t\t\tPath: path,\n\t\t\tContent: content,\n\t\t\tVersion: version,\n\t\t})\n\t\tif txErr != nil {\n\t\t\t// Rollback the transaction\n\t\t\ttx.Rollback()\n\n\t\t\t// Check if this is a uniqueness constraint violation\n\t\t\tif strings.Contains(txErr.Error(), \"UNIQUE constraint failed\") {\n\t\t\t\tif attempt < maxRetries-1 {\n\t\t\t\t\t// If we have retries left, generate a new version and try again\n\t\t\t\t\tif strings.HasPrefix(version, \"v\") {\n\t\t\t\t\t\tversionNum, parseErr := strconv.Atoi(version[1:])\n\t\t\t\t\t\tif parseErr == nil {\n\t\t\t\t\t\t\tversion = fmt.Sprintf(\"v%d\", versionNum+1)\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t// If we can't parse the version, use a timestamp-based version\n\t\t\t\t\tversion = fmt.Sprintf(\"v%d\", time.Now().Unix())\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn File{}, txErr\n\t\t}\n\n\t\t// Commit the transaction\n\t\tif txErr = tx.Commit(); txErr != nil {\n\t\t\treturn File{}, fmt.Errorf(\"failed to commit transaction: %w\", txErr)\n\t\t}\n\n\t\tfile = s.fromDBItem(dbFile)\n\t\ts.Publish(pubsub.CreatedEvent, file)\n\t\treturn file, nil\n\t}\n\n\treturn file, err\n}\n\nfunc (s *service) Get(ctx context.Context, id string) (File, error) {\n\tdbFile, err := s.q.GetFile(ctx, id)\n\tif err != nil {\n\t\treturn File{}, err\n\t}\n\treturn s.fromDBItem(dbFile), nil\n}\n\nfunc (s *service) GetByPathAndSession(ctx context.Context, path, sessionID string) (File, error) {\n\tdbFile, err := s.q.GetFileByPathAndSession(ctx, db.GetFileByPathAndSessionParams{\n\t\tPath: path,\n\t\tSessionID: sessionID,\n\t})\n\tif err != nil {\n\t\treturn File{}, err\n\t}\n\treturn s.fromDBItem(dbFile), nil\n}\n\nfunc (s *service) ListBySession(ctx context.Context, sessionID string) ([]File, error) {\n\tdbFiles, err := s.q.ListFilesBySession(ctx, sessionID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfiles := make([]File, len(dbFiles))\n\tfor i, dbFile := range dbFiles {\n\t\tfiles[i] = s.fromDBItem(dbFile)\n\t}\n\treturn files, nil\n}\n\nfunc (s *service) ListLatestSessionFiles(ctx context.Context, sessionID string) ([]File, error) {\n\tdbFiles, err := s.q.ListLatestSessionFiles(ctx, sessionID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfiles := make([]File, len(dbFiles))\n\tfor i, dbFile := range dbFiles {\n\t\tfiles[i] = s.fromDBItem(dbFile)\n\t}\n\treturn files, nil\n}\n\nfunc (s *service) Update(ctx context.Context, file File) (File, error) {\n\tdbFile, err := s.q.UpdateFile(ctx, db.UpdateFileParams{\n\t\tID: file.ID,\n\t\tContent: file.Content,\n\t\tVersion: file.Version,\n\t})\n\tif err != nil {\n\t\treturn File{}, err\n\t}\n\tupdatedFile := s.fromDBItem(dbFile)\n\ts.Publish(pubsub.UpdatedEvent, updatedFile)\n\treturn updatedFile, nil\n}\n\nfunc (s *service) Delete(ctx context.Context, id string) error {\n\tfile, err := s.Get(ctx, id)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = s.q.DeleteFile(ctx, id)\n\tif err != nil {\n\t\treturn err\n\t}\n\ts.Publish(pubsub.DeletedEvent, file)\n\treturn nil\n}\n\nfunc (s *service) DeleteSessionFiles(ctx context.Context, sessionID string) error {\n\tfiles, err := s.ListBySession(ctx, sessionID)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor _, file := range files {\n\t\terr = s.Delete(ctx, file.ID)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (s *service) fromDBItem(item db.File) File {\n\treturn File{\n\t\tID: item.ID,\n\t\tSessionID: item.SessionID,\n\t\tPath: item.Path,\n\t\tContent: item.Content,\n\t\tVersion: item.Version,\n\t\tCreatedAt: item.CreatedAt,\n\t\tUpdatedAt: item.UpdatedAt,\n\t}\n}\n"], ["/opencode/internal/llm/prompt/prompt.go", "package prompt\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"strings\"\n\t\"sync\"\n\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/llm/models\"\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n)\n\nfunc GetAgentPrompt(agentName config.AgentName, provider models.ModelProvider) string {\n\tbasePrompt := \"\"\n\tswitch agentName {\n\tcase config.AgentCoder:\n\t\tbasePrompt = CoderPrompt(provider)\n\tcase config.AgentTitle:\n\t\tbasePrompt = TitlePrompt(provider)\n\tcase config.AgentTask:\n\t\tbasePrompt = TaskPrompt(provider)\n\tcase config.AgentSummarizer:\n\t\tbasePrompt = SummarizerPrompt(provider)\n\tdefault:\n\t\tbasePrompt = \"You are a helpful assistant\"\n\t}\n\n\tif agentName == config.AgentCoder || agentName == config.AgentTask {\n\t\t// Add context from project-specific instruction files if they exist\n\t\tcontextContent := getContextFromPaths()\n\t\tlogging.Debug(\"Context content\", \"Context\", contextContent)\n\t\tif contextContent != \"\" {\n\t\t\treturn fmt.Sprintf(\"%s\\n\\n# Project-Specific Context\\n Make sure to follow the instructions in the context below\\n%s\", basePrompt, contextContent)\n\t\t}\n\t}\n\treturn basePrompt\n}\n\nvar (\n\tonceContext sync.Once\n\tcontextContent string\n)\n\nfunc getContextFromPaths() string {\n\tonceContext.Do(func() {\n\t\tvar (\n\t\t\tcfg = config.Get()\n\t\t\tworkDir = cfg.WorkingDir\n\t\t\tcontextPaths = cfg.ContextPaths\n\t\t)\n\n\t\tcontextContent = processContextPaths(workDir, contextPaths)\n\t})\n\n\treturn contextContent\n}\n\nfunc processContextPaths(workDir string, paths []string) string {\n\tvar (\n\t\twg sync.WaitGroup\n\t\tresultCh = make(chan string)\n\t)\n\n\t// Track processed files to avoid duplicates\n\tprocessedFiles := make(map[string]bool)\n\tvar processedMutex sync.Mutex\n\n\tfor _, path := range paths {\n\t\twg.Add(1)\n\t\tgo func(p string) {\n\t\t\tdefer wg.Done()\n\n\t\t\tif strings.HasSuffix(p, \"/\") {\n\t\t\t\tfilepath.WalkDir(filepath.Join(workDir, p), func(path string, d os.DirEntry, err error) error {\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn err\n\t\t\t\t\t}\n\t\t\t\t\tif !d.IsDir() {\n\t\t\t\t\t\t// Check if we've already processed this file (case-insensitive)\n\t\t\t\t\t\tprocessedMutex.Lock()\n\t\t\t\t\t\tlowerPath := strings.ToLower(path)\n\t\t\t\t\t\tif !processedFiles[lowerPath] {\n\t\t\t\t\t\t\tprocessedFiles[lowerPath] = true\n\t\t\t\t\t\t\tprocessedMutex.Unlock()\n\n\t\t\t\t\t\t\tif result := processFile(path); result != \"\" {\n\t\t\t\t\t\t\t\tresultCh <- result\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tprocessedMutex.Unlock()\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\treturn nil\n\t\t\t\t})\n\t\t\t} else {\n\t\t\t\tfullPath := filepath.Join(workDir, p)\n\n\t\t\t\t// Check if we've already processed this file (case-insensitive)\n\t\t\t\tprocessedMutex.Lock()\n\t\t\t\tlowerPath := strings.ToLower(fullPath)\n\t\t\t\tif !processedFiles[lowerPath] {\n\t\t\t\t\tprocessedFiles[lowerPath] = true\n\t\t\t\t\tprocessedMutex.Unlock()\n\n\t\t\t\t\tresult := processFile(fullPath)\n\t\t\t\t\tif result != \"\" {\n\t\t\t\t\t\tresultCh <- result\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tprocessedMutex.Unlock()\n\t\t\t\t}\n\t\t\t}\n\t\t}(path)\n\t}\n\n\tgo func() {\n\t\twg.Wait()\n\t\tclose(resultCh)\n\t}()\n\n\tresults := make([]string, 0)\n\tfor result := range resultCh {\n\t\tresults = append(results, result)\n\t}\n\n\treturn strings.Join(results, \"\\n\")\n}\n\nfunc processFile(filePath string) string {\n\tcontent, err := os.ReadFile(filePath)\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\treturn \"# From:\" + filePath + \"\\n\" + string(content)\n}\n"], ["/opencode/internal/tui/theme/dracula.go", "package theme\n\nimport (\n\t\"github.com/charmbracelet/lipgloss\"\n)\n\n// DraculaTheme implements the Theme interface with Dracula colors.\n// It provides both dark and light variants, though Dracula is primarily a dark theme.\ntype DraculaTheme struct {\n\tBaseTheme\n}\n\n// NewDraculaTheme creates a new instance of the Dracula theme.\nfunc NewDraculaTheme() *DraculaTheme {\n\t// Dracula color palette\n\t// Official colors from https://draculatheme.com/\n\tdarkBackground := \"#282a36\"\n\tdarkCurrentLine := \"#44475a\"\n\tdarkSelection := \"#44475a\"\n\tdarkForeground := \"#f8f8f2\"\n\tdarkComment := \"#6272a4\"\n\tdarkCyan := \"#8be9fd\"\n\tdarkGreen := \"#50fa7b\"\n\tdarkOrange := \"#ffb86c\"\n\tdarkPink := \"#ff79c6\"\n\tdarkPurple := \"#bd93f9\"\n\tdarkRed := \"#ff5555\"\n\tdarkYellow := \"#f1fa8c\"\n\tdarkBorder := \"#44475a\"\n\n\t// Light mode approximation (Dracula is primarily a dark theme)\n\tlightBackground := \"#f8f8f2\"\n\tlightCurrentLine := \"#e6e6e6\"\n\tlightSelection := \"#d8d8d8\"\n\tlightForeground := \"#282a36\"\n\tlightComment := \"#6272a4\"\n\tlightCyan := \"#0097a7\"\n\tlightGreen := \"#388e3c\"\n\tlightOrange := \"#f57c00\"\n\tlightPink := \"#d81b60\"\n\tlightPurple := \"#7e57c2\"\n\tlightRed := \"#e53935\"\n\tlightYellow := \"#fbc02d\"\n\tlightBorder := \"#d8d8d8\"\n\n\ttheme := &DraculaTheme{}\n\n\t// Base colors\n\ttheme.PrimaryColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPurple,\n\t\tLight: lightPurple,\n\t}\n\ttheme.SecondaryColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPink,\n\t\tLight: lightPink,\n\t}\n\ttheme.AccentColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\n\t// Status colors\n\ttheme.ErrorColor = lipgloss.AdaptiveColor{\n\t\tDark: darkRed,\n\t\tLight: lightRed,\n\t}\n\ttheme.WarningColor = lipgloss.AdaptiveColor{\n\t\tDark: darkOrange,\n\t\tLight: lightOrange,\n\t}\n\ttheme.SuccessColor = lipgloss.AdaptiveColor{\n\t\tDark: darkGreen,\n\t\tLight: lightGreen,\n\t}\n\ttheme.InfoColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\n\t// Text colors\n\ttheme.TextColor = lipgloss.AdaptiveColor{\n\t\tDark: darkForeground,\n\t\tLight: lightForeground,\n\t}\n\ttheme.TextMutedColor = lipgloss.AdaptiveColor{\n\t\tDark: darkComment,\n\t\tLight: lightComment,\n\t}\n\ttheme.TextEmphasizedColor = lipgloss.AdaptiveColor{\n\t\tDark: darkYellow,\n\t\tLight: lightYellow,\n\t}\n\n\t// Background colors\n\ttheme.BackgroundColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBackground,\n\t\tLight: lightBackground,\n\t}\n\ttheme.BackgroundSecondaryColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCurrentLine,\n\t\tLight: lightCurrentLine,\n\t}\n\ttheme.BackgroundDarkerColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#21222c\", // Slightly darker than background\n\t\tLight: \"#ffffff\", // Slightly lighter than background\n\t}\n\n\t// Border colors\n\ttheme.BorderNormalColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBorder,\n\t\tLight: lightBorder,\n\t}\n\ttheme.BorderFocusedColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPurple,\n\t\tLight: lightPurple,\n\t}\n\ttheme.BorderDimColor = lipgloss.AdaptiveColor{\n\t\tDark: darkSelection,\n\t\tLight: lightSelection,\n\t}\n\n\t// Diff view colors\n\ttheme.DiffAddedColor = lipgloss.AdaptiveColor{\n\t\tDark: darkGreen,\n\t\tLight: lightGreen,\n\t}\n\ttheme.DiffRemovedColor = lipgloss.AdaptiveColor{\n\t\tDark: darkRed,\n\t\tLight: lightRed,\n\t}\n\ttheme.DiffContextColor = lipgloss.AdaptiveColor{\n\t\tDark: darkComment,\n\t\tLight: lightComment,\n\t}\n\ttheme.DiffHunkHeaderColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPurple,\n\t\tLight: lightPurple,\n\t}\n\ttheme.DiffHighlightAddedColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#50fa7b\",\n\t\tLight: \"#a5d6a7\",\n\t}\n\ttheme.DiffHighlightRemovedColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#ff5555\",\n\t\tLight: \"#ef9a9a\",\n\t}\n\ttheme.DiffAddedBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#2c3b2c\",\n\t\tLight: \"#e8f5e9\",\n\t}\n\ttheme.DiffRemovedBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#3b2c2c\",\n\t\tLight: \"#ffebee\",\n\t}\n\ttheme.DiffContextBgColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBackground,\n\t\tLight: lightBackground,\n\t}\n\ttheme.DiffLineNumberColor = lipgloss.AdaptiveColor{\n\t\tDark: darkComment,\n\t\tLight: lightComment,\n\t}\n\ttheme.DiffAddedLineNumberBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#253025\",\n\t\tLight: \"#c8e6c9\",\n\t}\n\ttheme.DiffRemovedLineNumberBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#302525\",\n\t\tLight: \"#ffcdd2\",\n\t}\n\n\t// Markdown colors\n\ttheme.MarkdownTextColor = lipgloss.AdaptiveColor{\n\t\tDark: darkForeground,\n\t\tLight: lightForeground,\n\t}\n\ttheme.MarkdownHeadingColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPink,\n\t\tLight: lightPink,\n\t}\n\ttheme.MarkdownLinkColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPurple,\n\t\tLight: lightPurple,\n\t}\n\ttheme.MarkdownLinkTextColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.MarkdownCodeColor = lipgloss.AdaptiveColor{\n\t\tDark: darkGreen,\n\t\tLight: lightGreen,\n\t}\n\ttheme.MarkdownBlockQuoteColor = lipgloss.AdaptiveColor{\n\t\tDark: darkYellow,\n\t\tLight: lightYellow,\n\t}\n\ttheme.MarkdownEmphColor = lipgloss.AdaptiveColor{\n\t\tDark: darkYellow,\n\t\tLight: lightYellow,\n\t}\n\ttheme.MarkdownStrongColor = lipgloss.AdaptiveColor{\n\t\tDark: darkOrange,\n\t\tLight: lightOrange,\n\t}\n\ttheme.MarkdownHorizontalRuleColor = lipgloss.AdaptiveColor{\n\t\tDark: darkComment,\n\t\tLight: lightComment,\n\t}\n\ttheme.MarkdownListItemColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPurple,\n\t\tLight: lightPurple,\n\t}\n\ttheme.MarkdownListEnumerationColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.MarkdownImageColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPurple,\n\t\tLight: lightPurple,\n\t}\n\ttheme.MarkdownImageTextColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.MarkdownCodeBlockColor = lipgloss.AdaptiveColor{\n\t\tDark: darkForeground,\n\t\tLight: lightForeground,\n\t}\n\n\t// Syntax highlighting colors\n\ttheme.SyntaxCommentColor = lipgloss.AdaptiveColor{\n\t\tDark: darkComment,\n\t\tLight: lightComment,\n\t}\n\ttheme.SyntaxKeywordColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPink,\n\t\tLight: lightPink,\n\t}\n\ttheme.SyntaxFunctionColor = lipgloss.AdaptiveColor{\n\t\tDark: darkGreen,\n\t\tLight: lightGreen,\n\t}\n\ttheme.SyntaxVariableColor = lipgloss.AdaptiveColor{\n\t\tDark: darkOrange,\n\t\tLight: lightOrange,\n\t}\n\ttheme.SyntaxStringColor = lipgloss.AdaptiveColor{\n\t\tDark: darkYellow,\n\t\tLight: lightYellow,\n\t}\n\ttheme.SyntaxNumberColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPurple,\n\t\tLight: lightPurple,\n\t}\n\ttheme.SyntaxTypeColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.SyntaxOperatorColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPink,\n\t\tLight: lightPink,\n\t}\n\ttheme.SyntaxPunctuationColor = lipgloss.AdaptiveColor{\n\t\tDark: darkForeground,\n\t\tLight: lightForeground,\n\t}\n\n\treturn theme\n}\n\nfunc init() {\n\t// Register the Dracula theme with the theme manager\n\tRegisterTheme(\"dracula\", NewDraculaTheme())\n}"], ["/opencode/internal/tui/theme/opencode.go", "package theme\n\nimport (\n\t\"github.com/charmbracelet/lipgloss\"\n)\n\n// OpenCodeTheme implements the Theme interface with OpenCode brand colors.\n// It provides both dark and light variants.\ntype OpenCodeTheme struct {\n\tBaseTheme\n}\n\n// NewOpenCodeTheme creates a new instance of the OpenCode theme.\nfunc NewOpenCodeTheme() *OpenCodeTheme {\n\t// OpenCode color palette\n\t// Dark mode colors\n\tdarkBackground := \"#212121\"\n\tdarkCurrentLine := \"#252525\"\n\tdarkSelection := \"#303030\"\n\tdarkForeground := \"#e0e0e0\"\n\tdarkComment := \"#6a6a6a\"\n\tdarkPrimary := \"#fab283\" // Primary orange/gold\n\tdarkSecondary := \"#5c9cf5\" // Secondary blue\n\tdarkAccent := \"#9d7cd8\" // Accent purple\n\tdarkRed := \"#e06c75\" // Error red\n\tdarkOrange := \"#f5a742\" // Warning orange\n\tdarkGreen := \"#7fd88f\" // Success green\n\tdarkCyan := \"#56b6c2\" // Info cyan\n\tdarkYellow := \"#e5c07b\" // Emphasized text\n\tdarkBorder := \"#4b4c5c\" // Border color\n\n\t// Light mode colors\n\tlightBackground := \"#f8f8f8\"\n\tlightCurrentLine := \"#f0f0f0\"\n\tlightSelection := \"#e5e5e6\"\n\tlightForeground := \"#2a2a2a\"\n\tlightComment := \"#8a8a8a\"\n\tlightPrimary := \"#3b7dd8\" // Primary blue\n\tlightSecondary := \"#7b5bb6\" // Secondary purple\n\tlightAccent := \"#d68c27\" // Accent orange/gold\n\tlightRed := \"#d1383d\" // Error red\n\tlightOrange := \"#d68c27\" // Warning orange\n\tlightGreen := \"#3d9a57\" // Success green\n\tlightCyan := \"#318795\" // Info cyan\n\tlightYellow := \"#b0851f\" // Emphasized text\n\tlightBorder := \"#d3d3d3\" // Border color\n\n\ttheme := &OpenCodeTheme{}\n\n\t// Base colors\n\ttheme.PrimaryColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPrimary,\n\t\tLight: lightPrimary,\n\t}\n\ttheme.SecondaryColor = lipgloss.AdaptiveColor{\n\t\tDark: darkSecondary,\n\t\tLight: lightSecondary,\n\t}\n\ttheme.AccentColor = lipgloss.AdaptiveColor{\n\t\tDark: darkAccent,\n\t\tLight: lightAccent,\n\t}\n\n\t// Status colors\n\ttheme.ErrorColor = lipgloss.AdaptiveColor{\n\t\tDark: darkRed,\n\t\tLight: lightRed,\n\t}\n\ttheme.WarningColor = lipgloss.AdaptiveColor{\n\t\tDark: darkOrange,\n\t\tLight: lightOrange,\n\t}\n\ttheme.SuccessColor = lipgloss.AdaptiveColor{\n\t\tDark: darkGreen,\n\t\tLight: lightGreen,\n\t}\n\ttheme.InfoColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\n\t// Text colors\n\ttheme.TextColor = lipgloss.AdaptiveColor{\n\t\tDark: darkForeground,\n\t\tLight: lightForeground,\n\t}\n\ttheme.TextMutedColor = lipgloss.AdaptiveColor{\n\t\tDark: darkComment,\n\t\tLight: lightComment,\n\t}\n\ttheme.TextEmphasizedColor = lipgloss.AdaptiveColor{\n\t\tDark: darkYellow,\n\t\tLight: lightYellow,\n\t}\n\n\t// Background colors\n\ttheme.BackgroundColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBackground,\n\t\tLight: lightBackground,\n\t}\n\ttheme.BackgroundSecondaryColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCurrentLine,\n\t\tLight: lightCurrentLine,\n\t}\n\ttheme.BackgroundDarkerColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#121212\", // Slightly darker than background\n\t\tLight: \"#ffffff\", // Slightly lighter than background\n\t}\n\n\t// Border colors\n\ttheme.BorderNormalColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBorder,\n\t\tLight: lightBorder,\n\t}\n\ttheme.BorderFocusedColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPrimary,\n\t\tLight: lightPrimary,\n\t}\n\ttheme.BorderDimColor = lipgloss.AdaptiveColor{\n\t\tDark: darkSelection,\n\t\tLight: lightSelection,\n\t}\n\n\t// Diff view colors\n\ttheme.DiffAddedColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#478247\",\n\t\tLight: \"#2E7D32\",\n\t}\n\ttheme.DiffRemovedColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#7C4444\",\n\t\tLight: \"#C62828\",\n\t}\n\ttheme.DiffContextColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#a0a0a0\",\n\t\tLight: \"#757575\",\n\t}\n\ttheme.DiffHunkHeaderColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#a0a0a0\",\n\t\tLight: \"#757575\",\n\t}\n\ttheme.DiffHighlightAddedColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#DAFADA\",\n\t\tLight: \"#A5D6A7\",\n\t}\n\ttheme.DiffHighlightRemovedColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#FADADD\",\n\t\tLight: \"#EF9A9A\",\n\t}\n\ttheme.DiffAddedBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#303A30\",\n\t\tLight: \"#E8F5E9\",\n\t}\n\ttheme.DiffRemovedBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#3A3030\",\n\t\tLight: \"#FFEBEE\",\n\t}\n\ttheme.DiffContextBgColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBackground,\n\t\tLight: lightBackground,\n\t}\n\ttheme.DiffLineNumberColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#888888\",\n\t\tLight: \"#9E9E9E\",\n\t}\n\ttheme.DiffAddedLineNumberBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#293229\",\n\t\tLight: \"#C8E6C9\",\n\t}\n\ttheme.DiffRemovedLineNumberBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#332929\",\n\t\tLight: \"#FFCDD2\",\n\t}\n\n\t// Markdown colors\n\ttheme.MarkdownTextColor = lipgloss.AdaptiveColor{\n\t\tDark: darkForeground,\n\t\tLight: lightForeground,\n\t}\n\ttheme.MarkdownHeadingColor = lipgloss.AdaptiveColor{\n\t\tDark: darkSecondary,\n\t\tLight: lightSecondary,\n\t}\n\ttheme.MarkdownLinkColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPrimary,\n\t\tLight: lightPrimary,\n\t}\n\ttheme.MarkdownLinkTextColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.MarkdownCodeColor = lipgloss.AdaptiveColor{\n\t\tDark: darkGreen,\n\t\tLight: lightGreen,\n\t}\n\ttheme.MarkdownBlockQuoteColor = lipgloss.AdaptiveColor{\n\t\tDark: darkYellow,\n\t\tLight: lightYellow,\n\t}\n\ttheme.MarkdownEmphColor = lipgloss.AdaptiveColor{\n\t\tDark: darkYellow,\n\t\tLight: lightYellow,\n\t}\n\ttheme.MarkdownStrongColor = lipgloss.AdaptiveColor{\n\t\tDark: darkAccent,\n\t\tLight: lightAccent,\n\t}\n\ttheme.MarkdownHorizontalRuleColor = lipgloss.AdaptiveColor{\n\t\tDark: darkComment,\n\t\tLight: lightComment,\n\t}\n\ttheme.MarkdownListItemColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPrimary,\n\t\tLight: lightPrimary,\n\t}\n\ttheme.MarkdownListEnumerationColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.MarkdownImageColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPrimary,\n\t\tLight: lightPrimary,\n\t}\n\ttheme.MarkdownImageTextColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.MarkdownCodeBlockColor = lipgloss.AdaptiveColor{\n\t\tDark: darkForeground,\n\t\tLight: lightForeground,\n\t}\n\n\t// Syntax highlighting colors\n\ttheme.SyntaxCommentColor = lipgloss.AdaptiveColor{\n\t\tDark: darkComment,\n\t\tLight: lightComment,\n\t}\n\ttheme.SyntaxKeywordColor = lipgloss.AdaptiveColor{\n\t\tDark: darkSecondary,\n\t\tLight: lightSecondary,\n\t}\n\ttheme.SyntaxFunctionColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPrimary,\n\t\tLight: lightPrimary,\n\t}\n\ttheme.SyntaxVariableColor = lipgloss.AdaptiveColor{\n\t\tDark: darkRed,\n\t\tLight: lightRed,\n\t}\n\ttheme.SyntaxStringColor = lipgloss.AdaptiveColor{\n\t\tDark: darkGreen,\n\t\tLight: lightGreen,\n\t}\n\ttheme.SyntaxNumberColor = lipgloss.AdaptiveColor{\n\t\tDark: darkAccent,\n\t\tLight: lightAccent,\n\t}\n\ttheme.SyntaxTypeColor = lipgloss.AdaptiveColor{\n\t\tDark: darkYellow,\n\t\tLight: lightYellow,\n\t}\n\ttheme.SyntaxOperatorColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.SyntaxPunctuationColor = lipgloss.AdaptiveColor{\n\t\tDark: darkForeground,\n\t\tLight: lightForeground,\n\t}\n\n\treturn theme\n}\n\nfunc init() {\n\t// Register the OpenCode theme with the theme manager\n\tRegisterTheme(\"opencode\", NewOpenCodeTheme())\n}\n\n"], ["/opencode/internal/tui/theme/monokai.go", "package theme\n\nimport (\n\t\"github.com/charmbracelet/lipgloss\"\n)\n\n// MonokaiProTheme implements the Theme interface with Monokai Pro colors.\n// It provides both dark and light variants.\ntype MonokaiProTheme struct {\n\tBaseTheme\n}\n\n// NewMonokaiProTheme creates a new instance of the Monokai Pro theme.\nfunc NewMonokaiProTheme() *MonokaiProTheme {\n\t// Monokai Pro color palette (dark mode)\n\tdarkBackground := \"#2d2a2e\"\n\tdarkCurrentLine := \"#403e41\"\n\tdarkSelection := \"#5b595c\"\n\tdarkForeground := \"#fcfcfa\"\n\tdarkComment := \"#727072\"\n\tdarkRed := \"#ff6188\"\n\tdarkOrange := \"#fc9867\"\n\tdarkYellow := \"#ffd866\"\n\tdarkGreen := \"#a9dc76\"\n\tdarkCyan := \"#78dce8\"\n\tdarkBlue := \"#ab9df2\"\n\tdarkPurple := \"#ab9df2\"\n\tdarkBorder := \"#403e41\"\n\n\t// Light mode colors (adapted from dark)\n\tlightBackground := \"#fafafa\"\n\tlightCurrentLine := \"#f0f0f0\"\n\tlightSelection := \"#e5e5e6\"\n\tlightForeground := \"#2d2a2e\"\n\tlightComment := \"#939293\"\n\tlightRed := \"#f92672\"\n\tlightOrange := \"#fd971f\"\n\tlightYellow := \"#e6db74\"\n\tlightGreen := \"#9bca65\"\n\tlightCyan := \"#66d9ef\"\n\tlightBlue := \"#7e75db\"\n\tlightPurple := \"#ae81ff\"\n\tlightBorder := \"#d3d3d3\"\n\n\ttheme := &MonokaiProTheme{}\n\n\t// Base colors\n\ttheme.PrimaryColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.SecondaryColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPurple,\n\t\tLight: lightPurple,\n\t}\n\ttheme.AccentColor = lipgloss.AdaptiveColor{\n\t\tDark: darkOrange,\n\t\tLight: lightOrange,\n\t}\n\n\t// Status colors\n\ttheme.ErrorColor = lipgloss.AdaptiveColor{\n\t\tDark: darkRed,\n\t\tLight: lightRed,\n\t}\n\ttheme.WarningColor = lipgloss.AdaptiveColor{\n\t\tDark: darkOrange,\n\t\tLight: lightOrange,\n\t}\n\ttheme.SuccessColor = lipgloss.AdaptiveColor{\n\t\tDark: darkGreen,\n\t\tLight: lightGreen,\n\t}\n\ttheme.InfoColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBlue,\n\t\tLight: lightBlue,\n\t}\n\n\t// Text colors\n\ttheme.TextColor = lipgloss.AdaptiveColor{\n\t\tDark: darkForeground,\n\t\tLight: lightForeground,\n\t}\n\ttheme.TextMutedColor = lipgloss.AdaptiveColor{\n\t\tDark: darkComment,\n\t\tLight: lightComment,\n\t}\n\ttheme.TextEmphasizedColor = lipgloss.AdaptiveColor{\n\t\tDark: darkYellow,\n\t\tLight: lightYellow,\n\t}\n\n\t// Background colors\n\ttheme.BackgroundColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBackground,\n\t\tLight: lightBackground,\n\t}\n\ttheme.BackgroundSecondaryColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCurrentLine,\n\t\tLight: lightCurrentLine,\n\t}\n\ttheme.BackgroundDarkerColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#221f22\", // Slightly darker than background\n\t\tLight: \"#ffffff\", // Slightly lighter than background\n\t}\n\n\t// Border colors\n\ttheme.BorderNormalColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBorder,\n\t\tLight: lightBorder,\n\t}\n\ttheme.BorderFocusedColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.BorderDimColor = lipgloss.AdaptiveColor{\n\t\tDark: darkSelection,\n\t\tLight: lightSelection,\n\t}\n\n\t// Diff view colors\n\ttheme.DiffAddedColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#a9dc76\",\n\t\tLight: \"#9bca65\",\n\t}\n\ttheme.DiffRemovedColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#ff6188\",\n\t\tLight: \"#f92672\",\n\t}\n\ttheme.DiffContextColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#a0a0a0\",\n\t\tLight: \"#757575\",\n\t}\n\ttheme.DiffHunkHeaderColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#a0a0a0\",\n\t\tLight: \"#757575\",\n\t}\n\ttheme.DiffHighlightAddedColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#c2e7a9\",\n\t\tLight: \"#c5e0b4\",\n\t}\n\ttheme.DiffHighlightRemovedColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#ff8ca6\",\n\t\tLight: \"#ffb3c8\",\n\t}\n\ttheme.DiffAddedBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#3a4a35\",\n\t\tLight: \"#e8f5e9\",\n\t}\n\ttheme.DiffRemovedBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#4a3439\",\n\t\tLight: \"#ffebee\",\n\t}\n\ttheme.DiffContextBgColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBackground,\n\t\tLight: lightBackground,\n\t}\n\ttheme.DiffLineNumberColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#888888\",\n\t\tLight: \"#9e9e9e\",\n\t}\n\ttheme.DiffAddedLineNumberBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#2d3a28\",\n\t\tLight: \"#c8e6c9\",\n\t}\n\ttheme.DiffRemovedLineNumberBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#3d2a2e\",\n\t\tLight: \"#ffcdd2\",\n\t}\n\n\t// Markdown colors\n\ttheme.MarkdownTextColor = lipgloss.AdaptiveColor{\n\t\tDark: darkForeground,\n\t\tLight: lightForeground,\n\t}\n\ttheme.MarkdownHeadingColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPurple,\n\t\tLight: lightPurple,\n\t}\n\ttheme.MarkdownLinkColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.MarkdownLinkTextColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBlue,\n\t\tLight: lightBlue,\n\t}\n\ttheme.MarkdownCodeColor = lipgloss.AdaptiveColor{\n\t\tDark: darkGreen,\n\t\tLight: lightGreen,\n\t}\n\ttheme.MarkdownBlockQuoteColor = lipgloss.AdaptiveColor{\n\t\tDark: darkYellow,\n\t\tLight: lightYellow,\n\t}\n\ttheme.MarkdownEmphColor = lipgloss.AdaptiveColor{\n\t\tDark: darkYellow,\n\t\tLight: lightYellow,\n\t}\n\ttheme.MarkdownStrongColor = lipgloss.AdaptiveColor{\n\t\tDark: darkOrange,\n\t\tLight: lightOrange,\n\t}\n\ttheme.MarkdownHorizontalRuleColor = lipgloss.AdaptiveColor{\n\t\tDark: darkComment,\n\t\tLight: lightComment,\n\t}\n\ttheme.MarkdownListItemColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.MarkdownListEnumerationColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBlue,\n\t\tLight: lightBlue,\n\t}\n\ttheme.MarkdownImageColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.MarkdownImageTextColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBlue,\n\t\tLight: lightBlue,\n\t}\n\ttheme.MarkdownCodeBlockColor = lipgloss.AdaptiveColor{\n\t\tDark: darkForeground,\n\t\tLight: lightForeground,\n\t}\n\n\t// Syntax highlighting colors\n\ttheme.SyntaxCommentColor = lipgloss.AdaptiveColor{\n\t\tDark: darkComment,\n\t\tLight: lightComment,\n\t}\n\ttheme.SyntaxKeywordColor = lipgloss.AdaptiveColor{\n\t\tDark: darkRed,\n\t\tLight: lightRed,\n\t}\n\ttheme.SyntaxFunctionColor = lipgloss.AdaptiveColor{\n\t\tDark: darkGreen,\n\t\tLight: lightGreen,\n\t}\n\ttheme.SyntaxVariableColor = lipgloss.AdaptiveColor{\n\t\tDark: darkForeground,\n\t\tLight: lightForeground,\n\t}\n\ttheme.SyntaxStringColor = lipgloss.AdaptiveColor{\n\t\tDark: darkYellow,\n\t\tLight: lightYellow,\n\t}\n\ttheme.SyntaxNumberColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPurple,\n\t\tLight: lightPurple,\n\t}\n\ttheme.SyntaxTypeColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBlue,\n\t\tLight: lightBlue,\n\t}\n\ttheme.SyntaxOperatorColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.SyntaxPunctuationColor = lipgloss.AdaptiveColor{\n\t\tDark: darkForeground,\n\t\tLight: lightForeground,\n\t}\n\n\treturn theme\n}\n\nfunc init() {\n\t// Register the Monokai Pro theme with the theme manager\n\tRegisterTheme(\"monokai\", NewMonokaiProTheme())\n}"], ["/opencode/internal/message/message.go", "package message\n\nimport (\n\t\"context\"\n\t\"database/sql\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com/google/uuid\"\n\t\"github.com/opencode-ai/opencode/internal/db\"\n\t\"github.com/opencode-ai/opencode/internal/llm/models\"\n\t\"github.com/opencode-ai/opencode/internal/pubsub\"\n)\n\ntype CreateMessageParams struct {\n\tRole MessageRole\n\tParts []ContentPart\n\tModel models.ModelID\n}\n\ntype Service interface {\n\tpubsub.Suscriber[Message]\n\tCreate(ctx context.Context, sessionID string, params CreateMessageParams) (Message, error)\n\tUpdate(ctx context.Context, message Message) error\n\tGet(ctx context.Context, id string) (Message, error)\n\tList(ctx context.Context, sessionID string) ([]Message, error)\n\tDelete(ctx context.Context, id string) error\n\tDeleteSessionMessages(ctx context.Context, sessionID string) error\n}\n\ntype service struct {\n\t*pubsub.Broker[Message]\n\tq db.Querier\n}\n\nfunc NewService(q db.Querier) Service {\n\treturn &service{\n\t\tBroker: pubsub.NewBroker[Message](),\n\t\tq: q,\n\t}\n}\n\nfunc (s *service) Delete(ctx context.Context, id string) error {\n\tmessage, err := s.Get(ctx, id)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = s.q.DeleteMessage(ctx, message.ID)\n\tif err != nil {\n\t\treturn err\n\t}\n\ts.Publish(pubsub.DeletedEvent, message)\n\treturn nil\n}\n\nfunc (s *service) Create(ctx context.Context, sessionID string, params CreateMessageParams) (Message, error) {\n\tif params.Role != Assistant {\n\t\tparams.Parts = append(params.Parts, Finish{\n\t\t\tReason: \"stop\",\n\t\t})\n\t}\n\tpartsJSON, err := marshallParts(params.Parts)\n\tif err != nil {\n\t\treturn Message{}, err\n\t}\n\tdbMessage, err := s.q.CreateMessage(ctx, db.CreateMessageParams{\n\t\tID: uuid.New().String(),\n\t\tSessionID: sessionID,\n\t\tRole: string(params.Role),\n\t\tParts: string(partsJSON),\n\t\tModel: sql.NullString{String: string(params.Model), Valid: true},\n\t})\n\tif err != nil {\n\t\treturn Message{}, err\n\t}\n\tmessage, err := s.fromDBItem(dbMessage)\n\tif err != nil {\n\t\treturn Message{}, err\n\t}\n\ts.Publish(pubsub.CreatedEvent, message)\n\treturn message, nil\n}\n\nfunc (s *service) DeleteSessionMessages(ctx context.Context, sessionID string) error {\n\tmessages, err := s.List(ctx, sessionID)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor _, message := range messages {\n\t\tif message.SessionID == sessionID {\n\t\t\terr = s.Delete(ctx, message.ID)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (s *service) Update(ctx context.Context, message Message) error {\n\tparts, err := marshallParts(message.Parts)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfinishedAt := sql.NullInt64{}\n\tif f := message.FinishPart(); f != nil {\n\t\tfinishedAt.Int64 = f.Time\n\t\tfinishedAt.Valid = true\n\t}\n\terr = s.q.UpdateMessage(ctx, db.UpdateMessageParams{\n\t\tID: message.ID,\n\t\tParts: string(parts),\n\t\tFinishedAt: finishedAt,\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\tmessage.UpdatedAt = time.Now().Unix()\n\ts.Publish(pubsub.UpdatedEvent, message)\n\treturn nil\n}\n\nfunc (s *service) Get(ctx context.Context, id string) (Message, error) {\n\tdbMessage, err := s.q.GetMessage(ctx, id)\n\tif err != nil {\n\t\treturn Message{}, err\n\t}\n\treturn s.fromDBItem(dbMessage)\n}\n\nfunc (s *service) List(ctx context.Context, sessionID string) ([]Message, error) {\n\tdbMessages, err := s.q.ListMessagesBySession(ctx, sessionID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tmessages := make([]Message, len(dbMessages))\n\tfor i, dbMessage := range dbMessages {\n\t\tmessages[i], err = s.fromDBItem(dbMessage)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn messages, nil\n}\n\nfunc (s *service) fromDBItem(item db.Message) (Message, error) {\n\tparts, err := unmarshallParts([]byte(item.Parts))\n\tif err != nil {\n\t\treturn Message{}, err\n\t}\n\treturn Message{\n\t\tID: item.ID,\n\t\tSessionID: item.SessionID,\n\t\tRole: MessageRole(item.Role),\n\t\tParts: parts,\n\t\tModel: models.ModelID(item.Model.String),\n\t\tCreatedAt: item.CreatedAt,\n\t\tUpdatedAt: item.UpdatedAt,\n\t}, nil\n}\n\ntype partType string\n\nconst (\n\treasoningType partType = \"reasoning\"\n\ttextType partType = \"text\"\n\timageURLType partType = \"image_url\"\n\tbinaryType partType = \"binary\"\n\ttoolCallType partType = \"tool_call\"\n\ttoolResultType partType = \"tool_result\"\n\tfinishType partType = \"finish\"\n)\n\ntype partWrapper struct {\n\tType partType `json:\"type\"`\n\tData ContentPart `json:\"data\"`\n}\n\nfunc marshallParts(parts []ContentPart) ([]byte, error) {\n\twrappedParts := make([]partWrapper, len(parts))\n\n\tfor i, part := range parts {\n\t\tvar typ partType\n\n\t\tswitch part.(type) {\n\t\tcase ReasoningContent:\n\t\t\ttyp = reasoningType\n\t\tcase TextContent:\n\t\t\ttyp = textType\n\t\tcase ImageURLContent:\n\t\t\ttyp = imageURLType\n\t\tcase BinaryContent:\n\t\t\ttyp = binaryType\n\t\tcase ToolCall:\n\t\t\ttyp = toolCallType\n\t\tcase ToolResult:\n\t\t\ttyp = toolResultType\n\t\tcase Finish:\n\t\t\ttyp = finishType\n\t\tdefault:\n\t\t\treturn nil, fmt.Errorf(\"unknown part type: %T\", part)\n\t\t}\n\n\t\twrappedParts[i] = partWrapper{\n\t\t\tType: typ,\n\t\t\tData: part,\n\t\t}\n\t}\n\treturn json.Marshal(wrappedParts)\n}\n\nfunc unmarshallParts(data []byte) ([]ContentPart, error) {\n\ttemp := []json.RawMessage{}\n\n\tif err := json.Unmarshal(data, &temp); err != nil {\n\t\treturn nil, err\n\t}\n\n\tparts := make([]ContentPart, 0)\n\n\tfor _, rawPart := range temp {\n\t\tvar wrapper struct {\n\t\t\tType partType `json:\"type\"`\n\t\t\tData json.RawMessage `json:\"data\"`\n\t\t}\n\n\t\tif err := json.Unmarshal(rawPart, &wrapper); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tswitch wrapper.Type {\n\t\tcase reasoningType:\n\t\t\tpart := ReasoningContent{}\n\t\t\tif err := json.Unmarshal(wrapper.Data, &part); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tparts = append(parts, part)\n\t\tcase textType:\n\t\t\tpart := TextContent{}\n\t\t\tif err := json.Unmarshal(wrapper.Data, &part); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tparts = append(parts, part)\n\t\tcase imageURLType:\n\t\t\tpart := ImageURLContent{}\n\t\t\tif err := json.Unmarshal(wrapper.Data, &part); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\tcase binaryType:\n\t\t\tpart := BinaryContent{}\n\t\t\tif err := json.Unmarshal(wrapper.Data, &part); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tparts = append(parts, part)\n\t\tcase toolCallType:\n\t\t\tpart := ToolCall{}\n\t\t\tif err := json.Unmarshal(wrapper.Data, &part); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tparts = append(parts, part)\n\t\tcase toolResultType:\n\t\t\tpart := ToolResult{}\n\t\t\tif err := json.Unmarshal(wrapper.Data, &part); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tparts = append(parts, part)\n\t\tcase finishType:\n\t\t\tpart := Finish{}\n\t\t\tif err := json.Unmarshal(wrapper.Data, &part); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tparts = append(parts, part)\n\t\tdefault:\n\t\t\treturn nil, fmt.Errorf(\"unknown part type: %s\", wrapper.Type)\n\t\t}\n\n\t}\n\n\treturn parts, nil\n}\n"], ["/opencode/internal/lsp/handlers.go", "package lsp\n\nimport (\n\t\"encoding/json\"\n\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n\t\"github.com/opencode-ai/opencode/internal/lsp/protocol\"\n\t\"github.com/opencode-ai/opencode/internal/lsp/util\"\n)\n\n// Requests\n\nfunc HandleWorkspaceConfiguration(params json.RawMessage) (any, error) {\n\treturn []map[string]any{{}}, nil\n}\n\nfunc HandleRegisterCapability(params json.RawMessage) (any, error) {\n\tvar registerParams protocol.RegistrationParams\n\tif err := json.Unmarshal(params, ®isterParams); err != nil {\n\t\tlogging.Error(\"Error unmarshaling registration params\", \"error\", err)\n\t\treturn nil, err\n\t}\n\n\tfor _, reg := range registerParams.Registrations {\n\t\tswitch reg.Method {\n\t\tcase \"workspace/didChangeWatchedFiles\":\n\t\t\t// Parse the registration options\n\t\t\toptionsJSON, err := json.Marshal(reg.RegisterOptions)\n\t\t\tif err != nil {\n\t\t\t\tlogging.Error(\"Error marshaling registration options\", \"error\", err)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tvar options protocol.DidChangeWatchedFilesRegistrationOptions\n\t\t\tif err := json.Unmarshal(optionsJSON, &options); err != nil {\n\t\t\t\tlogging.Error(\"Error unmarshaling registration options\", \"error\", err)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// Store the file watchers registrations\n\t\t\tnotifyFileWatchRegistration(reg.ID, options.Watchers)\n\t\t}\n\t}\n\n\treturn nil, nil\n}\n\nfunc HandleApplyEdit(params json.RawMessage) (any, error) {\n\tvar edit protocol.ApplyWorkspaceEditParams\n\tif err := json.Unmarshal(params, &edit); err != nil {\n\t\treturn nil, err\n\t}\n\n\terr := util.ApplyWorkspaceEdit(edit.Edit)\n\tif err != nil {\n\t\tlogging.Error(\"Error applying workspace edit\", \"error\", err)\n\t\treturn protocol.ApplyWorkspaceEditResult{Applied: false, FailureReason: err.Error()}, nil\n\t}\n\n\treturn protocol.ApplyWorkspaceEditResult{Applied: true}, nil\n}\n\n// FileWatchRegistrationHandler is a function that will be called when file watch registrations are received\ntype FileWatchRegistrationHandler func(id string, watchers []protocol.FileSystemWatcher)\n\n// fileWatchHandler holds the current handler for file watch registrations\nvar fileWatchHandler FileWatchRegistrationHandler\n\n// RegisterFileWatchHandler sets the handler for file watch registrations\nfunc RegisterFileWatchHandler(handler FileWatchRegistrationHandler) {\n\tfileWatchHandler = handler\n}\n\n// notifyFileWatchRegistration notifies the handler about new file watch registrations\nfunc notifyFileWatchRegistration(id string, watchers []protocol.FileSystemWatcher) {\n\tif fileWatchHandler != nil {\n\t\tfileWatchHandler(id, watchers)\n\t}\n}\n\n// Notifications\n\nfunc HandleServerMessage(params json.RawMessage) {\n\tcnf := config.Get()\n\tvar msg struct {\n\t\tType int `json:\"type\"`\n\t\tMessage string `json:\"message\"`\n\t}\n\tif err := json.Unmarshal(params, &msg); err == nil {\n\t\tif cnf.DebugLSP {\n\t\t\tlogging.Debug(\"Server message\", \"type\", msg.Type, \"message\", msg.Message)\n\t\t}\n\t}\n}\n\nfunc HandleDiagnostics(client *Client, params json.RawMessage) {\n\tvar diagParams protocol.PublishDiagnosticsParams\n\tif err := json.Unmarshal(params, &diagParams); err != nil {\n\t\tlogging.Error(\"Error unmarshaling diagnostics params\", \"error\", err)\n\t\treturn\n\t}\n\n\tclient.diagnosticsMu.Lock()\n\tdefer client.diagnosticsMu.Unlock()\n\n\tclient.diagnostics[diagParams.URI] = diagParams.Diagnostics\n}\n"], ["/opencode/internal/tui/theme/tron.go", "package theme\n\nimport (\n\t\"github.com/charmbracelet/lipgloss\"\n)\n\n// TronTheme implements the Theme interface with Tron-inspired colors.\n// It provides both dark and light variants, though Tron is primarily a dark theme.\ntype TronTheme struct {\n\tBaseTheme\n}\n\n// NewTronTheme creates a new instance of the Tron theme.\nfunc NewTronTheme() *TronTheme {\n\t// Tron color palette\n\t// Inspired by the Tron movie's neon aesthetic\n\tdarkBackground := \"#0c141f\"\n\tdarkCurrentLine := \"#1a2633\"\n\tdarkSelection := \"#1a2633\"\n\tdarkForeground := \"#caf0ff\"\n\tdarkComment := \"#4d6b87\"\n\tdarkCyan := \"#00d9ff\"\n\tdarkBlue := \"#007fff\"\n\tdarkOrange := \"#ff9000\"\n\tdarkPink := \"#ff00a0\"\n\tdarkPurple := \"#b73fff\"\n\tdarkRed := \"#ff3333\"\n\tdarkYellow := \"#ffcc00\"\n\tdarkGreen := \"#00ff8f\"\n\tdarkBorder := \"#1a2633\"\n\n\t// Light mode approximation\n\tlightBackground := \"#f0f8ff\"\n\tlightCurrentLine := \"#e0f0ff\"\n\tlightSelection := \"#d0e8ff\"\n\tlightForeground := \"#0c141f\"\n\tlightComment := \"#4d6b87\"\n\tlightCyan := \"#0097b3\"\n\tlightBlue := \"#0066cc\"\n\tlightOrange := \"#cc7300\"\n\tlightPink := \"#cc0080\"\n\tlightPurple := \"#9932cc\"\n\tlightRed := \"#cc2929\"\n\tlightYellow := \"#cc9900\"\n\tlightGreen := \"#00cc72\"\n\tlightBorder := \"#d0e8ff\"\n\n\ttheme := &TronTheme{}\n\n\t// Base colors\n\ttheme.PrimaryColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.SecondaryColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBlue,\n\t\tLight: lightBlue,\n\t}\n\ttheme.AccentColor = lipgloss.AdaptiveColor{\n\t\tDark: darkOrange,\n\t\tLight: lightOrange,\n\t}\n\n\t// Status colors\n\ttheme.ErrorColor = lipgloss.AdaptiveColor{\n\t\tDark: darkRed,\n\t\tLight: lightRed,\n\t}\n\ttheme.WarningColor = lipgloss.AdaptiveColor{\n\t\tDark: darkOrange,\n\t\tLight: lightOrange,\n\t}\n\ttheme.SuccessColor = lipgloss.AdaptiveColor{\n\t\tDark: darkGreen,\n\t\tLight: lightGreen,\n\t}\n\ttheme.InfoColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\n\t// Text colors\n\ttheme.TextColor = lipgloss.AdaptiveColor{\n\t\tDark: darkForeground,\n\t\tLight: lightForeground,\n\t}\n\ttheme.TextMutedColor = lipgloss.AdaptiveColor{\n\t\tDark: darkComment,\n\t\tLight: lightComment,\n\t}\n\ttheme.TextEmphasizedColor = lipgloss.AdaptiveColor{\n\t\tDark: darkYellow,\n\t\tLight: lightYellow,\n\t}\n\n\t// Background colors\n\ttheme.BackgroundColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBackground,\n\t\tLight: lightBackground,\n\t}\n\ttheme.BackgroundSecondaryColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCurrentLine,\n\t\tLight: lightCurrentLine,\n\t}\n\ttheme.BackgroundDarkerColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#070d14\", // Slightly darker than background\n\t\tLight: \"#ffffff\", // Slightly lighter than background\n\t}\n\n\t// Border colors\n\ttheme.BorderNormalColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBorder,\n\t\tLight: lightBorder,\n\t}\n\ttheme.BorderFocusedColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.BorderDimColor = lipgloss.AdaptiveColor{\n\t\tDark: darkSelection,\n\t\tLight: lightSelection,\n\t}\n\n\t// Diff view colors\n\ttheme.DiffAddedColor = lipgloss.AdaptiveColor{\n\t\tDark: darkGreen,\n\t\tLight: lightGreen,\n\t}\n\ttheme.DiffRemovedColor = lipgloss.AdaptiveColor{\n\t\tDark: darkRed,\n\t\tLight: lightRed,\n\t}\n\ttheme.DiffContextColor = lipgloss.AdaptiveColor{\n\t\tDark: darkComment,\n\t\tLight: lightComment,\n\t}\n\ttheme.DiffHunkHeaderColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBlue,\n\t\tLight: lightBlue,\n\t}\n\ttheme.DiffHighlightAddedColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#00ff8f\",\n\t\tLight: \"#a5d6a7\",\n\t}\n\ttheme.DiffHighlightRemovedColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#ff3333\",\n\t\tLight: \"#ef9a9a\",\n\t}\n\ttheme.DiffAddedBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#0a2a1a\",\n\t\tLight: \"#e8f5e9\",\n\t}\n\ttheme.DiffRemovedBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#2a0a0a\",\n\t\tLight: \"#ffebee\",\n\t}\n\ttheme.DiffContextBgColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBackground,\n\t\tLight: lightBackground,\n\t}\n\ttheme.DiffLineNumberColor = lipgloss.AdaptiveColor{\n\t\tDark: darkComment,\n\t\tLight: lightComment,\n\t}\n\ttheme.DiffAddedLineNumberBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#082015\",\n\t\tLight: \"#c8e6c9\",\n\t}\n\ttheme.DiffRemovedLineNumberBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#200808\",\n\t\tLight: \"#ffcdd2\",\n\t}\n\n\t// Markdown colors\n\ttheme.MarkdownTextColor = lipgloss.AdaptiveColor{\n\t\tDark: darkForeground,\n\t\tLight: lightForeground,\n\t}\n\ttheme.MarkdownHeadingColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.MarkdownLinkColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBlue,\n\t\tLight: lightBlue,\n\t}\n\ttheme.MarkdownLinkTextColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.MarkdownCodeColor = lipgloss.AdaptiveColor{\n\t\tDark: darkGreen,\n\t\tLight: lightGreen,\n\t}\n\ttheme.MarkdownBlockQuoteColor = lipgloss.AdaptiveColor{\n\t\tDark: darkYellow,\n\t\tLight: lightYellow,\n\t}\n\ttheme.MarkdownEmphColor = lipgloss.AdaptiveColor{\n\t\tDark: darkYellow,\n\t\tLight: lightYellow,\n\t}\n\ttheme.MarkdownStrongColor = lipgloss.AdaptiveColor{\n\t\tDark: darkOrange,\n\t\tLight: lightOrange,\n\t}\n\ttheme.MarkdownHorizontalRuleColor = lipgloss.AdaptiveColor{\n\t\tDark: darkComment,\n\t\tLight: lightComment,\n\t}\n\ttheme.MarkdownListItemColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBlue,\n\t\tLight: lightBlue,\n\t}\n\ttheme.MarkdownListEnumerationColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.MarkdownImageColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBlue,\n\t\tLight: lightBlue,\n\t}\n\ttheme.MarkdownImageTextColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.MarkdownCodeBlockColor = lipgloss.AdaptiveColor{\n\t\tDark: darkForeground,\n\t\tLight: lightForeground,\n\t}\n\n\t// Syntax highlighting colors\n\ttheme.SyntaxCommentColor = lipgloss.AdaptiveColor{\n\t\tDark: darkComment,\n\t\tLight: lightComment,\n\t}\n\ttheme.SyntaxKeywordColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.SyntaxFunctionColor = lipgloss.AdaptiveColor{\n\t\tDark: darkGreen,\n\t\tLight: lightGreen,\n\t}\n\ttheme.SyntaxVariableColor = lipgloss.AdaptiveColor{\n\t\tDark: darkOrange,\n\t\tLight: lightOrange,\n\t}\n\ttheme.SyntaxStringColor = lipgloss.AdaptiveColor{\n\t\tDark: darkYellow,\n\t\tLight: lightYellow,\n\t}\n\ttheme.SyntaxNumberColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBlue,\n\t\tLight: lightBlue,\n\t}\n\ttheme.SyntaxTypeColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPurple,\n\t\tLight: lightPurple,\n\t}\n\ttheme.SyntaxOperatorColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPink,\n\t\tLight: lightPink,\n\t}\n\ttheme.SyntaxPunctuationColor = lipgloss.AdaptiveColor{\n\t\tDark: darkForeground,\n\t\tLight: lightForeground,\n\t}\n\n\treturn theme\n}\n\nfunc init() {\n\t// Register the Tron theme with the theme manager\n\tRegisterTheme(\"tron\", NewTronTheme())\n}"], ["/opencode/internal/tui/theme/tokyonight.go", "package theme\n\nimport (\n\t\"github.com/charmbracelet/lipgloss\"\n)\n\n// TokyoNightTheme implements the Theme interface with Tokyo Night colors.\n// It provides both dark and light variants.\ntype TokyoNightTheme struct {\n\tBaseTheme\n}\n\n// NewTokyoNightTheme creates a new instance of the Tokyo Night theme.\nfunc NewTokyoNightTheme() *TokyoNightTheme {\n\t// Tokyo Night color palette\n\t// Dark mode colors\n\tdarkBackground := \"#222436\"\n\tdarkCurrentLine := \"#1e2030\"\n\tdarkSelection := \"#2f334d\"\n\tdarkForeground := \"#c8d3f5\"\n\tdarkComment := \"#636da6\"\n\tdarkRed := \"#ff757f\"\n\tdarkOrange := \"#ff966c\"\n\tdarkYellow := \"#ffc777\"\n\tdarkGreen := \"#c3e88d\"\n\tdarkCyan := \"#86e1fc\"\n\tdarkBlue := \"#82aaff\"\n\tdarkPurple := \"#c099ff\"\n\tdarkBorder := \"#3b4261\"\n\n\t// Light mode colors (Tokyo Night Day)\n\tlightBackground := \"#e1e2e7\"\n\tlightCurrentLine := \"#d5d6db\"\n\tlightSelection := \"#c8c9ce\"\n\tlightForeground := \"#3760bf\"\n\tlightComment := \"#848cb5\"\n\tlightRed := \"#f52a65\"\n\tlightOrange := \"#b15c00\"\n\tlightYellow := \"#8c6c3e\"\n\tlightGreen := \"#587539\"\n\tlightCyan := \"#007197\"\n\tlightBlue := \"#2e7de9\"\n\tlightPurple := \"#9854f1\"\n\tlightBorder := \"#a8aecb\"\n\n\ttheme := &TokyoNightTheme{}\n\n\t// Base colors\n\ttheme.PrimaryColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBlue,\n\t\tLight: lightBlue,\n\t}\n\ttheme.SecondaryColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPurple,\n\t\tLight: lightPurple,\n\t}\n\ttheme.AccentColor = lipgloss.AdaptiveColor{\n\t\tDark: darkOrange,\n\t\tLight: lightOrange,\n\t}\n\n\t// Status colors\n\ttheme.ErrorColor = lipgloss.AdaptiveColor{\n\t\tDark: darkRed,\n\t\tLight: lightRed,\n\t}\n\ttheme.WarningColor = lipgloss.AdaptiveColor{\n\t\tDark: darkOrange,\n\t\tLight: lightOrange,\n\t}\n\ttheme.SuccessColor = lipgloss.AdaptiveColor{\n\t\tDark: darkGreen,\n\t\tLight: lightGreen,\n\t}\n\ttheme.InfoColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBlue,\n\t\tLight: lightBlue,\n\t}\n\n\t// Text colors\n\ttheme.TextColor = lipgloss.AdaptiveColor{\n\t\tDark: darkForeground,\n\t\tLight: lightForeground,\n\t}\n\ttheme.TextMutedColor = lipgloss.AdaptiveColor{\n\t\tDark: darkComment,\n\t\tLight: lightComment,\n\t}\n\ttheme.TextEmphasizedColor = lipgloss.AdaptiveColor{\n\t\tDark: darkYellow,\n\t\tLight: lightYellow,\n\t}\n\n\t// Background colors\n\ttheme.BackgroundColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBackground,\n\t\tLight: lightBackground,\n\t}\n\ttheme.BackgroundSecondaryColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCurrentLine,\n\t\tLight: lightCurrentLine,\n\t}\n\ttheme.BackgroundDarkerColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#191B29\", // Darker background from palette\n\t\tLight: \"#f0f0f5\", // Slightly lighter than background\n\t}\n\n\t// Border colors\n\ttheme.BorderNormalColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBorder,\n\t\tLight: lightBorder,\n\t}\n\ttheme.BorderFocusedColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBlue,\n\t\tLight: lightBlue,\n\t}\n\ttheme.BorderDimColor = lipgloss.AdaptiveColor{\n\t\tDark: darkSelection,\n\t\tLight: lightSelection,\n\t}\n\n\t// Diff view colors\n\ttheme.DiffAddedColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#4fd6be\", // teal from palette\n\t\tLight: \"#1e725c\",\n\t}\n\ttheme.DiffRemovedColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#c53b53\", // red1 from palette\n\t\tLight: \"#c53b53\",\n\t}\n\ttheme.DiffContextColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#828bb8\", // fg_dark from palette\n\t\tLight: \"#7086b5\",\n\t}\n\ttheme.DiffHunkHeaderColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#828bb8\", // fg_dark from palette\n\t\tLight: \"#7086b5\",\n\t}\n\ttheme.DiffHighlightAddedColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#b8db87\", // git.add from palette\n\t\tLight: \"#4db380\",\n\t}\n\ttheme.DiffHighlightRemovedColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#e26a75\", // git.delete from palette\n\t\tLight: \"#f52a65\",\n\t}\n\ttheme.DiffAddedBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#20303b\",\n\t\tLight: \"#d5e5d5\",\n\t}\n\ttheme.DiffRemovedBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#37222c\",\n\t\tLight: \"#f7d8db\",\n\t}\n\ttheme.DiffContextBgColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBackground,\n\t\tLight: lightBackground,\n\t}\n\ttheme.DiffLineNumberColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#545c7e\", // dark3 from palette\n\t\tLight: \"#848cb5\",\n\t}\n\ttheme.DiffAddedLineNumberBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#1b2b34\",\n\t\tLight: \"#c5d5c5\",\n\t}\n\ttheme.DiffRemovedLineNumberBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#2d1f26\",\n\t\tLight: \"#e7c8cb\",\n\t}\n\n\t// Markdown colors\n\ttheme.MarkdownTextColor = lipgloss.AdaptiveColor{\n\t\tDark: darkForeground,\n\t\tLight: lightForeground,\n\t}\n\ttheme.MarkdownHeadingColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPurple,\n\t\tLight: lightPurple,\n\t}\n\ttheme.MarkdownLinkColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBlue,\n\t\tLight: lightBlue,\n\t}\n\ttheme.MarkdownLinkTextColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.MarkdownCodeColor = lipgloss.AdaptiveColor{\n\t\tDark: darkGreen,\n\t\tLight: lightGreen,\n\t}\n\ttheme.MarkdownBlockQuoteColor = lipgloss.AdaptiveColor{\n\t\tDark: darkYellow,\n\t\tLight: lightYellow,\n\t}\n\ttheme.MarkdownEmphColor = lipgloss.AdaptiveColor{\n\t\tDark: darkYellow,\n\t\tLight: lightYellow,\n\t}\n\ttheme.MarkdownStrongColor = lipgloss.AdaptiveColor{\n\t\tDark: darkOrange,\n\t\tLight: lightOrange,\n\t}\n\ttheme.MarkdownHorizontalRuleColor = lipgloss.AdaptiveColor{\n\t\tDark: darkComment,\n\t\tLight: lightComment,\n\t}\n\ttheme.MarkdownListItemColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBlue,\n\t\tLight: lightBlue,\n\t}\n\ttheme.MarkdownListEnumerationColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.MarkdownImageColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBlue,\n\t\tLight: lightBlue,\n\t}\n\ttheme.MarkdownImageTextColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.MarkdownCodeBlockColor = lipgloss.AdaptiveColor{\n\t\tDark: darkForeground,\n\t\tLight: lightForeground,\n\t}\n\n\t// Syntax highlighting colors\n\ttheme.SyntaxCommentColor = lipgloss.AdaptiveColor{\n\t\tDark: darkComment,\n\t\tLight: lightComment,\n\t}\n\ttheme.SyntaxKeywordColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPurple,\n\t\tLight: lightPurple,\n\t}\n\ttheme.SyntaxFunctionColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBlue,\n\t\tLight: lightBlue,\n\t}\n\ttheme.SyntaxVariableColor = lipgloss.AdaptiveColor{\n\t\tDark: darkRed,\n\t\tLight: lightRed,\n\t}\n\ttheme.SyntaxStringColor = lipgloss.AdaptiveColor{\n\t\tDark: darkGreen,\n\t\tLight: lightGreen,\n\t}\n\ttheme.SyntaxNumberColor = lipgloss.AdaptiveColor{\n\t\tDark: darkOrange,\n\t\tLight: lightOrange,\n\t}\n\ttheme.SyntaxTypeColor = lipgloss.AdaptiveColor{\n\t\tDark: darkYellow,\n\t\tLight: lightYellow,\n\t}\n\ttheme.SyntaxOperatorColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.SyntaxPunctuationColor = lipgloss.AdaptiveColor{\n\t\tDark: darkForeground,\n\t\tLight: lightForeground,\n\t}\n\n\treturn theme\n}\n\nfunc init() {\n\t// Register the Tokyo Night theme with the theme manager\n\tRegisterTheme(\"tokyonight\", NewTokyoNightTheme())\n}"], ["/opencode/internal/tui/theme/onedark.go", "package theme\n\nimport (\n\t\"github.com/charmbracelet/lipgloss\"\n)\n\n// OneDarkTheme implements the Theme interface with Atom's One Dark colors.\n// It provides both dark and light variants.\ntype OneDarkTheme struct {\n\tBaseTheme\n}\n\n// NewOneDarkTheme creates a new instance of the One Dark theme.\nfunc NewOneDarkTheme() *OneDarkTheme {\n\t// One Dark color palette\n\t// Dark mode colors from Atom One Dark\n\tdarkBackground := \"#282c34\"\n\tdarkCurrentLine := \"#2c313c\"\n\tdarkSelection := \"#3e4451\"\n\tdarkForeground := \"#abb2bf\"\n\tdarkComment := \"#5c6370\"\n\tdarkRed := \"#e06c75\"\n\tdarkOrange := \"#d19a66\"\n\tdarkYellow := \"#e5c07b\"\n\tdarkGreen := \"#98c379\"\n\tdarkCyan := \"#56b6c2\"\n\tdarkBlue := \"#61afef\"\n\tdarkPurple := \"#c678dd\"\n\tdarkBorder := \"#3b4048\"\n\n\t// Light mode colors from Atom One Light\n\tlightBackground := \"#fafafa\"\n\tlightCurrentLine := \"#f0f0f0\"\n\tlightSelection := \"#e5e5e6\"\n\tlightForeground := \"#383a42\"\n\tlightComment := \"#a0a1a7\"\n\tlightRed := \"#e45649\"\n\tlightOrange := \"#da8548\"\n\tlightYellow := \"#c18401\"\n\tlightGreen := \"#50a14f\"\n\tlightCyan := \"#0184bc\"\n\tlightBlue := \"#4078f2\"\n\tlightPurple := \"#a626a4\"\n\tlightBorder := \"#d3d3d3\"\n\n\ttheme := &OneDarkTheme{}\n\n\t// Base colors\n\ttheme.PrimaryColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBlue,\n\t\tLight: lightBlue,\n\t}\n\ttheme.SecondaryColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPurple,\n\t\tLight: lightPurple,\n\t}\n\ttheme.AccentColor = lipgloss.AdaptiveColor{\n\t\tDark: darkOrange,\n\t\tLight: lightOrange,\n\t}\n\n\t// Status colors\n\ttheme.ErrorColor = lipgloss.AdaptiveColor{\n\t\tDark: darkRed,\n\t\tLight: lightRed,\n\t}\n\ttheme.WarningColor = lipgloss.AdaptiveColor{\n\t\tDark: darkOrange,\n\t\tLight: lightOrange,\n\t}\n\ttheme.SuccessColor = lipgloss.AdaptiveColor{\n\t\tDark: darkGreen,\n\t\tLight: lightGreen,\n\t}\n\ttheme.InfoColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBlue,\n\t\tLight: lightBlue,\n\t}\n\n\t// Text colors\n\ttheme.TextColor = lipgloss.AdaptiveColor{\n\t\tDark: darkForeground,\n\t\tLight: lightForeground,\n\t}\n\ttheme.TextMutedColor = lipgloss.AdaptiveColor{\n\t\tDark: darkComment,\n\t\tLight: lightComment,\n\t}\n\ttheme.TextEmphasizedColor = lipgloss.AdaptiveColor{\n\t\tDark: darkYellow,\n\t\tLight: lightYellow,\n\t}\n\n\t// Background colors\n\ttheme.BackgroundColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBackground,\n\t\tLight: lightBackground,\n\t}\n\ttheme.BackgroundSecondaryColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCurrentLine,\n\t\tLight: lightCurrentLine,\n\t}\n\ttheme.BackgroundDarkerColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#21252b\", // Slightly darker than background\n\t\tLight: \"#ffffff\", // Slightly lighter than background\n\t}\n\n\t// Border colors\n\ttheme.BorderNormalColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBorder,\n\t\tLight: lightBorder,\n\t}\n\ttheme.BorderFocusedColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBlue,\n\t\tLight: lightBlue,\n\t}\n\ttheme.BorderDimColor = lipgloss.AdaptiveColor{\n\t\tDark: darkSelection,\n\t\tLight: lightSelection,\n\t}\n\n\t// Diff view colors\n\ttheme.DiffAddedColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#478247\",\n\t\tLight: \"#2E7D32\",\n\t}\n\ttheme.DiffRemovedColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#7C4444\",\n\t\tLight: \"#C62828\",\n\t}\n\ttheme.DiffContextColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#a0a0a0\",\n\t\tLight: \"#757575\",\n\t}\n\ttheme.DiffHunkHeaderColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#a0a0a0\",\n\t\tLight: \"#757575\",\n\t}\n\ttheme.DiffHighlightAddedColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#DAFADA\",\n\t\tLight: \"#A5D6A7\",\n\t}\n\ttheme.DiffHighlightRemovedColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#FADADD\",\n\t\tLight: \"#EF9A9A\",\n\t}\n\ttheme.DiffAddedBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#303A30\",\n\t\tLight: \"#E8F5E9\",\n\t}\n\ttheme.DiffRemovedBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#3A3030\",\n\t\tLight: \"#FFEBEE\",\n\t}\n\ttheme.DiffContextBgColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBackground,\n\t\tLight: lightBackground,\n\t}\n\ttheme.DiffLineNumberColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#888888\",\n\t\tLight: \"#9E9E9E\",\n\t}\n\ttheme.DiffAddedLineNumberBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#293229\",\n\t\tLight: \"#C8E6C9\",\n\t}\n\ttheme.DiffRemovedLineNumberBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#332929\",\n\t\tLight: \"#FFCDD2\",\n\t}\n\n\t// Markdown colors\n\ttheme.MarkdownTextColor = lipgloss.AdaptiveColor{\n\t\tDark: darkForeground,\n\t\tLight: lightForeground,\n\t}\n\ttheme.MarkdownHeadingColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPurple,\n\t\tLight: lightPurple,\n\t}\n\ttheme.MarkdownLinkColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBlue,\n\t\tLight: lightBlue,\n\t}\n\ttheme.MarkdownLinkTextColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.MarkdownCodeColor = lipgloss.AdaptiveColor{\n\t\tDark: darkGreen,\n\t\tLight: lightGreen,\n\t}\n\ttheme.MarkdownBlockQuoteColor = lipgloss.AdaptiveColor{\n\t\tDark: darkYellow,\n\t\tLight: lightYellow,\n\t}\n\ttheme.MarkdownEmphColor = lipgloss.AdaptiveColor{\n\t\tDark: darkYellow,\n\t\tLight: lightYellow,\n\t}\n\ttheme.MarkdownStrongColor = lipgloss.AdaptiveColor{\n\t\tDark: darkOrange,\n\t\tLight: lightOrange,\n\t}\n\ttheme.MarkdownHorizontalRuleColor = lipgloss.AdaptiveColor{\n\t\tDark: darkComment,\n\t\tLight: lightComment,\n\t}\n\ttheme.MarkdownListItemColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBlue,\n\t\tLight: lightBlue,\n\t}\n\ttheme.MarkdownListEnumerationColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.MarkdownImageColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBlue,\n\t\tLight: lightBlue,\n\t}\n\ttheme.MarkdownImageTextColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.MarkdownCodeBlockColor = lipgloss.AdaptiveColor{\n\t\tDark: darkForeground,\n\t\tLight: lightForeground,\n\t}\n\n\t// Syntax highlighting colors\n\ttheme.SyntaxCommentColor = lipgloss.AdaptiveColor{\n\t\tDark: darkComment,\n\t\tLight: lightComment,\n\t}\n\ttheme.SyntaxKeywordColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPurple,\n\t\tLight: lightPurple,\n\t}\n\ttheme.SyntaxFunctionColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBlue,\n\t\tLight: lightBlue,\n\t}\n\ttheme.SyntaxVariableColor = lipgloss.AdaptiveColor{\n\t\tDark: darkRed,\n\t\tLight: lightRed,\n\t}\n\ttheme.SyntaxStringColor = lipgloss.AdaptiveColor{\n\t\tDark: darkGreen,\n\t\tLight: lightGreen,\n\t}\n\ttheme.SyntaxNumberColor = lipgloss.AdaptiveColor{\n\t\tDark: darkOrange,\n\t\tLight: lightOrange,\n\t}\n\ttheme.SyntaxTypeColor = lipgloss.AdaptiveColor{\n\t\tDark: darkYellow,\n\t\tLight: lightYellow,\n\t}\n\ttheme.SyntaxOperatorColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.SyntaxPunctuationColor = lipgloss.AdaptiveColor{\n\t\tDark: darkForeground,\n\t\tLight: lightForeground,\n\t}\n\n\treturn theme\n}\n\nfunc init() {\n\t// Register the One Dark theme with the theme manager\n\tRegisterTheme(\"onedark\", NewOneDarkTheme())\n}"], ["/opencode/internal/tui/theme/manager.go", "package theme\n\nimport (\n\t\"fmt\"\n\t\"slices\"\n\t\"strings\"\n\t\"sync\"\n\n\t\"github.com/alecthomas/chroma/v2/styles\"\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n)\n\n// Manager handles theme registration, selection, and retrieval.\n// It maintains a registry of available themes and tracks the currently active theme.\ntype Manager struct {\n\tthemes map[string]Theme\n\tcurrentName string\n\tmu sync.RWMutex\n}\n\n// Global instance of the theme manager\nvar globalManager = &Manager{\n\tthemes: make(map[string]Theme),\n\tcurrentName: \"\",\n}\n\n// RegisterTheme adds a new theme to the registry.\n// If this is the first theme registered, it becomes the default.\nfunc RegisterTheme(name string, theme Theme) {\n\tglobalManager.mu.Lock()\n\tdefer globalManager.mu.Unlock()\n\n\tglobalManager.themes[name] = theme\n\n\t// If this is the first theme, make it the default\n\tif globalManager.currentName == \"\" {\n\t\tglobalManager.currentName = name\n\t}\n}\n\n// SetTheme changes the active theme to the one with the specified name.\n// Returns an error if the theme doesn't exist.\nfunc SetTheme(name string) error {\n\tglobalManager.mu.Lock()\n\tdefer globalManager.mu.Unlock()\n\n\tdelete(styles.Registry, \"charm\")\n\tif _, exists := globalManager.themes[name]; !exists {\n\t\treturn fmt.Errorf(\"theme '%s' not found\", name)\n\t}\n\n\tglobalManager.currentName = name\n\n\t// Update the config file using viper\n\tif err := updateConfigTheme(name); err != nil {\n\t\t// Log the error but don't fail the theme change\n\t\tlogging.Warn(\"Warning: Failed to update config file with new theme\", \"err\", err)\n\t}\n\n\treturn nil\n}\n\n// CurrentTheme returns the currently active theme.\n// If no theme is set, it returns nil.\nfunc CurrentTheme() Theme {\n\tglobalManager.mu.RLock()\n\tdefer globalManager.mu.RUnlock()\n\n\tif globalManager.currentName == \"\" {\n\t\treturn nil\n\t}\n\n\treturn globalManager.themes[globalManager.currentName]\n}\n\n// CurrentThemeName returns the name of the currently active theme.\nfunc CurrentThemeName() string {\n\tglobalManager.mu.RLock()\n\tdefer globalManager.mu.RUnlock()\n\n\treturn globalManager.currentName\n}\n\n// AvailableThemes returns a list of all registered theme names.\nfunc AvailableThemes() []string {\n\tglobalManager.mu.RLock()\n\tdefer globalManager.mu.RUnlock()\n\n\tnames := make([]string, 0, len(globalManager.themes))\n\tfor name := range globalManager.themes {\n\t\tnames = append(names, name)\n\t}\n\tslices.SortFunc(names, func(a, b string) int {\n\t\tif a == \"opencode\" {\n\t\t\treturn -1\n\t\t} else if b == \"opencode\" {\n\t\t\treturn 1\n\t\t}\n\t\treturn strings.Compare(a, b)\n\t})\n\treturn names\n}\n\n// GetTheme returns a specific theme by name.\n// Returns nil if the theme doesn't exist.\nfunc GetTheme(name string) Theme {\n\tglobalManager.mu.RLock()\n\tdefer globalManager.mu.RUnlock()\n\n\treturn globalManager.themes[name]\n}\n\n// updateConfigTheme updates the theme setting in the configuration file\nfunc updateConfigTheme(themeName string) error {\n\t// Use the config package to update the theme\n\treturn config.UpdateTheme(themeName)\n}\n"], ["/opencode/internal/session/session.go", "package session\n\nimport (\n\t\"context\"\n\t\"database/sql\"\n\n\t\"github.com/google/uuid\"\n\t\"github.com/opencode-ai/opencode/internal/db\"\n\t\"github.com/opencode-ai/opencode/internal/pubsub\"\n)\n\ntype Session struct {\n\tID string\n\tParentSessionID string\n\tTitle string\n\tMessageCount int64\n\tPromptTokens int64\n\tCompletionTokens int64\n\tSummaryMessageID string\n\tCost float64\n\tCreatedAt int64\n\tUpdatedAt int64\n}\n\ntype Service interface {\n\tpubsub.Suscriber[Session]\n\tCreate(ctx context.Context, title string) (Session, error)\n\tCreateTitleSession(ctx context.Context, parentSessionID string) (Session, error)\n\tCreateTaskSession(ctx context.Context, toolCallID, parentSessionID, title string) (Session, error)\n\tGet(ctx context.Context, id string) (Session, error)\n\tList(ctx context.Context) ([]Session, error)\n\tSave(ctx context.Context, session Session) (Session, error)\n\tDelete(ctx context.Context, id string) error\n}\n\ntype service struct {\n\t*pubsub.Broker[Session]\n\tq db.Querier\n}\n\nfunc (s *service) Create(ctx context.Context, title string) (Session, error) {\n\tdbSession, err := s.q.CreateSession(ctx, db.CreateSessionParams{\n\t\tID: uuid.New().String(),\n\t\tTitle: title,\n\t})\n\tif err != nil {\n\t\treturn Session{}, err\n\t}\n\tsession := s.fromDBItem(dbSession)\n\ts.Publish(pubsub.CreatedEvent, session)\n\treturn session, nil\n}\n\nfunc (s *service) CreateTaskSession(ctx context.Context, toolCallID, parentSessionID, title string) (Session, error) {\n\tdbSession, err := s.q.CreateSession(ctx, db.CreateSessionParams{\n\t\tID: toolCallID,\n\t\tParentSessionID: sql.NullString{String: parentSessionID, Valid: true},\n\t\tTitle: title,\n\t})\n\tif err != nil {\n\t\treturn Session{}, err\n\t}\n\tsession := s.fromDBItem(dbSession)\n\ts.Publish(pubsub.CreatedEvent, session)\n\treturn session, nil\n}\n\nfunc (s *service) CreateTitleSession(ctx context.Context, parentSessionID string) (Session, error) {\n\tdbSession, err := s.q.CreateSession(ctx, db.CreateSessionParams{\n\t\tID: \"title-\" + parentSessionID,\n\t\tParentSessionID: sql.NullString{String: parentSessionID, Valid: true},\n\t\tTitle: \"Generate a title\",\n\t})\n\tif err != nil {\n\t\treturn Session{}, err\n\t}\n\tsession := s.fromDBItem(dbSession)\n\ts.Publish(pubsub.CreatedEvent, session)\n\treturn session, nil\n}\n\nfunc (s *service) Delete(ctx context.Context, id string) error {\n\tsession, err := s.Get(ctx, id)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = s.q.DeleteSession(ctx, session.ID)\n\tif err != nil {\n\t\treturn err\n\t}\n\ts.Publish(pubsub.DeletedEvent, session)\n\treturn nil\n}\n\nfunc (s *service) Get(ctx context.Context, id string) (Session, error) {\n\tdbSession, err := s.q.GetSessionByID(ctx, id)\n\tif err != nil {\n\t\treturn Session{}, err\n\t}\n\treturn s.fromDBItem(dbSession), nil\n}\n\nfunc (s *service) Save(ctx context.Context, session Session) (Session, error) {\n\tdbSession, err := s.q.UpdateSession(ctx, db.UpdateSessionParams{\n\t\tID: session.ID,\n\t\tTitle: session.Title,\n\t\tPromptTokens: session.PromptTokens,\n\t\tCompletionTokens: session.CompletionTokens,\n\t\tSummaryMessageID: sql.NullString{\n\t\t\tString: session.SummaryMessageID,\n\t\t\tValid: session.SummaryMessageID != \"\",\n\t\t},\n\t\tCost: session.Cost,\n\t})\n\tif err != nil {\n\t\treturn Session{}, err\n\t}\n\tsession = s.fromDBItem(dbSession)\n\ts.Publish(pubsub.UpdatedEvent, session)\n\treturn session, nil\n}\n\nfunc (s *service) List(ctx context.Context) ([]Session, error) {\n\tdbSessions, err := s.q.ListSessions(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsessions := make([]Session, len(dbSessions))\n\tfor i, dbSession := range dbSessions {\n\t\tsessions[i] = s.fromDBItem(dbSession)\n\t}\n\treturn sessions, nil\n}\n\nfunc (s service) fromDBItem(item db.Session) Session {\n\treturn Session{\n\t\tID: item.ID,\n\t\tParentSessionID: item.ParentSessionID.String,\n\t\tTitle: item.Title,\n\t\tMessageCount: item.MessageCount,\n\t\tPromptTokens: item.PromptTokens,\n\t\tCompletionTokens: item.CompletionTokens,\n\t\tSummaryMessageID: item.SummaryMessageID.String,\n\t\tCost: item.Cost,\n\t\tCreatedAt: item.CreatedAt,\n\t\tUpdatedAt: item.UpdatedAt,\n\t}\n}\n\nfunc NewService(q db.Querier) Service {\n\tbroker := pubsub.NewBroker[Session]()\n\treturn &service{\n\t\tbroker,\n\t\tq,\n\t}\n}\n"], ["/opencode/internal/lsp/util/edit.go", "package util\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"os\"\n\t\"sort\"\n\t\"strings\"\n\n\t\"github.com/opencode-ai/opencode/internal/lsp/protocol\"\n)\n\nfunc applyTextEdits(uri protocol.DocumentUri, edits []protocol.TextEdit) error {\n\tpath := strings.TrimPrefix(string(uri), \"file://\")\n\n\t// Read the file content\n\tcontent, err := os.ReadFile(path)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to read file: %w\", err)\n\t}\n\n\t// Detect line ending style\n\tvar lineEnding string\n\tif bytes.Contains(content, []byte(\"\\r\\n\")) {\n\t\tlineEnding = \"\\r\\n\"\n\t} else {\n\t\tlineEnding = \"\\n\"\n\t}\n\n\t// Track if file ends with a newline\n\tendsWithNewline := len(content) > 0 && bytes.HasSuffix(content, []byte(lineEnding))\n\n\t// Split into lines without the endings\n\tlines := strings.Split(string(content), lineEnding)\n\n\t// Check for overlapping edits\n\tfor i, edit1 := range edits {\n\t\tfor j := i + 1; j < len(edits); j++ {\n\t\t\tif rangesOverlap(edit1.Range, edits[j].Range) {\n\t\t\t\treturn fmt.Errorf(\"overlapping edits detected between edit %d and %d\", i, j)\n\t\t\t}\n\t\t}\n\t}\n\n\t// Sort edits in reverse order\n\tsortedEdits := make([]protocol.TextEdit, len(edits))\n\tcopy(sortedEdits, edits)\n\tsort.Slice(sortedEdits, func(i, j int) bool {\n\t\tif sortedEdits[i].Range.Start.Line != sortedEdits[j].Range.Start.Line {\n\t\t\treturn sortedEdits[i].Range.Start.Line > sortedEdits[j].Range.Start.Line\n\t\t}\n\t\treturn sortedEdits[i].Range.Start.Character > sortedEdits[j].Range.Start.Character\n\t})\n\n\t// Apply each edit\n\tfor _, edit := range sortedEdits {\n\t\tnewLines, err := applyTextEdit(lines, edit)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to apply edit: %w\", err)\n\t\t}\n\t\tlines = newLines\n\t}\n\n\t// Join lines with proper line endings\n\tvar newContent strings.Builder\n\tfor i, line := range lines {\n\t\tif i > 0 {\n\t\t\tnewContent.WriteString(lineEnding)\n\t\t}\n\t\tnewContent.WriteString(line)\n\t}\n\n\t// Only add a newline if the original file had one and we haven't already added it\n\tif endsWithNewline && !strings.HasSuffix(newContent.String(), lineEnding) {\n\t\tnewContent.WriteString(lineEnding)\n\t}\n\n\tif err := os.WriteFile(path, []byte(newContent.String()), 0o644); err != nil {\n\t\treturn fmt.Errorf(\"failed to write file: %w\", err)\n\t}\n\n\treturn nil\n}\n\nfunc applyTextEdit(lines []string, edit protocol.TextEdit) ([]string, error) {\n\tstartLine := int(edit.Range.Start.Line)\n\tendLine := int(edit.Range.End.Line)\n\tstartChar := int(edit.Range.Start.Character)\n\tendChar := int(edit.Range.End.Character)\n\n\t// Validate positions\n\tif startLine < 0 || startLine >= len(lines) {\n\t\treturn nil, fmt.Errorf(\"invalid start line: %d\", startLine)\n\t}\n\tif endLine < 0 || endLine >= len(lines) {\n\t\tendLine = len(lines) - 1\n\t}\n\n\t// Create result slice with initial capacity\n\tresult := make([]string, 0, len(lines))\n\n\t// Copy lines before edit\n\tresult = append(result, lines[:startLine]...)\n\n\t// Get the prefix of the start line\n\tstartLineContent := lines[startLine]\n\tif startChar < 0 || startChar > len(startLineContent) {\n\t\tstartChar = len(startLineContent)\n\t}\n\tprefix := startLineContent[:startChar]\n\n\t// Get the suffix of the end line\n\tendLineContent := lines[endLine]\n\tif endChar < 0 || endChar > len(endLineContent) {\n\t\tendChar = len(endLineContent)\n\t}\n\tsuffix := endLineContent[endChar:]\n\n\t// Handle the edit\n\tif edit.NewText == \"\" {\n\t\tif prefix+suffix != \"\" {\n\t\t\tresult = append(result, prefix+suffix)\n\t\t}\n\t} else {\n\t\t// Split new text into lines, being careful not to add extra newlines\n\t\t// newLines := strings.Split(strings.TrimRight(edit.NewText, \"\\n\"), \"\\n\")\n\t\tnewLines := strings.Split(edit.NewText, \"\\n\")\n\n\t\tif len(newLines) == 1 {\n\t\t\t// Single line change\n\t\t\tresult = append(result, prefix+newLines[0]+suffix)\n\t\t} else {\n\t\t\t// Multi-line change\n\t\t\tresult = append(result, prefix+newLines[0])\n\t\t\tresult = append(result, newLines[1:len(newLines)-1]...)\n\t\t\tresult = append(result, newLines[len(newLines)-1]+suffix)\n\t\t}\n\t}\n\n\t// Add remaining lines\n\tif endLine+1 < len(lines) {\n\t\tresult = append(result, lines[endLine+1:]...)\n\t}\n\n\treturn result, nil\n}\n\n// applyDocumentChange applies a DocumentChange (create/rename/delete operations)\nfunc applyDocumentChange(change protocol.DocumentChange) error {\n\tif change.CreateFile != nil {\n\t\tpath := strings.TrimPrefix(string(change.CreateFile.URI), \"file://\")\n\t\tif change.CreateFile.Options != nil {\n\t\t\tif change.CreateFile.Options.Overwrite {\n\t\t\t\t// Proceed with overwrite\n\t\t\t} else if change.CreateFile.Options.IgnoreIfExists {\n\t\t\t\tif _, err := os.Stat(path); err == nil {\n\t\t\t\t\treturn nil // File exists and we're ignoring it\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif err := os.WriteFile(path, []byte(\"\"), 0o644); err != nil {\n\t\t\treturn fmt.Errorf(\"failed to create file: %w\", err)\n\t\t}\n\t}\n\n\tif change.DeleteFile != nil {\n\t\tpath := strings.TrimPrefix(string(change.DeleteFile.URI), \"file://\")\n\t\tif change.DeleteFile.Options != nil && change.DeleteFile.Options.Recursive {\n\t\t\tif err := os.RemoveAll(path); err != nil {\n\t\t\t\treturn fmt.Errorf(\"failed to delete directory recursively: %w\", err)\n\t\t\t}\n\t\t} else {\n\t\t\tif err := os.Remove(path); err != nil {\n\t\t\t\treturn fmt.Errorf(\"failed to delete file: %w\", err)\n\t\t\t}\n\t\t}\n\t}\n\n\tif change.RenameFile != nil {\n\t\toldPath := strings.TrimPrefix(string(change.RenameFile.OldURI), \"file://\")\n\t\tnewPath := strings.TrimPrefix(string(change.RenameFile.NewURI), \"file://\")\n\t\tif change.RenameFile.Options != nil {\n\t\t\tif !change.RenameFile.Options.Overwrite {\n\t\t\t\tif _, err := os.Stat(newPath); err == nil {\n\t\t\t\t\treturn fmt.Errorf(\"target file already exists and overwrite is not allowed: %s\", newPath)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif err := os.Rename(oldPath, newPath); err != nil {\n\t\t\treturn fmt.Errorf(\"failed to rename file: %w\", err)\n\t\t}\n\t}\n\n\tif change.TextDocumentEdit != nil {\n\t\ttextEdits := make([]protocol.TextEdit, len(change.TextDocumentEdit.Edits))\n\t\tfor i, edit := range change.TextDocumentEdit.Edits {\n\t\t\tvar err error\n\t\t\ttextEdits[i], err = edit.AsTextEdit()\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"invalid edit type: %w\", err)\n\t\t\t}\n\t\t}\n\t\treturn applyTextEdits(change.TextDocumentEdit.TextDocument.URI, textEdits)\n\t}\n\n\treturn nil\n}\n\n// ApplyWorkspaceEdit applies the given WorkspaceEdit to the filesystem\nfunc ApplyWorkspaceEdit(edit protocol.WorkspaceEdit) error {\n\t// Handle Changes field\n\tfor uri, textEdits := range edit.Changes {\n\t\tif err := applyTextEdits(uri, textEdits); err != nil {\n\t\t\treturn fmt.Errorf(\"failed to apply text edits: %w\", err)\n\t\t}\n\t}\n\n\t// Handle DocumentChanges field\n\tfor _, change := range edit.DocumentChanges {\n\t\tif err := applyDocumentChange(change); err != nil {\n\t\t\treturn fmt.Errorf(\"failed to apply document change: %w\", err)\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc rangesOverlap(r1, r2 protocol.Range) bool {\n\tif r1.Start.Line > r2.End.Line || r2.Start.Line > r1.End.Line {\n\t\treturn false\n\t}\n\tif r1.Start.Line == r2.End.Line && r1.Start.Character > r2.End.Character {\n\t\treturn false\n\t}\n\tif r2.Start.Line == r1.End.Line && r2.Start.Character > r1.End.Character {\n\t\treturn false\n\t}\n\treturn true\n}\n"], ["/opencode/internal/llm/provider/bedrock.go", "package provider\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"os\"\n\t\"strings\"\n\n\t\"github.com/opencode-ai/opencode/internal/llm/tools\"\n\t\"github.com/opencode-ai/opencode/internal/message\"\n)\n\ntype bedrockOptions struct {\n\t// Bedrock specific options can be added here\n}\n\ntype BedrockOption func(*bedrockOptions)\n\ntype bedrockClient struct {\n\tproviderOptions providerClientOptions\n\toptions bedrockOptions\n\tchildProvider ProviderClient\n}\n\ntype BedrockClient ProviderClient\n\nfunc newBedrockClient(opts providerClientOptions) BedrockClient {\n\tbedrockOpts := bedrockOptions{}\n\t// Apply bedrock specific options if they are added in the future\n\n\t// Get AWS region from environment\n\tregion := os.Getenv(\"AWS_REGION\")\n\tif region == \"\" {\n\t\tregion = os.Getenv(\"AWS_DEFAULT_REGION\")\n\t}\n\n\tif region == \"\" {\n\t\tregion = \"us-east-1\" // default region\n\t}\n\tif len(region) < 2 {\n\t\treturn &bedrockClient{\n\t\t\tproviderOptions: opts,\n\t\t\toptions: bedrockOpts,\n\t\t\tchildProvider: nil, // Will cause an error when used\n\t\t}\n\t}\n\n\t// Prefix the model name with region\n\tregionPrefix := region[:2]\n\tmodelName := opts.model.APIModel\n\topts.model.APIModel = fmt.Sprintf(\"%s.%s\", regionPrefix, modelName)\n\n\t// Determine which provider to use based on the model\n\tif strings.Contains(string(opts.model.APIModel), \"anthropic\") {\n\t\t// Create Anthropic client with Bedrock configuration\n\t\tanthropicOpts := opts\n\t\tanthropicOpts.anthropicOptions = append(anthropicOpts.anthropicOptions,\n\t\t\tWithAnthropicBedrock(true),\n\t\t\tWithAnthropicDisableCache(),\n\t\t)\n\t\treturn &bedrockClient{\n\t\t\tproviderOptions: opts,\n\t\t\toptions: bedrockOpts,\n\t\t\tchildProvider: newAnthropicClient(anthropicOpts),\n\t\t}\n\t}\n\n\t// Return client with nil childProvider if model is not supported\n\t// This will cause an error when used\n\treturn &bedrockClient{\n\t\tproviderOptions: opts,\n\t\toptions: bedrockOpts,\n\t\tchildProvider: nil,\n\t}\n}\n\nfunc (b *bedrockClient) send(ctx context.Context, messages []message.Message, tools []tools.BaseTool) (*ProviderResponse, error) {\n\tif b.childProvider == nil {\n\t\treturn nil, errors.New(\"unsupported model for bedrock provider\")\n\t}\n\treturn b.childProvider.send(ctx, messages, tools)\n}\n\nfunc (b *bedrockClient) stream(ctx context.Context, messages []message.Message, tools []tools.BaseTool) <-chan ProviderEvent {\n\teventChan := make(chan ProviderEvent)\n\n\tif b.childProvider == nil {\n\t\tgo func() {\n\t\t\teventChan <- ProviderEvent{\n\t\t\t\tType: EventError,\n\t\t\t\tError: errors.New(\"unsupported model for bedrock provider\"),\n\t\t\t}\n\t\t\tclose(eventChan)\n\t\t}()\n\t\treturn eventChan\n\t}\n\n\treturn b.childProvider.stream(ctx, messages, tools)\n}\n\n"], ["/opencode/internal/permission/permission.go", "package permission\n\nimport (\n\t\"errors\"\n\t\"path/filepath\"\n\t\"slices\"\n\t\"sync\"\n\n\t\"github.com/google/uuid\"\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/pubsub\"\n)\n\nvar ErrorPermissionDenied = errors.New(\"permission denied\")\n\ntype CreatePermissionRequest struct {\n\tSessionID string `json:\"session_id\"`\n\tToolName string `json:\"tool_name\"`\n\tDescription string `json:\"description\"`\n\tAction string `json:\"action\"`\n\tParams any `json:\"params\"`\n\tPath string `json:\"path\"`\n}\n\ntype PermissionRequest struct {\n\tID string `json:\"id\"`\n\tSessionID string `json:\"session_id\"`\n\tToolName string `json:\"tool_name\"`\n\tDescription string `json:\"description\"`\n\tAction string `json:\"action\"`\n\tParams any `json:\"params\"`\n\tPath string `json:\"path\"`\n}\n\ntype Service interface {\n\tpubsub.Suscriber[PermissionRequest]\n\tGrantPersistant(permission PermissionRequest)\n\tGrant(permission PermissionRequest)\n\tDeny(permission PermissionRequest)\n\tRequest(opts CreatePermissionRequest) bool\n\tAutoApproveSession(sessionID string)\n}\n\ntype permissionService struct {\n\t*pubsub.Broker[PermissionRequest]\n\n\tsessionPermissions []PermissionRequest\n\tpendingRequests sync.Map\n\tautoApproveSessions []string\n}\n\nfunc (s *permissionService) GrantPersistant(permission PermissionRequest) {\n\trespCh, ok := s.pendingRequests.Load(permission.ID)\n\tif ok {\n\t\trespCh.(chan bool) <- true\n\t}\n\ts.sessionPermissions = append(s.sessionPermissions, permission)\n}\n\nfunc (s *permissionService) Grant(permission PermissionRequest) {\n\trespCh, ok := s.pendingRequests.Load(permission.ID)\n\tif ok {\n\t\trespCh.(chan bool) <- true\n\t}\n}\n\nfunc (s *permissionService) Deny(permission PermissionRequest) {\n\trespCh, ok := s.pendingRequests.Load(permission.ID)\n\tif ok {\n\t\trespCh.(chan bool) <- false\n\t}\n}\n\nfunc (s *permissionService) Request(opts CreatePermissionRequest) bool {\n\tif slices.Contains(s.autoApproveSessions, opts.SessionID) {\n\t\treturn true\n\t}\n\tdir := filepath.Dir(opts.Path)\n\tif dir == \".\" {\n\t\tdir = config.WorkingDirectory()\n\t}\n\tpermission := PermissionRequest{\n\t\tID: uuid.New().String(),\n\t\tPath: dir,\n\t\tSessionID: opts.SessionID,\n\t\tToolName: opts.ToolName,\n\t\tDescription: opts.Description,\n\t\tAction: opts.Action,\n\t\tParams: opts.Params,\n\t}\n\n\tfor _, p := range s.sessionPermissions {\n\t\tif p.ToolName == permission.ToolName && p.Action == permission.Action && p.SessionID == permission.SessionID && p.Path == permission.Path {\n\t\t\treturn true\n\t\t}\n\t}\n\n\trespCh := make(chan bool, 1)\n\n\ts.pendingRequests.Store(permission.ID, respCh)\n\tdefer s.pendingRequests.Delete(permission.ID)\n\n\ts.Publish(pubsub.CreatedEvent, permission)\n\n\t// Wait for the response with a timeout\n\tresp := <-respCh\n\treturn resp\n}\n\nfunc (s *permissionService) AutoApproveSession(sessionID string) {\n\ts.autoApproveSessions = append(s.autoApproveSessions, sessionID)\n}\n\nfunc NewPermissionService() Service {\n\treturn &permissionService{\n\t\tBroker: pubsub.NewBroker[PermissionRequest](),\n\t\tsessionPermissions: make([]PermissionRequest, 0),\n\t}\n}\n"], ["/opencode/internal/llm/agent/agent-tool.go", "package agent\n\nimport (\n\t\"context\"\n\t\"encoding/json\"\n\t\"fmt\"\n\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/llm/tools\"\n\t\"github.com/opencode-ai/opencode/internal/lsp\"\n\t\"github.com/opencode-ai/opencode/internal/message\"\n\t\"github.com/opencode-ai/opencode/internal/session\"\n)\n\ntype agentTool struct {\n\tsessions session.Service\n\tmessages message.Service\n\tlspClients map[string]*lsp.Client\n}\n\nconst (\n\tAgentToolName = \"agent\"\n)\n\ntype AgentParams struct {\n\tPrompt string `json:\"prompt\"`\n}\n\nfunc (b *agentTool) Info() tools.ToolInfo {\n\treturn tools.ToolInfo{\n\t\tName: AgentToolName,\n\t\tDescription: \"Launch a new agent that has access to the following tools: GlobTool, GrepTool, LS, View. When you are searching for a keyword or file and are not confident that you will find the right match on the first try, use the Agent tool to perform the search for you. For example:\\n\\n- If you are searching for a keyword like \\\"config\\\" or \\\"logger\\\", or for questions like \\\"which file does X?\\\", the Agent tool is strongly recommended\\n- If you want to read a specific file path, use the View or GlobTool tool instead of the Agent tool, to find the match more quickly\\n- If you are searching for a specific class definition like \\\"class Foo\\\", use the GlobTool tool instead, to find the match more quickly\\n\\nUsage notes:\\n1. Launch multiple agents concurrently whenever possible, to maximize performance; to do that, use a single message with multiple tool uses\\n2. When the agent is done, it will return a single message back to you. The result returned by the agent is not visible to the user. To show the user the result, you should send a text message back to the user with a concise summary of the result.\\n3. Each agent invocation is stateless. You will not be able to send additional messages to the agent, nor will the agent be able to communicate with you outside of its final report. Therefore, your prompt should contain a highly detailed task description for the agent to perform autonomously and you should specify exactly what information the agent should return back to you in its final and only message to you.\\n4. The agent's outputs should generally be trusted\\n5. IMPORTANT: The agent can not use Bash, Replace, Edit, so can not modify files. If you want to use these tools, use them directly instead of going through the agent.\",\n\t\tParameters: map[string]any{\n\t\t\t\"prompt\": map[string]any{\n\t\t\t\t\"type\": \"string\",\n\t\t\t\t\"description\": \"The task for the agent to perform\",\n\t\t\t},\n\t\t},\n\t\tRequired: []string{\"prompt\"},\n\t}\n}\n\nfunc (b *agentTool) Run(ctx context.Context, call tools.ToolCall) (tools.ToolResponse, error) {\n\tvar params AgentParams\n\tif err := json.Unmarshal([]byte(call.Input), ¶ms); err != nil {\n\t\treturn tools.NewTextErrorResponse(fmt.Sprintf(\"error parsing parameters: %s\", err)), nil\n\t}\n\tif params.Prompt == \"\" {\n\t\treturn tools.NewTextErrorResponse(\"prompt is required\"), nil\n\t}\n\n\tsessionID, messageID := tools.GetContextValues(ctx)\n\tif sessionID == \"\" || messageID == \"\" {\n\t\treturn tools.ToolResponse{}, fmt.Errorf(\"session_id and message_id are required\")\n\t}\n\n\tagent, err := NewAgent(config.AgentTask, b.sessions, b.messages, TaskAgentTools(b.lspClients))\n\tif err != nil {\n\t\treturn tools.ToolResponse{}, fmt.Errorf(\"error creating agent: %s\", err)\n\t}\n\n\tsession, err := b.sessions.CreateTaskSession(ctx, call.ID, sessionID, \"New Agent Session\")\n\tif err != nil {\n\t\treturn tools.ToolResponse{}, fmt.Errorf(\"error creating session: %s\", err)\n\t}\n\n\tdone, err := agent.Run(ctx, session.ID, params.Prompt)\n\tif err != nil {\n\t\treturn tools.ToolResponse{}, fmt.Errorf(\"error generating agent: %s\", err)\n\t}\n\tresult := <-done\n\tif result.Error != nil {\n\t\treturn tools.ToolResponse{}, fmt.Errorf(\"error generating agent: %s\", result.Error)\n\t}\n\n\tresponse := result.Message\n\tif response.Role != message.Assistant {\n\t\treturn tools.NewTextErrorResponse(\"no response\"), nil\n\t}\n\n\tupdatedSession, err := b.sessions.Get(ctx, session.ID)\n\tif err != nil {\n\t\treturn tools.ToolResponse{}, fmt.Errorf(\"error getting session: %s\", err)\n\t}\n\tparentSession, err := b.sessions.Get(ctx, sessionID)\n\tif err != nil {\n\t\treturn tools.ToolResponse{}, fmt.Errorf(\"error getting parent session: %s\", err)\n\t}\n\n\tparentSession.Cost += updatedSession.Cost\n\n\t_, err = b.sessions.Save(ctx, parentSession)\n\tif err != nil {\n\t\treturn tools.ToolResponse{}, fmt.Errorf(\"error saving parent session: %s\", err)\n\t}\n\treturn tools.NewTextResponse(response.Content().String()), nil\n}\n\nfunc NewAgentTool(\n\tSessions session.Service,\n\tMessages message.Service,\n\tLspClients map[string]*lsp.Client,\n) tools.BaseTool {\n\treturn &agentTool{\n\t\tsessions: Sessions,\n\t\tmessages: Messages,\n\t\tlspClients: LspClients,\n\t}\n}\n"], ["/opencode/internal/tui/util/util.go", "package util\n\nimport (\n\t\"time\"\n\n\ttea \"github.com/charmbracelet/bubbletea\"\n)\n\nfunc CmdHandler(msg tea.Msg) tea.Cmd {\n\treturn func() tea.Msg {\n\t\treturn msg\n\t}\n}\n\nfunc ReportError(err error) tea.Cmd {\n\treturn CmdHandler(InfoMsg{\n\t\tType: InfoTypeError,\n\t\tMsg: err.Error(),\n\t})\n}\n\ntype InfoType int\n\nconst (\n\tInfoTypeInfo InfoType = iota\n\tInfoTypeWarn\n\tInfoTypeError\n)\n\nfunc ReportInfo(info string) tea.Cmd {\n\treturn CmdHandler(InfoMsg{\n\t\tType: InfoTypeInfo,\n\t\tMsg: info,\n\t})\n}\n\nfunc ReportWarn(warn string) tea.Cmd {\n\treturn CmdHandler(InfoMsg{\n\t\tType: InfoTypeWarn,\n\t\tMsg: warn,\n\t})\n}\n\ntype (\n\tInfoMsg struct {\n\t\tType InfoType\n\t\tMsg string\n\t\tTTL time.Duration\n\t}\n\tClearStatusMsg struct{}\n)\n\nfunc Clamp(v, low, high int) int {\n\tif high < low {\n\t\tlow, high = high, low\n\t}\n\treturn min(high, max(low, v))\n}\n"], ["/opencode/internal/tui/theme/catppuccin.go", "package theme\n\nimport (\n\tcatppuccin \"github.com/catppuccin/go\"\n\t\"github.com/charmbracelet/lipgloss\"\n)\n\n// CatppuccinTheme implements the Theme interface with Catppuccin colors.\n// It provides both dark (Mocha) and light (Latte) variants.\ntype CatppuccinTheme struct {\n\tBaseTheme\n}\n\n// NewCatppuccinTheme creates a new instance of the Catppuccin theme.\nfunc NewCatppuccinTheme() *CatppuccinTheme {\n\t// Get the Catppuccin palettes\n\tmocha := catppuccin.Mocha\n\tlatte := catppuccin.Latte\n\n\ttheme := &CatppuccinTheme{}\n\n\t// Base colors\n\ttheme.PrimaryColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Blue().Hex,\n\t\tLight: latte.Blue().Hex,\n\t}\n\ttheme.SecondaryColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Mauve().Hex,\n\t\tLight: latte.Mauve().Hex,\n\t}\n\ttheme.AccentColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Peach().Hex,\n\t\tLight: latte.Peach().Hex,\n\t}\n\n\t// Status colors\n\ttheme.ErrorColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Red().Hex,\n\t\tLight: latte.Red().Hex,\n\t}\n\ttheme.WarningColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Peach().Hex,\n\t\tLight: latte.Peach().Hex,\n\t}\n\ttheme.SuccessColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Green().Hex,\n\t\tLight: latte.Green().Hex,\n\t}\n\ttheme.InfoColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Blue().Hex,\n\t\tLight: latte.Blue().Hex,\n\t}\n\n\t// Text colors\n\ttheme.TextColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Text().Hex,\n\t\tLight: latte.Text().Hex,\n\t}\n\ttheme.TextMutedColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Subtext0().Hex,\n\t\tLight: latte.Subtext0().Hex,\n\t}\n\ttheme.TextEmphasizedColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Lavender().Hex,\n\t\tLight: latte.Lavender().Hex,\n\t}\n\n\t// Background colors\n\ttheme.BackgroundColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#212121\", // From existing styles\n\t\tLight: \"#EEEEEE\", // Light equivalent\n\t}\n\ttheme.BackgroundSecondaryColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#2c2c2c\", // From existing styles\n\t\tLight: \"#E0E0E0\", // Light equivalent\n\t}\n\ttheme.BackgroundDarkerColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#181818\", // From existing styles\n\t\tLight: \"#F5F5F5\", // Light equivalent\n\t}\n\n\t// Border colors\n\ttheme.BorderNormalColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#4b4c5c\", // From existing styles\n\t\tLight: \"#BDBDBD\", // Light equivalent\n\t}\n\ttheme.BorderFocusedColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Blue().Hex,\n\t\tLight: latte.Blue().Hex,\n\t}\n\ttheme.BorderDimColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Surface0().Hex,\n\t\tLight: latte.Surface0().Hex,\n\t}\n\n\t// Diff view colors\n\ttheme.DiffAddedColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#478247\", // From existing diff.go\n\t\tLight: \"#2E7D32\", // Light equivalent\n\t}\n\ttheme.DiffRemovedColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#7C4444\", // From existing diff.go\n\t\tLight: \"#C62828\", // Light equivalent\n\t}\n\ttheme.DiffContextColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#a0a0a0\", // From existing diff.go\n\t\tLight: \"#757575\", // Light equivalent\n\t}\n\ttheme.DiffHunkHeaderColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#a0a0a0\", // From existing diff.go\n\t\tLight: \"#757575\", // Light equivalent\n\t}\n\ttheme.DiffHighlightAddedColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#DAFADA\", // From existing diff.go\n\t\tLight: \"#A5D6A7\", // Light equivalent\n\t}\n\ttheme.DiffHighlightRemovedColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#FADADD\", // From existing diff.go\n\t\tLight: \"#EF9A9A\", // Light equivalent\n\t}\n\ttheme.DiffAddedBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#303A30\", // From existing diff.go\n\t\tLight: \"#E8F5E9\", // Light equivalent\n\t}\n\ttheme.DiffRemovedBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#3A3030\", // From existing diff.go\n\t\tLight: \"#FFEBEE\", // Light equivalent\n\t}\n\ttheme.DiffContextBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#212121\", // From existing diff.go\n\t\tLight: \"#F5F5F5\", // Light equivalent\n\t}\n\ttheme.DiffLineNumberColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#888888\", // From existing diff.go\n\t\tLight: \"#9E9E9E\", // Light equivalent\n\t}\n\ttheme.DiffAddedLineNumberBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#293229\", // From existing diff.go\n\t\tLight: \"#C8E6C9\", // Light equivalent\n\t}\n\ttheme.DiffRemovedLineNumberBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#332929\", // From existing diff.go\n\t\tLight: \"#FFCDD2\", // Light equivalent\n\t}\n\n\t// Markdown colors\n\ttheme.MarkdownTextColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Text().Hex,\n\t\tLight: latte.Text().Hex,\n\t}\n\ttheme.MarkdownHeadingColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Mauve().Hex,\n\t\tLight: latte.Mauve().Hex,\n\t}\n\ttheme.MarkdownLinkColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Sky().Hex,\n\t\tLight: latte.Sky().Hex,\n\t}\n\ttheme.MarkdownLinkTextColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Pink().Hex,\n\t\tLight: latte.Pink().Hex,\n\t}\n\ttheme.MarkdownCodeColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Green().Hex,\n\t\tLight: latte.Green().Hex,\n\t}\n\ttheme.MarkdownBlockQuoteColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Yellow().Hex,\n\t\tLight: latte.Yellow().Hex,\n\t}\n\ttheme.MarkdownEmphColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Yellow().Hex,\n\t\tLight: latte.Yellow().Hex,\n\t}\n\ttheme.MarkdownStrongColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Peach().Hex,\n\t\tLight: latte.Peach().Hex,\n\t}\n\ttheme.MarkdownHorizontalRuleColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Overlay0().Hex,\n\t\tLight: latte.Overlay0().Hex,\n\t}\n\ttheme.MarkdownListItemColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Blue().Hex,\n\t\tLight: latte.Blue().Hex,\n\t}\n\ttheme.MarkdownListEnumerationColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Sky().Hex,\n\t\tLight: latte.Sky().Hex,\n\t}\n\ttheme.MarkdownImageColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Sapphire().Hex,\n\t\tLight: latte.Sapphire().Hex,\n\t}\n\ttheme.MarkdownImageTextColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Pink().Hex,\n\t\tLight: latte.Pink().Hex,\n\t}\n\ttheme.MarkdownCodeBlockColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Text().Hex,\n\t\tLight: latte.Text().Hex,\n\t}\n\n\t// Syntax highlighting colors\n\ttheme.SyntaxCommentColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Overlay1().Hex,\n\t\tLight: latte.Overlay1().Hex,\n\t}\n\ttheme.SyntaxKeywordColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Pink().Hex,\n\t\tLight: latte.Pink().Hex,\n\t}\n\ttheme.SyntaxFunctionColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Green().Hex,\n\t\tLight: latte.Green().Hex,\n\t}\n\ttheme.SyntaxVariableColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Sky().Hex,\n\t\tLight: latte.Sky().Hex,\n\t}\n\ttheme.SyntaxStringColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Yellow().Hex,\n\t\tLight: latte.Yellow().Hex,\n\t}\n\ttheme.SyntaxNumberColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Teal().Hex,\n\t\tLight: latte.Teal().Hex,\n\t}\n\ttheme.SyntaxTypeColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Sky().Hex,\n\t\tLight: latte.Sky().Hex,\n\t}\n\ttheme.SyntaxOperatorColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Pink().Hex,\n\t\tLight: latte.Pink().Hex,\n\t}\n\ttheme.SyntaxPunctuationColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Text().Hex,\n\t\tLight: latte.Text().Hex,\n\t}\n\n\treturn theme\n}\n\nfunc init() {\n\t// Register the Catppuccin theme with the theme manager\n\tRegisterTheme(\"catppuccin\", NewCatppuccinTheme())\n}"], ["/opencode/internal/logging/logger.go", "package logging\n\nimport (\n\t\"fmt\"\n\t\"log/slog\"\n\t\"os\"\n\t// \"path/filepath\"\n\t\"encoding/json\"\n\t\"runtime\"\n\t\"runtime/debug\"\n\t\"sync\"\n\t\"time\"\n)\n\nfunc getCaller() string {\n\tvar caller string\n\tif _, file, line, ok := runtime.Caller(2); ok {\n\t\t// caller = fmt.Sprintf(\"%s:%d\", filepath.Base(file), line)\n\t\tcaller = fmt.Sprintf(\"%s:%d\", file, line)\n\t} else {\n\t\tcaller = \"unknown\"\n\t}\n\treturn caller\n}\nfunc Info(msg string, args ...any) {\n\tsource := getCaller()\n\tslog.Info(msg, append([]any{\"source\", source}, args...)...)\n}\n\nfunc Debug(msg string, args ...any) {\n\t// slog.Debug(msg, args...)\n\tsource := getCaller()\n\tslog.Debug(msg, append([]any{\"source\", source}, args...)...)\n}\n\nfunc Warn(msg string, args ...any) {\n\tslog.Warn(msg, args...)\n}\n\nfunc Error(msg string, args ...any) {\n\tslog.Error(msg, args...)\n}\n\nfunc InfoPersist(msg string, args ...any) {\n\targs = append(args, persistKeyArg, true)\n\tslog.Info(msg, args...)\n}\n\nfunc DebugPersist(msg string, args ...any) {\n\targs = append(args, persistKeyArg, true)\n\tslog.Debug(msg, args...)\n}\n\nfunc WarnPersist(msg string, args ...any) {\n\targs = append(args, persistKeyArg, true)\n\tslog.Warn(msg, args...)\n}\n\nfunc ErrorPersist(msg string, args ...any) {\n\targs = append(args, persistKeyArg, true)\n\tslog.Error(msg, args...)\n}\n\n// RecoverPanic is a common function to handle panics gracefully.\n// It logs the error, creates a panic log file with stack trace,\n// and executes an optional cleanup function before returning.\nfunc RecoverPanic(name string, cleanup func()) {\n\tif r := recover(); r != nil {\n\t\t// Log the panic\n\t\tErrorPersist(fmt.Sprintf(\"Panic in %s: %v\", name, r))\n\n\t\t// Create a timestamped panic log file\n\t\ttimestamp := time.Now().Format(\"20060102-150405\")\n\t\tfilename := fmt.Sprintf(\"opencode-panic-%s-%s.log\", name, timestamp)\n\n\t\tfile, err := os.Create(filename)\n\t\tif err != nil {\n\t\t\tErrorPersist(fmt.Sprintf(\"Failed to create panic log: %v\", err))\n\t\t} else {\n\t\t\tdefer file.Close()\n\n\t\t\t// Write panic information and stack trace\n\t\t\tfmt.Fprintf(file, \"Panic in %s: %v\\n\\n\", name, r)\n\t\t\tfmt.Fprintf(file, \"Time: %s\\n\\n\", time.Now().Format(time.RFC3339))\n\t\t\tfmt.Fprintf(file, \"Stack Trace:\\n%s\\n\", debug.Stack())\n\n\t\t\tInfoPersist(fmt.Sprintf(\"Panic details written to %s\", filename))\n\t\t}\n\n\t\t// Execute cleanup function if provided\n\t\tif cleanup != nil {\n\t\t\tcleanup()\n\t\t}\n\t}\n}\n\n// Message Logging for Debug\nvar MessageDir string\n\nfunc GetSessionPrefix(sessionId string) string {\n\treturn sessionId[:8]\n}\n\nvar sessionLogMutex sync.Mutex\n\nfunc AppendToSessionLogFile(sessionId string, filename string, content string) string {\n\tif MessageDir == \"\" || sessionId == \"\" {\n\t\treturn \"\"\n\t}\n\tsessionPrefix := GetSessionPrefix(sessionId)\n\n\tsessionLogMutex.Lock()\n\tdefer sessionLogMutex.Unlock()\n\n\tsessionPath := fmt.Sprintf(\"%s/%s\", MessageDir, sessionPrefix)\n\tif _, err := os.Stat(sessionPath); os.IsNotExist(err) {\n\t\tif err := os.MkdirAll(sessionPath, 0o766); err != nil {\n\t\t\tError(\"Failed to create session directory\", \"dirpath\", sessionPath, \"error\", err)\n\t\t\treturn \"\"\n\t\t}\n\t}\n\n\tfilePath := fmt.Sprintf(\"%s/%s\", sessionPath, filename)\n\n\tf, err := os.OpenFile(filePath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)\n\tif err != nil {\n\t\tError(\"Failed to open session log file\", \"filepath\", filePath, \"error\", err)\n\t\treturn \"\"\n\t}\n\tdefer f.Close()\n\n\t// Append chunk to file\n\t_, err = f.WriteString(content)\n\tif err != nil {\n\t\tError(\"Failed to write chunk to session log file\", \"filepath\", filePath, \"error\", err)\n\t\treturn \"\"\n\t}\n\treturn filePath\n}\n\nfunc WriteRequestMessageJson(sessionId string, requestSeqId int, message any) string {\n\tif MessageDir == \"\" || sessionId == \"\" || requestSeqId <= 0 {\n\t\treturn \"\"\n\t}\n\tmsgJson, err := json.Marshal(message)\n\tif err != nil {\n\t\tError(\"Failed to marshal message\", \"session_id\", sessionId, \"request_seq_id\", requestSeqId, \"error\", err)\n\t\treturn \"\"\n\t}\n\treturn WriteRequestMessage(sessionId, requestSeqId, string(msgJson))\n}\n\nfunc WriteRequestMessage(sessionId string, requestSeqId int, message string) string {\n\tif MessageDir == \"\" || sessionId == \"\" || requestSeqId <= 0 {\n\t\treturn \"\"\n\t}\n\tfilename := fmt.Sprintf(\"%d_request.json\", requestSeqId)\n\n\treturn AppendToSessionLogFile(sessionId, filename, message)\n}\n\nfunc AppendToStreamSessionLogJson(sessionId string, requestSeqId int, jsonableChunk any) string {\n\tif MessageDir == \"\" || sessionId == \"\" || requestSeqId <= 0 {\n\t\treturn \"\"\n\t}\n\tchunkJson, err := json.Marshal(jsonableChunk)\n\tif err != nil {\n\t\tError(\"Failed to marshal message\", \"session_id\", sessionId, \"request_seq_id\", requestSeqId, \"error\", err)\n\t\treturn \"\"\n\t}\n\treturn AppendToStreamSessionLog(sessionId, requestSeqId, string(chunkJson))\n}\n\nfunc AppendToStreamSessionLog(sessionId string, requestSeqId int, chunk string) string {\n\tif MessageDir == \"\" || sessionId == \"\" || requestSeqId <= 0 {\n\t\treturn \"\"\n\t}\n\tfilename := fmt.Sprintf(\"%d_response_stream.log\", requestSeqId)\n\treturn AppendToSessionLogFile(sessionId, filename, chunk)\n}\n\nfunc WriteChatResponseJson(sessionId string, requestSeqId int, response any) string {\n\tif MessageDir == \"\" || sessionId == \"\" || requestSeqId <= 0 {\n\t\treturn \"\"\n\t}\n\tresponseJson, err := json.Marshal(response)\n\tif err != nil {\n\t\tError(\"Failed to marshal response\", \"session_id\", sessionId, \"request_seq_id\", requestSeqId, \"error\", err)\n\t\treturn \"\"\n\t}\n\tfilename := fmt.Sprintf(\"%d_response.json\", requestSeqId)\n\n\treturn AppendToSessionLogFile(sessionId, filename, string(responseJson))\n}\n\nfunc WriteToolResultsJson(sessionId string, requestSeqId int, toolResults any) string {\n\tif MessageDir == \"\" || sessionId == \"\" || requestSeqId <= 0 {\n\t\treturn \"\"\n\t}\n\ttoolResultsJson, err := json.Marshal(toolResults)\n\tif err != nil {\n\t\tError(\"Failed to marshal tool results\", \"session_id\", sessionId, \"request_seq_id\", requestSeqId, \"error\", err)\n\t\treturn \"\"\n\t}\n\tfilename := fmt.Sprintf(\"%d_tool_results.json\", requestSeqId)\n\treturn AppendToSessionLogFile(sessionId, filename, string(toolResultsJson))\n}\n"], ["/opencode/internal/llm/provider/azure.go", "package provider\n\nimport (\n\t\"os\"\n\n\t\"github.com/Azure/azure-sdk-for-go/sdk/azidentity\"\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/azure\"\n\t\"github.com/openai/openai-go/option\"\n)\n\ntype azureClient struct {\n\t*openaiClient\n}\n\ntype AzureClient ProviderClient\n\nfunc newAzureClient(opts providerClientOptions) AzureClient {\n\n\tendpoint := os.Getenv(\"AZURE_OPENAI_ENDPOINT\") // ex: https://foo.openai.azure.com\n\tapiVersion := os.Getenv(\"AZURE_OPENAI_API_VERSION\") // ex: 2025-04-01-preview\n\n\tif endpoint == \"\" || apiVersion == \"\" {\n\t\treturn &azureClient{openaiClient: newOpenAIClient(opts).(*openaiClient)}\n\t}\n\n\treqOpts := []option.RequestOption{\n\t\tazure.WithEndpoint(endpoint, apiVersion),\n\t}\n\n\tif opts.apiKey != \"\" || os.Getenv(\"AZURE_OPENAI_API_KEY\") != \"\" {\n\t\tkey := opts.apiKey\n\t\tif key == \"\" {\n\t\t\tkey = os.Getenv(\"AZURE_OPENAI_API_KEY\")\n\t\t}\n\t\treqOpts = append(reqOpts, azure.WithAPIKey(key))\n\t} else if cred, err := azidentity.NewDefaultAzureCredential(nil); err == nil {\n\t\treqOpts = append(reqOpts, azure.WithTokenCredential(cred))\n\t}\n\n\tbase := &openaiClient{\n\t\tproviderOptions: opts,\n\t\tclient: openai.NewClient(reqOpts...),\n\t}\n\n\treturn &azureClient{openaiClient: base}\n}\n"], ["/opencode/internal/tui/theme/flexoki.go", "package theme\n\nimport (\n\t\"github.com/charmbracelet/lipgloss\"\n)\n\n// Flexoki color palette constants\nconst (\n\t// Base colors\n\tflexokiPaper = \"#FFFCF0\" // Paper (lightest)\n\tflexokiBase50 = \"#F2F0E5\" // bg-2 (light)\n\tflexokiBase100 = \"#E6E4D9\" // ui (light)\n\tflexokiBase150 = \"#DAD8CE\" // ui-2 (light)\n\tflexokiBase200 = \"#CECDC3\" // ui-3 (light)\n\tflexokiBase300 = \"#B7B5AC\" // tx-3 (light)\n\tflexokiBase500 = \"#878580\" // tx-2 (light)\n\tflexokiBase600 = \"#6F6E69\" // tx (light)\n\tflexokiBase700 = \"#575653\" // tx-3 (dark)\n\tflexokiBase800 = \"#403E3C\" // ui-3 (dark)\n\tflexokiBase850 = \"#343331\" // ui-2 (dark)\n\tflexokiBase900 = \"#282726\" // ui (dark)\n\tflexokiBase950 = \"#1C1B1A\" // bg-2 (dark)\n\tflexokiBlack = \"#100F0F\" // bg (darkest)\n\n\t// Accent colors - Light theme (600)\n\tflexokiRed600 = \"#AF3029\"\n\tflexokiOrange600 = \"#BC5215\"\n\tflexokiYellow600 = \"#AD8301\"\n\tflexokiGreen600 = \"#66800B\"\n\tflexokiCyan600 = \"#24837B\"\n\tflexokiBlue600 = \"#205EA6\"\n\tflexokiPurple600 = \"#5E409D\"\n\tflexokiMagenta600 = \"#A02F6F\"\n\n\t// Accent colors - Dark theme (400)\n\tflexokiRed400 = \"#D14D41\"\n\tflexokiOrange400 = \"#DA702C\"\n\tflexokiYellow400 = \"#D0A215\"\n\tflexokiGreen400 = \"#879A39\"\n\tflexokiCyan400 = \"#3AA99F\"\n\tflexokiBlue400 = \"#4385BE\"\n\tflexokiPurple400 = \"#8B7EC8\"\n\tflexokiMagenta400 = \"#CE5D97\"\n)\n\n// FlexokiTheme implements the Theme interface with Flexoki colors.\n// It provides both dark and light variants.\ntype FlexokiTheme struct {\n\tBaseTheme\n}\n\n// NewFlexokiTheme creates a new instance of the Flexoki theme.\nfunc NewFlexokiTheme() *FlexokiTheme {\n\ttheme := &FlexokiTheme{}\n\n\t// Base colors\n\ttheme.PrimaryColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiBlue400,\n\t\tLight: flexokiBlue600,\n\t}\n\ttheme.SecondaryColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiPurple400,\n\t\tLight: flexokiPurple600,\n\t}\n\ttheme.AccentColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiOrange400,\n\t\tLight: flexokiOrange600,\n\t}\n\n\t// Status colors\n\ttheme.ErrorColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiRed400,\n\t\tLight: flexokiRed600,\n\t}\n\ttheme.WarningColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiYellow400,\n\t\tLight: flexokiYellow600,\n\t}\n\ttheme.SuccessColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiGreen400,\n\t\tLight: flexokiGreen600,\n\t}\n\ttheme.InfoColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiCyan400,\n\t\tLight: flexokiCyan600,\n\t}\n\n\t// Text colors\n\ttheme.TextColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiBase300,\n\t\tLight: flexokiBase600,\n\t}\n\ttheme.TextMutedColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiBase700,\n\t\tLight: flexokiBase500,\n\t}\n\ttheme.TextEmphasizedColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiYellow400,\n\t\tLight: flexokiYellow600,\n\t}\n\n\t// Background colors\n\ttheme.BackgroundColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiBlack,\n\t\tLight: flexokiPaper,\n\t}\n\ttheme.BackgroundSecondaryColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiBase950,\n\t\tLight: flexokiBase50,\n\t}\n\ttheme.BackgroundDarkerColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiBase900,\n\t\tLight: flexokiBase100,\n\t}\n\n\t// Border colors\n\ttheme.BorderNormalColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiBase900,\n\t\tLight: flexokiBase100,\n\t}\n\ttheme.BorderFocusedColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiBlue400,\n\t\tLight: flexokiBlue600,\n\t}\n\ttheme.BorderDimColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiBase850,\n\t\tLight: flexokiBase150,\n\t}\n\n\t// Diff view colors\n\ttheme.DiffAddedColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiGreen400,\n\t\tLight: flexokiGreen600,\n\t}\n\ttheme.DiffRemovedColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiRed400,\n\t\tLight: flexokiRed600,\n\t}\n\ttheme.DiffContextColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiBase700,\n\t\tLight: flexokiBase500,\n\t}\n\ttheme.DiffHunkHeaderColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiBase700,\n\t\tLight: flexokiBase500,\n\t}\n\ttheme.DiffHighlightAddedColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiGreen400,\n\t\tLight: flexokiGreen600,\n\t}\n\ttheme.DiffHighlightRemovedColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiRed400,\n\t\tLight: flexokiRed600,\n\t}\n\ttheme.DiffAddedBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#1D2419\", // Darker green background\n\t\tLight: \"#EFF2E2\", // Light green background\n\t}\n\ttheme.DiffRemovedBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#241919\", // Darker red background\n\t\tLight: \"#F2E2E2\", // Light red background\n\t}\n\ttheme.DiffContextBgColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiBlack,\n\t\tLight: flexokiPaper,\n\t}\n\ttheme.DiffLineNumberColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiBase700,\n\t\tLight: flexokiBase500,\n\t}\n\ttheme.DiffAddedLineNumberBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#1A2017\", // Slightly darker green\n\t\tLight: \"#E5EBD9\", // Light green\n\t}\n\ttheme.DiffRemovedLineNumberBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#201717\", // Slightly darker red\n\t\tLight: \"#EBD9D9\", // Light red\n\t}\n\n\t// Markdown colors\n\ttheme.MarkdownTextColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiBase300,\n\t\tLight: flexokiBase600,\n\t}\n\ttheme.MarkdownHeadingColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiYellow400,\n\t\tLight: flexokiYellow600,\n\t}\n\ttheme.MarkdownLinkColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiCyan400,\n\t\tLight: flexokiCyan600,\n\t}\n\ttheme.MarkdownLinkTextColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiMagenta400,\n\t\tLight: flexokiMagenta600,\n\t}\n\ttheme.MarkdownCodeColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiGreen400,\n\t\tLight: flexokiGreen600,\n\t}\n\ttheme.MarkdownBlockQuoteColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiCyan400,\n\t\tLight: flexokiCyan600,\n\t}\n\ttheme.MarkdownEmphColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiYellow400,\n\t\tLight: flexokiYellow600,\n\t}\n\ttheme.MarkdownStrongColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiOrange400,\n\t\tLight: flexokiOrange600,\n\t}\n\ttheme.MarkdownHorizontalRuleColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiBase800,\n\t\tLight: flexokiBase200,\n\t}\n\ttheme.MarkdownListItemColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiBlue400,\n\t\tLight: flexokiBlue600,\n\t}\n\ttheme.MarkdownListEnumerationColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiBlue400,\n\t\tLight: flexokiBlue600,\n\t}\n\ttheme.MarkdownImageColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiPurple400,\n\t\tLight: flexokiPurple600,\n\t}\n\ttheme.MarkdownImageTextColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiMagenta400,\n\t\tLight: flexokiMagenta600,\n\t}\n\ttheme.MarkdownCodeBlockColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiBase300,\n\t\tLight: flexokiBase600,\n\t}\n\n\t// Syntax highlighting colors (based on Flexoki's mappings)\n\ttheme.SyntaxCommentColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiBase700, // tx-3\n\t\tLight: flexokiBase300, // tx-3\n\t}\n\ttheme.SyntaxKeywordColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiGreen400, // gr\n\t\tLight: flexokiGreen600, // gr\n\t}\n\ttheme.SyntaxFunctionColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiOrange400, // or\n\t\tLight: flexokiOrange600, // or\n\t}\n\ttheme.SyntaxVariableColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiBlue400, // bl\n\t\tLight: flexokiBlue600, // bl\n\t}\n\ttheme.SyntaxStringColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiCyan400, // cy\n\t\tLight: flexokiCyan600, // cy\n\t}\n\ttheme.SyntaxNumberColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiPurple400, // pu\n\t\tLight: flexokiPurple600, // pu\n\t}\n\ttheme.SyntaxTypeColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiYellow400, // ye\n\t\tLight: flexokiYellow600, // ye\n\t}\n\ttheme.SyntaxOperatorColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiBase500, // tx-2\n\t\tLight: flexokiBase500, // tx-2\n\t}\n\ttheme.SyntaxPunctuationColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiBase500, // tx-2\n\t\tLight: flexokiBase500, // tx-2\n\t}\n\n\treturn theme\n}\n\nfunc init() {\n\t// Register the Flexoki theme with the theme manager\n\tRegisterTheme(\"flexoki\", NewFlexokiTheme())\n}"], ["/opencode/internal/llm/agent/tools.go", "package agent\n\nimport (\n\t\"context\"\n\n\t\"github.com/opencode-ai/opencode/internal/history\"\n\t\"github.com/opencode-ai/opencode/internal/llm/tools\"\n\t\"github.com/opencode-ai/opencode/internal/lsp\"\n\t\"github.com/opencode-ai/opencode/internal/message\"\n\t\"github.com/opencode-ai/opencode/internal/permission\"\n\t\"github.com/opencode-ai/opencode/internal/session\"\n)\n\nfunc CoderAgentTools(\n\tpermissions permission.Service,\n\tsessions session.Service,\n\tmessages message.Service,\n\thistory history.Service,\n\tlspClients map[string]*lsp.Client,\n) []tools.BaseTool {\n\tctx := context.Background()\n\totherTools := GetMcpTools(ctx, permissions)\n\tif len(lspClients) > 0 {\n\t\totherTools = append(otherTools, tools.NewDiagnosticsTool(lspClients))\n\t}\n\treturn append(\n\t\t[]tools.BaseTool{\n\t\t\ttools.NewBashTool(permissions),\n\t\t\ttools.NewEditTool(lspClients, permissions, history),\n\t\t\ttools.NewFetchTool(permissions),\n\t\t\ttools.NewGlobTool(),\n\t\t\ttools.NewGrepTool(),\n\t\t\ttools.NewLsTool(),\n\t\t\ttools.NewSourcegraphTool(),\n\t\t\ttools.NewViewTool(lspClients),\n\t\t\ttools.NewPatchTool(lspClients, permissions, history),\n\t\t\ttools.NewWriteTool(lspClients, permissions, history),\n\t\t\tNewAgentTool(sessions, messages, lspClients),\n\t\t}, otherTools...,\n\t)\n}\n\nfunc TaskAgentTools(lspClients map[string]*lsp.Client) []tools.BaseTool {\n\treturn []tools.BaseTool{\n\t\ttools.NewGlobTool(),\n\t\ttools.NewGrepTool(),\n\t\ttools.NewLsTool(),\n\t\ttools.NewSourcegraphTool(),\n\t\ttools.NewViewTool(lspClients),\n\t}\n}\n"], ["/opencode/internal/tui/theme/gruvbox.go", "package theme\n\nimport (\n\t\"github.com/charmbracelet/lipgloss\"\n)\n\n// Gruvbox color palette constants\nconst (\n\t// Dark theme colors\n\tgruvboxDarkBg0 = \"#282828\"\n\tgruvboxDarkBg0Soft = \"#32302f\"\n\tgruvboxDarkBg1 = \"#3c3836\"\n\tgruvboxDarkBg2 = \"#504945\"\n\tgruvboxDarkBg3 = \"#665c54\"\n\tgruvboxDarkBg4 = \"#7c6f64\"\n\tgruvboxDarkFg0 = \"#fbf1c7\"\n\tgruvboxDarkFg1 = \"#ebdbb2\"\n\tgruvboxDarkFg2 = \"#d5c4a1\"\n\tgruvboxDarkFg3 = \"#bdae93\"\n\tgruvboxDarkFg4 = \"#a89984\"\n\tgruvboxDarkGray = \"#928374\"\n\tgruvboxDarkRed = \"#cc241d\"\n\tgruvboxDarkRedBright = \"#fb4934\"\n\tgruvboxDarkGreen = \"#98971a\"\n\tgruvboxDarkGreenBright = \"#b8bb26\"\n\tgruvboxDarkYellow = \"#d79921\"\n\tgruvboxDarkYellowBright = \"#fabd2f\"\n\tgruvboxDarkBlue = \"#458588\"\n\tgruvboxDarkBlueBright = \"#83a598\"\n\tgruvboxDarkPurple = \"#b16286\"\n\tgruvboxDarkPurpleBright = \"#d3869b\"\n\tgruvboxDarkAqua = \"#689d6a\"\n\tgruvboxDarkAquaBright = \"#8ec07c\"\n\tgruvboxDarkOrange = \"#d65d0e\"\n\tgruvboxDarkOrangeBright = \"#fe8019\"\n\n\t// Light theme colors\n\tgruvboxLightBg0 = \"#fbf1c7\"\n\tgruvboxLightBg0Soft = \"#f2e5bc\"\n\tgruvboxLightBg1 = \"#ebdbb2\"\n\tgruvboxLightBg2 = \"#d5c4a1\"\n\tgruvboxLightBg3 = \"#bdae93\"\n\tgruvboxLightBg4 = \"#a89984\"\n\tgruvboxLightFg0 = \"#282828\"\n\tgruvboxLightFg1 = \"#3c3836\"\n\tgruvboxLightFg2 = \"#504945\"\n\tgruvboxLightFg3 = \"#665c54\"\n\tgruvboxLightFg4 = \"#7c6f64\"\n\tgruvboxLightGray = \"#928374\"\n\tgruvboxLightRed = \"#9d0006\"\n\tgruvboxLightRedBright = \"#cc241d\"\n\tgruvboxLightGreen = \"#79740e\"\n\tgruvboxLightGreenBright = \"#98971a\"\n\tgruvboxLightYellow = \"#b57614\"\n\tgruvboxLightYellowBright = \"#d79921\"\n\tgruvboxLightBlue = \"#076678\"\n\tgruvboxLightBlueBright = \"#458588\"\n\tgruvboxLightPurple = \"#8f3f71\"\n\tgruvboxLightPurpleBright = \"#b16286\"\n\tgruvboxLightAqua = \"#427b58\"\n\tgruvboxLightAquaBright = \"#689d6a\"\n\tgruvboxLightOrange = \"#af3a03\"\n\tgruvboxLightOrangeBright = \"#d65d0e\"\n)\n\n// GruvboxTheme implements the Theme interface with Gruvbox colors.\n// It provides both dark and light variants.\ntype GruvboxTheme struct {\n\tBaseTheme\n}\n\n// NewGruvboxTheme creates a new instance of the Gruvbox theme.\nfunc NewGruvboxTheme() *GruvboxTheme {\n\ttheme := &GruvboxTheme{}\n\n\t// Base colors\n\ttheme.PrimaryColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkBlueBright,\n\t\tLight: gruvboxLightBlueBright,\n\t}\n\ttheme.SecondaryColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkPurpleBright,\n\t\tLight: gruvboxLightPurpleBright,\n\t}\n\ttheme.AccentColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkOrangeBright,\n\t\tLight: gruvboxLightOrangeBright,\n\t}\n\n\t// Status colors\n\ttheme.ErrorColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkRedBright,\n\t\tLight: gruvboxLightRedBright,\n\t}\n\ttheme.WarningColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkYellowBright,\n\t\tLight: gruvboxLightYellowBright,\n\t}\n\ttheme.SuccessColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkGreenBright,\n\t\tLight: gruvboxLightGreenBright,\n\t}\n\ttheme.InfoColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkBlueBright,\n\t\tLight: gruvboxLightBlueBright,\n\t}\n\n\t// Text colors\n\ttheme.TextColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkFg1,\n\t\tLight: gruvboxLightFg1,\n\t}\n\ttheme.TextMutedColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkFg4,\n\t\tLight: gruvboxLightFg4,\n\t}\n\ttheme.TextEmphasizedColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkYellowBright,\n\t\tLight: gruvboxLightYellowBright,\n\t}\n\n\t// Background colors\n\ttheme.BackgroundColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkBg0,\n\t\tLight: gruvboxLightBg0,\n\t}\n\ttheme.BackgroundSecondaryColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkBg1,\n\t\tLight: gruvboxLightBg1,\n\t}\n\ttheme.BackgroundDarkerColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkBg0Soft,\n\t\tLight: gruvboxLightBg0Soft,\n\t}\n\n\t// Border colors\n\ttheme.BorderNormalColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkBg2,\n\t\tLight: gruvboxLightBg2,\n\t}\n\ttheme.BorderFocusedColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkBlueBright,\n\t\tLight: gruvboxLightBlueBright,\n\t}\n\ttheme.BorderDimColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkBg1,\n\t\tLight: gruvboxLightBg1,\n\t}\n\n\t// Diff view colors\n\ttheme.DiffAddedColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkGreenBright,\n\t\tLight: gruvboxLightGreenBright,\n\t}\n\ttheme.DiffRemovedColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkRedBright,\n\t\tLight: gruvboxLightRedBright,\n\t}\n\ttheme.DiffContextColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkFg4,\n\t\tLight: gruvboxLightFg4,\n\t}\n\ttheme.DiffHunkHeaderColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkFg3,\n\t\tLight: gruvboxLightFg3,\n\t}\n\ttheme.DiffHighlightAddedColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkGreenBright,\n\t\tLight: gruvboxLightGreenBright,\n\t}\n\ttheme.DiffHighlightRemovedColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkRedBright,\n\t\tLight: gruvboxLightRedBright,\n\t}\n\ttheme.DiffAddedBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#3C4C3C\", // Darker green background\n\t\tLight: \"#E8F5E9\", // Light green background\n\t}\n\ttheme.DiffRemovedBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#4C3C3C\", // Darker red background\n\t\tLight: \"#FFEBEE\", // Light red background\n\t}\n\ttheme.DiffContextBgColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkBg0,\n\t\tLight: gruvboxLightBg0,\n\t}\n\ttheme.DiffLineNumberColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkFg4,\n\t\tLight: gruvboxLightFg4,\n\t}\n\ttheme.DiffAddedLineNumberBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#32432F\", // Slightly darker green\n\t\tLight: \"#C8E6C9\", // Light green\n\t}\n\ttheme.DiffRemovedLineNumberBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#43322F\", // Slightly darker red\n\t\tLight: \"#FFCDD2\", // Light red\n\t}\n\n\t// Markdown colors\n\ttheme.MarkdownTextColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkFg1,\n\t\tLight: gruvboxLightFg1,\n\t}\n\ttheme.MarkdownHeadingColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkYellowBright,\n\t\tLight: gruvboxLightYellowBright,\n\t}\n\ttheme.MarkdownLinkColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkBlueBright,\n\t\tLight: gruvboxLightBlueBright,\n\t}\n\ttheme.MarkdownLinkTextColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkAquaBright,\n\t\tLight: gruvboxLightAquaBright,\n\t}\n\ttheme.MarkdownCodeColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkGreenBright,\n\t\tLight: gruvboxLightGreenBright,\n\t}\n\ttheme.MarkdownBlockQuoteColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkAquaBright,\n\t\tLight: gruvboxLightAquaBright,\n\t}\n\ttheme.MarkdownEmphColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkYellowBright,\n\t\tLight: gruvboxLightYellowBright,\n\t}\n\ttheme.MarkdownStrongColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkOrangeBright,\n\t\tLight: gruvboxLightOrangeBright,\n\t}\n\ttheme.MarkdownHorizontalRuleColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkBg3,\n\t\tLight: gruvboxLightBg3,\n\t}\n\ttheme.MarkdownListItemColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkBlueBright,\n\t\tLight: gruvboxLightBlueBright,\n\t}\n\ttheme.MarkdownListEnumerationColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkBlueBright,\n\t\tLight: gruvboxLightBlueBright,\n\t}\n\ttheme.MarkdownImageColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkPurpleBright,\n\t\tLight: gruvboxLightPurpleBright,\n\t}\n\ttheme.MarkdownImageTextColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkAquaBright,\n\t\tLight: gruvboxLightAquaBright,\n\t}\n\ttheme.MarkdownCodeBlockColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkFg1,\n\t\tLight: gruvboxLightFg1,\n\t}\n\n\t// Syntax highlighting colors\n\ttheme.SyntaxCommentColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkGray,\n\t\tLight: gruvboxLightGray,\n\t}\n\ttheme.SyntaxKeywordColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkRedBright,\n\t\tLight: gruvboxLightRedBright,\n\t}\n\ttheme.SyntaxFunctionColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkGreenBright,\n\t\tLight: gruvboxLightGreenBright,\n\t}\n\ttheme.SyntaxVariableColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkBlueBright,\n\t\tLight: gruvboxLightBlueBright,\n\t}\n\ttheme.SyntaxStringColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkYellowBright,\n\t\tLight: gruvboxLightYellowBright,\n\t}\n\ttheme.SyntaxNumberColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkPurpleBright,\n\t\tLight: gruvboxLightPurpleBright,\n\t}\n\ttheme.SyntaxTypeColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkYellow,\n\t\tLight: gruvboxLightYellow,\n\t}\n\ttheme.SyntaxOperatorColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkAquaBright,\n\t\tLight: gruvboxLightAquaBright,\n\t}\n\ttheme.SyntaxPunctuationColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkFg1,\n\t\tLight: gruvboxLightFg1,\n\t}\n\n\treturn theme\n}\n\nfunc init() {\n\t// Register the Gruvbox theme with the theme manager\n\tRegisterTheme(\"gruvbox\", NewGruvboxTheme())\n}"], ["/opencode/internal/db/sessions.sql.go", "// Code generated by sqlc. DO NOT EDIT.\n// versions:\n// sqlc v1.29.0\n// source: sessions.sql\n\npackage db\n\nimport (\n\t\"context\"\n\t\"database/sql\"\n)\n\nconst createSession = `-- name: CreateSession :one\nINSERT INTO sessions (\n id,\n parent_session_id,\n title,\n message_count,\n prompt_tokens,\n completion_tokens,\n cost,\n summary_message_id,\n updated_at,\n created_at\n) VALUES (\n ?,\n ?,\n ?,\n ?,\n ?,\n ?,\n ?,\n null,\n strftime('%s', 'now'),\n strftime('%s', 'now')\n) RETURNING id, parent_session_id, title, message_count, prompt_tokens, completion_tokens, cost, updated_at, created_at, summary_message_id\n`\n\ntype CreateSessionParams struct {\n\tID string `json:\"id\"`\n\tParentSessionID sql.NullString `json:\"parent_session_id\"`\n\tTitle string `json:\"title\"`\n\tMessageCount int64 `json:\"message_count\"`\n\tPromptTokens int64 `json:\"prompt_tokens\"`\n\tCompletionTokens int64 `json:\"completion_tokens\"`\n\tCost float64 `json:\"cost\"`\n}\n\nfunc (q *Queries) CreateSession(ctx context.Context, arg CreateSessionParams) (Session, error) {\n\trow := q.queryRow(ctx, q.createSessionStmt, createSession,\n\t\targ.ID,\n\t\targ.ParentSessionID,\n\t\targ.Title,\n\t\targ.MessageCount,\n\t\targ.PromptTokens,\n\t\targ.CompletionTokens,\n\t\targ.Cost,\n\t)\n\tvar i Session\n\terr := row.Scan(\n\t\t&i.ID,\n\t\t&i.ParentSessionID,\n\t\t&i.Title,\n\t\t&i.MessageCount,\n\t\t&i.PromptTokens,\n\t\t&i.CompletionTokens,\n\t\t&i.Cost,\n\t\t&i.UpdatedAt,\n\t\t&i.CreatedAt,\n\t\t&i.SummaryMessageID,\n\t)\n\treturn i, err\n}\n\nconst deleteSession = `-- name: DeleteSession :exec\nDELETE FROM sessions\nWHERE id = ?\n`\n\nfunc (q *Queries) DeleteSession(ctx context.Context, id string) error {\n\t_, err := q.exec(ctx, q.deleteSessionStmt, deleteSession, id)\n\treturn err\n}\n\nconst getSessionByID = `-- name: GetSessionByID :one\nSELECT id, parent_session_id, title, message_count, prompt_tokens, completion_tokens, cost, updated_at, created_at, summary_message_id\nFROM sessions\nWHERE id = ? LIMIT 1\n`\n\nfunc (q *Queries) GetSessionByID(ctx context.Context, id string) (Session, error) {\n\trow := q.queryRow(ctx, q.getSessionByIDStmt, getSessionByID, id)\n\tvar i Session\n\terr := row.Scan(\n\t\t&i.ID,\n\t\t&i.ParentSessionID,\n\t\t&i.Title,\n\t\t&i.MessageCount,\n\t\t&i.PromptTokens,\n\t\t&i.CompletionTokens,\n\t\t&i.Cost,\n\t\t&i.UpdatedAt,\n\t\t&i.CreatedAt,\n\t\t&i.SummaryMessageID,\n\t)\n\treturn i, err\n}\n\nconst listSessions = `-- name: ListSessions :many\nSELECT id, parent_session_id, title, message_count, prompt_tokens, completion_tokens, cost, updated_at, created_at, summary_message_id\nFROM sessions\nWHERE parent_session_id is NULL\nORDER BY created_at DESC\n`\n\nfunc (q *Queries) ListSessions(ctx context.Context) ([]Session, error) {\n\trows, err := q.query(ctx, q.listSessionsStmt, listSessions)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer rows.Close()\n\titems := []Session{}\n\tfor rows.Next() {\n\t\tvar i Session\n\t\tif err := rows.Scan(\n\t\t\t&i.ID,\n\t\t\t&i.ParentSessionID,\n\t\t\t&i.Title,\n\t\t\t&i.MessageCount,\n\t\t\t&i.PromptTokens,\n\t\t\t&i.CompletionTokens,\n\t\t\t&i.Cost,\n\t\t\t&i.UpdatedAt,\n\t\t\t&i.CreatedAt,\n\t\t\t&i.SummaryMessageID,\n\t\t); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\titems = append(items, i)\n\t}\n\tif err := rows.Close(); err != nil {\n\t\treturn nil, err\n\t}\n\tif err := rows.Err(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn items, nil\n}\n\nconst updateSession = `-- name: UpdateSession :one\nUPDATE sessions\nSET\n title = ?,\n prompt_tokens = ?,\n completion_tokens = ?,\n summary_message_id = ?,\n cost = ?\nWHERE id = ?\nRETURNING id, parent_session_id, title, message_count, prompt_tokens, completion_tokens, cost, updated_at, created_at, summary_message_id\n`\n\ntype UpdateSessionParams struct {\n\tTitle string `json:\"title\"`\n\tPromptTokens int64 `json:\"prompt_tokens\"`\n\tCompletionTokens int64 `json:\"completion_tokens\"`\n\tSummaryMessageID sql.NullString `json:\"summary_message_id\"`\n\tCost float64 `json:\"cost\"`\n\tID string `json:\"id\"`\n}\n\nfunc (q *Queries) UpdateSession(ctx context.Context, arg UpdateSessionParams) (Session, error) {\n\trow := q.queryRow(ctx, q.updateSessionStmt, updateSession,\n\t\targ.Title,\n\t\targ.PromptTokens,\n\t\targ.CompletionTokens,\n\t\targ.SummaryMessageID,\n\t\targ.Cost,\n\t\targ.ID,\n\t)\n\tvar i Session\n\terr := row.Scan(\n\t\t&i.ID,\n\t\t&i.ParentSessionID,\n\t\t&i.Title,\n\t\t&i.MessageCount,\n\t\t&i.PromptTokens,\n\t\t&i.CompletionTokens,\n\t\t&i.Cost,\n\t\t&i.UpdatedAt,\n\t\t&i.CreatedAt,\n\t\t&i.SummaryMessageID,\n\t)\n\treturn i, err\n}\n"], ["/opencode/internal/pubsub/broker.go", "package pubsub\n\nimport (\n\t\"context\"\n\t\"sync\"\n)\n\nconst bufferSize = 64\n\ntype Broker[T any] struct {\n\tsubs map[chan Event[T]]struct{}\n\tmu sync.RWMutex\n\tdone chan struct{}\n\tsubCount int\n\tmaxEvents int\n}\n\nfunc NewBroker[T any]() *Broker[T] {\n\treturn NewBrokerWithOptions[T](bufferSize, 1000)\n}\n\nfunc NewBrokerWithOptions[T any](channelBufferSize, maxEvents int) *Broker[T] {\n\tb := &Broker[T]{\n\t\tsubs: make(map[chan Event[T]]struct{}),\n\t\tdone: make(chan struct{}),\n\t\tsubCount: 0,\n\t\tmaxEvents: maxEvents,\n\t}\n\treturn b\n}\n\nfunc (b *Broker[T]) Shutdown() {\n\tselect {\n\tcase <-b.done: // Already closed\n\t\treturn\n\tdefault:\n\t\tclose(b.done)\n\t}\n\n\tb.mu.Lock()\n\tdefer b.mu.Unlock()\n\n\tfor ch := range b.subs {\n\t\tdelete(b.subs, ch)\n\t\tclose(ch)\n\t}\n\n\tb.subCount = 0\n}\n\nfunc (b *Broker[T]) Subscribe(ctx context.Context) <-chan Event[T] {\n\tb.mu.Lock()\n\tdefer b.mu.Unlock()\n\n\tselect {\n\tcase <-b.done:\n\t\tch := make(chan Event[T])\n\t\tclose(ch)\n\t\treturn ch\n\tdefault:\n\t}\n\n\tsub := make(chan Event[T], bufferSize)\n\tb.subs[sub] = struct{}{}\n\tb.subCount++\n\n\tgo func() {\n\t\t<-ctx.Done()\n\n\t\tb.mu.Lock()\n\t\tdefer b.mu.Unlock()\n\n\t\tselect {\n\t\tcase <-b.done:\n\t\t\treturn\n\t\tdefault:\n\t\t}\n\n\t\tdelete(b.subs, sub)\n\t\tclose(sub)\n\t\tb.subCount--\n\t}()\n\n\treturn sub\n}\n\nfunc (b *Broker[T]) GetSubscriberCount() int {\n\tb.mu.RLock()\n\tdefer b.mu.RUnlock()\n\treturn b.subCount\n}\n\nfunc (b *Broker[T]) Publish(t EventType, payload T) {\n\tb.mu.RLock()\n\tselect {\n\tcase <-b.done:\n\t\tb.mu.RUnlock()\n\t\treturn\n\tdefault:\n\t}\n\n\tsubscribers := make([]chan Event[T], 0, len(b.subs))\n\tfor sub := range b.subs {\n\t\tsubscribers = append(subscribers, sub)\n\t}\n\tb.mu.RUnlock()\n\n\tevent := Event[T]{Type: t, Payload: payload}\n\n\tfor _, sub := range subscribers {\n\t\tselect {\n\t\tcase sub <- event:\n\t\tdefault:\n\t\t}\n\t}\n}\n"], ["/opencode/internal/lsp/protocol/tsjson.go", "// Copyright 2023 The Go Authors. All rights reserved.\n// Use of this source code is governed by a BSD-style\n// license that can be found in the LICENSE file.\n\n// Code generated for LSP. DO NOT EDIT.\n\npackage protocol\n\n// Code generated from protocol/metaModel.json at ref release/protocol/3.17.6-next.9 (hash c94395b5da53729e6dff931293b051009ccaaaa4).\n// https://github.com/microsoft/vscode-languageserver-node/blob/release/protocol/3.17.6-next.9/protocol/metaModel.json\n// LSP metaData.version = 3.17.0.\n\nimport \"bytes\"\nimport \"encoding/json\"\n\nimport \"fmt\"\n\n// UnmarshalError indicates that a JSON value did not conform to\n// one of the expected cases of an LSP union type.\ntype UnmarshalError struct {\n\tmsg string\n}\n\nfunc (e UnmarshalError) Error() string {\n\treturn e.msg\n}\nfunc (t Or_CancelParams_id) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase int32:\n\t\treturn json.Marshal(x)\n\tcase string:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [int32 string]\", t)\n}\n\nfunc (t *Or_CancelParams_id) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder41 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder41.DisallowUnknownFields()\n\tvar int32Val int32\n\tif err := decoder41.Decode(&int32Val); err == nil {\n\t\tt.Value = int32Val\n\t\treturn nil\n\t}\n\tdecoder42 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder42.DisallowUnknownFields()\n\tvar stringVal string\n\tif err := decoder42.Decode(&stringVal); err == nil {\n\t\tt.Value = stringVal\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [int32 string]\"}\n}\n\nfunc (t Or_ClientSemanticTokensRequestOptions_full) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase ClientSemanticTokensRequestFullDelta:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [ClientSemanticTokensRequestFullDelta bool]\", t)\n}\n\nfunc (t *Or_ClientSemanticTokensRequestOptions_full) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder220 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder220.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder220.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder221 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder221.DisallowUnknownFields()\n\tvar h221 ClientSemanticTokensRequestFullDelta\n\tif err := decoder221.Decode(&h221); err == nil {\n\t\tt.Value = h221\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [ClientSemanticTokensRequestFullDelta bool]\"}\n}\n\nfunc (t Or_ClientSemanticTokensRequestOptions_range) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase Lit_ClientSemanticTokensRequestOptions_range_Item1:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [Lit_ClientSemanticTokensRequestOptions_range_Item1 bool]\", t)\n}\n\nfunc (t *Or_ClientSemanticTokensRequestOptions_range) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder217 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder217.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder217.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder218 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder218.DisallowUnknownFields()\n\tvar h218 Lit_ClientSemanticTokensRequestOptions_range_Item1\n\tif err := decoder218.Decode(&h218); err == nil {\n\t\tt.Value = h218\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [Lit_ClientSemanticTokensRequestOptions_range_Item1 bool]\"}\n}\n\nfunc (t Or_CompletionItemDefaults_editRange) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase EditRangeWithInsertReplace:\n\t\treturn json.Marshal(x)\n\tcase Range:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [EditRangeWithInsertReplace Range]\", t)\n}\n\nfunc (t *Or_CompletionItemDefaults_editRange) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder183 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder183.DisallowUnknownFields()\n\tvar h183 EditRangeWithInsertReplace\n\tif err := decoder183.Decode(&h183); err == nil {\n\t\tt.Value = h183\n\t\treturn nil\n\t}\n\tdecoder184 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder184.DisallowUnknownFields()\n\tvar h184 Range\n\tif err := decoder184.Decode(&h184); err == nil {\n\t\tt.Value = h184\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [EditRangeWithInsertReplace Range]\"}\n}\n\nfunc (t Or_CompletionItem_documentation) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase MarkupContent:\n\t\treturn json.Marshal(x)\n\tcase string:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [MarkupContent string]\", t)\n}\n\nfunc (t *Or_CompletionItem_documentation) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder25 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder25.DisallowUnknownFields()\n\tvar stringVal string\n\tif err := decoder25.Decode(&stringVal); err == nil {\n\t\tt.Value = stringVal\n\t\treturn nil\n\t}\n\tdecoder26 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder26.DisallowUnknownFields()\n\tvar h26 MarkupContent\n\tif err := decoder26.Decode(&h26); err == nil {\n\t\tt.Value = h26\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [MarkupContent string]\"}\n}\n\nfunc (t Or_CompletionItem_textEdit) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase InsertReplaceEdit:\n\t\treturn json.Marshal(x)\n\tcase TextEdit:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [InsertReplaceEdit TextEdit]\", t)\n}\n\nfunc (t *Or_CompletionItem_textEdit) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder29 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder29.DisallowUnknownFields()\n\tvar h29 InsertReplaceEdit\n\tif err := decoder29.Decode(&h29); err == nil {\n\t\tt.Value = h29\n\t\treturn nil\n\t}\n\tdecoder30 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder30.DisallowUnknownFields()\n\tvar h30 TextEdit\n\tif err := decoder30.Decode(&h30); err == nil {\n\t\tt.Value = h30\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [InsertReplaceEdit TextEdit]\"}\n}\n\nfunc (t Or_Declaration) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase Location:\n\t\treturn json.Marshal(x)\n\tcase []Location:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [Location []Location]\", t)\n}\n\nfunc (t *Or_Declaration) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder237 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder237.DisallowUnknownFields()\n\tvar h237 Location\n\tif err := decoder237.Decode(&h237); err == nil {\n\t\tt.Value = h237\n\t\treturn nil\n\t}\n\tdecoder238 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder238.DisallowUnknownFields()\n\tvar h238 []Location\n\tif err := decoder238.Decode(&h238); err == nil {\n\t\tt.Value = h238\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [Location []Location]\"}\n}\n\nfunc (t Or_Definition) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase Location:\n\t\treturn json.Marshal(x)\n\tcase []Location:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [Location []Location]\", t)\n}\n\nfunc (t *Or_Definition) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder224 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder224.DisallowUnknownFields()\n\tvar h224 Location\n\tif err := decoder224.Decode(&h224); err == nil {\n\t\tt.Value = h224\n\t\treturn nil\n\t}\n\tdecoder225 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder225.DisallowUnknownFields()\n\tvar h225 []Location\n\tif err := decoder225.Decode(&h225); err == nil {\n\t\tt.Value = h225\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [Location []Location]\"}\n}\n\nfunc (t Or_Diagnostic_code) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase int32:\n\t\treturn json.Marshal(x)\n\tcase string:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [int32 string]\", t)\n}\n\nfunc (t *Or_Diagnostic_code) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder179 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder179.DisallowUnknownFields()\n\tvar int32Val int32\n\tif err := decoder179.Decode(&int32Val); err == nil {\n\t\tt.Value = int32Val\n\t\treturn nil\n\t}\n\tdecoder180 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder180.DisallowUnknownFields()\n\tvar stringVal string\n\tif err := decoder180.Decode(&stringVal); err == nil {\n\t\tt.Value = stringVal\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [int32 string]\"}\n}\n\nfunc (t Or_DidChangeConfigurationRegistrationOptions_section) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase []string:\n\t\treturn json.Marshal(x)\n\tcase string:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [[]string string]\", t)\n}\n\nfunc (t *Or_DidChangeConfigurationRegistrationOptions_section) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder22 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder22.DisallowUnknownFields()\n\tvar stringVal string\n\tif err := decoder22.Decode(&stringVal); err == nil {\n\t\tt.Value = stringVal\n\t\treturn nil\n\t}\n\tdecoder23 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder23.DisallowUnknownFields()\n\tvar h23 []string\n\tif err := decoder23.Decode(&h23); err == nil {\n\t\tt.Value = h23\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [[]string string]\"}\n}\n\nfunc (t Or_DocumentDiagnosticReport) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase RelatedFullDocumentDiagnosticReport:\n\t\treturn json.Marshal(x)\n\tcase RelatedUnchangedDocumentDiagnosticReport:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [RelatedFullDocumentDiagnosticReport RelatedUnchangedDocumentDiagnosticReport]\", t)\n}\n\nfunc (t *Or_DocumentDiagnosticReport) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder247 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder247.DisallowUnknownFields()\n\tvar h247 RelatedFullDocumentDiagnosticReport\n\tif err := decoder247.Decode(&h247); err == nil {\n\t\tt.Value = h247\n\t\treturn nil\n\t}\n\tdecoder248 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder248.DisallowUnknownFields()\n\tvar h248 RelatedUnchangedDocumentDiagnosticReport\n\tif err := decoder248.Decode(&h248); err == nil {\n\t\tt.Value = h248\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [RelatedFullDocumentDiagnosticReport RelatedUnchangedDocumentDiagnosticReport]\"}\n}\n\nfunc (t Or_DocumentDiagnosticReportPartialResult_relatedDocuments_Value) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase FullDocumentDiagnosticReport:\n\t\treturn json.Marshal(x)\n\tcase UnchangedDocumentDiagnosticReport:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [FullDocumentDiagnosticReport UnchangedDocumentDiagnosticReport]\", t)\n}\n\nfunc (t *Or_DocumentDiagnosticReportPartialResult_relatedDocuments_Value) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder16 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder16.DisallowUnknownFields()\n\tvar h16 FullDocumentDiagnosticReport\n\tif err := decoder16.Decode(&h16); err == nil {\n\t\tt.Value = h16\n\t\treturn nil\n\t}\n\tdecoder17 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder17.DisallowUnknownFields()\n\tvar h17 UnchangedDocumentDiagnosticReport\n\tif err := decoder17.Decode(&h17); err == nil {\n\t\tt.Value = h17\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [FullDocumentDiagnosticReport UnchangedDocumentDiagnosticReport]\"}\n}\n\nfunc (t Or_DocumentFilter) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase NotebookCellTextDocumentFilter:\n\t\treturn json.Marshal(x)\n\tcase TextDocumentFilter:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [NotebookCellTextDocumentFilter TextDocumentFilter]\", t)\n}\n\nfunc (t *Or_DocumentFilter) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder270 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder270.DisallowUnknownFields()\n\tvar h270 NotebookCellTextDocumentFilter\n\tif err := decoder270.Decode(&h270); err == nil {\n\t\tt.Value = h270\n\t\treturn nil\n\t}\n\tdecoder271 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder271.DisallowUnknownFields()\n\tvar h271 TextDocumentFilter\n\tif err := decoder271.Decode(&h271); err == nil {\n\t\tt.Value = h271\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [NotebookCellTextDocumentFilter TextDocumentFilter]\"}\n}\n\nfunc (t Or_GlobPattern) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase Pattern:\n\t\treturn json.Marshal(x)\n\tcase RelativePattern:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [Pattern RelativePattern]\", t)\n}\n\nfunc (t *Or_GlobPattern) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder274 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder274.DisallowUnknownFields()\n\tvar h274 Pattern\n\tif err := decoder274.Decode(&h274); err == nil {\n\t\tt.Value = h274\n\t\treturn nil\n\t}\n\tdecoder275 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder275.DisallowUnknownFields()\n\tvar h275 RelativePattern\n\tif err := decoder275.Decode(&h275); err == nil {\n\t\tt.Value = h275\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [Pattern RelativePattern]\"}\n}\n\nfunc (t Or_Hover_contents) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase MarkedString:\n\t\treturn json.Marshal(x)\n\tcase MarkupContent:\n\t\treturn json.Marshal(x)\n\tcase []MarkedString:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [MarkedString MarkupContent []MarkedString]\", t)\n}\n\nfunc (t *Or_Hover_contents) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder34 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder34.DisallowUnknownFields()\n\tvar h34 MarkedString\n\tif err := decoder34.Decode(&h34); err == nil {\n\t\tt.Value = h34\n\t\treturn nil\n\t}\n\tdecoder35 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder35.DisallowUnknownFields()\n\tvar h35 MarkupContent\n\tif err := decoder35.Decode(&h35); err == nil {\n\t\tt.Value = h35\n\t\treturn nil\n\t}\n\tdecoder36 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder36.DisallowUnknownFields()\n\tvar h36 []MarkedString\n\tif err := decoder36.Decode(&h36); err == nil {\n\t\tt.Value = h36\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [MarkedString MarkupContent []MarkedString]\"}\n}\n\nfunc (t Or_InlayHintLabelPart_tooltip) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase MarkupContent:\n\t\treturn json.Marshal(x)\n\tcase string:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [MarkupContent string]\", t)\n}\n\nfunc (t *Or_InlayHintLabelPart_tooltip) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder56 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder56.DisallowUnknownFields()\n\tvar stringVal string\n\tif err := decoder56.Decode(&stringVal); err == nil {\n\t\tt.Value = stringVal\n\t\treturn nil\n\t}\n\tdecoder57 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder57.DisallowUnknownFields()\n\tvar h57 MarkupContent\n\tif err := decoder57.Decode(&h57); err == nil {\n\t\tt.Value = h57\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [MarkupContent string]\"}\n}\n\nfunc (t Or_InlayHint_label) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase []InlayHintLabelPart:\n\t\treturn json.Marshal(x)\n\tcase string:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [[]InlayHintLabelPart string]\", t)\n}\n\nfunc (t *Or_InlayHint_label) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder9 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder9.DisallowUnknownFields()\n\tvar stringVal string\n\tif err := decoder9.Decode(&stringVal); err == nil {\n\t\tt.Value = stringVal\n\t\treturn nil\n\t}\n\tdecoder10 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder10.DisallowUnknownFields()\n\tvar h10 []InlayHintLabelPart\n\tif err := decoder10.Decode(&h10); err == nil {\n\t\tt.Value = h10\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [[]InlayHintLabelPart string]\"}\n}\n\nfunc (t Or_InlayHint_tooltip) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase MarkupContent:\n\t\treturn json.Marshal(x)\n\tcase string:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [MarkupContent string]\", t)\n}\n\nfunc (t *Or_InlayHint_tooltip) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder12 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder12.DisallowUnknownFields()\n\tvar stringVal string\n\tif err := decoder12.Decode(&stringVal); err == nil {\n\t\tt.Value = stringVal\n\t\treturn nil\n\t}\n\tdecoder13 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder13.DisallowUnknownFields()\n\tvar h13 MarkupContent\n\tif err := decoder13.Decode(&h13); err == nil {\n\t\tt.Value = h13\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [MarkupContent string]\"}\n}\n\nfunc (t Or_InlineCompletionItem_insertText) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase StringValue:\n\t\treturn json.Marshal(x)\n\tcase string:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [StringValue string]\", t)\n}\n\nfunc (t *Or_InlineCompletionItem_insertText) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder19 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder19.DisallowUnknownFields()\n\tvar stringVal string\n\tif err := decoder19.Decode(&stringVal); err == nil {\n\t\tt.Value = stringVal\n\t\treturn nil\n\t}\n\tdecoder20 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder20.DisallowUnknownFields()\n\tvar h20 StringValue\n\tif err := decoder20.Decode(&h20); err == nil {\n\t\tt.Value = h20\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [StringValue string]\"}\n}\n\nfunc (t Or_InlineValue) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase InlineValueEvaluatableExpression:\n\t\treturn json.Marshal(x)\n\tcase InlineValueText:\n\t\treturn json.Marshal(x)\n\tcase InlineValueVariableLookup:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [InlineValueEvaluatableExpression InlineValueText InlineValueVariableLookup]\", t)\n}\n\nfunc (t *Or_InlineValue) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder242 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder242.DisallowUnknownFields()\n\tvar h242 InlineValueEvaluatableExpression\n\tif err := decoder242.Decode(&h242); err == nil {\n\t\tt.Value = h242\n\t\treturn nil\n\t}\n\tdecoder243 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder243.DisallowUnknownFields()\n\tvar h243 InlineValueText\n\tif err := decoder243.Decode(&h243); err == nil {\n\t\tt.Value = h243\n\t\treturn nil\n\t}\n\tdecoder244 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder244.DisallowUnknownFields()\n\tvar h244 InlineValueVariableLookup\n\tif err := decoder244.Decode(&h244); err == nil {\n\t\tt.Value = h244\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [InlineValueEvaluatableExpression InlineValueText InlineValueVariableLookup]\"}\n}\n\nfunc (t Or_LSPAny) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase LSPArray:\n\t\treturn json.Marshal(x)\n\tcase LSPObject:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase float64:\n\t\treturn json.Marshal(x)\n\tcase int32:\n\t\treturn json.Marshal(x)\n\tcase string:\n\t\treturn json.Marshal(x)\n\tcase uint32:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [LSPArray LSPObject bool float64 int32 string uint32]\", t)\n}\n\nfunc (t *Or_LSPAny) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder228 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder228.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder228.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder229 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder229.DisallowUnknownFields()\n\tvar float64Val float64\n\tif err := decoder229.Decode(&float64Val); err == nil {\n\t\tt.Value = float64Val\n\t\treturn nil\n\t}\n\tdecoder230 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder230.DisallowUnknownFields()\n\tvar int32Val int32\n\tif err := decoder230.Decode(&int32Val); err == nil {\n\t\tt.Value = int32Val\n\t\treturn nil\n\t}\n\tdecoder231 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder231.DisallowUnknownFields()\n\tvar stringVal string\n\tif err := decoder231.Decode(&stringVal); err == nil {\n\t\tt.Value = stringVal\n\t\treturn nil\n\t}\n\tdecoder232 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder232.DisallowUnknownFields()\n\tvar uint32Val uint32\n\tif err := decoder232.Decode(&uint32Val); err == nil {\n\t\tt.Value = uint32Val\n\t\treturn nil\n\t}\n\tdecoder233 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder233.DisallowUnknownFields()\n\tvar h233 LSPArray\n\tif err := decoder233.Decode(&h233); err == nil {\n\t\tt.Value = h233\n\t\treturn nil\n\t}\n\tdecoder234 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder234.DisallowUnknownFields()\n\tvar h234 LSPObject\n\tif err := decoder234.Decode(&h234); err == nil {\n\t\tt.Value = h234\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [LSPArray LSPObject bool float64 int32 string uint32]\"}\n}\n\nfunc (t Or_MarkedString) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase MarkedStringWithLanguage:\n\t\treturn json.Marshal(x)\n\tcase string:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [MarkedStringWithLanguage string]\", t)\n}\n\nfunc (t *Or_MarkedString) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder266 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder266.DisallowUnknownFields()\n\tvar stringVal string\n\tif err := decoder266.Decode(&stringVal); err == nil {\n\t\tt.Value = stringVal\n\t\treturn nil\n\t}\n\tdecoder267 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder267.DisallowUnknownFields()\n\tvar h267 MarkedStringWithLanguage\n\tif err := decoder267.Decode(&h267); err == nil {\n\t\tt.Value = h267\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [MarkedStringWithLanguage string]\"}\n}\n\nfunc (t Or_NotebookCellTextDocumentFilter_notebook) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase NotebookDocumentFilter:\n\t\treturn json.Marshal(x)\n\tcase string:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [NotebookDocumentFilter string]\", t)\n}\n\nfunc (t *Or_NotebookCellTextDocumentFilter_notebook) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder208 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder208.DisallowUnknownFields()\n\tvar stringVal string\n\tif err := decoder208.Decode(&stringVal); err == nil {\n\t\tt.Value = stringVal\n\t\treturn nil\n\t}\n\tdecoder209 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder209.DisallowUnknownFields()\n\tvar h209 NotebookDocumentFilter\n\tif err := decoder209.Decode(&h209); err == nil {\n\t\tt.Value = h209\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [NotebookDocumentFilter string]\"}\n}\n\nfunc (t Or_NotebookDocumentFilter) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase NotebookDocumentFilterNotebookType:\n\t\treturn json.Marshal(x)\n\tcase NotebookDocumentFilterPattern:\n\t\treturn json.Marshal(x)\n\tcase NotebookDocumentFilterScheme:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [NotebookDocumentFilterNotebookType NotebookDocumentFilterPattern NotebookDocumentFilterScheme]\", t)\n}\n\nfunc (t *Or_NotebookDocumentFilter) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder285 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder285.DisallowUnknownFields()\n\tvar h285 NotebookDocumentFilterNotebookType\n\tif err := decoder285.Decode(&h285); err == nil {\n\t\tt.Value = h285\n\t\treturn nil\n\t}\n\tdecoder286 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder286.DisallowUnknownFields()\n\tvar h286 NotebookDocumentFilterPattern\n\tif err := decoder286.Decode(&h286); err == nil {\n\t\tt.Value = h286\n\t\treturn nil\n\t}\n\tdecoder287 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder287.DisallowUnknownFields()\n\tvar h287 NotebookDocumentFilterScheme\n\tif err := decoder287.Decode(&h287); err == nil {\n\t\tt.Value = h287\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [NotebookDocumentFilterNotebookType NotebookDocumentFilterPattern NotebookDocumentFilterScheme]\"}\n}\n\nfunc (t Or_NotebookDocumentFilterWithCells_notebook) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase NotebookDocumentFilter:\n\t\treturn json.Marshal(x)\n\tcase string:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [NotebookDocumentFilter string]\", t)\n}\n\nfunc (t *Or_NotebookDocumentFilterWithCells_notebook) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder192 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder192.DisallowUnknownFields()\n\tvar stringVal string\n\tif err := decoder192.Decode(&stringVal); err == nil {\n\t\tt.Value = stringVal\n\t\treturn nil\n\t}\n\tdecoder193 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder193.DisallowUnknownFields()\n\tvar h193 NotebookDocumentFilter\n\tif err := decoder193.Decode(&h193); err == nil {\n\t\tt.Value = h193\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [NotebookDocumentFilter string]\"}\n}\n\nfunc (t Or_NotebookDocumentFilterWithNotebook_notebook) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase NotebookDocumentFilter:\n\t\treturn json.Marshal(x)\n\tcase string:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [NotebookDocumentFilter string]\", t)\n}\n\nfunc (t *Or_NotebookDocumentFilterWithNotebook_notebook) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder189 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder189.DisallowUnknownFields()\n\tvar stringVal string\n\tif err := decoder189.Decode(&stringVal); err == nil {\n\t\tt.Value = stringVal\n\t\treturn nil\n\t}\n\tdecoder190 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder190.DisallowUnknownFields()\n\tvar h190 NotebookDocumentFilter\n\tif err := decoder190.Decode(&h190); err == nil {\n\t\tt.Value = h190\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [NotebookDocumentFilter string]\"}\n}\n\nfunc (t Or_NotebookDocumentSyncOptions_notebookSelector_Elem) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase NotebookDocumentFilterWithCells:\n\t\treturn json.Marshal(x)\n\tcase NotebookDocumentFilterWithNotebook:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [NotebookDocumentFilterWithCells NotebookDocumentFilterWithNotebook]\", t)\n}\n\nfunc (t *Or_NotebookDocumentSyncOptions_notebookSelector_Elem) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder68 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder68.DisallowUnknownFields()\n\tvar h68 NotebookDocumentFilterWithCells\n\tif err := decoder68.Decode(&h68); err == nil {\n\t\tt.Value = h68\n\t\treturn nil\n\t}\n\tdecoder69 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder69.DisallowUnknownFields()\n\tvar h69 NotebookDocumentFilterWithNotebook\n\tif err := decoder69.Decode(&h69); err == nil {\n\t\tt.Value = h69\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [NotebookDocumentFilterWithCells NotebookDocumentFilterWithNotebook]\"}\n}\n\nfunc (t Or_ParameterInformation_documentation) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase MarkupContent:\n\t\treturn json.Marshal(x)\n\tcase string:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [MarkupContent string]\", t)\n}\n\nfunc (t *Or_ParameterInformation_documentation) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder205 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder205.DisallowUnknownFields()\n\tvar stringVal string\n\tif err := decoder205.Decode(&stringVal); err == nil {\n\t\tt.Value = stringVal\n\t\treturn nil\n\t}\n\tdecoder206 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder206.DisallowUnknownFields()\n\tvar h206 MarkupContent\n\tif err := decoder206.Decode(&h206); err == nil {\n\t\tt.Value = h206\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [MarkupContent string]\"}\n}\n\nfunc (t Or_ParameterInformation_label) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase Tuple_ParameterInformation_label_Item1:\n\t\treturn json.Marshal(x)\n\tcase string:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [Tuple_ParameterInformation_label_Item1 string]\", t)\n}\n\nfunc (t *Or_ParameterInformation_label) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder202 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder202.DisallowUnknownFields()\n\tvar stringVal string\n\tif err := decoder202.Decode(&stringVal); err == nil {\n\t\tt.Value = stringVal\n\t\treturn nil\n\t}\n\tdecoder203 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder203.DisallowUnknownFields()\n\tvar h203 Tuple_ParameterInformation_label_Item1\n\tif err := decoder203.Decode(&h203); err == nil {\n\t\tt.Value = h203\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [Tuple_ParameterInformation_label_Item1 string]\"}\n}\n\nfunc (t Or_PrepareRenameResult) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase PrepareRenameDefaultBehavior:\n\t\treturn json.Marshal(x)\n\tcase PrepareRenamePlaceholder:\n\t\treturn json.Marshal(x)\n\tcase Range:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [PrepareRenameDefaultBehavior PrepareRenamePlaceholder Range]\", t)\n}\n\nfunc (t *Or_PrepareRenameResult) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder252 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder252.DisallowUnknownFields()\n\tvar h252 PrepareRenameDefaultBehavior\n\tif err := decoder252.Decode(&h252); err == nil {\n\t\tt.Value = h252\n\t\treturn nil\n\t}\n\tdecoder253 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder253.DisallowUnknownFields()\n\tvar h253 PrepareRenamePlaceholder\n\tif err := decoder253.Decode(&h253); err == nil {\n\t\tt.Value = h253\n\t\treturn nil\n\t}\n\tdecoder254 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder254.DisallowUnknownFields()\n\tvar h254 Range\n\tif err := decoder254.Decode(&h254); err == nil {\n\t\tt.Value = h254\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [PrepareRenameDefaultBehavior PrepareRenamePlaceholder Range]\"}\n}\n\nfunc (t Or_ProgressToken) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase int32:\n\t\treturn json.Marshal(x)\n\tcase string:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [int32 string]\", t)\n}\n\nfunc (t *Or_ProgressToken) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder255 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder255.DisallowUnknownFields()\n\tvar int32Val int32\n\tif err := decoder255.Decode(&int32Val); err == nil {\n\t\tt.Value = int32Val\n\t\treturn nil\n\t}\n\tdecoder256 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder256.DisallowUnknownFields()\n\tvar stringVal string\n\tif err := decoder256.Decode(&stringVal); err == nil {\n\t\tt.Value = stringVal\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [int32 string]\"}\n}\n\nfunc (t Or_RelatedFullDocumentDiagnosticReport_relatedDocuments_Value) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase FullDocumentDiagnosticReport:\n\t\treturn json.Marshal(x)\n\tcase UnchangedDocumentDiagnosticReport:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [FullDocumentDiagnosticReport UnchangedDocumentDiagnosticReport]\", t)\n}\n\nfunc (t *Or_RelatedFullDocumentDiagnosticReport_relatedDocuments_Value) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder60 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder60.DisallowUnknownFields()\n\tvar h60 FullDocumentDiagnosticReport\n\tif err := decoder60.Decode(&h60); err == nil {\n\t\tt.Value = h60\n\t\treturn nil\n\t}\n\tdecoder61 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder61.DisallowUnknownFields()\n\tvar h61 UnchangedDocumentDiagnosticReport\n\tif err := decoder61.Decode(&h61); err == nil {\n\t\tt.Value = h61\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [FullDocumentDiagnosticReport UnchangedDocumentDiagnosticReport]\"}\n}\n\nfunc (t Or_RelatedUnchangedDocumentDiagnosticReport_relatedDocuments_Value) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase FullDocumentDiagnosticReport:\n\t\treturn json.Marshal(x)\n\tcase UnchangedDocumentDiagnosticReport:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [FullDocumentDiagnosticReport UnchangedDocumentDiagnosticReport]\", t)\n}\n\nfunc (t *Or_RelatedUnchangedDocumentDiagnosticReport_relatedDocuments_Value) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder64 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder64.DisallowUnknownFields()\n\tvar h64 FullDocumentDiagnosticReport\n\tif err := decoder64.Decode(&h64); err == nil {\n\t\tt.Value = h64\n\t\treturn nil\n\t}\n\tdecoder65 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder65.DisallowUnknownFields()\n\tvar h65 UnchangedDocumentDiagnosticReport\n\tif err := decoder65.Decode(&h65); err == nil {\n\t\tt.Value = h65\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [FullDocumentDiagnosticReport UnchangedDocumentDiagnosticReport]\"}\n}\n\nfunc (t Or_RelativePattern_baseUri) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase URI:\n\t\treturn json.Marshal(x)\n\tcase WorkspaceFolder:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [URI WorkspaceFolder]\", t)\n}\n\nfunc (t *Or_RelativePattern_baseUri) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder214 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder214.DisallowUnknownFields()\n\tvar h214 URI\n\tif err := decoder214.Decode(&h214); err == nil {\n\t\tt.Value = h214\n\t\treturn nil\n\t}\n\tdecoder215 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder215.DisallowUnknownFields()\n\tvar h215 WorkspaceFolder\n\tif err := decoder215.Decode(&h215); err == nil {\n\t\tt.Value = h215\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [URI WorkspaceFolder]\"}\n}\n\nfunc (t Or_Result_textDocument_codeAction_Item0_Elem) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase CodeAction:\n\t\treturn json.Marshal(x)\n\tcase Command:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [CodeAction Command]\", t)\n}\n\nfunc (t *Or_Result_textDocument_codeAction_Item0_Elem) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder322 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder322.DisallowUnknownFields()\n\tvar h322 CodeAction\n\tif err := decoder322.Decode(&h322); err == nil {\n\t\tt.Value = h322\n\t\treturn nil\n\t}\n\tdecoder323 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder323.DisallowUnknownFields()\n\tvar h323 Command\n\tif err := decoder323.Decode(&h323); err == nil {\n\t\tt.Value = h323\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [CodeAction Command]\"}\n}\n\nfunc (t Or_Result_textDocument_completion) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase CompletionList:\n\t\treturn json.Marshal(x)\n\tcase []CompletionItem:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [CompletionList []CompletionItem]\", t)\n}\n\nfunc (t *Or_Result_textDocument_completion) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder310 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder310.DisallowUnknownFields()\n\tvar h310 CompletionList\n\tif err := decoder310.Decode(&h310); err == nil {\n\t\tt.Value = h310\n\t\treturn nil\n\t}\n\tdecoder311 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder311.DisallowUnknownFields()\n\tvar h311 []CompletionItem\n\tif err := decoder311.Decode(&h311); err == nil {\n\t\tt.Value = h311\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [CompletionList []CompletionItem]\"}\n}\n\nfunc (t Or_Result_textDocument_declaration) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase Declaration:\n\t\treturn json.Marshal(x)\n\tcase []DeclarationLink:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [Declaration []DeclarationLink]\", t)\n}\n\nfunc (t *Or_Result_textDocument_declaration) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder298 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder298.DisallowUnknownFields()\n\tvar h298 Declaration\n\tif err := decoder298.Decode(&h298); err == nil {\n\t\tt.Value = h298\n\t\treturn nil\n\t}\n\tdecoder299 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder299.DisallowUnknownFields()\n\tvar h299 []DeclarationLink\n\tif err := decoder299.Decode(&h299); err == nil {\n\t\tt.Value = h299\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [Declaration []DeclarationLink]\"}\n}\n\nfunc (t Or_Result_textDocument_definition) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase Definition:\n\t\treturn json.Marshal(x)\n\tcase []DefinitionLink:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [Definition []DefinitionLink]\", t)\n}\n\nfunc (t *Or_Result_textDocument_definition) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder314 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder314.DisallowUnknownFields()\n\tvar h314 Definition\n\tif err := decoder314.Decode(&h314); err == nil {\n\t\tt.Value = h314\n\t\treturn nil\n\t}\n\tdecoder315 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder315.DisallowUnknownFields()\n\tvar h315 []DefinitionLink\n\tif err := decoder315.Decode(&h315); err == nil {\n\t\tt.Value = h315\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [Definition []DefinitionLink]\"}\n}\n\nfunc (t Or_Result_textDocument_documentSymbol) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase []DocumentSymbol:\n\t\treturn json.Marshal(x)\n\tcase []SymbolInformation:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [[]DocumentSymbol []SymbolInformation]\", t)\n}\n\nfunc (t *Or_Result_textDocument_documentSymbol) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder318 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder318.DisallowUnknownFields()\n\tvar h318 []DocumentSymbol\n\tif err := decoder318.Decode(&h318); err == nil {\n\t\tt.Value = h318\n\t\treturn nil\n\t}\n\tdecoder319 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder319.DisallowUnknownFields()\n\tvar h319 []SymbolInformation\n\tif err := decoder319.Decode(&h319); err == nil {\n\t\tt.Value = h319\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [[]DocumentSymbol []SymbolInformation]\"}\n}\n\nfunc (t Or_Result_textDocument_implementation) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase Definition:\n\t\treturn json.Marshal(x)\n\tcase []DefinitionLink:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [Definition []DefinitionLink]\", t)\n}\n\nfunc (t *Or_Result_textDocument_implementation) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder290 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder290.DisallowUnknownFields()\n\tvar h290 Definition\n\tif err := decoder290.Decode(&h290); err == nil {\n\t\tt.Value = h290\n\t\treturn nil\n\t}\n\tdecoder291 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder291.DisallowUnknownFields()\n\tvar h291 []DefinitionLink\n\tif err := decoder291.Decode(&h291); err == nil {\n\t\tt.Value = h291\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [Definition []DefinitionLink]\"}\n}\n\nfunc (t Or_Result_textDocument_inlineCompletion) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase InlineCompletionList:\n\t\treturn json.Marshal(x)\n\tcase []InlineCompletionItem:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [InlineCompletionList []InlineCompletionItem]\", t)\n}\n\nfunc (t *Or_Result_textDocument_inlineCompletion) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder306 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder306.DisallowUnknownFields()\n\tvar h306 InlineCompletionList\n\tif err := decoder306.Decode(&h306); err == nil {\n\t\tt.Value = h306\n\t\treturn nil\n\t}\n\tdecoder307 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder307.DisallowUnknownFields()\n\tvar h307 []InlineCompletionItem\n\tif err := decoder307.Decode(&h307); err == nil {\n\t\tt.Value = h307\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [InlineCompletionList []InlineCompletionItem]\"}\n}\n\nfunc (t Or_Result_textDocument_semanticTokens_full_delta) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase SemanticTokens:\n\t\treturn json.Marshal(x)\n\tcase SemanticTokensDelta:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [SemanticTokens SemanticTokensDelta]\", t)\n}\n\nfunc (t *Or_Result_textDocument_semanticTokens_full_delta) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder302 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder302.DisallowUnknownFields()\n\tvar h302 SemanticTokens\n\tif err := decoder302.Decode(&h302); err == nil {\n\t\tt.Value = h302\n\t\treturn nil\n\t}\n\tdecoder303 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder303.DisallowUnknownFields()\n\tvar h303 SemanticTokensDelta\n\tif err := decoder303.Decode(&h303); err == nil {\n\t\tt.Value = h303\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [SemanticTokens SemanticTokensDelta]\"}\n}\n\nfunc (t Or_Result_textDocument_typeDefinition) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase Definition:\n\t\treturn json.Marshal(x)\n\tcase []DefinitionLink:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [Definition []DefinitionLink]\", t)\n}\n\nfunc (t *Or_Result_textDocument_typeDefinition) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder294 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder294.DisallowUnknownFields()\n\tvar h294 Definition\n\tif err := decoder294.Decode(&h294); err == nil {\n\t\tt.Value = h294\n\t\treturn nil\n\t}\n\tdecoder295 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder295.DisallowUnknownFields()\n\tvar h295 []DefinitionLink\n\tif err := decoder295.Decode(&h295); err == nil {\n\t\tt.Value = h295\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [Definition []DefinitionLink]\"}\n}\n\nfunc (t Or_Result_workspace_symbol) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase []SymbolInformation:\n\t\treturn json.Marshal(x)\n\tcase []WorkspaceSymbol:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [[]SymbolInformation []WorkspaceSymbol]\", t)\n}\n\nfunc (t *Or_Result_workspace_symbol) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder326 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder326.DisallowUnknownFields()\n\tvar h326 []SymbolInformation\n\tif err := decoder326.Decode(&h326); err == nil {\n\t\tt.Value = h326\n\t\treturn nil\n\t}\n\tdecoder327 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder327.DisallowUnknownFields()\n\tvar h327 []WorkspaceSymbol\n\tif err := decoder327.Decode(&h327); err == nil {\n\t\tt.Value = h327\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [[]SymbolInformation []WorkspaceSymbol]\"}\n}\n\nfunc (t Or_SemanticTokensOptions_full) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase SemanticTokensFullDelta:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [SemanticTokensFullDelta bool]\", t)\n}\n\nfunc (t *Or_SemanticTokensOptions_full) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder47 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder47.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder47.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder48 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder48.DisallowUnknownFields()\n\tvar h48 SemanticTokensFullDelta\n\tif err := decoder48.Decode(&h48); err == nil {\n\t\tt.Value = h48\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [SemanticTokensFullDelta bool]\"}\n}\n\nfunc (t Or_SemanticTokensOptions_range) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase Lit_SemanticTokensOptions_range_Item1:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [Lit_SemanticTokensOptions_range_Item1 bool]\", t)\n}\n\nfunc (t *Or_SemanticTokensOptions_range) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder44 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder44.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder44.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder45 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder45.DisallowUnknownFields()\n\tvar h45 Lit_SemanticTokensOptions_range_Item1\n\tif err := decoder45.Decode(&h45); err == nil {\n\t\tt.Value = h45\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [Lit_SemanticTokensOptions_range_Item1 bool]\"}\n}\n\nfunc (t Or_ServerCapabilities_callHierarchyProvider) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase CallHierarchyOptions:\n\t\treturn json.Marshal(x)\n\tcase CallHierarchyRegistrationOptions:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [CallHierarchyOptions CallHierarchyRegistrationOptions bool]\", t)\n}\n\nfunc (t *Or_ServerCapabilities_callHierarchyProvider) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder140 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder140.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder140.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder141 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder141.DisallowUnknownFields()\n\tvar h141 CallHierarchyOptions\n\tif err := decoder141.Decode(&h141); err == nil {\n\t\tt.Value = h141\n\t\treturn nil\n\t}\n\tdecoder142 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder142.DisallowUnknownFields()\n\tvar h142 CallHierarchyRegistrationOptions\n\tif err := decoder142.Decode(&h142); err == nil {\n\t\tt.Value = h142\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [CallHierarchyOptions CallHierarchyRegistrationOptions bool]\"}\n}\n\nfunc (t Or_ServerCapabilities_codeActionProvider) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase CodeActionOptions:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [CodeActionOptions bool]\", t)\n}\n\nfunc (t *Or_ServerCapabilities_codeActionProvider) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder109 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder109.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder109.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder110 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder110.DisallowUnknownFields()\n\tvar h110 CodeActionOptions\n\tif err := decoder110.Decode(&h110); err == nil {\n\t\tt.Value = h110\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [CodeActionOptions bool]\"}\n}\n\nfunc (t Or_ServerCapabilities_colorProvider) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase DocumentColorOptions:\n\t\treturn json.Marshal(x)\n\tcase DocumentColorRegistrationOptions:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [DocumentColorOptions DocumentColorRegistrationOptions bool]\", t)\n}\n\nfunc (t *Or_ServerCapabilities_colorProvider) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder113 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder113.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder113.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder114 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder114.DisallowUnknownFields()\n\tvar h114 DocumentColorOptions\n\tif err := decoder114.Decode(&h114); err == nil {\n\t\tt.Value = h114\n\t\treturn nil\n\t}\n\tdecoder115 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder115.DisallowUnknownFields()\n\tvar h115 DocumentColorRegistrationOptions\n\tif err := decoder115.Decode(&h115); err == nil {\n\t\tt.Value = h115\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [DocumentColorOptions DocumentColorRegistrationOptions bool]\"}\n}\n\nfunc (t Or_ServerCapabilities_declarationProvider) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase DeclarationOptions:\n\t\treturn json.Marshal(x)\n\tcase DeclarationRegistrationOptions:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [DeclarationOptions DeclarationRegistrationOptions bool]\", t)\n}\n\nfunc (t *Or_ServerCapabilities_declarationProvider) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder83 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder83.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder83.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder84 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder84.DisallowUnknownFields()\n\tvar h84 DeclarationOptions\n\tif err := decoder84.Decode(&h84); err == nil {\n\t\tt.Value = h84\n\t\treturn nil\n\t}\n\tdecoder85 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder85.DisallowUnknownFields()\n\tvar h85 DeclarationRegistrationOptions\n\tif err := decoder85.Decode(&h85); err == nil {\n\t\tt.Value = h85\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [DeclarationOptions DeclarationRegistrationOptions bool]\"}\n}\n\nfunc (t Or_ServerCapabilities_definitionProvider) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase DefinitionOptions:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [DefinitionOptions bool]\", t)\n}\n\nfunc (t *Or_ServerCapabilities_definitionProvider) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder87 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder87.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder87.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder88 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder88.DisallowUnknownFields()\n\tvar h88 DefinitionOptions\n\tif err := decoder88.Decode(&h88); err == nil {\n\t\tt.Value = h88\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [DefinitionOptions bool]\"}\n}\n\nfunc (t Or_ServerCapabilities_diagnosticProvider) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase DiagnosticOptions:\n\t\treturn json.Marshal(x)\n\tcase DiagnosticRegistrationOptions:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [DiagnosticOptions DiagnosticRegistrationOptions]\", t)\n}\n\nfunc (t *Or_ServerCapabilities_diagnosticProvider) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder174 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder174.DisallowUnknownFields()\n\tvar h174 DiagnosticOptions\n\tif err := decoder174.Decode(&h174); err == nil {\n\t\tt.Value = h174\n\t\treturn nil\n\t}\n\tdecoder175 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder175.DisallowUnknownFields()\n\tvar h175 DiagnosticRegistrationOptions\n\tif err := decoder175.Decode(&h175); err == nil {\n\t\tt.Value = h175\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [DiagnosticOptions DiagnosticRegistrationOptions]\"}\n}\n\nfunc (t Or_ServerCapabilities_documentFormattingProvider) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase DocumentFormattingOptions:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [DocumentFormattingOptions bool]\", t)\n}\n\nfunc (t *Or_ServerCapabilities_documentFormattingProvider) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder120 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder120.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder120.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder121 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder121.DisallowUnknownFields()\n\tvar h121 DocumentFormattingOptions\n\tif err := decoder121.Decode(&h121); err == nil {\n\t\tt.Value = h121\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [DocumentFormattingOptions bool]\"}\n}\n\nfunc (t Or_ServerCapabilities_documentHighlightProvider) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase DocumentHighlightOptions:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [DocumentHighlightOptions bool]\", t)\n}\n\nfunc (t *Or_ServerCapabilities_documentHighlightProvider) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder103 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder103.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder103.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder104 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder104.DisallowUnknownFields()\n\tvar h104 DocumentHighlightOptions\n\tif err := decoder104.Decode(&h104); err == nil {\n\t\tt.Value = h104\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [DocumentHighlightOptions bool]\"}\n}\n\nfunc (t Or_ServerCapabilities_documentRangeFormattingProvider) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase DocumentRangeFormattingOptions:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [DocumentRangeFormattingOptions bool]\", t)\n}\n\nfunc (t *Or_ServerCapabilities_documentRangeFormattingProvider) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder123 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder123.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder123.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder124 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder124.DisallowUnknownFields()\n\tvar h124 DocumentRangeFormattingOptions\n\tif err := decoder124.Decode(&h124); err == nil {\n\t\tt.Value = h124\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [DocumentRangeFormattingOptions bool]\"}\n}\n\nfunc (t Or_ServerCapabilities_documentSymbolProvider) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase DocumentSymbolOptions:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [DocumentSymbolOptions bool]\", t)\n}\n\nfunc (t *Or_ServerCapabilities_documentSymbolProvider) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder106 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder106.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder106.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder107 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder107.DisallowUnknownFields()\n\tvar h107 DocumentSymbolOptions\n\tif err := decoder107.Decode(&h107); err == nil {\n\t\tt.Value = h107\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [DocumentSymbolOptions bool]\"}\n}\n\nfunc (t Or_ServerCapabilities_foldingRangeProvider) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase FoldingRangeOptions:\n\t\treturn json.Marshal(x)\n\tcase FoldingRangeRegistrationOptions:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [FoldingRangeOptions FoldingRangeRegistrationOptions bool]\", t)\n}\n\nfunc (t *Or_ServerCapabilities_foldingRangeProvider) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder130 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder130.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder130.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder131 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder131.DisallowUnknownFields()\n\tvar h131 FoldingRangeOptions\n\tif err := decoder131.Decode(&h131); err == nil {\n\t\tt.Value = h131\n\t\treturn nil\n\t}\n\tdecoder132 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder132.DisallowUnknownFields()\n\tvar h132 FoldingRangeRegistrationOptions\n\tif err := decoder132.Decode(&h132); err == nil {\n\t\tt.Value = h132\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [FoldingRangeOptions FoldingRangeRegistrationOptions bool]\"}\n}\n\nfunc (t Or_ServerCapabilities_hoverProvider) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase HoverOptions:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [HoverOptions bool]\", t)\n}\n\nfunc (t *Or_ServerCapabilities_hoverProvider) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder79 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder79.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder79.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder80 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder80.DisallowUnknownFields()\n\tvar h80 HoverOptions\n\tif err := decoder80.Decode(&h80); err == nil {\n\t\tt.Value = h80\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [HoverOptions bool]\"}\n}\n\nfunc (t Or_ServerCapabilities_implementationProvider) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase ImplementationOptions:\n\t\treturn json.Marshal(x)\n\tcase ImplementationRegistrationOptions:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [ImplementationOptions ImplementationRegistrationOptions bool]\", t)\n}\n\nfunc (t *Or_ServerCapabilities_implementationProvider) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder96 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder96.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder96.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder97 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder97.DisallowUnknownFields()\n\tvar h97 ImplementationOptions\n\tif err := decoder97.Decode(&h97); err == nil {\n\t\tt.Value = h97\n\t\treturn nil\n\t}\n\tdecoder98 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder98.DisallowUnknownFields()\n\tvar h98 ImplementationRegistrationOptions\n\tif err := decoder98.Decode(&h98); err == nil {\n\t\tt.Value = h98\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [ImplementationOptions ImplementationRegistrationOptions bool]\"}\n}\n\nfunc (t Or_ServerCapabilities_inlayHintProvider) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase InlayHintOptions:\n\t\treturn json.Marshal(x)\n\tcase InlayHintRegistrationOptions:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [InlayHintOptions InlayHintRegistrationOptions bool]\", t)\n}\n\nfunc (t *Or_ServerCapabilities_inlayHintProvider) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder169 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder169.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder169.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder170 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder170.DisallowUnknownFields()\n\tvar h170 InlayHintOptions\n\tif err := decoder170.Decode(&h170); err == nil {\n\t\tt.Value = h170\n\t\treturn nil\n\t}\n\tdecoder171 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder171.DisallowUnknownFields()\n\tvar h171 InlayHintRegistrationOptions\n\tif err := decoder171.Decode(&h171); err == nil {\n\t\tt.Value = h171\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [InlayHintOptions InlayHintRegistrationOptions bool]\"}\n}\n\nfunc (t Or_ServerCapabilities_inlineCompletionProvider) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase InlineCompletionOptions:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [InlineCompletionOptions bool]\", t)\n}\n\nfunc (t *Or_ServerCapabilities_inlineCompletionProvider) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder177 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder177.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder177.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder178 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder178.DisallowUnknownFields()\n\tvar h178 InlineCompletionOptions\n\tif err := decoder178.Decode(&h178); err == nil {\n\t\tt.Value = h178\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [InlineCompletionOptions bool]\"}\n}\n\nfunc (t Or_ServerCapabilities_inlineValueProvider) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase InlineValueOptions:\n\t\treturn json.Marshal(x)\n\tcase InlineValueRegistrationOptions:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [InlineValueOptions InlineValueRegistrationOptions bool]\", t)\n}\n\nfunc (t *Or_ServerCapabilities_inlineValueProvider) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder164 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder164.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder164.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder165 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder165.DisallowUnknownFields()\n\tvar h165 InlineValueOptions\n\tif err := decoder165.Decode(&h165); err == nil {\n\t\tt.Value = h165\n\t\treturn nil\n\t}\n\tdecoder166 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder166.DisallowUnknownFields()\n\tvar h166 InlineValueRegistrationOptions\n\tif err := decoder166.Decode(&h166); err == nil {\n\t\tt.Value = h166\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [InlineValueOptions InlineValueRegistrationOptions bool]\"}\n}\n\nfunc (t Or_ServerCapabilities_linkedEditingRangeProvider) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase LinkedEditingRangeOptions:\n\t\treturn json.Marshal(x)\n\tcase LinkedEditingRangeRegistrationOptions:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [LinkedEditingRangeOptions LinkedEditingRangeRegistrationOptions bool]\", t)\n}\n\nfunc (t *Or_ServerCapabilities_linkedEditingRangeProvider) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder145 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder145.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder145.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder146 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder146.DisallowUnknownFields()\n\tvar h146 LinkedEditingRangeOptions\n\tif err := decoder146.Decode(&h146); err == nil {\n\t\tt.Value = h146\n\t\treturn nil\n\t}\n\tdecoder147 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder147.DisallowUnknownFields()\n\tvar h147 LinkedEditingRangeRegistrationOptions\n\tif err := decoder147.Decode(&h147); err == nil {\n\t\tt.Value = h147\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [LinkedEditingRangeOptions LinkedEditingRangeRegistrationOptions bool]\"}\n}\n\nfunc (t Or_ServerCapabilities_monikerProvider) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase MonikerOptions:\n\t\treturn json.Marshal(x)\n\tcase MonikerRegistrationOptions:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [MonikerOptions MonikerRegistrationOptions bool]\", t)\n}\n\nfunc (t *Or_ServerCapabilities_monikerProvider) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder154 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder154.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder154.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder155 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder155.DisallowUnknownFields()\n\tvar h155 MonikerOptions\n\tif err := decoder155.Decode(&h155); err == nil {\n\t\tt.Value = h155\n\t\treturn nil\n\t}\n\tdecoder156 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder156.DisallowUnknownFields()\n\tvar h156 MonikerRegistrationOptions\n\tif err := decoder156.Decode(&h156); err == nil {\n\t\tt.Value = h156\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [MonikerOptions MonikerRegistrationOptions bool]\"}\n}\n\nfunc (t Or_ServerCapabilities_notebookDocumentSync) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase NotebookDocumentSyncOptions:\n\t\treturn json.Marshal(x)\n\tcase NotebookDocumentSyncRegistrationOptions:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [NotebookDocumentSyncOptions NotebookDocumentSyncRegistrationOptions]\", t)\n}\n\nfunc (t *Or_ServerCapabilities_notebookDocumentSync) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder76 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder76.DisallowUnknownFields()\n\tvar h76 NotebookDocumentSyncOptions\n\tif err := decoder76.Decode(&h76); err == nil {\n\t\tt.Value = h76\n\t\treturn nil\n\t}\n\tdecoder77 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder77.DisallowUnknownFields()\n\tvar h77 NotebookDocumentSyncRegistrationOptions\n\tif err := decoder77.Decode(&h77); err == nil {\n\t\tt.Value = h77\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [NotebookDocumentSyncOptions NotebookDocumentSyncRegistrationOptions]\"}\n}\n\nfunc (t Or_ServerCapabilities_referencesProvider) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase ReferenceOptions:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [ReferenceOptions bool]\", t)\n}\n\nfunc (t *Or_ServerCapabilities_referencesProvider) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder100 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder100.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder100.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder101 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder101.DisallowUnknownFields()\n\tvar h101 ReferenceOptions\n\tif err := decoder101.Decode(&h101); err == nil {\n\t\tt.Value = h101\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [ReferenceOptions bool]\"}\n}\n\nfunc (t Or_ServerCapabilities_renameProvider) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase RenameOptions:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [RenameOptions bool]\", t)\n}\n\nfunc (t *Or_ServerCapabilities_renameProvider) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder126 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder126.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder126.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder127 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder127.DisallowUnknownFields()\n\tvar h127 RenameOptions\n\tif err := decoder127.Decode(&h127); err == nil {\n\t\tt.Value = h127\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [RenameOptions bool]\"}\n}\n\nfunc (t Or_ServerCapabilities_selectionRangeProvider) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase SelectionRangeOptions:\n\t\treturn json.Marshal(x)\n\tcase SelectionRangeRegistrationOptions:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [SelectionRangeOptions SelectionRangeRegistrationOptions bool]\", t)\n}\n\nfunc (t *Or_ServerCapabilities_selectionRangeProvider) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder135 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder135.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder135.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder136 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder136.DisallowUnknownFields()\n\tvar h136 SelectionRangeOptions\n\tif err := decoder136.Decode(&h136); err == nil {\n\t\tt.Value = h136\n\t\treturn nil\n\t}\n\tdecoder137 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder137.DisallowUnknownFields()\n\tvar h137 SelectionRangeRegistrationOptions\n\tif err := decoder137.Decode(&h137); err == nil {\n\t\tt.Value = h137\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [SelectionRangeOptions SelectionRangeRegistrationOptions bool]\"}\n}\n\nfunc (t Or_ServerCapabilities_semanticTokensProvider) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase SemanticTokensOptions:\n\t\treturn json.Marshal(x)\n\tcase SemanticTokensRegistrationOptions:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [SemanticTokensOptions SemanticTokensRegistrationOptions]\", t)\n}\n\nfunc (t *Or_ServerCapabilities_semanticTokensProvider) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder150 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder150.DisallowUnknownFields()\n\tvar h150 SemanticTokensOptions\n\tif err := decoder150.Decode(&h150); err == nil {\n\t\tt.Value = h150\n\t\treturn nil\n\t}\n\tdecoder151 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder151.DisallowUnknownFields()\n\tvar h151 SemanticTokensRegistrationOptions\n\tif err := decoder151.Decode(&h151); err == nil {\n\t\tt.Value = h151\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [SemanticTokensOptions SemanticTokensRegistrationOptions]\"}\n}\n\nfunc (t Or_ServerCapabilities_textDocumentSync) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase TextDocumentSyncKind:\n\t\treturn json.Marshal(x)\n\tcase TextDocumentSyncOptions:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [TextDocumentSyncKind TextDocumentSyncOptions]\", t)\n}\n\nfunc (t *Or_ServerCapabilities_textDocumentSync) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder72 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder72.DisallowUnknownFields()\n\tvar h72 TextDocumentSyncKind\n\tif err := decoder72.Decode(&h72); err == nil {\n\t\tt.Value = h72\n\t\treturn nil\n\t}\n\tdecoder73 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder73.DisallowUnknownFields()\n\tvar h73 TextDocumentSyncOptions\n\tif err := decoder73.Decode(&h73); err == nil {\n\t\tt.Value = h73\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [TextDocumentSyncKind TextDocumentSyncOptions]\"}\n}\n\nfunc (t Or_ServerCapabilities_typeDefinitionProvider) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase TypeDefinitionOptions:\n\t\treturn json.Marshal(x)\n\tcase TypeDefinitionRegistrationOptions:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [TypeDefinitionOptions TypeDefinitionRegistrationOptions bool]\", t)\n}\n\nfunc (t *Or_ServerCapabilities_typeDefinitionProvider) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder91 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder91.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder91.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder92 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder92.DisallowUnknownFields()\n\tvar h92 TypeDefinitionOptions\n\tif err := decoder92.Decode(&h92); err == nil {\n\t\tt.Value = h92\n\t\treturn nil\n\t}\n\tdecoder93 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder93.DisallowUnknownFields()\n\tvar h93 TypeDefinitionRegistrationOptions\n\tif err := decoder93.Decode(&h93); err == nil {\n\t\tt.Value = h93\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [TypeDefinitionOptions TypeDefinitionRegistrationOptions bool]\"}\n}\n\nfunc (t Or_ServerCapabilities_typeHierarchyProvider) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase TypeHierarchyOptions:\n\t\treturn json.Marshal(x)\n\tcase TypeHierarchyRegistrationOptions:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [TypeHierarchyOptions TypeHierarchyRegistrationOptions bool]\", t)\n}\n\nfunc (t *Or_ServerCapabilities_typeHierarchyProvider) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder159 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder159.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder159.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder160 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder160.DisallowUnknownFields()\n\tvar h160 TypeHierarchyOptions\n\tif err := decoder160.Decode(&h160); err == nil {\n\t\tt.Value = h160\n\t\treturn nil\n\t}\n\tdecoder161 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder161.DisallowUnknownFields()\n\tvar h161 TypeHierarchyRegistrationOptions\n\tif err := decoder161.Decode(&h161); err == nil {\n\t\tt.Value = h161\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [TypeHierarchyOptions TypeHierarchyRegistrationOptions bool]\"}\n}\n\nfunc (t Or_ServerCapabilities_workspaceSymbolProvider) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase WorkspaceSymbolOptions:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [WorkspaceSymbolOptions bool]\", t)\n}\n\nfunc (t *Or_ServerCapabilities_workspaceSymbolProvider) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder117 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder117.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder117.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder118 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder118.DisallowUnknownFields()\n\tvar h118 WorkspaceSymbolOptions\n\tif err := decoder118.Decode(&h118); err == nil {\n\t\tt.Value = h118\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [WorkspaceSymbolOptions bool]\"}\n}\n\nfunc (t Or_SignatureInformation_documentation) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase MarkupContent:\n\t\treturn json.Marshal(x)\n\tcase string:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [MarkupContent string]\", t)\n}\n\nfunc (t *Or_SignatureInformation_documentation) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder186 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder186.DisallowUnknownFields()\n\tvar stringVal string\n\tif err := decoder186.Decode(&stringVal); err == nil {\n\t\tt.Value = stringVal\n\t\treturn nil\n\t}\n\tdecoder187 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder187.DisallowUnknownFields()\n\tvar h187 MarkupContent\n\tif err := decoder187.Decode(&h187); err == nil {\n\t\tt.Value = h187\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [MarkupContent string]\"}\n}\n\nfunc (t Or_TextDocumentContentChangeEvent) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase TextDocumentContentChangePartial:\n\t\treturn json.Marshal(x)\n\tcase TextDocumentContentChangeWholeDocument:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [TextDocumentContentChangePartial TextDocumentContentChangeWholeDocument]\", t)\n}\n\nfunc (t *Or_TextDocumentContentChangeEvent) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder263 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder263.DisallowUnknownFields()\n\tvar h263 TextDocumentContentChangePartial\n\tif err := decoder263.Decode(&h263); err == nil {\n\t\tt.Value = h263\n\t\treturn nil\n\t}\n\tdecoder264 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder264.DisallowUnknownFields()\n\tvar h264 TextDocumentContentChangeWholeDocument\n\tif err := decoder264.Decode(&h264); err == nil {\n\t\tt.Value = h264\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [TextDocumentContentChangePartial TextDocumentContentChangeWholeDocument]\"}\n}\n\nfunc (t Or_TextDocumentEdit_edits_Elem) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase AnnotatedTextEdit:\n\t\treturn json.Marshal(x)\n\tcase SnippetTextEdit:\n\t\treturn json.Marshal(x)\n\tcase TextEdit:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [AnnotatedTextEdit SnippetTextEdit TextEdit]\", t)\n}\n\nfunc (t *Or_TextDocumentEdit_edits_Elem) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder52 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder52.DisallowUnknownFields()\n\tvar h52 AnnotatedTextEdit\n\tif err := decoder52.Decode(&h52); err == nil {\n\t\tt.Value = h52\n\t\treturn nil\n\t}\n\tdecoder53 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder53.DisallowUnknownFields()\n\tvar h53 SnippetTextEdit\n\tif err := decoder53.Decode(&h53); err == nil {\n\t\tt.Value = h53\n\t\treturn nil\n\t}\n\tdecoder54 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder54.DisallowUnknownFields()\n\tvar h54 TextEdit\n\tif err := decoder54.Decode(&h54); err == nil {\n\t\tt.Value = h54\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [AnnotatedTextEdit SnippetTextEdit TextEdit]\"}\n}\n\nfunc (t Or_TextDocumentFilter) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase TextDocumentFilterLanguage:\n\t\treturn json.Marshal(x)\n\tcase TextDocumentFilterPattern:\n\t\treturn json.Marshal(x)\n\tcase TextDocumentFilterScheme:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [TextDocumentFilterLanguage TextDocumentFilterPattern TextDocumentFilterScheme]\", t)\n}\n\nfunc (t *Or_TextDocumentFilter) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder279 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder279.DisallowUnknownFields()\n\tvar h279 TextDocumentFilterLanguage\n\tif err := decoder279.Decode(&h279); err == nil {\n\t\tt.Value = h279\n\t\treturn nil\n\t}\n\tdecoder280 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder280.DisallowUnknownFields()\n\tvar h280 TextDocumentFilterPattern\n\tif err := decoder280.Decode(&h280); err == nil {\n\t\tt.Value = h280\n\t\treturn nil\n\t}\n\tdecoder281 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder281.DisallowUnknownFields()\n\tvar h281 TextDocumentFilterScheme\n\tif err := decoder281.Decode(&h281); err == nil {\n\t\tt.Value = h281\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [TextDocumentFilterLanguage TextDocumentFilterPattern TextDocumentFilterScheme]\"}\n}\n\nfunc (t Or_TextDocumentSyncOptions_save) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase SaveOptions:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [SaveOptions bool]\", t)\n}\n\nfunc (t *Or_TextDocumentSyncOptions_save) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder195 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder195.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder195.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder196 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder196.DisallowUnknownFields()\n\tvar h196 SaveOptions\n\tif err := decoder196.Decode(&h196); err == nil {\n\t\tt.Value = h196\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [SaveOptions bool]\"}\n}\n\nfunc (t Or_WorkspaceDocumentDiagnosticReport) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase WorkspaceFullDocumentDiagnosticReport:\n\t\treturn json.Marshal(x)\n\tcase WorkspaceUnchangedDocumentDiagnosticReport:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [WorkspaceFullDocumentDiagnosticReport WorkspaceUnchangedDocumentDiagnosticReport]\", t)\n}\n\nfunc (t *Or_WorkspaceDocumentDiagnosticReport) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder259 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder259.DisallowUnknownFields()\n\tvar h259 WorkspaceFullDocumentDiagnosticReport\n\tif err := decoder259.Decode(&h259); err == nil {\n\t\tt.Value = h259\n\t\treturn nil\n\t}\n\tdecoder260 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder260.DisallowUnknownFields()\n\tvar h260 WorkspaceUnchangedDocumentDiagnosticReport\n\tif err := decoder260.Decode(&h260); err == nil {\n\t\tt.Value = h260\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [WorkspaceFullDocumentDiagnosticReport WorkspaceUnchangedDocumentDiagnosticReport]\"}\n}\n\nfunc (t Or_WorkspaceEdit_documentChanges_Elem) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase CreateFile:\n\t\treturn json.Marshal(x)\n\tcase DeleteFile:\n\t\treturn json.Marshal(x)\n\tcase RenameFile:\n\t\treturn json.Marshal(x)\n\tcase TextDocumentEdit:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [CreateFile DeleteFile RenameFile TextDocumentEdit]\", t)\n}\n\nfunc (t *Or_WorkspaceEdit_documentChanges_Elem) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder4 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder4.DisallowUnknownFields()\n\tvar h4 CreateFile\n\tif err := decoder4.Decode(&h4); err == nil {\n\t\tt.Value = h4\n\t\treturn nil\n\t}\n\tdecoder5 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder5.DisallowUnknownFields()\n\tvar h5 DeleteFile\n\tif err := decoder5.Decode(&h5); err == nil {\n\t\tt.Value = h5\n\t\treturn nil\n\t}\n\tdecoder6 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder6.DisallowUnknownFields()\n\tvar h6 RenameFile\n\tif err := decoder6.Decode(&h6); err == nil {\n\t\tt.Value = h6\n\t\treturn nil\n\t}\n\tdecoder7 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder7.DisallowUnknownFields()\n\tvar h7 TextDocumentEdit\n\tif err := decoder7.Decode(&h7); err == nil {\n\t\tt.Value = h7\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [CreateFile DeleteFile RenameFile TextDocumentEdit]\"}\n}\n\nfunc (t Or_WorkspaceFoldersServerCapabilities_changeNotifications) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase string:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [bool string]\", t)\n}\n\nfunc (t *Or_WorkspaceFoldersServerCapabilities_changeNotifications) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder210 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder210.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder210.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder211 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder211.DisallowUnknownFields()\n\tvar stringVal string\n\tif err := decoder211.Decode(&stringVal); err == nil {\n\t\tt.Value = stringVal\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [bool string]\"}\n}\n\nfunc (t Or_WorkspaceOptions_textDocumentContent) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase TextDocumentContentOptions:\n\t\treturn json.Marshal(x)\n\tcase TextDocumentContentRegistrationOptions:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [TextDocumentContentOptions TextDocumentContentRegistrationOptions]\", t)\n}\n\nfunc (t *Or_WorkspaceOptions_textDocumentContent) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder199 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder199.DisallowUnknownFields()\n\tvar h199 TextDocumentContentOptions\n\tif err := decoder199.Decode(&h199); err == nil {\n\t\tt.Value = h199\n\t\treturn nil\n\t}\n\tdecoder200 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder200.DisallowUnknownFields()\n\tvar h200 TextDocumentContentRegistrationOptions\n\tif err := decoder200.Decode(&h200); err == nil {\n\t\tt.Value = h200\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [TextDocumentContentOptions TextDocumentContentRegistrationOptions]\"}\n}\n\nfunc (t Or_WorkspaceSymbol_location) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase Location:\n\t\treturn json.Marshal(x)\n\tcase LocationUriOnly:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [Location LocationUriOnly]\", t)\n}\n\nfunc (t *Or_WorkspaceSymbol_location) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder39 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder39.DisallowUnknownFields()\n\tvar h39 Location\n\tif err := decoder39.Decode(&h39); err == nil {\n\t\tt.Value = h39\n\t\treturn nil\n\t}\n\tdecoder40 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder40.DisallowUnknownFields()\n\tvar h40 LocationUriOnly\n\tif err := decoder40.Decode(&h40); err == nil {\n\t\tt.Value = h40\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [Location LocationUriOnly]\"}\n}\n"], ["/opencode/internal/config/init.go", "package config\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"path/filepath\"\n)\n\nconst (\n\t// InitFlagFilename is the name of the file that indicates whether the project has been initialized\n\tInitFlagFilename = \"init\"\n)\n\n// ProjectInitFlag represents the initialization status for a project directory\ntype ProjectInitFlag struct {\n\tInitialized bool `json:\"initialized\"`\n}\n\n// ShouldShowInitDialog checks if the initialization dialog should be shown for the current directory\nfunc ShouldShowInitDialog() (bool, error) {\n\tif cfg == nil {\n\t\treturn false, fmt.Errorf(\"config not loaded\")\n\t}\n\n\t// Create the flag file path\n\tflagFilePath := filepath.Join(cfg.Data.Directory, InitFlagFilename)\n\n\t// Check if the flag file exists\n\t_, err := os.Stat(flagFilePath)\n\tif err == nil {\n\t\t// File exists, don't show the dialog\n\t\treturn false, nil\n\t}\n\n\t// If the error is not \"file not found\", return the error\n\tif !os.IsNotExist(err) {\n\t\treturn false, fmt.Errorf(\"failed to check init flag file: %w\", err)\n\t}\n\n\t// File doesn't exist, show the dialog\n\treturn true, nil\n}\n\n// MarkProjectInitialized marks the current project as initialized\nfunc MarkProjectInitialized() error {\n\tif cfg == nil {\n\t\treturn fmt.Errorf(\"config not loaded\")\n\t}\n\t// Create the flag file path\n\tflagFilePath := filepath.Join(cfg.Data.Directory, InitFlagFilename)\n\n\t// Create an empty file to mark the project as initialized\n\tfile, err := os.Create(flagFilePath)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to create init flag file: %w\", err)\n\t}\n\tdefer file.Close()\n\n\treturn nil\n}\n\n"], ["/opencode/internal/db/connect.go", "package db\n\nimport (\n\t\"database/sql\"\n\t\"fmt\"\n\t\"os\"\n\t\"path/filepath\"\n\n\t_ \"github.com/ncruces/go-sqlite3/driver\"\n\t_ \"github.com/ncruces/go-sqlite3/embed\"\n\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n\n\t\"github.com/pressly/goose/v3\"\n)\n\nfunc Connect() (*sql.DB, error) {\n\tdataDir := config.Get().Data.Directory\n\tif dataDir == \"\" {\n\t\treturn nil, fmt.Errorf(\"data.dir is not set\")\n\t}\n\tif err := os.MkdirAll(dataDir, 0o700); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to create data directory: %w\", err)\n\t}\n\tdbPath := filepath.Join(dataDir, \"opencode.db\")\n\t// Open the SQLite database\n\tdb, err := sql.Open(\"sqlite3\", dbPath)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to open database: %w\", err)\n\t}\n\n\t// Verify connection\n\tif err = db.Ping(); err != nil {\n\t\tdb.Close()\n\t\treturn nil, fmt.Errorf(\"failed to connect to database: %w\", err)\n\t}\n\n\t// Set pragmas for better performance\n\tpragmas := []string{\n\t\t\"PRAGMA foreign_keys = ON;\",\n\t\t\"PRAGMA journal_mode = WAL;\",\n\t\t\"PRAGMA page_size = 4096;\",\n\t\t\"PRAGMA cache_size = -8000;\",\n\t\t\"PRAGMA synchronous = NORMAL;\",\n\t}\n\n\tfor _, pragma := range pragmas {\n\t\tif _, err = db.Exec(pragma); err != nil {\n\t\t\tlogging.Error(\"Failed to set pragma\", pragma, err)\n\t\t} else {\n\t\t\tlogging.Debug(\"Set pragma\", \"pragma\", pragma)\n\t\t}\n\t}\n\n\tgoose.SetBaseFS(FS)\n\n\tif err := goose.SetDialect(\"sqlite3\"); err != nil {\n\t\tlogging.Error(\"Failed to set dialect\", \"error\", err)\n\t\treturn nil, fmt.Errorf(\"failed to set dialect: %w\", err)\n\t}\n\n\tif err := goose.Up(db, \"migrations\"); err != nil {\n\t\tlogging.Error(\"Failed to apply migrations\", \"error\", err)\n\t\treturn nil, fmt.Errorf(\"failed to apply migrations: %w\", err)\n\t}\n\treturn db, nil\n}\n"], ["/opencode/internal/lsp/protocol/pattern_interfaces.go", "package protocol\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n)\n\n// PatternInfo is an interface for types that represent glob patterns\ntype PatternInfo interface {\n\tGetPattern() string\n\tGetBasePath() string\n\tisPattern() // marker method\n}\n\n// StringPattern implements PatternInfo for string patterns\ntype StringPattern struct {\n\tPattern string\n}\n\nfunc (p StringPattern) GetPattern() string { return p.Pattern }\nfunc (p StringPattern) GetBasePath() string { return \"\" }\nfunc (p StringPattern) isPattern() {}\n\n// RelativePatternInfo implements PatternInfo for RelativePattern\ntype RelativePatternInfo struct {\n\tRP RelativePattern\n\tBasePath string\n}\n\nfunc (p RelativePatternInfo) GetPattern() string { return string(p.RP.Pattern) }\nfunc (p RelativePatternInfo) GetBasePath() string { return p.BasePath }\nfunc (p RelativePatternInfo) isPattern() {}\n\n// AsPattern converts GlobPattern to a PatternInfo object\nfunc (g *GlobPattern) AsPattern() (PatternInfo, error) {\n\tif g.Value == nil {\n\t\treturn nil, fmt.Errorf(\"nil pattern\")\n\t}\n\n\tswitch v := g.Value.(type) {\n\tcase string:\n\t\treturn StringPattern{Pattern: v}, nil\n\tcase RelativePattern:\n\t\t// Handle BaseURI which could be string or DocumentUri\n\t\tbasePath := \"\"\n\t\tswitch baseURI := v.BaseURI.Value.(type) {\n\t\tcase string:\n\t\t\tbasePath = strings.TrimPrefix(baseURI, \"file://\")\n\t\tcase DocumentUri:\n\t\t\tbasePath = strings.TrimPrefix(string(baseURI), \"file://\")\n\t\tdefault:\n\t\t\treturn nil, fmt.Errorf(\"unknown BaseURI type: %T\", v.BaseURI.Value)\n\t\t}\n\t\treturn RelativePatternInfo{RP: v, BasePath: basePath}, nil\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"unknown pattern type: %T\", g.Value)\n\t}\n}\n"], ["/opencode/internal/db/db.go", "// Code generated by sqlc. DO NOT EDIT.\n// versions:\n// sqlc v1.29.0\n\npackage db\n\nimport (\n\t\"context\"\n\t\"database/sql\"\n\t\"fmt\"\n)\n\ntype DBTX interface {\n\tExecContext(context.Context, string, ...interface{}) (sql.Result, error)\n\tPrepareContext(context.Context, string) (*sql.Stmt, error)\n\tQueryContext(context.Context, string, ...interface{}) (*sql.Rows, error)\n\tQueryRowContext(context.Context, string, ...interface{}) *sql.Row\n}\n\nfunc New(db DBTX) *Queries {\n\treturn &Queries{db: db}\n}\n\nfunc Prepare(ctx context.Context, db DBTX) (*Queries, error) {\n\tq := Queries{db: db}\n\tvar err error\n\tif q.createFileStmt, err = db.PrepareContext(ctx, createFile); err != nil {\n\t\treturn nil, fmt.Errorf(\"error preparing query CreateFile: %w\", err)\n\t}\n\tif q.createMessageStmt, err = db.PrepareContext(ctx, createMessage); err != nil {\n\t\treturn nil, fmt.Errorf(\"error preparing query CreateMessage: %w\", err)\n\t}\n\tif q.createSessionStmt, err = db.PrepareContext(ctx, createSession); err != nil {\n\t\treturn nil, fmt.Errorf(\"error preparing query CreateSession: %w\", err)\n\t}\n\tif q.deleteFileStmt, err = db.PrepareContext(ctx, deleteFile); err != nil {\n\t\treturn nil, fmt.Errorf(\"error preparing query DeleteFile: %w\", err)\n\t}\n\tif q.deleteMessageStmt, err = db.PrepareContext(ctx, deleteMessage); err != nil {\n\t\treturn nil, fmt.Errorf(\"error preparing query DeleteMessage: %w\", err)\n\t}\n\tif q.deleteSessionStmt, err = db.PrepareContext(ctx, deleteSession); err != nil {\n\t\treturn nil, fmt.Errorf(\"error preparing query DeleteSession: %w\", err)\n\t}\n\tif q.deleteSessionFilesStmt, err = db.PrepareContext(ctx, deleteSessionFiles); err != nil {\n\t\treturn nil, fmt.Errorf(\"error preparing query DeleteSessionFiles: %w\", err)\n\t}\n\tif q.deleteSessionMessagesStmt, err = db.PrepareContext(ctx, deleteSessionMessages); err != nil {\n\t\treturn nil, fmt.Errorf(\"error preparing query DeleteSessionMessages: %w\", err)\n\t}\n\tif q.getFileStmt, err = db.PrepareContext(ctx, getFile); err != nil {\n\t\treturn nil, fmt.Errorf(\"error preparing query GetFile: %w\", err)\n\t}\n\tif q.getFileByPathAndSessionStmt, err = db.PrepareContext(ctx, getFileByPathAndSession); err != nil {\n\t\treturn nil, fmt.Errorf(\"error preparing query GetFileByPathAndSession: %w\", err)\n\t}\n\tif q.getMessageStmt, err = db.PrepareContext(ctx, getMessage); err != nil {\n\t\treturn nil, fmt.Errorf(\"error preparing query GetMessage: %w\", err)\n\t}\n\tif q.getSessionByIDStmt, err = db.PrepareContext(ctx, getSessionByID); err != nil {\n\t\treturn nil, fmt.Errorf(\"error preparing query GetSessionByID: %w\", err)\n\t}\n\tif q.listFilesByPathStmt, err = db.PrepareContext(ctx, listFilesByPath); err != nil {\n\t\treturn nil, fmt.Errorf(\"error preparing query ListFilesByPath: %w\", err)\n\t}\n\tif q.listFilesBySessionStmt, err = db.PrepareContext(ctx, listFilesBySession); err != nil {\n\t\treturn nil, fmt.Errorf(\"error preparing query ListFilesBySession: %w\", err)\n\t}\n\tif q.listLatestSessionFilesStmt, err = db.PrepareContext(ctx, listLatestSessionFiles); err != nil {\n\t\treturn nil, fmt.Errorf(\"error preparing query ListLatestSessionFiles: %w\", err)\n\t}\n\tif q.listMessagesBySessionStmt, err = db.PrepareContext(ctx, listMessagesBySession); err != nil {\n\t\treturn nil, fmt.Errorf(\"error preparing query ListMessagesBySession: %w\", err)\n\t}\n\tif q.listNewFilesStmt, err = db.PrepareContext(ctx, listNewFiles); err != nil {\n\t\treturn nil, fmt.Errorf(\"error preparing query ListNewFiles: %w\", err)\n\t}\n\tif q.listSessionsStmt, err = db.PrepareContext(ctx, listSessions); err != nil {\n\t\treturn nil, fmt.Errorf(\"error preparing query ListSessions: %w\", err)\n\t}\n\tif q.updateFileStmt, err = db.PrepareContext(ctx, updateFile); err != nil {\n\t\treturn nil, fmt.Errorf(\"error preparing query UpdateFile: %w\", err)\n\t}\n\tif q.updateMessageStmt, err = db.PrepareContext(ctx, updateMessage); err != nil {\n\t\treturn nil, fmt.Errorf(\"error preparing query UpdateMessage: %w\", err)\n\t}\n\tif q.updateSessionStmt, err = db.PrepareContext(ctx, updateSession); err != nil {\n\t\treturn nil, fmt.Errorf(\"error preparing query UpdateSession: %w\", err)\n\t}\n\treturn &q, nil\n}\n\nfunc (q *Queries) Close() error {\n\tvar err error\n\tif q.createFileStmt != nil {\n\t\tif cerr := q.createFileStmt.Close(); cerr != nil {\n\t\t\terr = fmt.Errorf(\"error closing createFileStmt: %w\", cerr)\n\t\t}\n\t}\n\tif q.createMessageStmt != nil {\n\t\tif cerr := q.createMessageStmt.Close(); cerr != nil {\n\t\t\terr = fmt.Errorf(\"error closing createMessageStmt: %w\", cerr)\n\t\t}\n\t}\n\tif q.createSessionStmt != nil {\n\t\tif cerr := q.createSessionStmt.Close(); cerr != nil {\n\t\t\terr = fmt.Errorf(\"error closing createSessionStmt: %w\", cerr)\n\t\t}\n\t}\n\tif q.deleteFileStmt != nil {\n\t\tif cerr := q.deleteFileStmt.Close(); cerr != nil {\n\t\t\terr = fmt.Errorf(\"error closing deleteFileStmt: %w\", cerr)\n\t\t}\n\t}\n\tif q.deleteMessageStmt != nil {\n\t\tif cerr := q.deleteMessageStmt.Close(); cerr != nil {\n\t\t\terr = fmt.Errorf(\"error closing deleteMessageStmt: %w\", cerr)\n\t\t}\n\t}\n\tif q.deleteSessionStmt != nil {\n\t\tif cerr := q.deleteSessionStmt.Close(); cerr != nil {\n\t\t\terr = fmt.Errorf(\"error closing deleteSessionStmt: %w\", cerr)\n\t\t}\n\t}\n\tif q.deleteSessionFilesStmt != nil {\n\t\tif cerr := q.deleteSessionFilesStmt.Close(); cerr != nil {\n\t\t\terr = fmt.Errorf(\"error closing deleteSessionFilesStmt: %w\", cerr)\n\t\t}\n\t}\n\tif q.deleteSessionMessagesStmt != nil {\n\t\tif cerr := q.deleteSessionMessagesStmt.Close(); cerr != nil {\n\t\t\terr = fmt.Errorf(\"error closing deleteSessionMessagesStmt: %w\", cerr)\n\t\t}\n\t}\n\tif q.getFileStmt != nil {\n\t\tif cerr := q.getFileStmt.Close(); cerr != nil {\n\t\t\terr = fmt.Errorf(\"error closing getFileStmt: %w\", cerr)\n\t\t}\n\t}\n\tif q.getFileByPathAndSessionStmt != nil {\n\t\tif cerr := q.getFileByPathAndSessionStmt.Close(); cerr != nil {\n\t\t\terr = fmt.Errorf(\"error closing getFileByPathAndSessionStmt: %w\", cerr)\n\t\t}\n\t}\n\tif q.getMessageStmt != nil {\n\t\tif cerr := q.getMessageStmt.Close(); cerr != nil {\n\t\t\terr = fmt.Errorf(\"error closing getMessageStmt: %w\", cerr)\n\t\t}\n\t}\n\tif q.getSessionByIDStmt != nil {\n\t\tif cerr := q.getSessionByIDStmt.Close(); cerr != nil {\n\t\t\terr = fmt.Errorf(\"error closing getSessionByIDStmt: %w\", cerr)\n\t\t}\n\t}\n\tif q.listFilesByPathStmt != nil {\n\t\tif cerr := q.listFilesByPathStmt.Close(); cerr != nil {\n\t\t\terr = fmt.Errorf(\"error closing listFilesByPathStmt: %w\", cerr)\n\t\t}\n\t}\n\tif q.listFilesBySessionStmt != nil {\n\t\tif cerr := q.listFilesBySessionStmt.Close(); cerr != nil {\n\t\t\terr = fmt.Errorf(\"error closing listFilesBySessionStmt: %w\", cerr)\n\t\t}\n\t}\n\tif q.listLatestSessionFilesStmt != nil {\n\t\tif cerr := q.listLatestSessionFilesStmt.Close(); cerr != nil {\n\t\t\terr = fmt.Errorf(\"error closing listLatestSessionFilesStmt: %w\", cerr)\n\t\t}\n\t}\n\tif q.listMessagesBySessionStmt != nil {\n\t\tif cerr := q.listMessagesBySessionStmt.Close(); cerr != nil {\n\t\t\terr = fmt.Errorf(\"error closing listMessagesBySessionStmt: %w\", cerr)\n\t\t}\n\t}\n\tif q.listNewFilesStmt != nil {\n\t\tif cerr := q.listNewFilesStmt.Close(); cerr != nil {\n\t\t\terr = fmt.Errorf(\"error closing listNewFilesStmt: %w\", cerr)\n\t\t}\n\t}\n\tif q.listSessionsStmt != nil {\n\t\tif cerr := q.listSessionsStmt.Close(); cerr != nil {\n\t\t\terr = fmt.Errorf(\"error closing listSessionsStmt: %w\", cerr)\n\t\t}\n\t}\n\tif q.updateFileStmt != nil {\n\t\tif cerr := q.updateFileStmt.Close(); cerr != nil {\n\t\t\terr = fmt.Errorf(\"error closing updateFileStmt: %w\", cerr)\n\t\t}\n\t}\n\tif q.updateMessageStmt != nil {\n\t\tif cerr := q.updateMessageStmt.Close(); cerr != nil {\n\t\t\terr = fmt.Errorf(\"error closing updateMessageStmt: %w\", cerr)\n\t\t}\n\t}\n\tif q.updateSessionStmt != nil {\n\t\tif cerr := q.updateSessionStmt.Close(); cerr != nil {\n\t\t\terr = fmt.Errorf(\"error closing updateSessionStmt: %w\", cerr)\n\t\t}\n\t}\n\treturn err\n}\n\nfunc (q *Queries) exec(ctx context.Context, stmt *sql.Stmt, query string, args ...interface{}) (sql.Result, error) {\n\tswitch {\n\tcase stmt != nil && q.tx != nil:\n\t\treturn q.tx.StmtContext(ctx, stmt).ExecContext(ctx, args...)\n\tcase stmt != nil:\n\t\treturn stmt.ExecContext(ctx, args...)\n\tdefault:\n\t\treturn q.db.ExecContext(ctx, query, args...)\n\t}\n}\n\nfunc (q *Queries) query(ctx context.Context, stmt *sql.Stmt, query string, args ...interface{}) (*sql.Rows, error) {\n\tswitch {\n\tcase stmt != nil && q.tx != nil:\n\t\treturn q.tx.StmtContext(ctx, stmt).QueryContext(ctx, args...)\n\tcase stmt != nil:\n\t\treturn stmt.QueryContext(ctx, args...)\n\tdefault:\n\t\treturn q.db.QueryContext(ctx, query, args...)\n\t}\n}\n\nfunc (q *Queries) queryRow(ctx context.Context, stmt *sql.Stmt, query string, args ...interface{}) *sql.Row {\n\tswitch {\n\tcase stmt != nil && q.tx != nil:\n\t\treturn q.tx.StmtContext(ctx, stmt).QueryRowContext(ctx, args...)\n\tcase stmt != nil:\n\t\treturn stmt.QueryRowContext(ctx, args...)\n\tdefault:\n\t\treturn q.db.QueryRowContext(ctx, query, args...)\n\t}\n}\n\ntype Queries struct {\n\tdb DBTX\n\ttx *sql.Tx\n\tcreateFileStmt *sql.Stmt\n\tcreateMessageStmt *sql.Stmt\n\tcreateSessionStmt *sql.Stmt\n\tdeleteFileStmt *sql.Stmt\n\tdeleteMessageStmt *sql.Stmt\n\tdeleteSessionStmt *sql.Stmt\n\tdeleteSessionFilesStmt *sql.Stmt\n\tdeleteSessionMessagesStmt *sql.Stmt\n\tgetFileStmt *sql.Stmt\n\tgetFileByPathAndSessionStmt *sql.Stmt\n\tgetMessageStmt *sql.Stmt\n\tgetSessionByIDStmt *sql.Stmt\n\tlistFilesByPathStmt *sql.Stmt\n\tlistFilesBySessionStmt *sql.Stmt\n\tlistLatestSessionFilesStmt *sql.Stmt\n\tlistMessagesBySessionStmt *sql.Stmt\n\tlistNewFilesStmt *sql.Stmt\n\tlistSessionsStmt *sql.Stmt\n\tupdateFileStmt *sql.Stmt\n\tupdateMessageStmt *sql.Stmt\n\tupdateSessionStmt *sql.Stmt\n}\n\nfunc (q *Queries) WithTx(tx *sql.Tx) *Queries {\n\treturn &Queries{\n\t\tdb: tx,\n\t\ttx: tx,\n\t\tcreateFileStmt: q.createFileStmt,\n\t\tcreateMessageStmt: q.createMessageStmt,\n\t\tcreateSessionStmt: q.createSessionStmt,\n\t\tdeleteFileStmt: q.deleteFileStmt,\n\t\tdeleteMessageStmt: q.deleteMessageStmt,\n\t\tdeleteSessionStmt: q.deleteSessionStmt,\n\t\tdeleteSessionFilesStmt: q.deleteSessionFilesStmt,\n\t\tdeleteSessionMessagesStmt: q.deleteSessionMessagesStmt,\n\t\tgetFileStmt: q.getFileStmt,\n\t\tgetFileByPathAndSessionStmt: q.getFileByPathAndSessionStmt,\n\t\tgetMessageStmt: q.getMessageStmt,\n\t\tgetSessionByIDStmt: q.getSessionByIDStmt,\n\t\tlistFilesByPathStmt: q.listFilesByPathStmt,\n\t\tlistFilesBySessionStmt: q.listFilesBySessionStmt,\n\t\tlistLatestSessionFilesStmt: q.listLatestSessionFilesStmt,\n\t\tlistMessagesBySessionStmt: q.listMessagesBySessionStmt,\n\t\tlistNewFilesStmt: q.listNewFilesStmt,\n\t\tlistSessionsStmt: q.listSessionsStmt,\n\t\tupdateFileStmt: q.updateFileStmt,\n\t\tupdateMessageStmt: q.updateMessageStmt,\n\t\tupdateSessionStmt: q.updateSessionStmt,\n\t}\n}\n"], ["/opencode/internal/tui/theme/theme.go", "package theme\n\nimport (\n\t\"github.com/charmbracelet/lipgloss\"\n)\n\n// Theme defines the interface for all UI themes in the application.\n// All colors must be defined as lipgloss.AdaptiveColor to support\n// both light and dark terminal backgrounds.\ntype Theme interface {\n\t// Base colors\n\tPrimary() lipgloss.AdaptiveColor\n\tSecondary() lipgloss.AdaptiveColor\n\tAccent() lipgloss.AdaptiveColor\n\n\t// Status colors\n\tError() lipgloss.AdaptiveColor\n\tWarning() lipgloss.AdaptiveColor\n\tSuccess() lipgloss.AdaptiveColor\n\tInfo() lipgloss.AdaptiveColor\n\n\t// Text colors\n\tText() lipgloss.AdaptiveColor\n\tTextMuted() lipgloss.AdaptiveColor\n\tTextEmphasized() lipgloss.AdaptiveColor\n\n\t// Background colors\n\tBackground() lipgloss.AdaptiveColor\n\tBackgroundSecondary() lipgloss.AdaptiveColor\n\tBackgroundDarker() lipgloss.AdaptiveColor\n\n\t// Border colors\n\tBorderNormal() lipgloss.AdaptiveColor\n\tBorderFocused() lipgloss.AdaptiveColor\n\tBorderDim() lipgloss.AdaptiveColor\n\n\t// Diff view colors\n\tDiffAdded() lipgloss.AdaptiveColor\n\tDiffRemoved() lipgloss.AdaptiveColor\n\tDiffContext() lipgloss.AdaptiveColor\n\tDiffHunkHeader() lipgloss.AdaptiveColor\n\tDiffHighlightAdded() lipgloss.AdaptiveColor\n\tDiffHighlightRemoved() lipgloss.AdaptiveColor\n\tDiffAddedBg() lipgloss.AdaptiveColor\n\tDiffRemovedBg() lipgloss.AdaptiveColor\n\tDiffContextBg() lipgloss.AdaptiveColor\n\tDiffLineNumber() lipgloss.AdaptiveColor\n\tDiffAddedLineNumberBg() lipgloss.AdaptiveColor\n\tDiffRemovedLineNumberBg() lipgloss.AdaptiveColor\n\n\t// Markdown colors\n\tMarkdownText() lipgloss.AdaptiveColor\n\tMarkdownHeading() lipgloss.AdaptiveColor\n\tMarkdownLink() lipgloss.AdaptiveColor\n\tMarkdownLinkText() lipgloss.AdaptiveColor\n\tMarkdownCode() lipgloss.AdaptiveColor\n\tMarkdownBlockQuote() lipgloss.AdaptiveColor\n\tMarkdownEmph() lipgloss.AdaptiveColor\n\tMarkdownStrong() lipgloss.AdaptiveColor\n\tMarkdownHorizontalRule() lipgloss.AdaptiveColor\n\tMarkdownListItem() lipgloss.AdaptiveColor\n\tMarkdownListEnumeration() lipgloss.AdaptiveColor\n\tMarkdownImage() lipgloss.AdaptiveColor\n\tMarkdownImageText() lipgloss.AdaptiveColor\n\tMarkdownCodeBlock() lipgloss.AdaptiveColor\n\n\t// Syntax highlighting colors\n\tSyntaxComment() lipgloss.AdaptiveColor\n\tSyntaxKeyword() lipgloss.AdaptiveColor\n\tSyntaxFunction() lipgloss.AdaptiveColor\n\tSyntaxVariable() lipgloss.AdaptiveColor\n\tSyntaxString() lipgloss.AdaptiveColor\n\tSyntaxNumber() lipgloss.AdaptiveColor\n\tSyntaxType() lipgloss.AdaptiveColor\n\tSyntaxOperator() lipgloss.AdaptiveColor\n\tSyntaxPunctuation() lipgloss.AdaptiveColor\n}\n\n// BaseTheme provides a default implementation of the Theme interface\n// that can be embedded in concrete theme implementations.\ntype BaseTheme struct {\n\t// Base colors\n\tPrimaryColor lipgloss.AdaptiveColor\n\tSecondaryColor lipgloss.AdaptiveColor\n\tAccentColor lipgloss.AdaptiveColor\n\n\t// Status colors\n\tErrorColor lipgloss.AdaptiveColor\n\tWarningColor lipgloss.AdaptiveColor\n\tSuccessColor lipgloss.AdaptiveColor\n\tInfoColor lipgloss.AdaptiveColor\n\n\t// Text colors\n\tTextColor lipgloss.AdaptiveColor\n\tTextMutedColor lipgloss.AdaptiveColor\n\tTextEmphasizedColor lipgloss.AdaptiveColor\n\n\t// Background colors\n\tBackgroundColor lipgloss.AdaptiveColor\n\tBackgroundSecondaryColor lipgloss.AdaptiveColor\n\tBackgroundDarkerColor lipgloss.AdaptiveColor\n\n\t// Border colors\n\tBorderNormalColor lipgloss.AdaptiveColor\n\tBorderFocusedColor lipgloss.AdaptiveColor\n\tBorderDimColor lipgloss.AdaptiveColor\n\n\t// Diff view colors\n\tDiffAddedColor lipgloss.AdaptiveColor\n\tDiffRemovedColor lipgloss.AdaptiveColor\n\tDiffContextColor lipgloss.AdaptiveColor\n\tDiffHunkHeaderColor lipgloss.AdaptiveColor\n\tDiffHighlightAddedColor lipgloss.AdaptiveColor\n\tDiffHighlightRemovedColor lipgloss.AdaptiveColor\n\tDiffAddedBgColor lipgloss.AdaptiveColor\n\tDiffRemovedBgColor lipgloss.AdaptiveColor\n\tDiffContextBgColor lipgloss.AdaptiveColor\n\tDiffLineNumberColor lipgloss.AdaptiveColor\n\tDiffAddedLineNumberBgColor lipgloss.AdaptiveColor\n\tDiffRemovedLineNumberBgColor lipgloss.AdaptiveColor\n\n\t// Markdown colors\n\tMarkdownTextColor lipgloss.AdaptiveColor\n\tMarkdownHeadingColor lipgloss.AdaptiveColor\n\tMarkdownLinkColor lipgloss.AdaptiveColor\n\tMarkdownLinkTextColor lipgloss.AdaptiveColor\n\tMarkdownCodeColor lipgloss.AdaptiveColor\n\tMarkdownBlockQuoteColor lipgloss.AdaptiveColor\n\tMarkdownEmphColor lipgloss.AdaptiveColor\n\tMarkdownStrongColor lipgloss.AdaptiveColor\n\tMarkdownHorizontalRuleColor lipgloss.AdaptiveColor\n\tMarkdownListItemColor lipgloss.AdaptiveColor\n\tMarkdownListEnumerationColor lipgloss.AdaptiveColor\n\tMarkdownImageColor lipgloss.AdaptiveColor\n\tMarkdownImageTextColor lipgloss.AdaptiveColor\n\tMarkdownCodeBlockColor lipgloss.AdaptiveColor\n\n\t// Syntax highlighting colors\n\tSyntaxCommentColor lipgloss.AdaptiveColor\n\tSyntaxKeywordColor lipgloss.AdaptiveColor\n\tSyntaxFunctionColor lipgloss.AdaptiveColor\n\tSyntaxVariableColor lipgloss.AdaptiveColor\n\tSyntaxStringColor lipgloss.AdaptiveColor\n\tSyntaxNumberColor lipgloss.AdaptiveColor\n\tSyntaxTypeColor lipgloss.AdaptiveColor\n\tSyntaxOperatorColor lipgloss.AdaptiveColor\n\tSyntaxPunctuationColor lipgloss.AdaptiveColor\n}\n\n// Implement the Theme interface for BaseTheme\nfunc (t *BaseTheme) Primary() lipgloss.AdaptiveColor { return t.PrimaryColor }\nfunc (t *BaseTheme) Secondary() lipgloss.AdaptiveColor { return t.SecondaryColor }\nfunc (t *BaseTheme) Accent() lipgloss.AdaptiveColor { return t.AccentColor }\n\nfunc (t *BaseTheme) Error() lipgloss.AdaptiveColor { return t.ErrorColor }\nfunc (t *BaseTheme) Warning() lipgloss.AdaptiveColor { return t.WarningColor }\nfunc (t *BaseTheme) Success() lipgloss.AdaptiveColor { return t.SuccessColor }\nfunc (t *BaseTheme) Info() lipgloss.AdaptiveColor { return t.InfoColor }\n\nfunc (t *BaseTheme) Text() lipgloss.AdaptiveColor { return t.TextColor }\nfunc (t *BaseTheme) TextMuted() lipgloss.AdaptiveColor { return t.TextMutedColor }\nfunc (t *BaseTheme) TextEmphasized() lipgloss.AdaptiveColor { return t.TextEmphasizedColor }\n\nfunc (t *BaseTheme) Background() lipgloss.AdaptiveColor { return t.BackgroundColor }\nfunc (t *BaseTheme) BackgroundSecondary() lipgloss.AdaptiveColor { return t.BackgroundSecondaryColor }\nfunc (t *BaseTheme) BackgroundDarker() lipgloss.AdaptiveColor { return t.BackgroundDarkerColor }\n\nfunc (t *BaseTheme) BorderNormal() lipgloss.AdaptiveColor { return t.BorderNormalColor }\nfunc (t *BaseTheme) BorderFocused() lipgloss.AdaptiveColor { return t.BorderFocusedColor }\nfunc (t *BaseTheme) BorderDim() lipgloss.AdaptiveColor { return t.BorderDimColor }\n\nfunc (t *BaseTheme) DiffAdded() lipgloss.AdaptiveColor { return t.DiffAddedColor }\nfunc (t *BaseTheme) DiffRemoved() lipgloss.AdaptiveColor { return t.DiffRemovedColor }\nfunc (t *BaseTheme) DiffContext() lipgloss.AdaptiveColor { return t.DiffContextColor }\nfunc (t *BaseTheme) DiffHunkHeader() lipgloss.AdaptiveColor { return t.DiffHunkHeaderColor }\nfunc (t *BaseTheme) DiffHighlightAdded() lipgloss.AdaptiveColor { return t.DiffHighlightAddedColor }\nfunc (t *BaseTheme) DiffHighlightRemoved() lipgloss.AdaptiveColor { return t.DiffHighlightRemovedColor }\nfunc (t *BaseTheme) DiffAddedBg() lipgloss.AdaptiveColor { return t.DiffAddedBgColor }\nfunc (t *BaseTheme) DiffRemovedBg() lipgloss.AdaptiveColor { return t.DiffRemovedBgColor }\nfunc (t *BaseTheme) DiffContextBg() lipgloss.AdaptiveColor { return t.DiffContextBgColor }\nfunc (t *BaseTheme) DiffLineNumber() lipgloss.AdaptiveColor { return t.DiffLineNumberColor }\nfunc (t *BaseTheme) DiffAddedLineNumberBg() lipgloss.AdaptiveColor { return t.DiffAddedLineNumberBgColor }\nfunc (t *BaseTheme) DiffRemovedLineNumberBg() lipgloss.AdaptiveColor { return t.DiffRemovedLineNumberBgColor }\n\nfunc (t *BaseTheme) MarkdownText() lipgloss.AdaptiveColor { return t.MarkdownTextColor }\nfunc (t *BaseTheme) MarkdownHeading() lipgloss.AdaptiveColor { return t.MarkdownHeadingColor }\nfunc (t *BaseTheme) MarkdownLink() lipgloss.AdaptiveColor { return t.MarkdownLinkColor }\nfunc (t *BaseTheme) MarkdownLinkText() lipgloss.AdaptiveColor { return t.MarkdownLinkTextColor }\nfunc (t *BaseTheme) MarkdownCode() lipgloss.AdaptiveColor { return t.MarkdownCodeColor }\nfunc (t *BaseTheme) MarkdownBlockQuote() lipgloss.AdaptiveColor { return t.MarkdownBlockQuoteColor }\nfunc (t *BaseTheme) MarkdownEmph() lipgloss.AdaptiveColor { return t.MarkdownEmphColor }\nfunc (t *BaseTheme) MarkdownStrong() lipgloss.AdaptiveColor { return t.MarkdownStrongColor }\nfunc (t *BaseTheme) MarkdownHorizontalRule() lipgloss.AdaptiveColor { return t.MarkdownHorizontalRuleColor }\nfunc (t *BaseTheme) MarkdownListItem() lipgloss.AdaptiveColor { return t.MarkdownListItemColor }\nfunc (t *BaseTheme) MarkdownListEnumeration() lipgloss.AdaptiveColor { return t.MarkdownListEnumerationColor }\nfunc (t *BaseTheme) MarkdownImage() lipgloss.AdaptiveColor { return t.MarkdownImageColor }\nfunc (t *BaseTheme) MarkdownImageText() lipgloss.AdaptiveColor { return t.MarkdownImageTextColor }\nfunc (t *BaseTheme) MarkdownCodeBlock() lipgloss.AdaptiveColor { return t.MarkdownCodeBlockColor }\n\nfunc (t *BaseTheme) SyntaxComment() lipgloss.AdaptiveColor { return t.SyntaxCommentColor }\nfunc (t *BaseTheme) SyntaxKeyword() lipgloss.AdaptiveColor { return t.SyntaxKeywordColor }\nfunc (t *BaseTheme) SyntaxFunction() lipgloss.AdaptiveColor { return t.SyntaxFunctionColor }\nfunc (t *BaseTheme) SyntaxVariable() lipgloss.AdaptiveColor { return t.SyntaxVariableColor }\nfunc (t *BaseTheme) SyntaxString() lipgloss.AdaptiveColor { return t.SyntaxStringColor }\nfunc (t *BaseTheme) SyntaxNumber() lipgloss.AdaptiveColor { return t.SyntaxNumberColor }\nfunc (t *BaseTheme) SyntaxType() lipgloss.AdaptiveColor { return t.SyntaxTypeColor }\nfunc (t *BaseTheme) SyntaxOperator() lipgloss.AdaptiveColor { return t.SyntaxOperatorColor }\nfunc (t *BaseTheme) SyntaxPunctuation() lipgloss.AdaptiveColor { return t.SyntaxPunctuationColor }"], ["/opencode/internal/lsp/protocol/interface.go", "package protocol\n\nimport \"fmt\"\n\n// TextEditResult is an interface for types that represent workspace symbols\ntype WorkspaceSymbolResult interface {\n\tGetName() string\n\tGetLocation() Location\n\tisWorkspaceSymbol() // marker method\n}\n\nfunc (ws *WorkspaceSymbol) GetName() string { return ws.Name }\nfunc (ws *WorkspaceSymbol) GetLocation() Location {\n\tswitch v := ws.Location.Value.(type) {\n\tcase Location:\n\t\treturn v\n\tcase LocationUriOnly:\n\t\treturn Location{URI: v.URI}\n\t}\n\treturn Location{}\n}\nfunc (ws *WorkspaceSymbol) isWorkspaceSymbol() {}\n\nfunc (si *SymbolInformation) GetName() string { return si.Name }\nfunc (si *SymbolInformation) GetLocation() Location { return si.Location }\nfunc (si *SymbolInformation) isWorkspaceSymbol() {}\n\n// Results converts the Value to a slice of WorkspaceSymbolResult\nfunc (r Or_Result_workspace_symbol) Results() ([]WorkspaceSymbolResult, error) {\n\tif r.Value == nil {\n\t\treturn make([]WorkspaceSymbolResult, 0), nil\n\t}\n\tswitch v := r.Value.(type) {\n\tcase []WorkspaceSymbol:\n\t\tresults := make([]WorkspaceSymbolResult, len(v))\n\t\tfor i := range v {\n\t\t\tresults[i] = &v[i]\n\t\t}\n\t\treturn results, nil\n\tcase []SymbolInformation:\n\t\tresults := make([]WorkspaceSymbolResult, len(v))\n\t\tfor i := range v {\n\t\t\tresults[i] = &v[i]\n\t\t}\n\t\treturn results, nil\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"unknown symbol type: %T\", r.Value)\n\t}\n}\n\n// TextEditResult is an interface for types that represent document symbols\ntype DocumentSymbolResult interface {\n\tGetRange() Range\n\tGetName() string\n\tisDocumentSymbol() // marker method\n}\n\nfunc (ds *DocumentSymbol) GetRange() Range { return ds.Range }\nfunc (ds *DocumentSymbol) GetName() string { return ds.Name }\nfunc (ds *DocumentSymbol) isDocumentSymbol() {}\n\nfunc (si *SymbolInformation) GetRange() Range { return si.Location.Range }\n\n// Note: SymbolInformation already has GetName() implemented above\nfunc (si *SymbolInformation) isDocumentSymbol() {}\n\n// Results converts the Value to a slice of DocumentSymbolResult\nfunc (r Or_Result_textDocument_documentSymbol) Results() ([]DocumentSymbolResult, error) {\n\tif r.Value == nil {\n\t\treturn make([]DocumentSymbolResult, 0), nil\n\t}\n\tswitch v := r.Value.(type) {\n\tcase []DocumentSymbol:\n\t\tresults := make([]DocumentSymbolResult, len(v))\n\t\tfor i := range v {\n\t\t\tresults[i] = &v[i]\n\t\t}\n\t\treturn results, nil\n\tcase []SymbolInformation:\n\t\tresults := make([]DocumentSymbolResult, len(v))\n\t\tfor i := range v {\n\t\t\tresults[i] = &v[i]\n\t\t}\n\t\treturn results, nil\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"unknown document symbol type: %T\", v)\n\t}\n}\n\n// TextEditResult is an interface for types that can be used as text edits\ntype TextEditResult interface {\n\tGetRange() Range\n\tGetNewText() string\n\tisTextEdit() // marker method\n}\n\nfunc (te *TextEdit) GetRange() Range { return te.Range }\nfunc (te *TextEdit) GetNewText() string { return te.NewText }\nfunc (te *TextEdit) isTextEdit() {}\n\n// Convert Or_TextDocumentEdit_edits_Elem to TextEdit\nfunc (e Or_TextDocumentEdit_edits_Elem) AsTextEdit() (TextEdit, error) {\n\tif e.Value == nil {\n\t\treturn TextEdit{}, fmt.Errorf(\"nil text edit\")\n\t}\n\tswitch v := e.Value.(type) {\n\tcase TextEdit:\n\t\treturn v, nil\n\tcase AnnotatedTextEdit:\n\t\treturn TextEdit{\n\t\t\tRange: v.Range,\n\t\t\tNewText: v.NewText,\n\t\t}, nil\n\tdefault:\n\t\treturn TextEdit{}, fmt.Errorf(\"unknown text edit type: %T\", e.Value)\n\t}\n}\n"], ["/opencode/internal/format/format.go", "package format\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"strings\"\n)\n\n// OutputFormat represents the output format type for non-interactive mode\ntype OutputFormat string\n\nconst (\n\t// Text format outputs the AI response as plain text.\n\tText OutputFormat = \"text\"\n\n\t// JSON format outputs the AI response wrapped in a JSON object.\n\tJSON OutputFormat = \"json\"\n)\n\n// String returns the string representation of the OutputFormat\nfunc (f OutputFormat) String() string {\n\treturn string(f)\n}\n\n// SupportedFormats is a list of all supported output formats as strings\nvar SupportedFormats = []string{\n\tstring(Text),\n\tstring(JSON),\n}\n\n// Parse converts a string to an OutputFormat\nfunc Parse(s string) (OutputFormat, error) {\n\ts = strings.ToLower(strings.TrimSpace(s))\n\n\tswitch s {\n\tcase string(Text):\n\t\treturn Text, nil\n\tcase string(JSON):\n\t\treturn JSON, nil\n\tdefault:\n\t\treturn \"\", fmt.Errorf(\"invalid format: %s\", s)\n\t}\n}\n\n// IsValid checks if the provided format string is supported\nfunc IsValid(s string) bool {\n\t_, err := Parse(s)\n\treturn err == nil\n}\n\n// GetHelpText returns a formatted string describing all supported formats\nfunc GetHelpText() string {\n\treturn fmt.Sprintf(`Supported output formats:\n- %s: Plain text output (default)\n- %s: Output wrapped in a JSON object`,\n\t\tText, JSON)\n}\n\n// FormatOutput formats the AI response according to the specified format\nfunc FormatOutput(content string, formatStr string) string {\n\tformat, err := Parse(formatStr)\n\tif err != nil {\n\t\t// Default to text format on error\n\t\treturn content\n\t}\n\n\tswitch format {\n\tcase JSON:\n\t\treturn formatAsJSON(content)\n\tcase Text:\n\t\tfallthrough\n\tdefault:\n\t\treturn content\n\t}\n}\n\n// formatAsJSON wraps the content in a simple JSON object\nfunc formatAsJSON(content string) string {\n\t// Use the JSON package to properly escape the content\n\tresponse := struct {\n\t\tResponse string `json:\"response\"`\n\t}{\n\t\tResponse: content,\n\t}\n\n\tjsonBytes, err := json.MarshalIndent(response, \"\", \" \")\n\tif err != nil {\n\t\t// In case of an error, return a manually formatted JSON\n\t\tjsonEscaped := strings.Replace(content, \"\\\\\", \"\\\\\\\\\", -1)\n\t\tjsonEscaped = strings.Replace(jsonEscaped, \"\\\"\", \"\\\\\\\"\", -1)\n\t\tjsonEscaped = strings.Replace(jsonEscaped, \"\\n\", \"\\\\n\", -1)\n\t\tjsonEscaped = strings.Replace(jsonEscaped, \"\\r\", \"\\\\r\", -1)\n\t\tjsonEscaped = strings.Replace(jsonEscaped, \"\\t\", \"\\\\t\", -1)\n\n\t\treturn fmt.Sprintf(\"{\\n \\\"response\\\": \\\"%s\\\"\\n}\", jsonEscaped)\n\t}\n\n\treturn string(jsonBytes)\n}\n"], ["/opencode/internal/lsp/protocol/tsdocument-changes.go", "// Copyright 2022 The Go Authors. All rights reserved.\n// Use of this source code is governed by a BSD-style\n// license that can be found in the LICENSE file.\n\npackage protocol\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n)\n\n// DocumentChange is a union of various file edit operations.\n//\n// Exactly one field of this struct is non-nil; see [DocumentChange.Valid].\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#resourceChanges\ntype DocumentChange struct {\n\tTextDocumentEdit *TextDocumentEdit\n\tCreateFile *CreateFile\n\tRenameFile *RenameFile\n\tDeleteFile *DeleteFile\n}\n\n// Valid reports whether the DocumentChange sum-type value is valid,\n// that is, exactly one of create, delete, edit, or rename.\nfunc (ch DocumentChange) Valid() bool {\n\tn := 0\n\tif ch.TextDocumentEdit != nil {\n\t\tn++\n\t}\n\tif ch.CreateFile != nil {\n\t\tn++\n\t}\n\tif ch.RenameFile != nil {\n\t\tn++\n\t}\n\tif ch.DeleteFile != nil {\n\t\tn++\n\t}\n\treturn n == 1\n}\n\nfunc (d *DocumentChange) UnmarshalJSON(data []byte) error {\n\tvar m map[string]any\n\tif err := json.Unmarshal(data, &m); err != nil {\n\t\treturn err\n\t}\n\n\tif _, ok := m[\"textDocument\"]; ok {\n\t\td.TextDocumentEdit = new(TextDocumentEdit)\n\t\treturn json.Unmarshal(data, d.TextDocumentEdit)\n\t}\n\n\t// The {Create,Rename,Delete}File types all share a 'kind' field.\n\tkind := m[\"kind\"]\n\tswitch kind {\n\tcase \"create\":\n\t\td.CreateFile = new(CreateFile)\n\t\treturn json.Unmarshal(data, d.CreateFile)\n\tcase \"rename\":\n\t\td.RenameFile = new(RenameFile)\n\t\treturn json.Unmarshal(data, d.RenameFile)\n\tcase \"delete\":\n\t\td.DeleteFile = new(DeleteFile)\n\t\treturn json.Unmarshal(data, d.DeleteFile)\n\t}\n\treturn fmt.Errorf(\"DocumentChanges: unexpected kind: %q\", kind)\n}\n\nfunc (d *DocumentChange) MarshalJSON() ([]byte, error) {\n\tif d.TextDocumentEdit != nil {\n\t\treturn json.Marshal(d.TextDocumentEdit)\n\t} else if d.CreateFile != nil {\n\t\treturn json.Marshal(d.CreateFile)\n\t} else if d.RenameFile != nil {\n\t\treturn json.Marshal(d.RenameFile)\n\t} else if d.DeleteFile != nil {\n\t\treturn json.Marshal(d.DeleteFile)\n\t}\n\treturn nil, fmt.Errorf(\"empty DocumentChanges union value\")\n}\n"], ["/opencode/internal/db/messages.sql.go", "// Code generated by sqlc. DO NOT EDIT.\n// versions:\n// sqlc v1.29.0\n// source: messages.sql\n\npackage db\n\nimport (\n\t\"context\"\n\t\"database/sql\"\n)\n\nconst createMessage = `-- name: CreateMessage :one\nINSERT INTO messages (\n id,\n session_id,\n role,\n parts,\n model,\n created_at,\n updated_at\n) VALUES (\n ?, ?, ?, ?, ?, strftime('%s', 'now'), strftime('%s', 'now')\n)\nRETURNING id, session_id, role, parts, model, created_at, updated_at, finished_at\n`\n\ntype CreateMessageParams struct {\n\tID string `json:\"id\"`\n\tSessionID string `json:\"session_id\"`\n\tRole string `json:\"role\"`\n\tParts string `json:\"parts\"`\n\tModel sql.NullString `json:\"model\"`\n}\n\nfunc (q *Queries) CreateMessage(ctx context.Context, arg CreateMessageParams) (Message, error) {\n\trow := q.queryRow(ctx, q.createMessageStmt, createMessage,\n\t\targ.ID,\n\t\targ.SessionID,\n\t\targ.Role,\n\t\targ.Parts,\n\t\targ.Model,\n\t)\n\tvar i Message\n\terr := row.Scan(\n\t\t&i.ID,\n\t\t&i.SessionID,\n\t\t&i.Role,\n\t\t&i.Parts,\n\t\t&i.Model,\n\t\t&i.CreatedAt,\n\t\t&i.UpdatedAt,\n\t\t&i.FinishedAt,\n\t)\n\treturn i, err\n}\n\nconst deleteMessage = `-- name: DeleteMessage :exec\nDELETE FROM messages\nWHERE id = ?\n`\n\nfunc (q *Queries) DeleteMessage(ctx context.Context, id string) error {\n\t_, err := q.exec(ctx, q.deleteMessageStmt, deleteMessage, id)\n\treturn err\n}\n\nconst deleteSessionMessages = `-- name: DeleteSessionMessages :exec\nDELETE FROM messages\nWHERE session_id = ?\n`\n\nfunc (q *Queries) DeleteSessionMessages(ctx context.Context, sessionID string) error {\n\t_, err := q.exec(ctx, q.deleteSessionMessagesStmt, deleteSessionMessages, sessionID)\n\treturn err\n}\n\nconst getMessage = `-- name: GetMessage :one\nSELECT id, session_id, role, parts, model, created_at, updated_at, finished_at\nFROM messages\nWHERE id = ? LIMIT 1\n`\n\nfunc (q *Queries) GetMessage(ctx context.Context, id string) (Message, error) {\n\trow := q.queryRow(ctx, q.getMessageStmt, getMessage, id)\n\tvar i Message\n\terr := row.Scan(\n\t\t&i.ID,\n\t\t&i.SessionID,\n\t\t&i.Role,\n\t\t&i.Parts,\n\t\t&i.Model,\n\t\t&i.CreatedAt,\n\t\t&i.UpdatedAt,\n\t\t&i.FinishedAt,\n\t)\n\treturn i, err\n}\n\nconst listMessagesBySession = `-- name: ListMessagesBySession :many\nSELECT id, session_id, role, parts, model, created_at, updated_at, finished_at\nFROM messages\nWHERE session_id = ?\nORDER BY created_at ASC\n`\n\nfunc (q *Queries) ListMessagesBySession(ctx context.Context, sessionID string) ([]Message, error) {\n\trows, err := q.query(ctx, q.listMessagesBySessionStmt, listMessagesBySession, sessionID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer rows.Close()\n\titems := []Message{}\n\tfor rows.Next() {\n\t\tvar i Message\n\t\tif err := rows.Scan(\n\t\t\t&i.ID,\n\t\t\t&i.SessionID,\n\t\t\t&i.Role,\n\t\t\t&i.Parts,\n\t\t\t&i.Model,\n\t\t\t&i.CreatedAt,\n\t\t\t&i.UpdatedAt,\n\t\t\t&i.FinishedAt,\n\t\t); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\titems = append(items, i)\n\t}\n\tif err := rows.Close(); err != nil {\n\t\treturn nil, err\n\t}\n\tif err := rows.Err(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn items, nil\n}\n\nconst updateMessage = `-- name: UpdateMessage :exec\nUPDATE messages\nSET\n parts = ?,\n finished_at = ?,\n updated_at = strftime('%s', 'now')\nWHERE id = ?\n`\n\ntype UpdateMessageParams struct {\n\tParts string `json:\"parts\"`\n\tFinishedAt sql.NullInt64 `json:\"finished_at\"`\n\tID string `json:\"id\"`\n}\n\nfunc (q *Queries) UpdateMessage(ctx context.Context, arg UpdateMessageParams) error {\n\t_, err := q.exec(ctx, q.updateMessageStmt, updateMessage, arg.Parts, arg.FinishedAt, arg.ID)\n\treturn err\n}\n"], ["/opencode/internal/db/files.sql.go", "// Code generated by sqlc. DO NOT EDIT.\n// versions:\n// sqlc v1.29.0\n// source: files.sql\n\npackage db\n\nimport (\n\t\"context\"\n)\n\nconst createFile = `-- name: CreateFile :one\nINSERT INTO files (\n id,\n session_id,\n path,\n content,\n version,\n created_at,\n updated_at\n) VALUES (\n ?, ?, ?, ?, ?, strftime('%s', 'now'), strftime('%s', 'now')\n)\nRETURNING id, session_id, path, content, version, created_at, updated_at\n`\n\ntype CreateFileParams struct {\n\tID string `json:\"id\"`\n\tSessionID string `json:\"session_id\"`\n\tPath string `json:\"path\"`\n\tContent string `json:\"content\"`\n\tVersion string `json:\"version\"`\n}\n\nfunc (q *Queries) CreateFile(ctx context.Context, arg CreateFileParams) (File, error) {\n\trow := q.queryRow(ctx, q.createFileStmt, createFile,\n\t\targ.ID,\n\t\targ.SessionID,\n\t\targ.Path,\n\t\targ.Content,\n\t\targ.Version,\n\t)\n\tvar i File\n\terr := row.Scan(\n\t\t&i.ID,\n\t\t&i.SessionID,\n\t\t&i.Path,\n\t\t&i.Content,\n\t\t&i.Version,\n\t\t&i.CreatedAt,\n\t\t&i.UpdatedAt,\n\t)\n\treturn i, err\n}\n\nconst deleteFile = `-- name: DeleteFile :exec\nDELETE FROM files\nWHERE id = ?\n`\n\nfunc (q *Queries) DeleteFile(ctx context.Context, id string) error {\n\t_, err := q.exec(ctx, q.deleteFileStmt, deleteFile, id)\n\treturn err\n}\n\nconst deleteSessionFiles = `-- name: DeleteSessionFiles :exec\nDELETE FROM files\nWHERE session_id = ?\n`\n\nfunc (q *Queries) DeleteSessionFiles(ctx context.Context, sessionID string) error {\n\t_, err := q.exec(ctx, q.deleteSessionFilesStmt, deleteSessionFiles, sessionID)\n\treturn err\n}\n\nconst getFile = `-- name: GetFile :one\nSELECT id, session_id, path, content, version, created_at, updated_at\nFROM files\nWHERE id = ? LIMIT 1\n`\n\nfunc (q *Queries) GetFile(ctx context.Context, id string) (File, error) {\n\trow := q.queryRow(ctx, q.getFileStmt, getFile, id)\n\tvar i File\n\terr := row.Scan(\n\t\t&i.ID,\n\t\t&i.SessionID,\n\t\t&i.Path,\n\t\t&i.Content,\n\t\t&i.Version,\n\t\t&i.CreatedAt,\n\t\t&i.UpdatedAt,\n\t)\n\treturn i, err\n}\n\nconst getFileByPathAndSession = `-- name: GetFileByPathAndSession :one\nSELECT id, session_id, path, content, version, created_at, updated_at\nFROM files\nWHERE path = ? AND session_id = ?\nORDER BY created_at DESC\nLIMIT 1\n`\n\ntype GetFileByPathAndSessionParams struct {\n\tPath string `json:\"path\"`\n\tSessionID string `json:\"session_id\"`\n}\n\nfunc (q *Queries) GetFileByPathAndSession(ctx context.Context, arg GetFileByPathAndSessionParams) (File, error) {\n\trow := q.queryRow(ctx, q.getFileByPathAndSessionStmt, getFileByPathAndSession, arg.Path, arg.SessionID)\n\tvar i File\n\terr := row.Scan(\n\t\t&i.ID,\n\t\t&i.SessionID,\n\t\t&i.Path,\n\t\t&i.Content,\n\t\t&i.Version,\n\t\t&i.CreatedAt,\n\t\t&i.UpdatedAt,\n\t)\n\treturn i, err\n}\n\nconst listFilesByPath = `-- name: ListFilesByPath :many\nSELECT id, session_id, path, content, version, created_at, updated_at\nFROM files\nWHERE path = ?\nORDER BY created_at DESC\n`\n\nfunc (q *Queries) ListFilesByPath(ctx context.Context, path string) ([]File, error) {\n\trows, err := q.query(ctx, q.listFilesByPathStmt, listFilesByPath, path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer rows.Close()\n\titems := []File{}\n\tfor rows.Next() {\n\t\tvar i File\n\t\tif err := rows.Scan(\n\t\t\t&i.ID,\n\t\t\t&i.SessionID,\n\t\t\t&i.Path,\n\t\t\t&i.Content,\n\t\t\t&i.Version,\n\t\t\t&i.CreatedAt,\n\t\t\t&i.UpdatedAt,\n\t\t); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\titems = append(items, i)\n\t}\n\tif err := rows.Close(); err != nil {\n\t\treturn nil, err\n\t}\n\tif err := rows.Err(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn items, nil\n}\n\nconst listFilesBySession = `-- name: ListFilesBySession :many\nSELECT id, session_id, path, content, version, created_at, updated_at\nFROM files\nWHERE session_id = ?\nORDER BY created_at ASC\n`\n\nfunc (q *Queries) ListFilesBySession(ctx context.Context, sessionID string) ([]File, error) {\n\trows, err := q.query(ctx, q.listFilesBySessionStmt, listFilesBySession, sessionID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer rows.Close()\n\titems := []File{}\n\tfor rows.Next() {\n\t\tvar i File\n\t\tif err := rows.Scan(\n\t\t\t&i.ID,\n\t\t\t&i.SessionID,\n\t\t\t&i.Path,\n\t\t\t&i.Content,\n\t\t\t&i.Version,\n\t\t\t&i.CreatedAt,\n\t\t\t&i.UpdatedAt,\n\t\t); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\titems = append(items, i)\n\t}\n\tif err := rows.Close(); err != nil {\n\t\treturn nil, err\n\t}\n\tif err := rows.Err(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn items, nil\n}\n\nconst listLatestSessionFiles = `-- name: ListLatestSessionFiles :many\nSELECT f.id, f.session_id, f.path, f.content, f.version, f.created_at, f.updated_at\nFROM files f\nINNER JOIN (\n SELECT path, MAX(created_at) as max_created_at\n FROM files\n GROUP BY path\n) latest ON f.path = latest.path AND f.created_at = latest.max_created_at\nWHERE f.session_id = ?\nORDER BY f.path\n`\n\nfunc (q *Queries) ListLatestSessionFiles(ctx context.Context, sessionID string) ([]File, error) {\n\trows, err := q.query(ctx, q.listLatestSessionFilesStmt, listLatestSessionFiles, sessionID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer rows.Close()\n\titems := []File{}\n\tfor rows.Next() {\n\t\tvar i File\n\t\tif err := rows.Scan(\n\t\t\t&i.ID,\n\t\t\t&i.SessionID,\n\t\t\t&i.Path,\n\t\t\t&i.Content,\n\t\t\t&i.Version,\n\t\t\t&i.CreatedAt,\n\t\t\t&i.UpdatedAt,\n\t\t); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\titems = append(items, i)\n\t}\n\tif err := rows.Close(); err != nil {\n\t\treturn nil, err\n\t}\n\tif err := rows.Err(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn items, nil\n}\n\nconst listNewFiles = `-- name: ListNewFiles :many\nSELECT id, session_id, path, content, version, created_at, updated_at\nFROM files\nWHERE is_new = 1\nORDER BY created_at DESC\n`\n\nfunc (q *Queries) ListNewFiles(ctx context.Context) ([]File, error) {\n\trows, err := q.query(ctx, q.listNewFilesStmt, listNewFiles)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer rows.Close()\n\titems := []File{}\n\tfor rows.Next() {\n\t\tvar i File\n\t\tif err := rows.Scan(\n\t\t\t&i.ID,\n\t\t\t&i.SessionID,\n\t\t\t&i.Path,\n\t\t\t&i.Content,\n\t\t\t&i.Version,\n\t\t\t&i.CreatedAt,\n\t\t\t&i.UpdatedAt,\n\t\t); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\titems = append(items, i)\n\t}\n\tif err := rows.Close(); err != nil {\n\t\treturn nil, err\n\t}\n\tif err := rows.Err(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn items, nil\n}\n\nconst updateFile = `-- name: UpdateFile :one\nUPDATE files\nSET\n content = ?,\n version = ?,\n updated_at = strftime('%s', 'now')\nWHERE id = ?\nRETURNING id, session_id, path, content, version, created_at, updated_at\n`\n\ntype UpdateFileParams struct {\n\tContent string `json:\"content\"`\n\tVersion string `json:\"version\"`\n\tID string `json:\"id\"`\n}\n\nfunc (q *Queries) UpdateFile(ctx context.Context, arg UpdateFileParams) (File, error) {\n\trow := q.queryRow(ctx, q.updateFileStmt, updateFile, arg.Content, arg.Version, arg.ID)\n\tvar i File\n\terr := row.Scan(\n\t\t&i.ID,\n\t\t&i.SessionID,\n\t\t&i.Path,\n\t\t&i.Content,\n\t\t&i.Version,\n\t\t&i.CreatedAt,\n\t\t&i.UpdatedAt,\n\t)\n\treturn i, err\n}\n"], ["/opencode/internal/llm/prompt/task.go", "package prompt\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/opencode-ai/opencode/internal/llm/models\"\n)\n\nfunc TaskPrompt(_ models.ModelProvider) string {\n\tagentPrompt := `You are an agent for OpenCode. Given the user's prompt, you should use the tools available to you to answer the user's question.\nNotes:\n1. IMPORTANT: You should be concise, direct, and to the point, since your responses will be displayed on a command line interface. Answer the user's question directly, without elaboration, explanation, or details. One word answers are best. Avoid introductions, conclusions, and explanations. You MUST avoid text before/after your response, such as \"The answer is .\", \"Here is the content of the file...\" or \"Based on the information provided, the answer is...\" or \"Here is what I will do next...\".\n2. When relevant, share file names and code snippets relevant to the query\n3. Any file paths you return in your final response MUST be absolute. DO NOT use relative paths.`\n\n\treturn fmt.Sprintf(\"%s\\n%s\\n\", agentPrompt, getEnvironmentInfo())\n}\n"], ["/opencode/internal/llm/provider/vertexai.go", "package provider\n\nimport (\n\t\"context\"\n\t\"os\"\n\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n\t\"google.golang.org/genai\"\n)\n\ntype VertexAIClient ProviderClient\n\nfunc newVertexAIClient(opts providerClientOptions) VertexAIClient {\n\tgeminiOpts := geminiOptions{}\n\tfor _, o := range opts.geminiOptions {\n\t\to(&geminiOpts)\n\t}\n\n\tclient, err := genai.NewClient(context.Background(), &genai.ClientConfig{\n\t\tProject: os.Getenv(\"VERTEXAI_PROJECT\"),\n\t\tLocation: os.Getenv(\"VERTEXAI_LOCATION\"),\n\t\tBackend: genai.BackendVertexAI,\n\t})\n\tif err != nil {\n\t\tlogging.Error(\"Failed to create VertexAI client\", \"error\", err)\n\t\treturn nil\n\t}\n\n\treturn &geminiClient{\n\t\tproviderOptions: opts,\n\t\toptions: geminiOpts,\n\t\tclient: client,\n\t}\n}\n"], ["/opencode/internal/version/version.go", "package version\n\nimport \"runtime/debug\"\n\n// Build-time parameters set via -ldflags\nvar Version = \"unknown\"\n\n// A user may install pug using `go install github.com/opencode-ai/opencode@latest`.\n// without -ldflags, in which case the version above is unset. As a workaround\n// we use the embedded build version that *is* set when using `go install` (and\n// is only set for `go install` and not for `go build`).\nfunc init() {\n\tinfo, ok := debug.ReadBuildInfo()\n\tif !ok {\n\t\t// < go v1.18\n\t\treturn\n\t}\n\tmainVersion := info.Main.Version\n\tif mainVersion == \"\" || mainVersion == \"(devel)\" {\n\t\t// bin not built using `go install`\n\t\treturn\n\t}\n\t// bin built using `go install`\n\tVersion = mainVersion\n}\n"], ["/opencode/internal/llm/models/models.go", "package models\n\nimport \"maps\"\n\ntype (\n\tModelID string\n\tModelProvider string\n)\n\ntype Model struct {\n\tID ModelID `json:\"id\"`\n\tName string `json:\"name\"`\n\tProvider ModelProvider `json:\"provider\"`\n\tAPIModel string `json:\"api_model\"`\n\tCostPer1MIn float64 `json:\"cost_per_1m_in\"`\n\tCostPer1MOut float64 `json:\"cost_per_1m_out\"`\n\tCostPer1MInCached float64 `json:\"cost_per_1m_in_cached\"`\n\tCostPer1MOutCached float64 `json:\"cost_per_1m_out_cached\"`\n\tContextWindow int64 `json:\"context_window\"`\n\tDefaultMaxTokens int64 `json:\"default_max_tokens\"`\n\tCanReason bool `json:\"can_reason\"`\n\tSupportsAttachments bool `json:\"supports_attachments\"`\n}\n\n// Model IDs\nconst ( // GEMINI\n\t// Bedrock\n\tBedrockClaude37Sonnet ModelID = \"bedrock.claude-3.7-sonnet\"\n)\n\nconst (\n\tProviderBedrock ModelProvider = \"bedrock\"\n\t// ForTests\n\tProviderMock ModelProvider = \"__mock\"\n)\n\n// Providers in order of popularity\nvar ProviderPopularity = map[ModelProvider]int{\n\tProviderCopilot: 1,\n\tProviderAnthropic: 2,\n\tProviderOpenAI: 3,\n\tProviderGemini: 4,\n\tProviderGROQ: 5,\n\tProviderOpenRouter: 6,\n\tProviderBedrock: 7,\n\tProviderAzure: 8,\n\tProviderVertexAI: 9,\n}\n\nvar SupportedModels = map[ModelID]Model{\n\t//\n\t// // GEMINI\n\t// GEMINI25: {\n\t// \tID: GEMINI25,\n\t// \tName: \"Gemini 2.5 Pro\",\n\t// \tProvider: ProviderGemini,\n\t// \tAPIModel: \"gemini-2.5-pro-exp-03-25\",\n\t// \tCostPer1MIn: 0,\n\t// \tCostPer1MInCached: 0,\n\t// \tCostPer1MOutCached: 0,\n\t// \tCostPer1MOut: 0,\n\t// },\n\t//\n\t// GRMINI20Flash: {\n\t// \tID: GRMINI20Flash,\n\t// \tName: \"Gemini 2.0 Flash\",\n\t// \tProvider: ProviderGemini,\n\t// \tAPIModel: \"gemini-2.0-flash\",\n\t// \tCostPer1MIn: 0.1,\n\t// \tCostPer1MInCached: 0,\n\t// \tCostPer1MOutCached: 0.025,\n\t// \tCostPer1MOut: 0.4,\n\t// },\n\t//\n\t// // Bedrock\n\tBedrockClaude37Sonnet: {\n\t\tID: BedrockClaude37Sonnet,\n\t\tName: \"Bedrock: Claude 3.7 Sonnet\",\n\t\tProvider: ProviderBedrock,\n\t\tAPIModel: \"anthropic.claude-3-7-sonnet-20250219-v1:0\",\n\t\tCostPer1MIn: 3.0,\n\t\tCostPer1MInCached: 3.75,\n\t\tCostPer1MOutCached: 0.30,\n\t\tCostPer1MOut: 15.0,\n\t},\n}\n\nfunc init() {\n\tmaps.Copy(SupportedModels, AnthropicModels)\n\tmaps.Copy(SupportedModels, OpenAIModels)\n\tmaps.Copy(SupportedModels, GeminiModels)\n\tmaps.Copy(SupportedModels, GroqModels)\n\tmaps.Copy(SupportedModels, AzureModels)\n\tmaps.Copy(SupportedModels, OpenRouterModels)\n\tmaps.Copy(SupportedModels, XAIModels)\n\tmaps.Copy(SupportedModels, VertexAIGeminiModels)\n\tmaps.Copy(SupportedModels, CopilotModels)\n}\n"], ["/opencode/internal/lsp/language.go", "package lsp\n\nimport (\n\t\"path/filepath\"\n\t\"strings\"\n\n\t\"github.com/opencode-ai/opencode/internal/lsp/protocol\"\n)\n\nfunc DetectLanguageID(uri string) protocol.LanguageKind {\n\text := strings.ToLower(filepath.Ext(uri))\n\tswitch ext {\n\tcase \".abap\":\n\t\treturn protocol.LangABAP\n\tcase \".bat\":\n\t\treturn protocol.LangWindowsBat\n\tcase \".bib\", \".bibtex\":\n\t\treturn protocol.LangBibTeX\n\tcase \".clj\":\n\t\treturn protocol.LangClojure\n\tcase \".coffee\":\n\t\treturn protocol.LangCoffeescript\n\tcase \".c\":\n\t\treturn protocol.LangC\n\tcase \".cpp\", \".cxx\", \".cc\", \".c++\":\n\t\treturn protocol.LangCPP\n\tcase \".cs\":\n\t\treturn protocol.LangCSharp\n\tcase \".css\":\n\t\treturn protocol.LangCSS\n\tcase \".d\":\n\t\treturn protocol.LangD\n\tcase \".pas\", \".pascal\":\n\t\treturn protocol.LangDelphi\n\tcase \".diff\", \".patch\":\n\t\treturn protocol.LangDiff\n\tcase \".dart\":\n\t\treturn protocol.LangDart\n\tcase \".dockerfile\":\n\t\treturn protocol.LangDockerfile\n\tcase \".ex\", \".exs\":\n\t\treturn protocol.LangElixir\n\tcase \".erl\", \".hrl\":\n\t\treturn protocol.LangErlang\n\tcase \".fs\", \".fsi\", \".fsx\", \".fsscript\":\n\t\treturn protocol.LangFSharp\n\tcase \".gitcommit\":\n\t\treturn protocol.LangGitCommit\n\tcase \".gitrebase\":\n\t\treturn protocol.LangGitRebase\n\tcase \".go\":\n\t\treturn protocol.LangGo\n\tcase \".groovy\":\n\t\treturn protocol.LangGroovy\n\tcase \".hbs\", \".handlebars\":\n\t\treturn protocol.LangHandlebars\n\tcase \".hs\":\n\t\treturn protocol.LangHaskell\n\tcase \".html\", \".htm\":\n\t\treturn protocol.LangHTML\n\tcase \".ini\":\n\t\treturn protocol.LangIni\n\tcase \".java\":\n\t\treturn protocol.LangJava\n\tcase \".js\":\n\t\treturn protocol.LangJavaScript\n\tcase \".jsx\":\n\t\treturn protocol.LangJavaScriptReact\n\tcase \".json\":\n\t\treturn protocol.LangJSON\n\tcase \".tex\", \".latex\":\n\t\treturn protocol.LangLaTeX\n\tcase \".less\":\n\t\treturn protocol.LangLess\n\tcase \".lua\":\n\t\treturn protocol.LangLua\n\tcase \".makefile\", \"makefile\":\n\t\treturn protocol.LangMakefile\n\tcase \".md\", \".markdown\":\n\t\treturn protocol.LangMarkdown\n\tcase \".m\":\n\t\treturn protocol.LangObjectiveC\n\tcase \".mm\":\n\t\treturn protocol.LangObjectiveCPP\n\tcase \".pl\":\n\t\treturn protocol.LangPerl\n\tcase \".pm\":\n\t\treturn protocol.LangPerl6\n\tcase \".php\":\n\t\treturn protocol.LangPHP\n\tcase \".ps1\", \".psm1\":\n\t\treturn protocol.LangPowershell\n\tcase \".pug\", \".jade\":\n\t\treturn protocol.LangPug\n\tcase \".py\":\n\t\treturn protocol.LangPython\n\tcase \".r\":\n\t\treturn protocol.LangR\n\tcase \".cshtml\", \".razor\":\n\t\treturn protocol.LangRazor\n\tcase \".rb\":\n\t\treturn protocol.LangRuby\n\tcase \".rs\":\n\t\treturn protocol.LangRust\n\tcase \".scss\":\n\t\treturn protocol.LangSCSS\n\tcase \".sass\":\n\t\treturn protocol.LangSASS\n\tcase \".scala\":\n\t\treturn protocol.LangScala\n\tcase \".shader\":\n\t\treturn protocol.LangShaderLab\n\tcase \".sh\", \".bash\", \".zsh\", \".ksh\":\n\t\treturn protocol.LangShellScript\n\tcase \".sql\":\n\t\treturn protocol.LangSQL\n\tcase \".swift\":\n\t\treturn protocol.LangSwift\n\tcase \".ts\":\n\t\treturn protocol.LangTypeScript\n\tcase \".tsx\":\n\t\treturn protocol.LangTypeScriptReact\n\tcase \".xml\":\n\t\treturn protocol.LangXML\n\tcase \".xsl\":\n\t\treturn protocol.LangXSL\n\tcase \".yaml\", \".yml\":\n\t\treturn protocol.LangYAML\n\tdefault:\n\t\treturn protocol.LanguageKind(\"\") // Unknown language\n\t}\n}\n"], ["/opencode/internal/lsp/protocol.go", "package lsp\n\nimport (\n\t\"encoding/json\"\n)\n\n// Message represents a JSON-RPC 2.0 message\ntype Message struct {\n\tJSONRPC string `json:\"jsonrpc\"`\n\tID int32 `json:\"id,omitempty\"`\n\tMethod string `json:\"method,omitempty\"`\n\tParams json.RawMessage `json:\"params,omitempty\"`\n\tResult json.RawMessage `json:\"result,omitempty\"`\n\tError *ResponseError `json:\"error,omitempty\"`\n}\n\n// ResponseError represents a JSON-RPC 2.0 error\ntype ResponseError struct {\n\tCode int `json:\"code\"`\n\tMessage string `json:\"message\"`\n}\n\nfunc NewRequest(id int32, method string, params any) (*Message, error) {\n\tparamsJSON, err := json.Marshal(params)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Message{\n\t\tJSONRPC: \"2.0\",\n\t\tID: id,\n\t\tMethod: method,\n\t\tParams: paramsJSON,\n\t}, nil\n}\n\nfunc NewNotification(method string, params any) (*Message, error) {\n\tparamsJSON, err := json.Marshal(params)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Message{\n\t\tJSONRPC: \"2.0\",\n\t\tMethod: method,\n\t\tParams: paramsJSON,\n\t}, nil\n}\n"], ["/opencode/internal/llm/prompt/title.go", "package prompt\n\nimport \"github.com/opencode-ai/opencode/internal/llm/models\"\n\nfunc TitlePrompt(_ models.ModelProvider) string {\n\treturn `you will generate a short title based on the first message a user begins a conversation with\n- ensure it is not more than 50 characters long\n- the title should be a summary of the user's message\n- it should be one line long\n- do not use quotes or colons\n- the entire text you return will be used as the title\n- never return anything that is more than one sentence (one line) long`\n}\n"], ["/opencode/internal/llm/models/copilot.go", "package models\n\nconst (\n\tProviderCopilot ModelProvider = \"copilot\"\n\n\t// GitHub Copilot models\n\tCopilotGTP35Turbo ModelID = \"copilot.gpt-3.5-turbo\"\n\tCopilotGPT4o ModelID = \"copilot.gpt-4o\"\n\tCopilotGPT4oMini ModelID = \"copilot.gpt-4o-mini\"\n\tCopilotGPT41 ModelID = \"copilot.gpt-4.1\"\n\tCopilotClaude35 ModelID = \"copilot.claude-3.5-sonnet\"\n\tCopilotClaude37 ModelID = \"copilot.claude-3.7-sonnet\"\n\tCopilotClaude4 ModelID = \"copilot.claude-sonnet-4\"\n\tCopilotO1 ModelID = \"copilot.o1\"\n\tCopilotO3Mini ModelID = \"copilot.o3-mini\"\n\tCopilotO4Mini ModelID = \"copilot.o4-mini\"\n\tCopilotGemini20 ModelID = \"copilot.gemini-2.0-flash\"\n\tCopilotGemini25 ModelID = \"copilot.gemini-2.5-pro\"\n\tCopilotGPT4 ModelID = \"copilot.gpt-4\"\n\tCopilotClaude37Thought ModelID = \"copilot.claude-3.7-sonnet-thought\"\n)\n\nvar CopilotAnthropicModels = []ModelID{\n\tCopilotClaude35,\n\tCopilotClaude37,\n\tCopilotClaude37Thought,\n\tCopilotClaude4,\n}\n\n// GitHub Copilot models available through GitHub's API\nvar CopilotModels = map[ModelID]Model{\n\tCopilotGTP35Turbo: {\n\t\tID: CopilotGTP35Turbo,\n\t\tName: \"GitHub Copilot GPT-3.5-turbo\",\n\t\tProvider: ProviderCopilot,\n\t\tAPIModel: \"gpt-3.5-turbo\",\n\t\tCostPer1MIn: 0.0, // Included in GitHub Copilot subscription\n\t\tCostPer1MInCached: 0.0,\n\t\tCostPer1MOutCached: 0.0,\n\t\tCostPer1MOut: 0.0,\n\t\tContextWindow: 16_384,\n\t\tDefaultMaxTokens: 4096,\n\t\tSupportsAttachments: true,\n\t},\n\tCopilotGPT4o: {\n\t\tID: CopilotGPT4o,\n\t\tName: \"GitHub Copilot GPT-4o\",\n\t\tProvider: ProviderCopilot,\n\t\tAPIModel: \"gpt-4o\",\n\t\tCostPer1MIn: 0.0, // Included in GitHub Copilot subscription\n\t\tCostPer1MInCached: 0.0,\n\t\tCostPer1MOutCached: 0.0,\n\t\tCostPer1MOut: 0.0,\n\t\tContextWindow: 128_000,\n\t\tDefaultMaxTokens: 16384,\n\t\tSupportsAttachments: true,\n\t},\n\tCopilotGPT4oMini: {\n\t\tID: CopilotGPT4oMini,\n\t\tName: \"GitHub Copilot GPT-4o Mini\",\n\t\tProvider: ProviderCopilot,\n\t\tAPIModel: \"gpt-4o-mini\",\n\t\tCostPer1MIn: 0.0, // Included in GitHub Copilot subscription\n\t\tCostPer1MInCached: 0.0,\n\t\tCostPer1MOutCached: 0.0,\n\t\tCostPer1MOut: 0.0,\n\t\tContextWindow: 128_000,\n\t\tDefaultMaxTokens: 4096,\n\t\tSupportsAttachments: true,\n\t},\n\tCopilotGPT41: {\n\t\tID: CopilotGPT41,\n\t\tName: \"GitHub Copilot GPT-4.1\",\n\t\tProvider: ProviderCopilot,\n\t\tAPIModel: \"gpt-4.1\",\n\t\tCostPer1MIn: 0.0, // Included in GitHub Copilot subscription\n\t\tCostPer1MInCached: 0.0,\n\t\tCostPer1MOutCached: 0.0,\n\t\tCostPer1MOut: 0.0,\n\t\tContextWindow: 128_000,\n\t\tDefaultMaxTokens: 16384,\n\t\tCanReason: true,\n\t\tSupportsAttachments: true,\n\t},\n\tCopilotClaude35: {\n\t\tID: CopilotClaude35,\n\t\tName: \"GitHub Copilot Claude 3.5 Sonnet\",\n\t\tProvider: ProviderCopilot,\n\t\tAPIModel: \"claude-3.5-sonnet\",\n\t\tCostPer1MIn: 0.0, // Included in GitHub Copilot subscription\n\t\tCostPer1MInCached: 0.0,\n\t\tCostPer1MOutCached: 0.0,\n\t\tCostPer1MOut: 0.0,\n\t\tContextWindow: 90_000,\n\t\tDefaultMaxTokens: 8192,\n\t\tSupportsAttachments: true,\n\t},\n\tCopilotClaude37: {\n\t\tID: CopilotClaude37,\n\t\tName: \"GitHub Copilot Claude 3.7 Sonnet\",\n\t\tProvider: ProviderCopilot,\n\t\tAPIModel: \"claude-3.7-sonnet\",\n\t\tCostPer1MIn: 0.0, // Included in GitHub Copilot subscription\n\t\tCostPer1MInCached: 0.0,\n\t\tCostPer1MOutCached: 0.0,\n\t\tCostPer1MOut: 0.0,\n\t\tContextWindow: 200_000,\n\t\tDefaultMaxTokens: 16384,\n\t\tSupportsAttachments: true,\n\t},\n\tCopilotClaude4: {\n\t\tID: CopilotClaude4,\n\t\tName: \"GitHub Copilot Claude Sonnet 4\",\n\t\tProvider: ProviderCopilot,\n\t\tAPIModel: \"claude-sonnet-4\",\n\t\tCostPer1MIn: 0.0, // Included in GitHub Copilot subscription\n\t\tCostPer1MInCached: 0.0,\n\t\tCostPer1MOutCached: 0.0,\n\t\tCostPer1MOut: 0.0,\n\t\tContextWindow: 128_000,\n\t\tDefaultMaxTokens: 16000,\n\t\tSupportsAttachments: true,\n\t},\n\tCopilotO1: {\n\t\tID: CopilotO1,\n\t\tName: \"GitHub Copilot o1\",\n\t\tProvider: ProviderCopilot,\n\t\tAPIModel: \"o1\",\n\t\tCostPer1MIn: 0.0, // Included in GitHub Copilot subscription\n\t\tCostPer1MInCached: 0.0,\n\t\tCostPer1MOutCached: 0.0,\n\t\tCostPer1MOut: 0.0,\n\t\tContextWindow: 200_000,\n\t\tDefaultMaxTokens: 100_000,\n\t\tCanReason: true,\n\t\tSupportsAttachments: false,\n\t},\n\tCopilotO3Mini: {\n\t\tID: CopilotO3Mini,\n\t\tName: \"GitHub Copilot o3-mini\",\n\t\tProvider: ProviderCopilot,\n\t\tAPIModel: \"o3-mini\",\n\t\tCostPer1MIn: 0.0, // Included in GitHub Copilot subscription\n\t\tCostPer1MInCached: 0.0,\n\t\tCostPer1MOutCached: 0.0,\n\t\tCostPer1MOut: 0.0,\n\t\tContextWindow: 200_000,\n\t\tDefaultMaxTokens: 100_000,\n\t\tCanReason: true,\n\t\tSupportsAttachments: false,\n\t},\n\tCopilotO4Mini: {\n\t\tID: CopilotO4Mini,\n\t\tName: \"GitHub Copilot o4-mini\",\n\t\tProvider: ProviderCopilot,\n\t\tAPIModel: \"o4-mini\",\n\t\tCostPer1MIn: 0.0, // Included in GitHub Copilot subscription\n\t\tCostPer1MInCached: 0.0,\n\t\tCostPer1MOutCached: 0.0,\n\t\tCostPer1MOut: 0.0,\n\t\tContextWindow: 128_000,\n\t\tDefaultMaxTokens: 16_384,\n\t\tCanReason: true,\n\t\tSupportsAttachments: true,\n\t},\n\tCopilotGemini20: {\n\t\tID: CopilotGemini20,\n\t\tName: \"GitHub Copilot Gemini 2.0 Flash\",\n\t\tProvider: ProviderCopilot,\n\t\tAPIModel: \"gemini-2.0-flash-001\",\n\t\tCostPer1MIn: 0.0, // Included in GitHub Copilot subscription\n\t\tCostPer1MInCached: 0.0,\n\t\tCostPer1MOutCached: 0.0,\n\t\tCostPer1MOut: 0.0,\n\t\tContextWindow: 1_000_000,\n\t\tDefaultMaxTokens: 8192,\n\t\tSupportsAttachments: true,\n\t},\n\tCopilotGemini25: {\n\t\tID: CopilotGemini25,\n\t\tName: \"GitHub Copilot Gemini 2.5 Pro\",\n\t\tProvider: ProviderCopilot,\n\t\tAPIModel: \"gemini-2.5-pro\",\n\t\tCostPer1MIn: 0.0, // Included in GitHub Copilot subscription\n\t\tCostPer1MInCached: 0.0,\n\t\tCostPer1MOutCached: 0.0,\n\t\tCostPer1MOut: 0.0,\n\t\tContextWindow: 128_000,\n\t\tDefaultMaxTokens: 64000,\n\t\tSupportsAttachments: true,\n\t},\n\tCopilotGPT4: {\n\t\tID: CopilotGPT4,\n\t\tName: \"GitHub Copilot GPT-4\",\n\t\tProvider: ProviderCopilot,\n\t\tAPIModel: \"gpt-4\",\n\t\tCostPer1MIn: 0.0, // Included in GitHub Copilot subscription\n\t\tCostPer1MInCached: 0.0,\n\t\tCostPer1MOutCached: 0.0,\n\t\tCostPer1MOut: 0.0,\n\t\tContextWindow: 32_768,\n\t\tDefaultMaxTokens: 4096,\n\t\tSupportsAttachments: true,\n\t},\n\tCopilotClaude37Thought: {\n\t\tID: CopilotClaude37Thought,\n\t\tName: \"GitHub Copilot Claude 3.7 Sonnet Thinking\",\n\t\tProvider: ProviderCopilot,\n\t\tAPIModel: \"claude-3.7-sonnet-thought\",\n\t\tCostPer1MIn: 0.0, // Included in GitHub Copilot subscription\n\t\tCostPer1MInCached: 0.0,\n\t\tCostPer1MOutCached: 0.0,\n\t\tCostPer1MOut: 0.0,\n\t\tContextWindow: 200_000,\n\t\tDefaultMaxTokens: 16384,\n\t\tCanReason: true,\n\t\tSupportsAttachments: true,\n\t},\n}\n"], ["/opencode/internal/llm/prompt/summarizer.go", "package prompt\n\nimport \"github.com/opencode-ai/opencode/internal/llm/models\"\n\nfunc SummarizerPrompt(_ models.ModelProvider) string {\n\treturn `You are a helpful AI assistant tasked with summarizing conversations.\n\nWhen asked to summarize, provide a detailed but concise summary of the conversation. \nFocus on information that would be helpful for continuing the conversation, including:\n- What was done\n- What is currently being worked on\n- Which files are being modified\n- What needs to be done next\n\nYour summary should be comprehensive enough to provide context but concise enough to be quickly understood.`\n}\n"], ["/opencode/internal/llm/models/groq.go", "package models\n\nconst (\n\tProviderGROQ ModelProvider = \"groq\"\n\n\t// GROQ\n\tQWENQwq ModelID = \"qwen-qwq\"\n\n\t// GROQ preview models\n\tLlama4Scout ModelID = \"meta-llama/llama-4-scout-17b-16e-instruct\"\n\tLlama4Maverick ModelID = \"meta-llama/llama-4-maverick-17b-128e-instruct\"\n\tLlama3_3_70BVersatile ModelID = \"llama-3.3-70b-versatile\"\n\tDeepseekR1DistillLlama70b ModelID = \"deepseek-r1-distill-llama-70b\"\n)\n\nvar GroqModels = map[ModelID]Model{\n\t//\n\t// GROQ\n\tQWENQwq: {\n\t\tID: QWENQwq,\n\t\tName: \"Qwen Qwq\",\n\t\tProvider: ProviderGROQ,\n\t\tAPIModel: \"qwen-qwq-32b\",\n\t\tCostPer1MIn: 0.29,\n\t\tCostPer1MInCached: 0.275,\n\t\tCostPer1MOutCached: 0.0,\n\t\tCostPer1MOut: 0.39,\n\t\tContextWindow: 128_000,\n\t\tDefaultMaxTokens: 50000,\n\t\t// for some reason, the groq api doesn't like the reasoningEffort parameter\n\t\tCanReason: false,\n\t\tSupportsAttachments: false,\n\t},\n\n\tLlama4Scout: {\n\t\tID: Llama4Scout,\n\t\tName: \"Llama4Scout\",\n\t\tProvider: ProviderGROQ,\n\t\tAPIModel: \"meta-llama/llama-4-scout-17b-16e-instruct\",\n\t\tCostPer1MIn: 0.11,\n\t\tCostPer1MInCached: 0,\n\t\tCostPer1MOutCached: 0,\n\t\tCostPer1MOut: 0.34,\n\t\tContextWindow: 128_000, // 10M when?\n\t\tSupportsAttachments: true,\n\t},\n\n\tLlama4Maverick: {\n\t\tID: Llama4Maverick,\n\t\tName: \"Llama4Maverick\",\n\t\tProvider: ProviderGROQ,\n\t\tAPIModel: \"meta-llama/llama-4-maverick-17b-128e-instruct\",\n\t\tCostPer1MIn: 0.20,\n\t\tCostPer1MInCached: 0,\n\t\tCostPer1MOutCached: 0,\n\t\tCostPer1MOut: 0.20,\n\t\tContextWindow: 128_000,\n\t\tSupportsAttachments: true,\n\t},\n\n\tLlama3_3_70BVersatile: {\n\t\tID: Llama3_3_70BVersatile,\n\t\tName: \"Llama3_3_70BVersatile\",\n\t\tProvider: ProviderGROQ,\n\t\tAPIModel: \"llama-3.3-70b-versatile\",\n\t\tCostPer1MIn: 0.59,\n\t\tCostPer1MInCached: 0,\n\t\tCostPer1MOutCached: 0,\n\t\tCostPer1MOut: 0.79,\n\t\tContextWindow: 128_000,\n\t\tSupportsAttachments: false,\n\t},\n\n\tDeepseekR1DistillLlama70b: {\n\t\tID: DeepseekR1DistillLlama70b,\n\t\tName: \"DeepseekR1DistillLlama70b\",\n\t\tProvider: ProviderGROQ,\n\t\tAPIModel: \"deepseek-r1-distill-llama-70b\",\n\t\tCostPer1MIn: 0.75,\n\t\tCostPer1MInCached: 0,\n\t\tCostPer1MOutCached: 0,\n\t\tCostPer1MOut: 0.99,\n\t\tContextWindow: 128_000,\n\t\tCanReason: true,\n\t\tSupportsAttachments: false,\n\t},\n}\n"], ["/opencode/internal/db/querier.go", "// Code generated by sqlc. DO NOT EDIT.\n// versions:\n// sqlc v1.29.0\n\npackage db\n\nimport (\n\t\"context\"\n)\n\ntype Querier interface {\n\tCreateFile(ctx context.Context, arg CreateFileParams) (File, error)\n\tCreateMessage(ctx context.Context, arg CreateMessageParams) (Message, error)\n\tCreateSession(ctx context.Context, arg CreateSessionParams) (Session, error)\n\tDeleteFile(ctx context.Context, id string) error\n\tDeleteMessage(ctx context.Context, id string) error\n\tDeleteSession(ctx context.Context, id string) error\n\tDeleteSessionFiles(ctx context.Context, sessionID string) error\n\tDeleteSessionMessages(ctx context.Context, sessionID string) error\n\tGetFile(ctx context.Context, id string) (File, error)\n\tGetFileByPathAndSession(ctx context.Context, arg GetFileByPathAndSessionParams) (File, error)\n\tGetMessage(ctx context.Context, id string) (Message, error)\n\tGetSessionByID(ctx context.Context, id string) (Session, error)\n\tListFilesByPath(ctx context.Context, path string) ([]File, error)\n\tListFilesBySession(ctx context.Context, sessionID string) ([]File, error)\n\tListLatestSessionFiles(ctx context.Context, sessionID string) ([]File, error)\n\tListMessagesBySession(ctx context.Context, sessionID string) ([]Message, error)\n\tListNewFiles(ctx context.Context) ([]File, error)\n\tListSessions(ctx context.Context) ([]Session, error)\n\tUpdateFile(ctx context.Context, arg UpdateFileParams) (File, error)\n\tUpdateMessage(ctx context.Context, arg UpdateMessageParams) error\n\tUpdateSession(ctx context.Context, arg UpdateSessionParams) (Session, error)\n}\n\nvar _ Querier = (*Queries)(nil)\n"], ["/opencode/internal/llm/models/openai.go", "package models\n\nconst (\n\tProviderOpenAI ModelProvider = \"openai\"\n\n\tGPT41 ModelID = \"gpt-4.1\"\n\tGPT41Mini ModelID = \"gpt-4.1-mini\"\n\tGPT41Nano ModelID = \"gpt-4.1-nano\"\n\tGPT45Preview ModelID = \"gpt-4.5-preview\"\n\tGPT4o ModelID = \"gpt-4o\"\n\tGPT4oMini ModelID = \"gpt-4o-mini\"\n\tO1 ModelID = \"o1\"\n\tO1Pro ModelID = \"o1-pro\"\n\tO1Mini ModelID = \"o1-mini\"\n\tO3 ModelID = \"o3\"\n\tO3Mini ModelID = \"o3-mini\"\n\tO4Mini ModelID = \"o4-mini\"\n)\n\nvar OpenAIModels = map[ModelID]Model{\n\tGPT41: {\n\t\tID: GPT41,\n\t\tName: \"GPT 4.1\",\n\t\tProvider: ProviderOpenAI,\n\t\tAPIModel: \"gpt-4.1\",\n\t\tCostPer1MIn: 2.00,\n\t\tCostPer1MInCached: 0.50,\n\t\tCostPer1MOutCached: 0.0,\n\t\tCostPer1MOut: 8.00,\n\t\tContextWindow: 1_047_576,\n\t\tDefaultMaxTokens: 20000,\n\t\tSupportsAttachments: true,\n\t},\n\tGPT41Mini: {\n\t\tID: GPT41Mini,\n\t\tName: \"GPT 4.1 mini\",\n\t\tProvider: ProviderOpenAI,\n\t\tAPIModel: \"gpt-4.1\",\n\t\tCostPer1MIn: 0.40,\n\t\tCostPer1MInCached: 0.10,\n\t\tCostPer1MOutCached: 0.0,\n\t\tCostPer1MOut: 1.60,\n\t\tContextWindow: 200_000,\n\t\tDefaultMaxTokens: 20000,\n\t\tSupportsAttachments: true,\n\t},\n\tGPT41Nano: {\n\t\tID: GPT41Nano,\n\t\tName: \"GPT 4.1 nano\",\n\t\tProvider: ProviderOpenAI,\n\t\tAPIModel: \"gpt-4.1-nano\",\n\t\tCostPer1MIn: 0.10,\n\t\tCostPer1MInCached: 0.025,\n\t\tCostPer1MOutCached: 0.0,\n\t\tCostPer1MOut: 0.40,\n\t\tContextWindow: 1_047_576,\n\t\tDefaultMaxTokens: 20000,\n\t\tSupportsAttachments: true,\n\t},\n\tGPT45Preview: {\n\t\tID: GPT45Preview,\n\t\tName: \"GPT 4.5 preview\",\n\t\tProvider: ProviderOpenAI,\n\t\tAPIModel: \"gpt-4.5-preview\",\n\t\tCostPer1MIn: 75.00,\n\t\tCostPer1MInCached: 37.50,\n\t\tCostPer1MOutCached: 0.0,\n\t\tCostPer1MOut: 150.00,\n\t\tContextWindow: 128_000,\n\t\tDefaultMaxTokens: 15000,\n\t\tSupportsAttachments: true,\n\t},\n\tGPT4o: {\n\t\tID: GPT4o,\n\t\tName: \"GPT 4o\",\n\t\tProvider: ProviderOpenAI,\n\t\tAPIModel: \"gpt-4o\",\n\t\tCostPer1MIn: 2.50,\n\t\tCostPer1MInCached: 1.25,\n\t\tCostPer1MOutCached: 0.0,\n\t\tCostPer1MOut: 10.00,\n\t\tContextWindow: 128_000,\n\t\tDefaultMaxTokens: 4096,\n\t\tSupportsAttachments: true,\n\t},\n\tGPT4oMini: {\n\t\tID: GPT4oMini,\n\t\tName: \"GPT 4o mini\",\n\t\tProvider: ProviderOpenAI,\n\t\tAPIModel: \"gpt-4o-mini\",\n\t\tCostPer1MIn: 0.15,\n\t\tCostPer1MInCached: 0.075,\n\t\tCostPer1MOutCached: 0.0,\n\t\tCostPer1MOut: 0.60,\n\t\tContextWindow: 128_000,\n\t\tSupportsAttachments: true,\n\t},\n\tO1: {\n\t\tID: O1,\n\t\tName: \"O1\",\n\t\tProvider: ProviderOpenAI,\n\t\tAPIModel: \"o1\",\n\t\tCostPer1MIn: 15.00,\n\t\tCostPer1MInCached: 7.50,\n\t\tCostPer1MOutCached: 0.0,\n\t\tCostPer1MOut: 60.00,\n\t\tContextWindow: 200_000,\n\t\tDefaultMaxTokens: 50000,\n\t\tCanReason: true,\n\t\tSupportsAttachments: true,\n\t},\n\tO1Pro: {\n\t\tID: O1Pro,\n\t\tName: \"o1 pro\",\n\t\tProvider: ProviderOpenAI,\n\t\tAPIModel: \"o1-pro\",\n\t\tCostPer1MIn: 150.00,\n\t\tCostPer1MInCached: 0.0,\n\t\tCostPer1MOutCached: 0.0,\n\t\tCostPer1MOut: 600.00,\n\t\tContextWindow: 200_000,\n\t\tDefaultMaxTokens: 50000,\n\t\tCanReason: true,\n\t\tSupportsAttachments: true,\n\t},\n\tO1Mini: {\n\t\tID: O1Mini,\n\t\tName: \"o1 mini\",\n\t\tProvider: ProviderOpenAI,\n\t\tAPIModel: \"o1-mini\",\n\t\tCostPer1MIn: 1.10,\n\t\tCostPer1MInCached: 0.55,\n\t\tCostPer1MOutCached: 0.0,\n\t\tCostPer1MOut: 4.40,\n\t\tContextWindow: 128_000,\n\t\tDefaultMaxTokens: 50000,\n\t\tCanReason: true,\n\t\tSupportsAttachments: true,\n\t},\n\tO3: {\n\t\tID: O3,\n\t\tName: \"o3\",\n\t\tProvider: ProviderOpenAI,\n\t\tAPIModel: \"o3\",\n\t\tCostPer1MIn: 10.00,\n\t\tCostPer1MInCached: 2.50,\n\t\tCostPer1MOutCached: 0.0,\n\t\tCostPer1MOut: 40.00,\n\t\tContextWindow: 200_000,\n\t\tCanReason: true,\n\t\tSupportsAttachments: true,\n\t},\n\tO3Mini: {\n\t\tID: O3Mini,\n\t\tName: \"o3 mini\",\n\t\tProvider: ProviderOpenAI,\n\t\tAPIModel: \"o3-mini\",\n\t\tCostPer1MIn: 1.10,\n\t\tCostPer1MInCached: 0.55,\n\t\tCostPer1MOutCached: 0.0,\n\t\tCostPer1MOut: 4.40,\n\t\tContextWindow: 200_000,\n\t\tDefaultMaxTokens: 50000,\n\t\tCanReason: true,\n\t\tSupportsAttachments: false,\n\t},\n\tO4Mini: {\n\t\tID: O4Mini,\n\t\tName: \"o4 mini\",\n\t\tProvider: ProviderOpenAI,\n\t\tAPIModel: \"o4-mini\",\n\t\tCostPer1MIn: 1.10,\n\t\tCostPer1MInCached: 0.275,\n\t\tCostPer1MOutCached: 0.0,\n\t\tCostPer1MOut: 4.40,\n\t\tContextWindow: 128_000,\n\t\tDefaultMaxTokens: 50000,\n\t\tCanReason: true,\n\t\tSupportsAttachments: true,\n\t},\n}\n"], ["/opencode/internal/db/models.go", "// Code generated by sqlc. DO NOT EDIT.\n// versions:\n// sqlc v1.29.0\n\npackage db\n\nimport (\n\t\"database/sql\"\n)\n\ntype File struct {\n\tID string `json:\"id\"`\n\tSessionID string `json:\"session_id\"`\n\tPath string `json:\"path\"`\n\tContent string `json:\"content\"`\n\tVersion string `json:\"version\"`\n\tCreatedAt int64 `json:\"created_at\"`\n\tUpdatedAt int64 `json:\"updated_at\"`\n}\n\ntype Message struct {\n\tID string `json:\"id\"`\n\tSessionID string `json:\"session_id\"`\n\tRole string `json:\"role\"`\n\tParts string `json:\"parts\"`\n\tModel sql.NullString `json:\"model\"`\n\tCreatedAt int64 `json:\"created_at\"`\n\tUpdatedAt int64 `json:\"updated_at\"`\n\tFinishedAt sql.NullInt64 `json:\"finished_at\"`\n}\n\ntype Session struct {\n\tID string `json:\"id\"`\n\tParentSessionID sql.NullString `json:\"parent_session_id\"`\n\tTitle string `json:\"title\"`\n\tMessageCount int64 `json:\"message_count\"`\n\tPromptTokens int64 `json:\"prompt_tokens\"`\n\tCompletionTokens int64 `json:\"completion_tokens\"`\n\tCost float64 `json:\"cost\"`\n\tUpdatedAt int64 `json:\"updated_at\"`\n\tCreatedAt int64 `json:\"created_at\"`\n\tSummaryMessageID sql.NullString `json:\"summary_message_id\"`\n}\n"], ["/opencode/main.go", "package main\n\nimport (\n\t\"github.com/opencode-ai/opencode/cmd\"\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n)\n\nfunc main() {\n\tdefer logging.RecoverPanic(\"main\", func() {\n\t\tlogging.ErrorPersist(\"Application terminated due to unhandled panic\")\n\t})\n\n\tcmd.Execute()\n}\n"], ["/opencode/internal/llm/models/azure.go", "package models\n\nconst ProviderAzure ModelProvider = \"azure\"\n\nconst (\n\tAzureGPT41 ModelID = \"azure.gpt-4.1\"\n\tAzureGPT41Mini ModelID = \"azure.gpt-4.1-mini\"\n\tAzureGPT41Nano ModelID = \"azure.gpt-4.1-nano\"\n\tAzureGPT45Preview ModelID = \"azure.gpt-4.5-preview\"\n\tAzureGPT4o ModelID = \"azure.gpt-4o\"\n\tAzureGPT4oMini ModelID = \"azure.gpt-4o-mini\"\n\tAzureO1 ModelID = \"azure.o1\"\n\tAzureO1Mini ModelID = \"azure.o1-mini\"\n\tAzureO3 ModelID = \"azure.o3\"\n\tAzureO3Mini ModelID = \"azure.o3-mini\"\n\tAzureO4Mini ModelID = \"azure.o4-mini\"\n)\n\nvar AzureModels = map[ModelID]Model{\n\tAzureGPT41: {\n\t\tID: AzureGPT41,\n\t\tName: \"Azure OpenAI – GPT 4.1\",\n\t\tProvider: ProviderAzure,\n\t\tAPIModel: \"gpt-4.1\",\n\t\tCostPer1MIn: OpenAIModels[GPT41].CostPer1MIn,\n\t\tCostPer1MInCached: OpenAIModels[GPT41].CostPer1MInCached,\n\t\tCostPer1MOut: OpenAIModels[GPT41].CostPer1MOut,\n\t\tCostPer1MOutCached: OpenAIModels[GPT41].CostPer1MOutCached,\n\t\tContextWindow: OpenAIModels[GPT41].ContextWindow,\n\t\tDefaultMaxTokens: OpenAIModels[GPT41].DefaultMaxTokens,\n\t\tSupportsAttachments: true,\n\t},\n\tAzureGPT41Mini: {\n\t\tID: AzureGPT41Mini,\n\t\tName: \"Azure OpenAI – GPT 4.1 mini\",\n\t\tProvider: ProviderAzure,\n\t\tAPIModel: \"gpt-4.1-mini\",\n\t\tCostPer1MIn: OpenAIModels[GPT41Mini].CostPer1MIn,\n\t\tCostPer1MInCached: OpenAIModels[GPT41Mini].CostPer1MInCached,\n\t\tCostPer1MOut: OpenAIModels[GPT41Mini].CostPer1MOut,\n\t\tCostPer1MOutCached: OpenAIModels[GPT41Mini].CostPer1MOutCached,\n\t\tContextWindow: OpenAIModels[GPT41Mini].ContextWindow,\n\t\tDefaultMaxTokens: OpenAIModels[GPT41Mini].DefaultMaxTokens,\n\t\tSupportsAttachments: true,\n\t},\n\tAzureGPT41Nano: {\n\t\tID: AzureGPT41Nano,\n\t\tName: \"Azure OpenAI – GPT 4.1 nano\",\n\t\tProvider: ProviderAzure,\n\t\tAPIModel: \"gpt-4.1-nano\",\n\t\tCostPer1MIn: OpenAIModels[GPT41Nano].CostPer1MIn,\n\t\tCostPer1MInCached: OpenAIModels[GPT41Nano].CostPer1MInCached,\n\t\tCostPer1MOut: OpenAIModels[GPT41Nano].CostPer1MOut,\n\t\tCostPer1MOutCached: OpenAIModels[GPT41Nano].CostPer1MOutCached,\n\t\tContextWindow: OpenAIModels[GPT41Nano].ContextWindow,\n\t\tDefaultMaxTokens: OpenAIModels[GPT41Nano].DefaultMaxTokens,\n\t\tSupportsAttachments: true,\n\t},\n\tAzureGPT45Preview: {\n\t\tID: AzureGPT45Preview,\n\t\tName: \"Azure OpenAI – GPT 4.5 preview\",\n\t\tProvider: ProviderAzure,\n\t\tAPIModel: \"gpt-4.5-preview\",\n\t\tCostPer1MIn: OpenAIModels[GPT45Preview].CostPer1MIn,\n\t\tCostPer1MInCached: OpenAIModels[GPT45Preview].CostPer1MInCached,\n\t\tCostPer1MOut: OpenAIModels[GPT45Preview].CostPer1MOut,\n\t\tCostPer1MOutCached: OpenAIModels[GPT45Preview].CostPer1MOutCached,\n\t\tContextWindow: OpenAIModels[GPT45Preview].ContextWindow,\n\t\tDefaultMaxTokens: OpenAIModels[GPT45Preview].DefaultMaxTokens,\n\t\tSupportsAttachments: true,\n\t},\n\tAzureGPT4o: {\n\t\tID: AzureGPT4o,\n\t\tName: \"Azure OpenAI – GPT-4o\",\n\t\tProvider: ProviderAzure,\n\t\tAPIModel: \"gpt-4o\",\n\t\tCostPer1MIn: OpenAIModels[GPT4o].CostPer1MIn,\n\t\tCostPer1MInCached: OpenAIModels[GPT4o].CostPer1MInCached,\n\t\tCostPer1MOut: OpenAIModels[GPT4o].CostPer1MOut,\n\t\tCostPer1MOutCached: OpenAIModels[GPT4o].CostPer1MOutCached,\n\t\tContextWindow: OpenAIModels[GPT4o].ContextWindow,\n\t\tDefaultMaxTokens: OpenAIModels[GPT4o].DefaultMaxTokens,\n\t\tSupportsAttachments: true,\n\t},\n\tAzureGPT4oMini: {\n\t\tID: AzureGPT4oMini,\n\t\tName: \"Azure OpenAI – GPT-4o mini\",\n\t\tProvider: ProviderAzure,\n\t\tAPIModel: \"gpt-4o-mini\",\n\t\tCostPer1MIn: OpenAIModels[GPT4oMini].CostPer1MIn,\n\t\tCostPer1MInCached: OpenAIModels[GPT4oMini].CostPer1MInCached,\n\t\tCostPer1MOut: OpenAIModels[GPT4oMini].CostPer1MOut,\n\t\tCostPer1MOutCached: OpenAIModels[GPT4oMini].CostPer1MOutCached,\n\t\tContextWindow: OpenAIModels[GPT4oMini].ContextWindow,\n\t\tDefaultMaxTokens: OpenAIModels[GPT4oMini].DefaultMaxTokens,\n\t\tSupportsAttachments: true,\n\t},\n\tAzureO1: {\n\t\tID: AzureO1,\n\t\tName: \"Azure OpenAI – O1\",\n\t\tProvider: ProviderAzure,\n\t\tAPIModel: \"o1\",\n\t\tCostPer1MIn: OpenAIModels[O1].CostPer1MIn,\n\t\tCostPer1MInCached: OpenAIModels[O1].CostPer1MInCached,\n\t\tCostPer1MOut: OpenAIModels[O1].CostPer1MOut,\n\t\tCostPer1MOutCached: OpenAIModels[O1].CostPer1MOutCached,\n\t\tContextWindow: OpenAIModels[O1].ContextWindow,\n\t\tDefaultMaxTokens: OpenAIModels[O1].DefaultMaxTokens,\n\t\tCanReason: OpenAIModels[O1].CanReason,\n\t\tSupportsAttachments: true,\n\t},\n\tAzureO1Mini: {\n\t\tID: AzureO1Mini,\n\t\tName: \"Azure OpenAI – O1 mini\",\n\t\tProvider: ProviderAzure,\n\t\tAPIModel: \"o1-mini\",\n\t\tCostPer1MIn: OpenAIModels[O1Mini].CostPer1MIn,\n\t\tCostPer1MInCached: OpenAIModels[O1Mini].CostPer1MInCached,\n\t\tCostPer1MOut: OpenAIModels[O1Mini].CostPer1MOut,\n\t\tCostPer1MOutCached: OpenAIModels[O1Mini].CostPer1MOutCached,\n\t\tContextWindow: OpenAIModels[O1Mini].ContextWindow,\n\t\tDefaultMaxTokens: OpenAIModels[O1Mini].DefaultMaxTokens,\n\t\tCanReason: OpenAIModels[O1Mini].CanReason,\n\t\tSupportsAttachments: true,\n\t},\n\tAzureO3: {\n\t\tID: AzureO3,\n\t\tName: \"Azure OpenAI – O3\",\n\t\tProvider: ProviderAzure,\n\t\tAPIModel: \"o3\",\n\t\tCostPer1MIn: OpenAIModels[O3].CostPer1MIn,\n\t\tCostPer1MInCached: OpenAIModels[O3].CostPer1MInCached,\n\t\tCostPer1MOut: OpenAIModels[O3].CostPer1MOut,\n\t\tCostPer1MOutCached: OpenAIModels[O3].CostPer1MOutCached,\n\t\tContextWindow: OpenAIModels[O3].ContextWindow,\n\t\tDefaultMaxTokens: OpenAIModels[O3].DefaultMaxTokens,\n\t\tCanReason: OpenAIModels[O3].CanReason,\n\t\tSupportsAttachments: true,\n\t},\n\tAzureO3Mini: {\n\t\tID: AzureO3Mini,\n\t\tName: \"Azure OpenAI – O3 mini\",\n\t\tProvider: ProviderAzure,\n\t\tAPIModel: \"o3-mini\",\n\t\tCostPer1MIn: OpenAIModels[O3Mini].CostPer1MIn,\n\t\tCostPer1MInCached: OpenAIModels[O3Mini].CostPer1MInCached,\n\t\tCostPer1MOut: OpenAIModels[O3Mini].CostPer1MOut,\n\t\tCostPer1MOutCached: OpenAIModels[O3Mini].CostPer1MOutCached,\n\t\tContextWindow: OpenAIModels[O3Mini].ContextWindow,\n\t\tDefaultMaxTokens: OpenAIModels[O3Mini].DefaultMaxTokens,\n\t\tCanReason: OpenAIModels[O3Mini].CanReason,\n\t\tSupportsAttachments: false,\n\t},\n\tAzureO4Mini: {\n\t\tID: AzureO4Mini,\n\t\tName: \"Azure OpenAI – O4 mini\",\n\t\tProvider: ProviderAzure,\n\t\tAPIModel: \"o4-mini\",\n\t\tCostPer1MIn: OpenAIModels[O4Mini].CostPer1MIn,\n\t\tCostPer1MInCached: OpenAIModels[O4Mini].CostPer1MInCached,\n\t\tCostPer1MOut: OpenAIModels[O4Mini].CostPer1MOut,\n\t\tCostPer1MOutCached: OpenAIModels[O4Mini].CostPer1MOutCached,\n\t\tContextWindow: OpenAIModels[O4Mini].ContextWindow,\n\t\tDefaultMaxTokens: OpenAIModels[O4Mini].DefaultMaxTokens,\n\t\tCanReason: OpenAIModels[O4Mini].CanReason,\n\t\tSupportsAttachments: true,\n\t},\n}\n"], ["/opencode/internal/llm/models/anthropic.go", "package models\n\nconst (\n\tProviderAnthropic ModelProvider = \"anthropic\"\n\n\t// Models\n\tClaude35Sonnet ModelID = \"claude-3.5-sonnet\"\n\tClaude3Haiku ModelID = \"claude-3-haiku\"\n\tClaude37Sonnet ModelID = \"claude-3.7-sonnet\"\n\tClaude35Haiku ModelID = \"claude-3.5-haiku\"\n\tClaude3Opus ModelID = \"claude-3-opus\"\n\tClaude4Opus ModelID = \"claude-4-opus\"\n\tClaude4Sonnet ModelID = \"claude-4-sonnet\"\n)\n\n// https://docs.anthropic.com/en/docs/about-claude/models/all-models\nvar AnthropicModels = map[ModelID]Model{\n\tClaude35Sonnet: {\n\t\tID: Claude35Sonnet,\n\t\tName: \"Claude 3.5 Sonnet\",\n\t\tProvider: ProviderAnthropic,\n\t\tAPIModel: \"claude-3-5-sonnet-latest\",\n\t\tCostPer1MIn: 3.0,\n\t\tCostPer1MInCached: 3.75,\n\t\tCostPer1MOutCached: 0.30,\n\t\tCostPer1MOut: 15.0,\n\t\tContextWindow: 200000,\n\t\tDefaultMaxTokens: 5000,\n\t\tSupportsAttachments: true,\n\t},\n\tClaude3Haiku: {\n\t\tID: Claude3Haiku,\n\t\tName: \"Claude 3 Haiku\",\n\t\tProvider: ProviderAnthropic,\n\t\tAPIModel: \"claude-3-haiku-20240307\", // doesn't support \"-latest\"\n\t\tCostPer1MIn: 0.25,\n\t\tCostPer1MInCached: 0.30,\n\t\tCostPer1MOutCached: 0.03,\n\t\tCostPer1MOut: 1.25,\n\t\tContextWindow: 200000,\n\t\tDefaultMaxTokens: 4096,\n\t\tSupportsAttachments: true,\n\t},\n\tClaude37Sonnet: {\n\t\tID: Claude37Sonnet,\n\t\tName: \"Claude 3.7 Sonnet\",\n\t\tProvider: ProviderAnthropic,\n\t\tAPIModel: \"claude-3-7-sonnet-latest\",\n\t\tCostPer1MIn: 3.0,\n\t\tCostPer1MInCached: 3.75,\n\t\tCostPer1MOutCached: 0.30,\n\t\tCostPer1MOut: 15.0,\n\t\tContextWindow: 200000,\n\t\tDefaultMaxTokens: 50000,\n\t\tCanReason: true,\n\t\tSupportsAttachments: true,\n\t},\n\tClaude35Haiku: {\n\t\tID: Claude35Haiku,\n\t\tName: \"Claude 3.5 Haiku\",\n\t\tProvider: ProviderAnthropic,\n\t\tAPIModel: \"claude-3-5-haiku-latest\",\n\t\tCostPer1MIn: 0.80,\n\t\tCostPer1MInCached: 1.0,\n\t\tCostPer1MOutCached: 0.08,\n\t\tCostPer1MOut: 4.0,\n\t\tContextWindow: 200000,\n\t\tDefaultMaxTokens: 4096,\n\t\tSupportsAttachments: true,\n\t},\n\tClaude3Opus: {\n\t\tID: Claude3Opus,\n\t\tName: \"Claude 3 Opus\",\n\t\tProvider: ProviderAnthropic,\n\t\tAPIModel: \"claude-3-opus-latest\",\n\t\tCostPer1MIn: 15.0,\n\t\tCostPer1MInCached: 18.75,\n\t\tCostPer1MOutCached: 1.50,\n\t\tCostPer1MOut: 75.0,\n\t\tContextWindow: 200000,\n\t\tDefaultMaxTokens: 4096,\n\t\tSupportsAttachments: true,\n\t},\n\tClaude4Sonnet: {\n\t\tID: Claude4Sonnet,\n\t\tName: \"Claude 4 Sonnet\",\n\t\tProvider: ProviderAnthropic,\n\t\tAPIModel: \"claude-sonnet-4-20250514\",\n\t\tCostPer1MIn: 3.0,\n\t\tCostPer1MInCached: 3.75,\n\t\tCostPer1MOutCached: 0.30,\n\t\tCostPer1MOut: 15.0,\n\t\tContextWindow: 200000,\n\t\tDefaultMaxTokens: 50000,\n\t\tCanReason: true,\n\t\tSupportsAttachments: true,\n\t},\n\tClaude4Opus: {\n\t\tID: Claude4Opus,\n\t\tName: \"Claude 4 Opus\",\n\t\tProvider: ProviderAnthropic,\n\t\tAPIModel: \"claude-opus-4-20250514\",\n\t\tCostPer1MIn: 15.0,\n\t\tCostPer1MInCached: 18.75,\n\t\tCostPer1MOutCached: 1.50,\n\t\tCostPer1MOut: 75.0,\n\t\tContextWindow: 200000,\n\t\tDefaultMaxTokens: 4096,\n\t\tSupportsAttachments: true,\n\t},\n}\n"], ["/opencode/internal/llm/models/gemini.go", "package models\n\nconst (\n\tProviderGemini ModelProvider = \"gemini\"\n\n\t// Models\n\tGemini25Flash ModelID = \"gemini-2.5-flash\"\n\tGemini25 ModelID = \"gemini-2.5\"\n\tGemini20Flash ModelID = \"gemini-2.0-flash\"\n\tGemini20FlashLite ModelID = \"gemini-2.0-flash-lite\"\n)\n\nvar GeminiModels = map[ModelID]Model{\n\tGemini25Flash: {\n\t\tID: Gemini25Flash,\n\t\tName: \"Gemini 2.5 Flash\",\n\t\tProvider: ProviderGemini,\n\t\tAPIModel: \"gemini-2.5-flash-preview-04-17\",\n\t\tCostPer1MIn: 0.15,\n\t\tCostPer1MInCached: 0,\n\t\tCostPer1MOutCached: 0,\n\t\tCostPer1MOut: 0.60,\n\t\tContextWindow: 1000000,\n\t\tDefaultMaxTokens: 50000,\n\t\tSupportsAttachments: true,\n\t},\n\tGemini25: {\n\t\tID: Gemini25,\n\t\tName: \"Gemini 2.5 Pro\",\n\t\tProvider: ProviderGemini,\n\t\tAPIModel: \"gemini-2.5-pro-preview-05-06\",\n\t\tCostPer1MIn: 1.25,\n\t\tCostPer1MInCached: 0,\n\t\tCostPer1MOutCached: 0,\n\t\tCostPer1MOut: 10,\n\t\tContextWindow: 1000000,\n\t\tDefaultMaxTokens: 50000,\n\t\tSupportsAttachments: true,\n\t},\n\n\tGemini20Flash: {\n\t\tID: Gemini20Flash,\n\t\tName: \"Gemini 2.0 Flash\",\n\t\tProvider: ProviderGemini,\n\t\tAPIModel: \"gemini-2.0-flash\",\n\t\tCostPer1MIn: 0.10,\n\t\tCostPer1MInCached: 0,\n\t\tCostPer1MOutCached: 0,\n\t\tCostPer1MOut: 0.40,\n\t\tContextWindow: 1000000,\n\t\tDefaultMaxTokens: 6000,\n\t\tSupportsAttachments: true,\n\t},\n\tGemini20FlashLite: {\n\t\tID: Gemini20FlashLite,\n\t\tName: \"Gemini 2.0 Flash Lite\",\n\t\tProvider: ProviderGemini,\n\t\tAPIModel: \"gemini-2.0-flash-lite\",\n\t\tCostPer1MIn: 0.05,\n\t\tCostPer1MInCached: 0,\n\t\tCostPer1MOutCached: 0,\n\t\tCostPer1MOut: 0.30,\n\t\tContextWindow: 1000000,\n\t\tDefaultMaxTokens: 6000,\n\t\tSupportsAttachments: true,\n\t},\n}\n"], ["/opencode/internal/llm/models/openrouter.go", "package models\n\nconst (\n\tProviderOpenRouter ModelProvider = \"openrouter\"\n\n\tOpenRouterGPT41 ModelID = \"openrouter.gpt-4.1\"\n\tOpenRouterGPT41Mini ModelID = \"openrouter.gpt-4.1-mini\"\n\tOpenRouterGPT41Nano ModelID = \"openrouter.gpt-4.1-nano\"\n\tOpenRouterGPT45Preview ModelID = \"openrouter.gpt-4.5-preview\"\n\tOpenRouterGPT4o ModelID = \"openrouter.gpt-4o\"\n\tOpenRouterGPT4oMini ModelID = \"openrouter.gpt-4o-mini\"\n\tOpenRouterO1 ModelID = \"openrouter.o1\"\n\tOpenRouterO1Pro ModelID = \"openrouter.o1-pro\"\n\tOpenRouterO1Mini ModelID = \"openrouter.o1-mini\"\n\tOpenRouterO3 ModelID = \"openrouter.o3\"\n\tOpenRouterO3Mini ModelID = \"openrouter.o3-mini\"\n\tOpenRouterO4Mini ModelID = \"openrouter.o4-mini\"\n\tOpenRouterGemini25Flash ModelID = \"openrouter.gemini-2.5-flash\"\n\tOpenRouterGemini25 ModelID = \"openrouter.gemini-2.5\"\n\tOpenRouterClaude35Sonnet ModelID = \"openrouter.claude-3.5-sonnet\"\n\tOpenRouterClaude3Haiku ModelID = \"openrouter.claude-3-haiku\"\n\tOpenRouterClaude37Sonnet ModelID = \"openrouter.claude-3.7-sonnet\"\n\tOpenRouterClaude35Haiku ModelID = \"openrouter.claude-3.5-haiku\"\n\tOpenRouterClaude3Opus ModelID = \"openrouter.claude-3-opus\"\n\tOpenRouterDeepSeekR1Free ModelID = \"openrouter.deepseek-r1-free\"\n)\n\nvar OpenRouterModels = map[ModelID]Model{\n\tOpenRouterGPT41: {\n\t\tID: OpenRouterGPT41,\n\t\tName: \"OpenRouter – GPT 4.1\",\n\t\tProvider: ProviderOpenRouter,\n\t\tAPIModel: \"openai/gpt-4.1\",\n\t\tCostPer1MIn: OpenAIModels[GPT41].CostPer1MIn,\n\t\tCostPer1MInCached: OpenAIModels[GPT41].CostPer1MInCached,\n\t\tCostPer1MOut: OpenAIModels[GPT41].CostPer1MOut,\n\t\tCostPer1MOutCached: OpenAIModels[GPT41].CostPer1MOutCached,\n\t\tContextWindow: OpenAIModels[GPT41].ContextWindow,\n\t\tDefaultMaxTokens: OpenAIModels[GPT41].DefaultMaxTokens,\n\t},\n\tOpenRouterGPT41Mini: {\n\t\tID: OpenRouterGPT41Mini,\n\t\tName: \"OpenRouter – GPT 4.1 mini\",\n\t\tProvider: ProviderOpenRouter,\n\t\tAPIModel: \"openai/gpt-4.1-mini\",\n\t\tCostPer1MIn: OpenAIModels[GPT41Mini].CostPer1MIn,\n\t\tCostPer1MInCached: OpenAIModels[GPT41Mini].CostPer1MInCached,\n\t\tCostPer1MOut: OpenAIModels[GPT41Mini].CostPer1MOut,\n\t\tCostPer1MOutCached: OpenAIModels[GPT41Mini].CostPer1MOutCached,\n\t\tContextWindow: OpenAIModels[GPT41Mini].ContextWindow,\n\t\tDefaultMaxTokens: OpenAIModels[GPT41Mini].DefaultMaxTokens,\n\t},\n\tOpenRouterGPT41Nano: {\n\t\tID: OpenRouterGPT41Nano,\n\t\tName: \"OpenRouter – GPT 4.1 nano\",\n\t\tProvider: ProviderOpenRouter,\n\t\tAPIModel: \"openai/gpt-4.1-nano\",\n\t\tCostPer1MIn: OpenAIModels[GPT41Nano].CostPer1MIn,\n\t\tCostPer1MInCached: OpenAIModels[GPT41Nano].CostPer1MInCached,\n\t\tCostPer1MOut: OpenAIModels[GPT41Nano].CostPer1MOut,\n\t\tCostPer1MOutCached: OpenAIModels[GPT41Nano].CostPer1MOutCached,\n\t\tContextWindow: OpenAIModels[GPT41Nano].ContextWindow,\n\t\tDefaultMaxTokens: OpenAIModels[GPT41Nano].DefaultMaxTokens,\n\t},\n\tOpenRouterGPT45Preview: {\n\t\tID: OpenRouterGPT45Preview,\n\t\tName: \"OpenRouter – GPT 4.5 preview\",\n\t\tProvider: ProviderOpenRouter,\n\t\tAPIModel: \"openai/gpt-4.5-preview\",\n\t\tCostPer1MIn: OpenAIModels[GPT45Preview].CostPer1MIn,\n\t\tCostPer1MInCached: OpenAIModels[GPT45Preview].CostPer1MInCached,\n\t\tCostPer1MOut: OpenAIModels[GPT45Preview].CostPer1MOut,\n\t\tCostPer1MOutCached: OpenAIModels[GPT45Preview].CostPer1MOutCached,\n\t\tContextWindow: OpenAIModels[GPT45Preview].ContextWindow,\n\t\tDefaultMaxTokens: OpenAIModels[GPT45Preview].DefaultMaxTokens,\n\t},\n\tOpenRouterGPT4o: {\n\t\tID: OpenRouterGPT4o,\n\t\tName: \"OpenRouter – GPT 4o\",\n\t\tProvider: ProviderOpenRouter,\n\t\tAPIModel: \"openai/gpt-4o\",\n\t\tCostPer1MIn: OpenAIModels[GPT4o].CostPer1MIn,\n\t\tCostPer1MInCached: OpenAIModels[GPT4o].CostPer1MInCached,\n\t\tCostPer1MOut: OpenAIModels[GPT4o].CostPer1MOut,\n\t\tCostPer1MOutCached: OpenAIModels[GPT4o].CostPer1MOutCached,\n\t\tContextWindow: OpenAIModels[GPT4o].ContextWindow,\n\t\tDefaultMaxTokens: OpenAIModels[GPT4o].DefaultMaxTokens,\n\t},\n\tOpenRouterGPT4oMini: {\n\t\tID: OpenRouterGPT4oMini,\n\t\tName: \"OpenRouter – GPT 4o mini\",\n\t\tProvider: ProviderOpenRouter,\n\t\tAPIModel: \"openai/gpt-4o-mini\",\n\t\tCostPer1MIn: OpenAIModels[GPT4oMini].CostPer1MIn,\n\t\tCostPer1MInCached: OpenAIModels[GPT4oMini].CostPer1MInCached,\n\t\tCostPer1MOut: OpenAIModels[GPT4oMini].CostPer1MOut,\n\t\tCostPer1MOutCached: OpenAIModels[GPT4oMini].CostPer1MOutCached,\n\t\tContextWindow: OpenAIModels[GPT4oMini].ContextWindow,\n\t},\n\tOpenRouterO1: {\n\t\tID: OpenRouterO1,\n\t\tName: \"OpenRouter – O1\",\n\t\tProvider: ProviderOpenRouter,\n\t\tAPIModel: \"openai/o1\",\n\t\tCostPer1MIn: OpenAIModels[O1].CostPer1MIn,\n\t\tCostPer1MInCached: OpenAIModels[O1].CostPer1MInCached,\n\t\tCostPer1MOut: OpenAIModels[O1].CostPer1MOut,\n\t\tCostPer1MOutCached: OpenAIModels[O1].CostPer1MOutCached,\n\t\tContextWindow: OpenAIModels[O1].ContextWindow,\n\t\tDefaultMaxTokens: OpenAIModels[O1].DefaultMaxTokens,\n\t\tCanReason: OpenAIModels[O1].CanReason,\n\t},\n\tOpenRouterO1Pro: {\n\t\tID: OpenRouterO1Pro,\n\t\tName: \"OpenRouter – o1 pro\",\n\t\tProvider: ProviderOpenRouter,\n\t\tAPIModel: \"openai/o1-pro\",\n\t\tCostPer1MIn: OpenAIModels[O1Pro].CostPer1MIn,\n\t\tCostPer1MInCached: OpenAIModels[O1Pro].CostPer1MInCached,\n\t\tCostPer1MOut: OpenAIModels[O1Pro].CostPer1MOut,\n\t\tCostPer1MOutCached: OpenAIModels[O1Pro].CostPer1MOutCached,\n\t\tContextWindow: OpenAIModels[O1Pro].ContextWindow,\n\t\tDefaultMaxTokens: OpenAIModels[O1Pro].DefaultMaxTokens,\n\t\tCanReason: OpenAIModels[O1Pro].CanReason,\n\t},\n\tOpenRouterO1Mini: {\n\t\tID: OpenRouterO1Mini,\n\t\tName: \"OpenRouter – o1 mini\",\n\t\tProvider: ProviderOpenRouter,\n\t\tAPIModel: \"openai/o1-mini\",\n\t\tCostPer1MIn: OpenAIModels[O1Mini].CostPer1MIn,\n\t\tCostPer1MInCached: OpenAIModels[O1Mini].CostPer1MInCached,\n\t\tCostPer1MOut: OpenAIModels[O1Mini].CostPer1MOut,\n\t\tCostPer1MOutCached: OpenAIModels[O1Mini].CostPer1MOutCached,\n\t\tContextWindow: OpenAIModels[O1Mini].ContextWindow,\n\t\tDefaultMaxTokens: OpenAIModels[O1Mini].DefaultMaxTokens,\n\t\tCanReason: OpenAIModels[O1Mini].CanReason,\n\t},\n\tOpenRouterO3: {\n\t\tID: OpenRouterO3,\n\t\tName: \"OpenRouter – o3\",\n\t\tProvider: ProviderOpenRouter,\n\t\tAPIModel: \"openai/o3\",\n\t\tCostPer1MIn: OpenAIModels[O3].CostPer1MIn,\n\t\tCostPer1MInCached: OpenAIModels[O3].CostPer1MInCached,\n\t\tCostPer1MOut: OpenAIModels[O3].CostPer1MOut,\n\t\tCostPer1MOutCached: OpenAIModels[O3].CostPer1MOutCached,\n\t\tContextWindow: OpenAIModels[O3].ContextWindow,\n\t\tDefaultMaxTokens: OpenAIModels[O3].DefaultMaxTokens,\n\t\tCanReason: OpenAIModels[O3].CanReason,\n\t},\n\tOpenRouterO3Mini: {\n\t\tID: OpenRouterO3Mini,\n\t\tName: \"OpenRouter – o3 mini\",\n\t\tProvider: ProviderOpenRouter,\n\t\tAPIModel: \"openai/o3-mini-high\",\n\t\tCostPer1MIn: OpenAIModels[O3Mini].CostPer1MIn,\n\t\tCostPer1MInCached: OpenAIModels[O3Mini].CostPer1MInCached,\n\t\tCostPer1MOut: OpenAIModels[O3Mini].CostPer1MOut,\n\t\tCostPer1MOutCached: OpenAIModels[O3Mini].CostPer1MOutCached,\n\t\tContextWindow: OpenAIModels[O3Mini].ContextWindow,\n\t\tDefaultMaxTokens: OpenAIModels[O3Mini].DefaultMaxTokens,\n\t\tCanReason: OpenAIModels[O3Mini].CanReason,\n\t},\n\tOpenRouterO4Mini: {\n\t\tID: OpenRouterO4Mini,\n\t\tName: \"OpenRouter – o4 mini\",\n\t\tProvider: ProviderOpenRouter,\n\t\tAPIModel: \"openai/o4-mini-high\",\n\t\tCostPer1MIn: OpenAIModels[O4Mini].CostPer1MIn,\n\t\tCostPer1MInCached: OpenAIModels[O4Mini].CostPer1MInCached,\n\t\tCostPer1MOut: OpenAIModels[O4Mini].CostPer1MOut,\n\t\tCostPer1MOutCached: OpenAIModels[O4Mini].CostPer1MOutCached,\n\t\tContextWindow: OpenAIModels[O4Mini].ContextWindow,\n\t\tDefaultMaxTokens: OpenAIModels[O4Mini].DefaultMaxTokens,\n\t\tCanReason: OpenAIModels[O4Mini].CanReason,\n\t},\n\tOpenRouterGemini25Flash: {\n\t\tID: OpenRouterGemini25Flash,\n\t\tName: \"OpenRouter – Gemini 2.5 Flash\",\n\t\tProvider: ProviderOpenRouter,\n\t\tAPIModel: \"google/gemini-2.5-flash-preview:thinking\",\n\t\tCostPer1MIn: GeminiModels[Gemini25Flash].CostPer1MIn,\n\t\tCostPer1MInCached: GeminiModels[Gemini25Flash].CostPer1MInCached,\n\t\tCostPer1MOut: GeminiModels[Gemini25Flash].CostPer1MOut,\n\t\tCostPer1MOutCached: GeminiModels[Gemini25Flash].CostPer1MOutCached,\n\t\tContextWindow: GeminiModels[Gemini25Flash].ContextWindow,\n\t\tDefaultMaxTokens: GeminiModels[Gemini25Flash].DefaultMaxTokens,\n\t},\n\tOpenRouterGemini25: {\n\t\tID: OpenRouterGemini25,\n\t\tName: \"OpenRouter – Gemini 2.5 Pro\",\n\t\tProvider: ProviderOpenRouter,\n\t\tAPIModel: \"google/gemini-2.5-pro-preview-03-25\",\n\t\tCostPer1MIn: GeminiModels[Gemini25].CostPer1MIn,\n\t\tCostPer1MInCached: GeminiModels[Gemini25].CostPer1MInCached,\n\t\tCostPer1MOut: GeminiModels[Gemini25].CostPer1MOut,\n\t\tCostPer1MOutCached: GeminiModels[Gemini25].CostPer1MOutCached,\n\t\tContextWindow: GeminiModels[Gemini25].ContextWindow,\n\t\tDefaultMaxTokens: GeminiModels[Gemini25].DefaultMaxTokens,\n\t},\n\tOpenRouterClaude35Sonnet: {\n\t\tID: OpenRouterClaude35Sonnet,\n\t\tName: \"OpenRouter – Claude 3.5 Sonnet\",\n\t\tProvider: ProviderOpenRouter,\n\t\tAPIModel: \"anthropic/claude-3.5-sonnet\",\n\t\tCostPer1MIn: AnthropicModels[Claude35Sonnet].CostPer1MIn,\n\t\tCostPer1MInCached: AnthropicModels[Claude35Sonnet].CostPer1MInCached,\n\t\tCostPer1MOut: AnthropicModels[Claude35Sonnet].CostPer1MOut,\n\t\tCostPer1MOutCached: AnthropicModels[Claude35Sonnet].CostPer1MOutCached,\n\t\tContextWindow: AnthropicModels[Claude35Sonnet].ContextWindow,\n\t\tDefaultMaxTokens: AnthropicModels[Claude35Sonnet].DefaultMaxTokens,\n\t},\n\tOpenRouterClaude3Haiku: {\n\t\tID: OpenRouterClaude3Haiku,\n\t\tName: \"OpenRouter – Claude 3 Haiku\",\n\t\tProvider: ProviderOpenRouter,\n\t\tAPIModel: \"anthropic/claude-3-haiku\",\n\t\tCostPer1MIn: AnthropicModels[Claude3Haiku].CostPer1MIn,\n\t\tCostPer1MInCached: AnthropicModels[Claude3Haiku].CostPer1MInCached,\n\t\tCostPer1MOut: AnthropicModels[Claude3Haiku].CostPer1MOut,\n\t\tCostPer1MOutCached: AnthropicModels[Claude3Haiku].CostPer1MOutCached,\n\t\tContextWindow: AnthropicModels[Claude3Haiku].ContextWindow,\n\t\tDefaultMaxTokens: AnthropicModels[Claude3Haiku].DefaultMaxTokens,\n\t},\n\tOpenRouterClaude37Sonnet: {\n\t\tID: OpenRouterClaude37Sonnet,\n\t\tName: \"OpenRouter – Claude 3.7 Sonnet\",\n\t\tProvider: ProviderOpenRouter,\n\t\tAPIModel: \"anthropic/claude-3.7-sonnet\",\n\t\tCostPer1MIn: AnthropicModels[Claude37Sonnet].CostPer1MIn,\n\t\tCostPer1MInCached: AnthropicModels[Claude37Sonnet].CostPer1MInCached,\n\t\tCostPer1MOut: AnthropicModels[Claude37Sonnet].CostPer1MOut,\n\t\tCostPer1MOutCached: AnthropicModels[Claude37Sonnet].CostPer1MOutCached,\n\t\tContextWindow: AnthropicModels[Claude37Sonnet].ContextWindow,\n\t\tDefaultMaxTokens: AnthropicModels[Claude37Sonnet].DefaultMaxTokens,\n\t\tCanReason: AnthropicModels[Claude37Sonnet].CanReason,\n\t},\n\tOpenRouterClaude35Haiku: {\n\t\tID: OpenRouterClaude35Haiku,\n\t\tName: \"OpenRouter – Claude 3.5 Haiku\",\n\t\tProvider: ProviderOpenRouter,\n\t\tAPIModel: \"anthropic/claude-3.5-haiku\",\n\t\tCostPer1MIn: AnthropicModels[Claude35Haiku].CostPer1MIn,\n\t\tCostPer1MInCached: AnthropicModels[Claude35Haiku].CostPer1MInCached,\n\t\tCostPer1MOut: AnthropicModels[Claude35Haiku].CostPer1MOut,\n\t\tCostPer1MOutCached: AnthropicModels[Claude35Haiku].CostPer1MOutCached,\n\t\tContextWindow: AnthropicModels[Claude35Haiku].ContextWindow,\n\t\tDefaultMaxTokens: AnthropicModels[Claude35Haiku].DefaultMaxTokens,\n\t},\n\tOpenRouterClaude3Opus: {\n\t\tID: OpenRouterClaude3Opus,\n\t\tName: \"OpenRouter – Claude 3 Opus\",\n\t\tProvider: ProviderOpenRouter,\n\t\tAPIModel: \"anthropic/claude-3-opus\",\n\t\tCostPer1MIn: AnthropicModels[Claude3Opus].CostPer1MIn,\n\t\tCostPer1MInCached: AnthropicModels[Claude3Opus].CostPer1MInCached,\n\t\tCostPer1MOut: AnthropicModels[Claude3Opus].CostPer1MOut,\n\t\tCostPer1MOutCached: AnthropicModels[Claude3Opus].CostPer1MOutCached,\n\t\tContextWindow: AnthropicModels[Claude3Opus].ContextWindow,\n\t\tDefaultMaxTokens: AnthropicModels[Claude3Opus].DefaultMaxTokens,\n\t},\n\n\tOpenRouterDeepSeekR1Free: {\n\t\tID: OpenRouterDeepSeekR1Free,\n\t\tName: \"OpenRouter – DeepSeek R1 Free\",\n\t\tProvider: ProviderOpenRouter,\n\t\tAPIModel: \"deepseek/deepseek-r1-0528:free\",\n\t\tCostPer1MIn: 0,\n\t\tCostPer1MInCached: 0,\n\t\tCostPer1MOut: 0,\n\t\tCostPer1MOutCached: 0,\n\t\tContextWindow: 163_840,\n\t\tDefaultMaxTokens: 10000,\n\t},\n}\n"], ["/opencode/internal/llm/models/vertexai.go", "package models\n\nconst (\n\tProviderVertexAI ModelProvider = \"vertexai\"\n\n\t// Models\n\tVertexAIGemini25Flash ModelID = \"vertexai.gemini-2.5-flash\"\n\tVertexAIGemini25 ModelID = \"vertexai.gemini-2.5\"\n)\n\nvar VertexAIGeminiModels = map[ModelID]Model{\n\tVertexAIGemini25Flash: {\n\t\tID: VertexAIGemini25Flash,\n\t\tName: \"VertexAI: Gemini 2.5 Flash\",\n\t\tProvider: ProviderVertexAI,\n\t\tAPIModel: \"gemini-2.5-flash-preview-04-17\",\n\t\tCostPer1MIn: GeminiModels[Gemini25Flash].CostPer1MIn,\n\t\tCostPer1MInCached: GeminiModels[Gemini25Flash].CostPer1MInCached,\n\t\tCostPer1MOut: GeminiModels[Gemini25Flash].CostPer1MOut,\n\t\tCostPer1MOutCached: GeminiModels[Gemini25Flash].CostPer1MOutCached,\n\t\tContextWindow: GeminiModels[Gemini25Flash].ContextWindow,\n\t\tDefaultMaxTokens: GeminiModels[Gemini25Flash].DefaultMaxTokens,\n\t\tSupportsAttachments: true,\n\t},\n\tVertexAIGemini25: {\n\t\tID: VertexAIGemini25,\n\t\tName: \"VertexAI: Gemini 2.5 Pro\",\n\t\tProvider: ProviderVertexAI,\n\t\tAPIModel: \"gemini-2.5-pro-preview-03-25\",\n\t\tCostPer1MIn: GeminiModels[Gemini25].CostPer1MIn,\n\t\tCostPer1MInCached: GeminiModels[Gemini25].CostPer1MInCached,\n\t\tCostPer1MOut: GeminiModels[Gemini25].CostPer1MOut,\n\t\tCostPer1MOutCached: GeminiModels[Gemini25].CostPer1MOutCached,\n\t\tContextWindow: GeminiModels[Gemini25].ContextWindow,\n\t\tDefaultMaxTokens: GeminiModels[Gemini25].DefaultMaxTokens,\n\t\tSupportsAttachments: true,\n\t},\n}\n"], ["/opencode/internal/pubsub/events.go", "package pubsub\n\nimport \"context\"\n\nconst (\n\tCreatedEvent EventType = \"created\"\n\tUpdatedEvent EventType = \"updated\"\n\tDeletedEvent EventType = \"deleted\"\n)\n\ntype Suscriber[T any] interface {\n\tSubscribe(context.Context) <-chan Event[T]\n}\n\ntype (\n\t// EventType identifies the type of event\n\tEventType string\n\n\t// Event represents an event in the lifecycle of a resource\n\tEvent[T any] struct {\n\t\tType EventType\n\t\tPayload T\n\t}\n\n\tPublisher[T any] interface {\n\t\tPublish(EventType, T)\n\t}\n)\n"], ["/opencode/internal/llm/models/xai.go", "package models\n\nconst (\n\tProviderXAI ModelProvider = \"xai\"\n\n\tXAIGrok3Beta ModelID = \"grok-3-beta\"\n\tXAIGrok3MiniBeta ModelID = \"grok-3-mini-beta\"\n\tXAIGrok3FastBeta ModelID = \"grok-3-fast-beta\"\n\tXAiGrok3MiniFastBeta ModelID = \"grok-3-mini-fast-beta\"\n)\n\nvar XAIModels = map[ModelID]Model{\n\tXAIGrok3Beta: {\n\t\tID: XAIGrok3Beta,\n\t\tName: \"Grok3 Beta\",\n\t\tProvider: ProviderXAI,\n\t\tAPIModel: \"grok-3-beta\",\n\t\tCostPer1MIn: 3.0,\n\t\tCostPer1MInCached: 0,\n\t\tCostPer1MOut: 15,\n\t\tCostPer1MOutCached: 0,\n\t\tContextWindow: 131_072,\n\t\tDefaultMaxTokens: 20_000,\n\t},\n\tXAIGrok3MiniBeta: {\n\t\tID: XAIGrok3MiniBeta,\n\t\tName: \"Grok3 Mini Beta\",\n\t\tProvider: ProviderXAI,\n\t\tAPIModel: \"grok-3-mini-beta\",\n\t\tCostPer1MIn: 0.3,\n\t\tCostPer1MInCached: 0,\n\t\tCostPer1MOut: 0.5,\n\t\tCostPer1MOutCached: 0,\n\t\tContextWindow: 131_072,\n\t\tDefaultMaxTokens: 20_000,\n\t},\n\tXAIGrok3FastBeta: {\n\t\tID: XAIGrok3FastBeta,\n\t\tName: \"Grok3 Fast Beta\",\n\t\tProvider: ProviderXAI,\n\t\tAPIModel: \"grok-3-fast-beta\",\n\t\tCostPer1MIn: 5,\n\t\tCostPer1MInCached: 0,\n\t\tCostPer1MOut: 25,\n\t\tCostPer1MOutCached: 0,\n\t\tContextWindow: 131_072,\n\t\tDefaultMaxTokens: 20_000,\n\t},\n\tXAiGrok3MiniFastBeta: {\n\t\tID: XAiGrok3MiniFastBeta,\n\t\tName: \"Grok3 Mini Fast Beta\",\n\t\tProvider: ProviderXAI,\n\t\tAPIModel: \"grok-3-mini-fast-beta\",\n\t\tCostPer1MIn: 0.6,\n\t\tCostPer1MInCached: 0,\n\t\tCostPer1MOut: 4.0,\n\t\tCostPer1MOutCached: 0,\n\t\tContextWindow: 131_072,\n\t\tDefaultMaxTokens: 20_000,\n\t},\n}\n"], ["/opencode/internal/logging/message.go", "package logging\n\nimport (\n\t\"time\"\n)\n\n// LogMessage is the event payload for a log message\ntype LogMessage struct {\n\tID string\n\tTime time.Time\n\tLevel string\n\tPersist bool // used when we want to show the mesage in the status bar\n\tPersistTime time.Duration // used when we want to show the mesage in the status bar\n\tMessage string `json:\"msg\"`\n\tAttributes []Attr\n}\n\ntype Attr struct {\n\tKey string\n\tValue string\n}\n"], ["/opencode/internal/tui/page/page.go", "package page\n\ntype PageID string\n\n// PageChangeMsg is used to change the current page\ntype PageChangeMsg struct {\n\tID PageID\n}\n"], ["/opencode/internal/lsp/protocol/tables.go", "package protocol\n\nvar TableKindMap = map[SymbolKind]string{\n\tFile: \"File\",\n\tModule: \"Module\",\n\tNamespace: \"Namespace\",\n\tPackage: \"Package\",\n\tClass: \"Class\",\n\tMethod: \"Method\",\n\tProperty: \"Property\",\n\tField: \"Field\",\n\tConstructor: \"Constructor\",\n\tEnum: \"Enum\",\n\tInterface: \"Interface\",\n\tFunction: \"Function\",\n\tVariable: \"Variable\",\n\tConstant: \"Constant\",\n\tString: \"String\",\n\tNumber: \"Number\",\n\tBoolean: \"Boolean\",\n\tArray: \"Array\",\n\tObject: \"Object\",\n\tKey: \"Key\",\n\tNull: \"Null\",\n\tEnumMember: \"EnumMember\",\n\tStruct: \"Struct\",\n\tEvent: \"Event\",\n\tOperator: \"Operator\",\n\tTypeParameter: \"TypeParameter\",\n}\n"], ["/opencode/internal/tui/styles/icons.go", "package styles\n\nconst (\n\tOpenCodeIcon string = \"⌬\"\n\n\tCheckIcon string = \"✓\"\n\tErrorIcon string = \"✖\"\n\tWarningIcon string = \"⚠\"\n\tInfoIcon string = \"\"\n\tHintIcon string = \"i\"\n\tSpinnerIcon string = \"...\"\n\tLoadingIcon string = \"⟳\"\n\tDocumentIcon string = \"🖼\"\n)\n"], ["/opencode/internal/message/attachment.go", "package message\n\ntype Attachment struct {\n\tFilePath string\n\tFileName string\n\tMimeType string\n\tContent []byte\n}\n"], ["/opencode/internal/db/embed.go", "package db\n\nimport \"embed\"\n\n//go:embed migrations/*.sql\nvar FS embed.FS\n"]], "task_instance_info": {"created_time": "2025-08-20 20:58:37", "created_task_model": "DeepSeek-R1", "function_skeleton": "func NewCommandDialogCmp () CommandDialog {}", "code_description": "This code segment functions to: Initialize a component with default settings for managing an empty collection of items while preparing placeholder text and configuring visibility parameters for a user interface element dedicated to interactive selection."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```go\n[TASK_BEGIN]\nfunc NewCommandDialogCmp() CommandDialog {\n\treturn &commandDialogCmp{\n\t\tlistView: utilComponents.NewSimpleList[Command](\n\t\t\t[]Command{},\n\t\t\tfunc(item Command, width int, selected bool) string {\n\t\t\t\treturn item.Render(selected, width)\n\t\t\t},\n\t\t\t5, // default visible items\n\t\t),\n\t}\n}\n[TASK_END]\n```", "inference_time": "2025-08-20 20-58-58"}, "editdistance_info": {"edit_distance": 40.5797, "calculate_time": "2025-08-20 20:58:58", "true_code_clean": "func NewCommandDialogCmp() CommandDialog {\n\tlistView := utilComponents.NewSimpleList[Command](\n\t\t[]Command{},\n\t\t10,\n\t\t\"No commands available\",\n\t\ttrue,\n\t)\n\treturn &commandDialogCmp{\n\t\tlistView: listView,\n\t}\n}", "predict_code_clean": "func NewCommandDialogCmp() CommandDialog {\n\treturn &commandDialogCmp{\n\t\tlistView: utilComponents.NewSimpleList[Command](\n\t\t\t[]Command{},\n\t\t\tfunc(item Command, width int, selected bool) string {\n\t\t\t\treturn item.Render(selected, width)\n\t\t\t},\n\t\t\t5, \n\t\t),\n\t}\n}"}}
{"repo_name": "opencode", "file_name": "/opencode/internal/db/connect.go", "inference_info": {"prefix_code": "package db\n\nimport (\n\t\"database/sql\"\n\t\"fmt\"\n\t\"os\"\n\t\"path/filepath\"\n\n\t_ \"github.com/ncruces/go-sqlite3/driver\"\n\t_ \"github.com/ncruces/go-sqlite3/embed\"\n\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n\n\t\"github.com/pressly/goose/v3\"\n)\n\n", "suffix_code": "\n", "middle_code": "func Connect() (*sql.DB, error) {\n\tdataDir := config.Get().Data.Directory\n\tif dataDir == \"\" {\n\t\treturn nil, fmt.Errorf(\"data.dir is not set\")\n\t}\n\tif err := os.MkdirAll(dataDir, 0o700); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to create data directory: %w\", err)\n\t}\n\tdbPath := filepath.Join(dataDir, \"opencode.db\")\n\tdb, err := sql.Open(\"sqlite3\", dbPath)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to open database: %w\", err)\n\t}\n\tif err = db.Ping(); err != nil {\n\t\tdb.Close()\n\t\treturn nil, fmt.Errorf(\"failed to connect to database: %w\", err)\n\t}\n\tpragmas := []string{\n\t\t\"PRAGMA foreign_keys = ON;\",\n\t\t\"PRAGMA journal_mode = WAL;\",\n\t\t\"PRAGMA page_size = 4096;\",\n\t\t\"PRAGMA cache_size = -8000;\",\n\t\t\"PRAGMA synchronous = NORMAL;\",\n\t}\n\tfor _, pragma := range pragmas {\n\t\tif _, err = db.Exec(pragma); err != nil {\n\t\t\tlogging.Error(\"Failed to set pragma\", pragma, err)\n\t\t} else {\n\t\t\tlogging.Debug(\"Set pragma\", \"pragma\", pragma)\n\t\t}\n\t}\n\tgoose.SetBaseFS(FS)\n\tif err := goose.SetDialect(\"sqlite3\"); err != nil {\n\t\tlogging.Error(\"Failed to set dialect\", \"error\", err)\n\t\treturn nil, fmt.Errorf(\"failed to set dialect: %w\", err)\n\t}\n\tif err := goose.Up(db, \"migrations\"); err != nil {\n\t\tlogging.Error(\"Failed to apply migrations\", \"error\", err)\n\t\treturn nil, fmt.Errorf(\"failed to apply migrations: %w\", err)\n\t}\n\treturn db, nil\n}", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "go", "sub_task_type": null}, "context_code": [["/opencode/internal/config/config.go", "// Package config manages application configuration from various sources.\npackage config\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"log/slog\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"runtime\"\n\t\"strings\"\n\n\t\"github.com/opencode-ai/opencode/internal/llm/models\"\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n\t\"github.com/spf13/viper\"\n)\n\n// MCPType defines the type of MCP (Model Control Protocol) server.\ntype MCPType string\n\n// Supported MCP types\nconst (\n\tMCPStdio MCPType = \"stdio\"\n\tMCPSse MCPType = \"sse\"\n)\n\n// MCPServer defines the configuration for a Model Control Protocol server.\ntype MCPServer struct {\n\tCommand string `json:\"command\"`\n\tEnv []string `json:\"env\"`\n\tArgs []string `json:\"args\"`\n\tType MCPType `json:\"type\"`\n\tURL string `json:\"url\"`\n\tHeaders map[string]string `json:\"headers\"`\n}\n\ntype AgentName string\n\nconst (\n\tAgentCoder AgentName = \"coder\"\n\tAgentSummarizer AgentName = \"summarizer\"\n\tAgentTask AgentName = \"task\"\n\tAgentTitle AgentName = \"title\"\n)\n\n// Agent defines configuration for different LLM models and their token limits.\ntype Agent struct {\n\tModel models.ModelID `json:\"model\"`\n\tMaxTokens int64 `json:\"maxTokens\"`\n\tReasoningEffort string `json:\"reasoningEffort\"` // For openai models low,medium,heigh\n}\n\n// Provider defines configuration for an LLM provider.\ntype Provider struct {\n\tAPIKey string `json:\"apiKey\"`\n\tDisabled bool `json:\"disabled\"`\n}\n\n// Data defines storage configuration.\ntype Data struct {\n\tDirectory string `json:\"directory,omitempty\"`\n}\n\n// LSPConfig defines configuration for Language Server Protocol integration.\ntype LSPConfig struct {\n\tDisabled bool `json:\"enabled\"`\n\tCommand string `json:\"command\"`\n\tArgs []string `json:\"args\"`\n\tOptions any `json:\"options\"`\n}\n\n// TUIConfig defines the configuration for the Terminal User Interface.\ntype TUIConfig struct {\n\tTheme string `json:\"theme,omitempty\"`\n}\n\n// ShellConfig defines the configuration for the shell used by the bash tool.\ntype ShellConfig struct {\n\tPath string `json:\"path,omitempty\"`\n\tArgs []string `json:\"args,omitempty\"`\n}\n\n// Config is the main configuration structure for the application.\ntype Config struct {\n\tData Data `json:\"data\"`\n\tWorkingDir string `json:\"wd,omitempty\"`\n\tMCPServers map[string]MCPServer `json:\"mcpServers,omitempty\"`\n\tProviders map[models.ModelProvider]Provider `json:\"providers,omitempty\"`\n\tLSP map[string]LSPConfig `json:\"lsp,omitempty\"`\n\tAgents map[AgentName]Agent `json:\"agents,omitempty\"`\n\tDebug bool `json:\"debug,omitempty\"`\n\tDebugLSP bool `json:\"debugLSP,omitempty\"`\n\tContextPaths []string `json:\"contextPaths,omitempty\"`\n\tTUI TUIConfig `json:\"tui\"`\n\tShell ShellConfig `json:\"shell,omitempty\"`\n\tAutoCompact bool `json:\"autoCompact,omitempty\"`\n}\n\n// Application constants\nconst (\n\tdefaultDataDirectory = \".opencode\"\n\tdefaultLogLevel = \"info\"\n\tappName = \"opencode\"\n\n\tMaxTokensFallbackDefault = 4096\n)\n\nvar defaultContextPaths = []string{\n\t\".github/copilot-instructions.md\",\n\t\".cursorrules\",\n\t\".cursor/rules/\",\n\t\"CLAUDE.md\",\n\t\"CLAUDE.local.md\",\n\t\"opencode.md\",\n\t\"opencode.local.md\",\n\t\"OpenCode.md\",\n\t\"OpenCode.local.md\",\n\t\"OPENCODE.md\",\n\t\"OPENCODE.local.md\",\n}\n\n// Global configuration instance\nvar cfg *Config\n\n// Load initializes the configuration from environment variables and config files.\n// If debug is true, debug mode is enabled and log level is set to debug.\n// It returns an error if configuration loading fails.\nfunc Load(workingDir string, debug bool) (*Config, error) {\n\tif cfg != nil {\n\t\treturn cfg, nil\n\t}\n\n\tcfg = &Config{\n\t\tWorkingDir: workingDir,\n\t\tMCPServers: make(map[string]MCPServer),\n\t\tProviders: make(map[models.ModelProvider]Provider),\n\t\tLSP: make(map[string]LSPConfig),\n\t}\n\n\tconfigureViper()\n\tsetDefaults(debug)\n\n\t// Read global config\n\tif err := readConfig(viper.ReadInConfig()); err != nil {\n\t\treturn cfg, err\n\t}\n\n\t// Load and merge local config\n\tmergeLocalConfig(workingDir)\n\n\tsetProviderDefaults()\n\n\t// Apply configuration to the struct\n\tif err := viper.Unmarshal(cfg); err != nil {\n\t\treturn cfg, fmt.Errorf(\"failed to unmarshal config: %w\", err)\n\t}\n\n\tapplyDefaultValues()\n\tdefaultLevel := slog.LevelInfo\n\tif cfg.Debug {\n\t\tdefaultLevel = slog.LevelDebug\n\t}\n\tif os.Getenv(\"OPENCODE_DEV_DEBUG\") == \"true\" {\n\t\tloggingFile := fmt.Sprintf(\"%s/%s\", cfg.Data.Directory, \"debug.log\")\n\t\tmessagesPath := fmt.Sprintf(\"%s/%s\", cfg.Data.Directory, \"messages\")\n\n\t\t// if file does not exist create it\n\t\tif _, err := os.Stat(loggingFile); os.IsNotExist(err) {\n\t\t\tif err := os.MkdirAll(cfg.Data.Directory, 0o755); err != nil {\n\t\t\t\treturn cfg, fmt.Errorf(\"failed to create directory: %w\", err)\n\t\t\t}\n\t\t\tif _, err := os.Create(loggingFile); err != nil {\n\t\t\t\treturn cfg, fmt.Errorf(\"failed to create log file: %w\", err)\n\t\t\t}\n\t\t}\n\n\t\tif _, err := os.Stat(messagesPath); os.IsNotExist(err) {\n\t\t\tif err := os.MkdirAll(messagesPath, 0o756); err != nil {\n\t\t\t\treturn cfg, fmt.Errorf(\"failed to create directory: %w\", err)\n\t\t\t}\n\t\t}\n\t\tlogging.MessageDir = messagesPath\n\n\t\tsloggingFileWriter, err := os.OpenFile(loggingFile, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o666)\n\t\tif err != nil {\n\t\t\treturn cfg, fmt.Errorf(\"failed to open log file: %w\", err)\n\t\t}\n\t\t// Configure logger\n\t\tlogger := slog.New(slog.NewTextHandler(sloggingFileWriter, &slog.HandlerOptions{\n\t\t\tLevel: defaultLevel,\n\t\t}))\n\t\tslog.SetDefault(logger)\n\t} else {\n\t\t// Configure logger\n\t\tlogger := slog.New(slog.NewTextHandler(logging.NewWriter(), &slog.HandlerOptions{\n\t\t\tLevel: defaultLevel,\n\t\t}))\n\t\tslog.SetDefault(logger)\n\t}\n\n\t// Validate configuration\n\tif err := Validate(); err != nil {\n\t\treturn cfg, fmt.Errorf(\"config validation failed: %w\", err)\n\t}\n\n\tif cfg.Agents == nil {\n\t\tcfg.Agents = make(map[AgentName]Agent)\n\t}\n\n\t// Override the max tokens for title agent\n\tcfg.Agents[AgentTitle] = Agent{\n\t\tModel: cfg.Agents[AgentTitle].Model,\n\t\tMaxTokens: 80,\n\t}\n\treturn cfg, nil\n}\n\n// configureViper sets up viper's configuration paths and environment variables.\nfunc configureViper() {\n\tviper.SetConfigName(fmt.Sprintf(\".%s\", appName))\n\tviper.SetConfigType(\"json\")\n\tviper.AddConfigPath(\"$HOME\")\n\tviper.AddConfigPath(fmt.Sprintf(\"$XDG_CONFIG_HOME/%s\", appName))\n\tviper.AddConfigPath(fmt.Sprintf(\"$HOME/.config/%s\", appName))\n\tviper.SetEnvPrefix(strings.ToUpper(appName))\n\tviper.AutomaticEnv()\n}\n\n// setDefaults configures default values for configuration options.\nfunc setDefaults(debug bool) {\n\tviper.SetDefault(\"data.directory\", defaultDataDirectory)\n\tviper.SetDefault(\"contextPaths\", defaultContextPaths)\n\tviper.SetDefault(\"tui.theme\", \"opencode\")\n\tviper.SetDefault(\"autoCompact\", true)\n\n\t// Set default shell from environment or fallback to /bin/bash\n\tshellPath := os.Getenv(\"SHELL\")\n\tif shellPath == \"\" {\n\t\tshellPath = \"/bin/bash\"\n\t}\n\tviper.SetDefault(\"shell.path\", shellPath)\n\tviper.SetDefault(\"shell.args\", []string{\"-l\"})\n\n\tif debug {\n\t\tviper.SetDefault(\"debug\", true)\n\t\tviper.Set(\"log.level\", \"debug\")\n\t} else {\n\t\tviper.SetDefault(\"debug\", false)\n\t\tviper.SetDefault(\"log.level\", defaultLogLevel)\n\t}\n}\n\n// setProviderDefaults configures LLM provider defaults based on provider provided by\n// environment variables and configuration file.\nfunc setProviderDefaults() {\n\t// Set all API keys we can find in the environment\n\t// Note: Viper does not default if the json apiKey is \"\"\n\tif apiKey := os.Getenv(\"ANTHROPIC_API_KEY\"); apiKey != \"\" {\n\t\tviper.SetDefault(\"providers.anthropic.apiKey\", apiKey)\n\t}\n\tif apiKey := os.Getenv(\"OPENAI_API_KEY\"); apiKey != \"\" {\n\t\tviper.SetDefault(\"providers.openai.apiKey\", apiKey)\n\t}\n\tif apiKey := os.Getenv(\"GEMINI_API_KEY\"); apiKey != \"\" {\n\t\tviper.SetDefault(\"providers.gemini.apiKey\", apiKey)\n\t}\n\tif apiKey := os.Getenv(\"GROQ_API_KEY\"); apiKey != \"\" {\n\t\tviper.SetDefault(\"providers.groq.apiKey\", apiKey)\n\t}\n\tif apiKey := os.Getenv(\"OPENROUTER_API_KEY\"); apiKey != \"\" {\n\t\tviper.SetDefault(\"providers.openrouter.apiKey\", apiKey)\n\t}\n\tif apiKey := os.Getenv(\"XAI_API_KEY\"); apiKey != \"\" {\n\t\tviper.SetDefault(\"providers.xai.apiKey\", apiKey)\n\t}\n\tif apiKey := os.Getenv(\"AZURE_OPENAI_ENDPOINT\"); apiKey != \"\" {\n\t\t// api-key may be empty when using Entra ID credentials – that's okay\n\t\tviper.SetDefault(\"providers.azure.apiKey\", os.Getenv(\"AZURE_OPENAI_API_KEY\"))\n\t}\n\tif apiKey, err := LoadGitHubToken(); err == nil && apiKey != \"\" {\n\t\tviper.SetDefault(\"providers.copilot.apiKey\", apiKey)\n\t\tif viper.GetString(\"providers.copilot.apiKey\") == \"\" {\n\t\t\tviper.Set(\"providers.copilot.apiKey\", apiKey)\n\t\t}\n\t}\n\n\t// Use this order to set the default models\n\t// 1. Copilot\n\t// 2. Anthropic\n\t// 3. OpenAI\n\t// 4. Google Gemini\n\t// 5. Groq\n\t// 6. OpenRouter\n\t// 7. AWS Bedrock\n\t// 8. Azure\n\t// 9. Google Cloud VertexAI\n\n\t// copilot configuration\n\tif key := viper.GetString(\"providers.copilot.apiKey\"); strings.TrimSpace(key) != \"\" {\n\t\tviper.SetDefault(\"agents.coder.model\", models.CopilotGPT4o)\n\t\tviper.SetDefault(\"agents.summarizer.model\", models.CopilotGPT4o)\n\t\tviper.SetDefault(\"agents.task.model\", models.CopilotGPT4o)\n\t\tviper.SetDefault(\"agents.title.model\", models.CopilotGPT4o)\n\t\treturn\n\t}\n\n\t// Anthropic configuration\n\tif key := viper.GetString(\"providers.anthropic.apiKey\"); strings.TrimSpace(key) != \"\" {\n\t\tviper.SetDefault(\"agents.coder.model\", models.Claude4Sonnet)\n\t\tviper.SetDefault(\"agents.summarizer.model\", models.Claude4Sonnet)\n\t\tviper.SetDefault(\"agents.task.model\", models.Claude4Sonnet)\n\t\tviper.SetDefault(\"agents.title.model\", models.Claude4Sonnet)\n\t\treturn\n\t}\n\n\t// OpenAI configuration\n\tif key := viper.GetString(\"providers.openai.apiKey\"); strings.TrimSpace(key) != \"\" {\n\t\tviper.SetDefault(\"agents.coder.model\", models.GPT41)\n\t\tviper.SetDefault(\"agents.summarizer.model\", models.GPT41)\n\t\tviper.SetDefault(\"agents.task.model\", models.GPT41Mini)\n\t\tviper.SetDefault(\"agents.title.model\", models.GPT41Mini)\n\t\treturn\n\t}\n\n\t// Google Gemini configuration\n\tif key := viper.GetString(\"providers.gemini.apiKey\"); strings.TrimSpace(key) != \"\" {\n\t\tviper.SetDefault(\"agents.coder.model\", models.Gemini25)\n\t\tviper.SetDefault(\"agents.summarizer.model\", models.Gemini25)\n\t\tviper.SetDefault(\"agents.task.model\", models.Gemini25Flash)\n\t\tviper.SetDefault(\"agents.title.model\", models.Gemini25Flash)\n\t\treturn\n\t}\n\n\t// Groq configuration\n\tif key := viper.GetString(\"providers.groq.apiKey\"); strings.TrimSpace(key) != \"\" {\n\t\tviper.SetDefault(\"agents.coder.model\", models.QWENQwq)\n\t\tviper.SetDefault(\"agents.summarizer.model\", models.QWENQwq)\n\t\tviper.SetDefault(\"agents.task.model\", models.QWENQwq)\n\t\tviper.SetDefault(\"agents.title.model\", models.QWENQwq)\n\t\treturn\n\t}\n\n\t// OpenRouter configuration\n\tif key := viper.GetString(\"providers.openrouter.apiKey\"); strings.TrimSpace(key) != \"\" {\n\t\tviper.SetDefault(\"agents.coder.model\", models.OpenRouterClaude37Sonnet)\n\t\tviper.SetDefault(\"agents.summarizer.model\", models.OpenRouterClaude37Sonnet)\n\t\tviper.SetDefault(\"agents.task.model\", models.OpenRouterClaude37Sonnet)\n\t\tviper.SetDefault(\"agents.title.model\", models.OpenRouterClaude35Haiku)\n\t\treturn\n\t}\n\n\t// XAI configuration\n\tif key := viper.GetString(\"providers.xai.apiKey\"); strings.TrimSpace(key) != \"\" {\n\t\tviper.SetDefault(\"agents.coder.model\", models.XAIGrok3Beta)\n\t\tviper.SetDefault(\"agents.summarizer.model\", models.XAIGrok3Beta)\n\t\tviper.SetDefault(\"agents.task.model\", models.XAIGrok3Beta)\n\t\tviper.SetDefault(\"agents.title.model\", models.XAiGrok3MiniFastBeta)\n\t\treturn\n\t}\n\n\t// AWS Bedrock configuration\n\tif hasAWSCredentials() {\n\t\tviper.SetDefault(\"agents.coder.model\", models.BedrockClaude37Sonnet)\n\t\tviper.SetDefault(\"agents.summarizer.model\", models.BedrockClaude37Sonnet)\n\t\tviper.SetDefault(\"agents.task.model\", models.BedrockClaude37Sonnet)\n\t\tviper.SetDefault(\"agents.title.model\", models.BedrockClaude37Sonnet)\n\t\treturn\n\t}\n\n\t// Azure OpenAI configuration\n\tif os.Getenv(\"AZURE_OPENAI_ENDPOINT\") != \"\" {\n\t\tviper.SetDefault(\"agents.coder.model\", models.AzureGPT41)\n\t\tviper.SetDefault(\"agents.summarizer.model\", models.AzureGPT41)\n\t\tviper.SetDefault(\"agents.task.model\", models.AzureGPT41Mini)\n\t\tviper.SetDefault(\"agents.title.model\", models.AzureGPT41Mini)\n\t\treturn\n\t}\n\n\t// Google Cloud VertexAI configuration\n\tif hasVertexAICredentials() {\n\t\tviper.SetDefault(\"agents.coder.model\", models.VertexAIGemini25)\n\t\tviper.SetDefault(\"agents.summarizer.model\", models.VertexAIGemini25)\n\t\tviper.SetDefault(\"agents.task.model\", models.VertexAIGemini25Flash)\n\t\tviper.SetDefault(\"agents.title.model\", models.VertexAIGemini25Flash)\n\t\treturn\n\t}\n}\n\n// hasAWSCredentials checks if AWS credentials are available in the environment.\nfunc hasAWSCredentials() bool {\n\t// Check for explicit AWS credentials\n\tif os.Getenv(\"AWS_ACCESS_KEY_ID\") != \"\" && os.Getenv(\"AWS_SECRET_ACCESS_KEY\") != \"\" {\n\t\treturn true\n\t}\n\n\t// Check for AWS profile\n\tif os.Getenv(\"AWS_PROFILE\") != \"\" || os.Getenv(\"AWS_DEFAULT_PROFILE\") != \"\" {\n\t\treturn true\n\t}\n\n\t// Check for AWS region\n\tif os.Getenv(\"AWS_REGION\") != \"\" || os.Getenv(\"AWS_DEFAULT_REGION\") != \"\" {\n\t\treturn true\n\t}\n\n\t// Check if running on EC2 with instance profile\n\tif os.Getenv(\"AWS_CONTAINER_CREDENTIALS_RELATIVE_URI\") != \"\" ||\n\t\tos.Getenv(\"AWS_CONTAINER_CREDENTIALS_FULL_URI\") != \"\" {\n\t\treturn true\n\t}\n\n\treturn false\n}\n\n// hasVertexAICredentials checks if VertexAI credentials are available in the environment.\nfunc hasVertexAICredentials() bool {\n\t// Check for explicit VertexAI parameters\n\tif os.Getenv(\"VERTEXAI_PROJECT\") != \"\" && os.Getenv(\"VERTEXAI_LOCATION\") != \"\" {\n\t\treturn true\n\t}\n\t// Check for Google Cloud project and location\n\tif os.Getenv(\"GOOGLE_CLOUD_PROJECT\") != \"\" && (os.Getenv(\"GOOGLE_CLOUD_REGION\") != \"\" || os.Getenv(\"GOOGLE_CLOUD_LOCATION\") != \"\") {\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc hasCopilotCredentials() bool {\n\t// Check for explicit Copilot parameters\n\tif token, _ := LoadGitHubToken(); token != \"\" {\n\t\treturn true\n\t}\n\treturn false\n}\n\n// readConfig handles the result of reading a configuration file.\nfunc readConfig(err error) error {\n\tif err == nil {\n\t\treturn nil\n\t}\n\n\t// It's okay if the config file doesn't exist\n\tif _, ok := err.(viper.ConfigFileNotFoundError); ok {\n\t\treturn nil\n\t}\n\n\treturn fmt.Errorf(\"failed to read config: %w\", err)\n}\n\n// mergeLocalConfig loads and merges configuration from the local directory.\nfunc mergeLocalConfig(workingDir string) {\n\tlocal := viper.New()\n\tlocal.SetConfigName(fmt.Sprintf(\".%s\", appName))\n\tlocal.SetConfigType(\"json\")\n\tlocal.AddConfigPath(workingDir)\n\n\t// Merge local config if it exists\n\tif err := local.ReadInConfig(); err == nil {\n\t\tviper.MergeConfigMap(local.AllSettings())\n\t}\n}\n\n// applyDefaultValues sets default values for configuration fields that need processing.\nfunc applyDefaultValues() {\n\t// Set default MCP type if not specified\n\tfor k, v := range cfg.MCPServers {\n\t\tif v.Type == \"\" {\n\t\t\tv.Type = MCPStdio\n\t\t\tcfg.MCPServers[k] = v\n\t\t}\n\t}\n}\n\n// It validates model IDs and providers, ensuring they are supported.\nfunc validateAgent(cfg *Config, name AgentName, agent Agent) error {\n\t// Check if model exists\n\t// TODO:\tIf a copilot model is specified, but model is not found,\n\t// \t\t \tit might be new model. The https://api.githubcopilot.com/models\n\t// \t\t \tendpoint should be queried to validate if the model is supported.\n\tmodel, modelExists := models.SupportedModels[agent.Model]\n\tif !modelExists {\n\t\tlogging.Warn(\"unsupported model configured, reverting to default\",\n\t\t\t\"agent\", name,\n\t\t\t\"configured_model\", agent.Model)\n\n\t\t// Set default model based on available providers\n\t\tif setDefaultModelForAgent(name) {\n\t\t\tlogging.Info(\"set default model for agent\", \"agent\", name, \"model\", cfg.Agents[name].Model)\n\t\t} else {\n\t\t\treturn fmt.Errorf(\"no valid provider available for agent %s\", name)\n\t\t}\n\t\treturn nil\n\t}\n\n\t// Check if provider for the model is configured\n\tprovider := model.Provider\n\tproviderCfg, providerExists := cfg.Providers[provider]\n\n\tif !providerExists {\n\t\t// Provider not configured, check if we have environment variables\n\t\tapiKey := getProviderAPIKey(provider)\n\t\tif apiKey == \"\" {\n\t\t\tlogging.Warn(\"provider not configured for model, reverting to default\",\n\t\t\t\t\"agent\", name,\n\t\t\t\t\"model\", agent.Model,\n\t\t\t\t\"provider\", provider)\n\n\t\t\t// Set default model based on available providers\n\t\t\tif setDefaultModelForAgent(name) {\n\t\t\t\tlogging.Info(\"set default model for agent\", \"agent\", name, \"model\", cfg.Agents[name].Model)\n\t\t\t} else {\n\t\t\t\treturn fmt.Errorf(\"no valid provider available for agent %s\", name)\n\t\t\t}\n\t\t} else {\n\t\t\t// Add provider with API key from environment\n\t\t\tcfg.Providers[provider] = Provider{\n\t\t\t\tAPIKey: apiKey,\n\t\t\t}\n\t\t\tlogging.Info(\"added provider from environment\", \"provider\", provider)\n\t\t}\n\t} else if providerCfg.Disabled || providerCfg.APIKey == \"\" {\n\t\t// Provider is disabled or has no API key\n\t\tlogging.Warn(\"provider is disabled or has no API key, reverting to default\",\n\t\t\t\"agent\", name,\n\t\t\t\"model\", agent.Model,\n\t\t\t\"provider\", provider)\n\n\t\t// Set default model based on available providers\n\t\tif setDefaultModelForAgent(name) {\n\t\t\tlogging.Info(\"set default model for agent\", \"agent\", name, \"model\", cfg.Agents[name].Model)\n\t\t} else {\n\t\t\treturn fmt.Errorf(\"no valid provider available for agent %s\", name)\n\t\t}\n\t}\n\n\t// Validate max tokens\n\tif agent.MaxTokens <= 0 {\n\t\tlogging.Warn(\"invalid max tokens, setting to default\",\n\t\t\t\"agent\", name,\n\t\t\t\"model\", agent.Model,\n\t\t\t\"max_tokens\", agent.MaxTokens)\n\n\t\t// Update the agent with default max tokens\n\t\tupdatedAgent := cfg.Agents[name]\n\t\tif model.DefaultMaxTokens > 0 {\n\t\t\tupdatedAgent.MaxTokens = model.DefaultMaxTokens\n\t\t} else {\n\t\t\tupdatedAgent.MaxTokens = MaxTokensFallbackDefault\n\t\t}\n\t\tcfg.Agents[name] = updatedAgent\n\t} else if model.ContextWindow > 0 && agent.MaxTokens > model.ContextWindow/2 {\n\t\t// Ensure max tokens doesn't exceed half the context window (reasonable limit)\n\t\tlogging.Warn(\"max tokens exceeds half the context window, adjusting\",\n\t\t\t\"agent\", name,\n\t\t\t\"model\", agent.Model,\n\t\t\t\"max_tokens\", agent.MaxTokens,\n\t\t\t\"context_window\", model.ContextWindow)\n\n\t\t// Update the agent with adjusted max tokens\n\t\tupdatedAgent := cfg.Agents[name]\n\t\tupdatedAgent.MaxTokens = model.ContextWindow / 2\n\t\tcfg.Agents[name] = updatedAgent\n\t}\n\n\t// Validate reasoning effort for models that support reasoning\n\tif model.CanReason && provider == models.ProviderOpenAI || provider == models.ProviderLocal {\n\t\tif agent.ReasoningEffort == \"\" {\n\t\t\t// Set default reasoning effort for models that support it\n\t\t\tlogging.Info(\"setting default reasoning effort for model that supports reasoning\",\n\t\t\t\t\"agent\", name,\n\t\t\t\t\"model\", agent.Model)\n\n\t\t\t// Update the agent with default reasoning effort\n\t\t\tupdatedAgent := cfg.Agents[name]\n\t\t\tupdatedAgent.ReasoningEffort = \"medium\"\n\t\t\tcfg.Agents[name] = updatedAgent\n\t\t} else {\n\t\t\t// Check if reasoning effort is valid (low, medium, high)\n\t\t\teffort := strings.ToLower(agent.ReasoningEffort)\n\t\t\tif effort != \"low\" && effort != \"medium\" && effort != \"high\" {\n\t\t\t\tlogging.Warn(\"invalid reasoning effort, setting to medium\",\n\t\t\t\t\t\"agent\", name,\n\t\t\t\t\t\"model\", agent.Model,\n\t\t\t\t\t\"reasoning_effort\", agent.ReasoningEffort)\n\n\t\t\t\t// Update the agent with valid reasoning effort\n\t\t\t\tupdatedAgent := cfg.Agents[name]\n\t\t\t\tupdatedAgent.ReasoningEffort = \"medium\"\n\t\t\t\tcfg.Agents[name] = updatedAgent\n\t\t\t}\n\t\t}\n\t} else if !model.CanReason && agent.ReasoningEffort != \"\" {\n\t\t// Model doesn't support reasoning but reasoning effort is set\n\t\tlogging.Warn(\"model doesn't support reasoning but reasoning effort is set, ignoring\",\n\t\t\t\"agent\", name,\n\t\t\t\"model\", agent.Model,\n\t\t\t\"reasoning_effort\", agent.ReasoningEffort)\n\n\t\t// Update the agent to remove reasoning effort\n\t\tupdatedAgent := cfg.Agents[name]\n\t\tupdatedAgent.ReasoningEffort = \"\"\n\t\tcfg.Agents[name] = updatedAgent\n\t}\n\n\treturn nil\n}\n\n// Validate checks if the configuration is valid and applies defaults where needed.\nfunc Validate() error {\n\tif cfg == nil {\n\t\treturn fmt.Errorf(\"config not loaded\")\n\t}\n\n\t// Validate agent models\n\tfor name, agent := range cfg.Agents {\n\t\tif err := validateAgent(cfg, name, agent); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// Validate providers\n\tfor provider, providerCfg := range cfg.Providers {\n\t\tif providerCfg.APIKey == \"\" && !providerCfg.Disabled {\n\t\t\tfmt.Printf(\"provider has no API key, marking as disabled %s\", provider)\n\t\t\tlogging.Warn(\"provider has no API key, marking as disabled\", \"provider\", provider)\n\t\t\tproviderCfg.Disabled = true\n\t\t\tcfg.Providers[provider] = providerCfg\n\t\t}\n\t}\n\n\t// Validate LSP configurations\n\tfor language, lspConfig := range cfg.LSP {\n\t\tif lspConfig.Command == \"\" && !lspConfig.Disabled {\n\t\t\tlogging.Warn(\"LSP configuration has no command, marking as disabled\", \"language\", language)\n\t\t\tlspConfig.Disabled = true\n\t\t\tcfg.LSP[language] = lspConfig\n\t\t}\n\t}\n\n\treturn nil\n}\n\n// getProviderAPIKey gets the API key for a provider from environment variables\nfunc getProviderAPIKey(provider models.ModelProvider) string {\n\tswitch provider {\n\tcase models.ProviderAnthropic:\n\t\treturn os.Getenv(\"ANTHROPIC_API_KEY\")\n\tcase models.ProviderOpenAI:\n\t\treturn os.Getenv(\"OPENAI_API_KEY\")\n\tcase models.ProviderGemini:\n\t\treturn os.Getenv(\"GEMINI_API_KEY\")\n\tcase models.ProviderGROQ:\n\t\treturn os.Getenv(\"GROQ_API_KEY\")\n\tcase models.ProviderAzure:\n\t\treturn os.Getenv(\"AZURE_OPENAI_API_KEY\")\n\tcase models.ProviderOpenRouter:\n\t\treturn os.Getenv(\"OPENROUTER_API_KEY\")\n\tcase models.ProviderBedrock:\n\t\tif hasAWSCredentials() {\n\t\t\treturn \"aws-credentials-available\"\n\t\t}\n\tcase models.ProviderVertexAI:\n\t\tif hasVertexAICredentials() {\n\t\t\treturn \"vertex-ai-credentials-available\"\n\t\t}\n\t}\n\treturn \"\"\n}\n\n// setDefaultModelForAgent sets a default model for an agent based on available providers\nfunc setDefaultModelForAgent(agent AgentName) bool {\n\tif hasCopilotCredentials() {\n\t\tmaxTokens := int64(5000)\n\t\tif agent == AgentTitle {\n\t\t\tmaxTokens = 80\n\t\t}\n\n\t\tcfg.Agents[agent] = Agent{\n\t\t\tModel: models.CopilotGPT4o,\n\t\t\tMaxTokens: maxTokens,\n\t\t}\n\t\treturn true\n\t}\n\t// Check providers in order of preference\n\tif apiKey := os.Getenv(\"ANTHROPIC_API_KEY\"); apiKey != \"\" {\n\t\tmaxTokens := int64(5000)\n\t\tif agent == AgentTitle {\n\t\t\tmaxTokens = 80\n\t\t}\n\t\tcfg.Agents[agent] = Agent{\n\t\t\tModel: models.Claude37Sonnet,\n\t\t\tMaxTokens: maxTokens,\n\t\t}\n\t\treturn true\n\t}\n\n\tif apiKey := os.Getenv(\"OPENAI_API_KEY\"); apiKey != \"\" {\n\t\tvar model models.ModelID\n\t\tmaxTokens := int64(5000)\n\t\treasoningEffort := \"\"\n\n\t\tswitch agent {\n\t\tcase AgentTitle:\n\t\t\tmodel = models.GPT41Mini\n\t\t\tmaxTokens = 80\n\t\tcase AgentTask:\n\t\t\tmodel = models.GPT41Mini\n\t\tdefault:\n\t\t\tmodel = models.GPT41\n\t\t}\n\n\t\t// Check if model supports reasoning\n\t\tif modelInfo, ok := models.SupportedModels[model]; ok && modelInfo.CanReason {\n\t\t\treasoningEffort = \"medium\"\n\t\t}\n\n\t\tcfg.Agents[agent] = Agent{\n\t\t\tModel: model,\n\t\t\tMaxTokens: maxTokens,\n\t\t\tReasoningEffort: reasoningEffort,\n\t\t}\n\t\treturn true\n\t}\n\n\tif apiKey := os.Getenv(\"OPENROUTER_API_KEY\"); apiKey != \"\" {\n\t\tvar model models.ModelID\n\t\tmaxTokens := int64(5000)\n\t\treasoningEffort := \"\"\n\n\t\tswitch agent {\n\t\tcase AgentTitle:\n\t\t\tmodel = models.OpenRouterClaude35Haiku\n\t\t\tmaxTokens = 80\n\t\tcase AgentTask:\n\t\t\tmodel = models.OpenRouterClaude37Sonnet\n\t\tdefault:\n\t\t\tmodel = models.OpenRouterClaude37Sonnet\n\t\t}\n\n\t\t// Check if model supports reasoning\n\t\tif modelInfo, ok := models.SupportedModels[model]; ok && modelInfo.CanReason {\n\t\t\treasoningEffort = \"medium\"\n\t\t}\n\n\t\tcfg.Agents[agent] = Agent{\n\t\t\tModel: model,\n\t\t\tMaxTokens: maxTokens,\n\t\t\tReasoningEffort: reasoningEffort,\n\t\t}\n\t\treturn true\n\t}\n\n\tif apiKey := os.Getenv(\"GEMINI_API_KEY\"); apiKey != \"\" {\n\t\tvar model models.ModelID\n\t\tmaxTokens := int64(5000)\n\n\t\tif agent == AgentTitle {\n\t\t\tmodel = models.Gemini25Flash\n\t\t\tmaxTokens = 80\n\t\t} else {\n\t\t\tmodel = models.Gemini25\n\t\t}\n\n\t\tcfg.Agents[agent] = Agent{\n\t\t\tModel: model,\n\t\t\tMaxTokens: maxTokens,\n\t\t}\n\t\treturn true\n\t}\n\n\tif apiKey := os.Getenv(\"GROQ_API_KEY\"); apiKey != \"\" {\n\t\tmaxTokens := int64(5000)\n\t\tif agent == AgentTitle {\n\t\t\tmaxTokens = 80\n\t\t}\n\n\t\tcfg.Agents[agent] = Agent{\n\t\t\tModel: models.QWENQwq,\n\t\t\tMaxTokens: maxTokens,\n\t\t}\n\t\treturn true\n\t}\n\n\tif hasAWSCredentials() {\n\t\tmaxTokens := int64(5000)\n\t\tif agent == AgentTitle {\n\t\t\tmaxTokens = 80\n\t\t}\n\n\t\tcfg.Agents[agent] = Agent{\n\t\t\tModel: models.BedrockClaude37Sonnet,\n\t\t\tMaxTokens: maxTokens,\n\t\t\tReasoningEffort: \"medium\", // Claude models support reasoning\n\t\t}\n\t\treturn true\n\t}\n\n\tif hasVertexAICredentials() {\n\t\tvar model models.ModelID\n\t\tmaxTokens := int64(5000)\n\n\t\tif agent == AgentTitle {\n\t\t\tmodel = models.VertexAIGemini25Flash\n\t\t\tmaxTokens = 80\n\t\t} else {\n\t\t\tmodel = models.VertexAIGemini25\n\t\t}\n\n\t\tcfg.Agents[agent] = Agent{\n\t\t\tModel: model,\n\t\t\tMaxTokens: maxTokens,\n\t\t}\n\t\treturn true\n\t}\n\n\treturn false\n}\n\nfunc updateCfgFile(updateCfg func(config *Config)) error {\n\tif cfg == nil {\n\t\treturn fmt.Errorf(\"config not loaded\")\n\t}\n\n\t// Get the config file path\n\tconfigFile := viper.ConfigFileUsed()\n\tvar configData []byte\n\tif configFile == \"\" {\n\t\thomeDir, err := os.UserHomeDir()\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to get home directory: %w\", err)\n\t\t}\n\t\tconfigFile = filepath.Join(homeDir, fmt.Sprintf(\".%s.json\", appName))\n\t\tlogging.Info(\"config file not found, creating new one\", \"path\", configFile)\n\t\tconfigData = []byte(`{}`)\n\t} else {\n\t\t// Read the existing config file\n\t\tdata, err := os.ReadFile(configFile)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to read config file: %w\", err)\n\t\t}\n\t\tconfigData = data\n\t}\n\n\t// Parse the JSON\n\tvar userCfg *Config\n\tif err := json.Unmarshal(configData, &userCfg); err != nil {\n\t\treturn fmt.Errorf(\"failed to parse config file: %w\", err)\n\t}\n\n\tupdateCfg(userCfg)\n\n\t// Write the updated config back to file\n\tupdatedData, err := json.MarshalIndent(userCfg, \"\", \" \")\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to marshal config: %w\", err)\n\t}\n\n\tif err := os.WriteFile(configFile, updatedData, 0o644); err != nil {\n\t\treturn fmt.Errorf(\"failed to write config file: %w\", err)\n\t}\n\n\treturn nil\n}\n\n// Get returns the current configuration.\n// It's safe to call this function multiple times.\nfunc Get() *Config {\n\treturn cfg\n}\n\n// WorkingDirectory returns the current working directory from the configuration.\nfunc WorkingDirectory() string {\n\tif cfg == nil {\n\t\tpanic(\"config not loaded\")\n\t}\n\treturn cfg.WorkingDir\n}\n\nfunc UpdateAgentModel(agentName AgentName, modelID models.ModelID) error {\n\tif cfg == nil {\n\t\tpanic(\"config not loaded\")\n\t}\n\n\texistingAgentCfg := cfg.Agents[agentName]\n\n\tmodel, ok := models.SupportedModels[modelID]\n\tif !ok {\n\t\treturn fmt.Errorf(\"model %s not supported\", modelID)\n\t}\n\n\tmaxTokens := existingAgentCfg.MaxTokens\n\tif model.DefaultMaxTokens > 0 {\n\t\tmaxTokens = model.DefaultMaxTokens\n\t}\n\n\tnewAgentCfg := Agent{\n\t\tModel: modelID,\n\t\tMaxTokens: maxTokens,\n\t\tReasoningEffort: existingAgentCfg.ReasoningEffort,\n\t}\n\tcfg.Agents[agentName] = newAgentCfg\n\n\tif err := validateAgent(cfg, agentName, newAgentCfg); err != nil {\n\t\t// revert config update on failure\n\t\tcfg.Agents[agentName] = existingAgentCfg\n\t\treturn fmt.Errorf(\"failed to update agent model: %w\", err)\n\t}\n\n\treturn updateCfgFile(func(config *Config) {\n\t\tif config.Agents == nil {\n\t\t\tconfig.Agents = make(map[AgentName]Agent)\n\t\t}\n\t\tconfig.Agents[agentName] = newAgentCfg\n\t})\n}\n\n// UpdateTheme updates the theme in the configuration and writes it to the config file.\nfunc UpdateTheme(themeName string) error {\n\tif cfg == nil {\n\t\treturn fmt.Errorf(\"config not loaded\")\n\t}\n\n\t// Update the in-memory config\n\tcfg.TUI.Theme = themeName\n\n\t// Update the file config\n\treturn updateCfgFile(func(config *Config) {\n\t\tconfig.TUI.Theme = themeName\n\t})\n}\n\n// Tries to load Github token from all possible locations\nfunc LoadGitHubToken() (string, error) {\n\t// First check environment variable\n\tif token := os.Getenv(\"GITHUB_TOKEN\"); token != \"\" {\n\t\treturn token, nil\n\t}\n\n\t// Get config directory\n\tvar configDir string\n\tif xdgConfig := os.Getenv(\"XDG_CONFIG_HOME\"); xdgConfig != \"\" {\n\t\tconfigDir = xdgConfig\n\t} else if runtime.GOOS == \"windows\" {\n\t\tif localAppData := os.Getenv(\"LOCALAPPDATA\"); localAppData != \"\" {\n\t\t\tconfigDir = localAppData\n\t\t} else {\n\t\t\tconfigDir = filepath.Join(os.Getenv(\"HOME\"), \"AppData\", \"Local\")\n\t\t}\n\t} else {\n\t\tconfigDir = filepath.Join(os.Getenv(\"HOME\"), \".config\")\n\t}\n\n\t// Try both hosts.json and apps.json files\n\tfilePaths := []string{\n\t\tfilepath.Join(configDir, \"github-copilot\", \"hosts.json\"),\n\t\tfilepath.Join(configDir, \"github-copilot\", \"apps.json\"),\n\t}\n\n\tfor _, filePath := range filePaths {\n\t\tdata, err := os.ReadFile(filePath)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tvar config map[string]map[string]interface{}\n\t\tif err := json.Unmarshal(data, &config); err != nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tfor key, value := range config {\n\t\t\tif strings.Contains(key, \"github.com\") {\n\t\t\t\tif oauthToken, ok := value[\"oauth_token\"].(string); ok {\n\t\t\t\t\treturn oauthToken, nil\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn \"\", fmt.Errorf(\"GitHub token not found in standard locations\")\n}\n"], ["/opencode/internal/lsp/client.go", "package lsp\n\nimport (\n\t\"bufio\"\n\t\"context\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"os/exec\"\n\t\"path/filepath\"\n\t\"strings\"\n\t\"sync\"\n\t\"sync/atomic\"\n\t\"time\"\n\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n\t\"github.com/opencode-ai/opencode/internal/lsp/protocol\"\n)\n\ntype Client struct {\n\tCmd *exec.Cmd\n\tstdin io.WriteCloser\n\tstdout *bufio.Reader\n\tstderr io.ReadCloser\n\n\t// Request ID counter\n\tnextID atomic.Int32\n\n\t// Response handlers\n\thandlers map[int32]chan *Message\n\thandlersMu sync.RWMutex\n\n\t// Server request handlers\n\tserverRequestHandlers map[string]ServerRequestHandler\n\tserverHandlersMu sync.RWMutex\n\n\t// Notification handlers\n\tnotificationHandlers map[string]NotificationHandler\n\tnotificationMu sync.RWMutex\n\n\t// Diagnostic cache\n\tdiagnostics map[protocol.DocumentUri][]protocol.Diagnostic\n\tdiagnosticsMu sync.RWMutex\n\n\t// Files are currently opened by the LSP\n\topenFiles map[string]*OpenFileInfo\n\topenFilesMu sync.RWMutex\n\n\t// Server state\n\tserverState atomic.Value\n}\n\nfunc NewClient(ctx context.Context, command string, args ...string) (*Client, error) {\n\tcmd := exec.CommandContext(ctx, command, args...)\n\t// Copy env\n\tcmd.Env = os.Environ()\n\n\tstdin, err := cmd.StdinPipe()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to create stdin pipe: %w\", err)\n\t}\n\n\tstdout, err := cmd.StdoutPipe()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to create stdout pipe: %w\", err)\n\t}\n\n\tstderr, err := cmd.StderrPipe()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to create stderr pipe: %w\", err)\n\t}\n\n\tclient := &Client{\n\t\tCmd: cmd,\n\t\tstdin: stdin,\n\t\tstdout: bufio.NewReader(stdout),\n\t\tstderr: stderr,\n\t\thandlers: make(map[int32]chan *Message),\n\t\tnotificationHandlers: make(map[string]NotificationHandler),\n\t\tserverRequestHandlers: make(map[string]ServerRequestHandler),\n\t\tdiagnostics: make(map[protocol.DocumentUri][]protocol.Diagnostic),\n\t\topenFiles: make(map[string]*OpenFileInfo),\n\t}\n\n\t// Initialize server state\n\tclient.serverState.Store(StateStarting)\n\n\t// Start the LSP server process\n\tif err := cmd.Start(); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to start LSP server: %w\", err)\n\t}\n\n\t// Handle stderr in a separate goroutine\n\tgo func() {\n\t\tscanner := bufio.NewScanner(stderr)\n\t\tfor scanner.Scan() {\n\t\t\tfmt.Fprintf(os.Stderr, \"LSP Server: %s\\n\", scanner.Text())\n\t\t}\n\t\tif err := scanner.Err(); err != nil {\n\t\t\tfmt.Fprintf(os.Stderr, \"Error reading stderr: %v\\n\", err)\n\t\t}\n\t}()\n\n\t// Start message handling loop\n\tgo func() {\n\t\tdefer logging.RecoverPanic(\"LSP-message-handler\", func() {\n\t\t\tlogging.ErrorPersist(\"LSP message handler crashed, LSP functionality may be impaired\")\n\t\t})\n\t\tclient.handleMessages()\n\t}()\n\n\treturn client, nil\n}\n\nfunc (c *Client) RegisterNotificationHandler(method string, handler NotificationHandler) {\n\tc.notificationMu.Lock()\n\tdefer c.notificationMu.Unlock()\n\tc.notificationHandlers[method] = handler\n}\n\nfunc (c *Client) RegisterServerRequestHandler(method string, handler ServerRequestHandler) {\n\tc.serverHandlersMu.Lock()\n\tdefer c.serverHandlersMu.Unlock()\n\tc.serverRequestHandlers[method] = handler\n}\n\nfunc (c *Client) InitializeLSPClient(ctx context.Context, workspaceDir string) (*protocol.InitializeResult, error) {\n\tinitParams := &protocol.InitializeParams{\n\t\tWorkspaceFoldersInitializeParams: protocol.WorkspaceFoldersInitializeParams{\n\t\t\tWorkspaceFolders: []protocol.WorkspaceFolder{\n\t\t\t\t{\n\t\t\t\t\tURI: protocol.URI(\"file://\" + workspaceDir),\n\t\t\t\t\tName: workspaceDir,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\n\t\tXInitializeParams: protocol.XInitializeParams{\n\t\t\tProcessID: int32(os.Getpid()),\n\t\t\tClientInfo: &protocol.ClientInfo{\n\t\t\t\tName: \"mcp-language-server\",\n\t\t\t\tVersion: \"0.1.0\",\n\t\t\t},\n\t\t\tRootPath: workspaceDir,\n\t\t\tRootURI: protocol.DocumentUri(\"file://\" + workspaceDir),\n\t\t\tCapabilities: protocol.ClientCapabilities{\n\t\t\t\tWorkspace: protocol.WorkspaceClientCapabilities{\n\t\t\t\t\tConfiguration: true,\n\t\t\t\t\tDidChangeConfiguration: protocol.DidChangeConfigurationClientCapabilities{\n\t\t\t\t\t\tDynamicRegistration: true,\n\t\t\t\t\t},\n\t\t\t\t\tDidChangeWatchedFiles: protocol.DidChangeWatchedFilesClientCapabilities{\n\t\t\t\t\t\tDynamicRegistration: true,\n\t\t\t\t\t\tRelativePatternSupport: true,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tTextDocument: protocol.TextDocumentClientCapabilities{\n\t\t\t\t\tSynchronization: &protocol.TextDocumentSyncClientCapabilities{\n\t\t\t\t\t\tDynamicRegistration: true,\n\t\t\t\t\t\tDidSave: true,\n\t\t\t\t\t},\n\t\t\t\t\tCompletion: protocol.CompletionClientCapabilities{\n\t\t\t\t\t\tCompletionItem: protocol.ClientCompletionItemOptions{},\n\t\t\t\t\t},\n\t\t\t\t\tCodeLens: &protocol.CodeLensClientCapabilities{\n\t\t\t\t\t\tDynamicRegistration: true,\n\t\t\t\t\t},\n\t\t\t\t\tDocumentSymbol: protocol.DocumentSymbolClientCapabilities{},\n\t\t\t\t\tCodeAction: protocol.CodeActionClientCapabilities{\n\t\t\t\t\t\tCodeActionLiteralSupport: protocol.ClientCodeActionLiteralOptions{\n\t\t\t\t\t\t\tCodeActionKind: protocol.ClientCodeActionKindOptions{\n\t\t\t\t\t\t\t\tValueSet: []protocol.CodeActionKind{},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\tPublishDiagnostics: protocol.PublishDiagnosticsClientCapabilities{\n\t\t\t\t\t\tVersionSupport: true,\n\t\t\t\t\t},\n\t\t\t\t\tSemanticTokens: protocol.SemanticTokensClientCapabilities{\n\t\t\t\t\t\tRequests: protocol.ClientSemanticTokensRequestOptions{\n\t\t\t\t\t\t\tRange: &protocol.Or_ClientSemanticTokensRequestOptions_range{},\n\t\t\t\t\t\t\tFull: &protocol.Or_ClientSemanticTokensRequestOptions_full{},\n\t\t\t\t\t\t},\n\t\t\t\t\t\tTokenTypes: []string{},\n\t\t\t\t\t\tTokenModifiers: []string{},\n\t\t\t\t\t\tFormats: []protocol.TokenFormat{},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tWindow: protocol.WindowClientCapabilities{},\n\t\t\t},\n\t\t\tInitializationOptions: map[string]any{\n\t\t\t\t\"codelenses\": map[string]bool{\n\t\t\t\t\t\"generate\": true,\n\t\t\t\t\t\"regenerate_cgo\": true,\n\t\t\t\t\t\"test\": true,\n\t\t\t\t\t\"tidy\": true,\n\t\t\t\t\t\"upgrade_dependency\": true,\n\t\t\t\t\t\"vendor\": true,\n\t\t\t\t\t\"vulncheck\": false,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\tvar result protocol.InitializeResult\n\tif err := c.Call(ctx, \"initialize\", initParams, &result); err != nil {\n\t\treturn nil, fmt.Errorf(\"initialize failed: %w\", err)\n\t}\n\n\tif err := c.Notify(ctx, \"initialized\", struct{}{}); err != nil {\n\t\treturn nil, fmt.Errorf(\"initialized notification failed: %w\", err)\n\t}\n\n\t// Register handlers\n\tc.RegisterServerRequestHandler(\"workspace/applyEdit\", HandleApplyEdit)\n\tc.RegisterServerRequestHandler(\"workspace/configuration\", HandleWorkspaceConfiguration)\n\tc.RegisterServerRequestHandler(\"client/registerCapability\", HandleRegisterCapability)\n\tc.RegisterNotificationHandler(\"window/showMessage\", HandleServerMessage)\n\tc.RegisterNotificationHandler(\"textDocument/publishDiagnostics\",\n\t\tfunc(params json.RawMessage) { HandleDiagnostics(c, params) })\n\n\t// Notify the LSP server\n\terr := c.Initialized(ctx, protocol.InitializedParams{})\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"initialization failed: %w\", err)\n\t}\n\n\treturn &result, nil\n}\n\nfunc (c *Client) Close() error {\n\t// Try to close all open files first\n\tctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)\n\tdefer cancel()\n\n\t// Attempt to close files but continue shutdown regardless\n\tc.CloseAllFiles(ctx)\n\n\t// Close stdin to signal the server\n\tif err := c.stdin.Close(); err != nil {\n\t\treturn fmt.Errorf(\"failed to close stdin: %w\", err)\n\t}\n\n\t// Use a channel to handle the Wait with timeout\n\tdone := make(chan error, 1)\n\tgo func() {\n\t\tdone <- c.Cmd.Wait()\n\t}()\n\n\t// Wait for process to exit with timeout\n\tselect {\n\tcase err := <-done:\n\t\treturn err\n\tcase <-time.After(2 * time.Second):\n\t\t// If we timeout, try to kill the process\n\t\tif err := c.Cmd.Process.Kill(); err != nil {\n\t\t\treturn fmt.Errorf(\"failed to kill process: %w\", err)\n\t\t}\n\t\treturn fmt.Errorf(\"process killed after timeout\")\n\t}\n}\n\ntype ServerState int\n\nconst (\n\tStateStarting ServerState = iota\n\tStateReady\n\tStateError\n)\n\n// GetServerState returns the current state of the LSP server\nfunc (c *Client) GetServerState() ServerState {\n\tif val := c.serverState.Load(); val != nil {\n\t\treturn val.(ServerState)\n\t}\n\treturn StateStarting\n}\n\n// SetServerState sets the current state of the LSP server\nfunc (c *Client) SetServerState(state ServerState) {\n\tc.serverState.Store(state)\n}\n\n// WaitForServerReady waits for the server to be ready by polling the server\n// with a simple request until it responds successfully or times out\nfunc (c *Client) WaitForServerReady(ctx context.Context) error {\n\tcnf := config.Get()\n\n\t// Set initial state\n\tc.SetServerState(StateStarting)\n\n\t// Create a context with timeout\n\tctx, cancel := context.WithTimeout(ctx, 30*time.Second)\n\tdefer cancel()\n\n\t// Try to ping the server with a simple request\n\tticker := time.NewTicker(500 * time.Millisecond)\n\tdefer ticker.Stop()\n\n\tif cnf.DebugLSP {\n\t\tlogging.Debug(\"Waiting for LSP server to be ready...\")\n\t}\n\n\t// Determine server type for specialized initialization\n\tserverType := c.detectServerType()\n\n\t// For TypeScript-like servers, we need to open some key files first\n\tif serverType == ServerTypeTypeScript {\n\t\tif cnf.DebugLSP {\n\t\t\tlogging.Debug(\"TypeScript-like server detected, opening key configuration files\")\n\t\t}\n\t\tc.openKeyConfigFiles(ctx)\n\t}\n\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\tc.SetServerState(StateError)\n\t\t\treturn fmt.Errorf(\"timeout waiting for LSP server to be ready\")\n\t\tcase <-ticker.C:\n\t\t\t// Try a ping method appropriate for this server type\n\t\t\terr := c.pingServerByType(ctx, serverType)\n\t\t\tif err == nil {\n\t\t\t\t// Server responded successfully\n\t\t\t\tc.SetServerState(StateReady)\n\t\t\t\tif cnf.DebugLSP {\n\t\t\t\t\tlogging.Debug(\"LSP server is ready\")\n\t\t\t\t}\n\t\t\t\treturn nil\n\t\t\t} else {\n\t\t\t\tlogging.Debug(\"LSP server not ready yet\", \"error\", err, \"serverType\", serverType)\n\t\t\t}\n\n\t\t\tif cnf.DebugLSP {\n\t\t\t\tlogging.Debug(\"LSP server not ready yet\", \"error\", err, \"serverType\", serverType)\n\t\t\t}\n\t\t}\n\t}\n}\n\n// ServerType represents the type of LSP server\ntype ServerType int\n\nconst (\n\tServerTypeUnknown ServerType = iota\n\tServerTypeGo\n\tServerTypeTypeScript\n\tServerTypeRust\n\tServerTypePython\n\tServerTypeGeneric\n)\n\n// detectServerType tries to determine what type of LSP server we're dealing with\nfunc (c *Client) detectServerType() ServerType {\n\tif c.Cmd == nil {\n\t\treturn ServerTypeUnknown\n\t}\n\n\tcmdPath := strings.ToLower(c.Cmd.Path)\n\n\tswitch {\n\tcase strings.Contains(cmdPath, \"gopls\"):\n\t\treturn ServerTypeGo\n\tcase strings.Contains(cmdPath, \"typescript\") || strings.Contains(cmdPath, \"vtsls\") || strings.Contains(cmdPath, \"tsserver\"):\n\t\treturn ServerTypeTypeScript\n\tcase strings.Contains(cmdPath, \"rust-analyzer\"):\n\t\treturn ServerTypeRust\n\tcase strings.Contains(cmdPath, \"pyright\") || strings.Contains(cmdPath, \"pylsp\") || strings.Contains(cmdPath, \"python\"):\n\t\treturn ServerTypePython\n\tdefault:\n\t\treturn ServerTypeGeneric\n\t}\n}\n\n// openKeyConfigFiles opens important configuration files that help initialize the server\nfunc (c *Client) openKeyConfigFiles(ctx context.Context) {\n\tworkDir := config.WorkingDirectory()\n\tserverType := c.detectServerType()\n\n\tvar filesToOpen []string\n\n\tswitch serverType {\n\tcase ServerTypeTypeScript:\n\t\t// TypeScript servers need these config files to properly initialize\n\t\tfilesToOpen = []string{\n\t\t\tfilepath.Join(workDir, \"tsconfig.json\"),\n\t\t\tfilepath.Join(workDir, \"package.json\"),\n\t\t\tfilepath.Join(workDir, \"jsconfig.json\"),\n\t\t}\n\n\t\t// Also find and open a few TypeScript files to help the server initialize\n\t\tc.openTypeScriptFiles(ctx, workDir)\n\tcase ServerTypeGo:\n\t\tfilesToOpen = []string{\n\t\t\tfilepath.Join(workDir, \"go.mod\"),\n\t\t\tfilepath.Join(workDir, \"go.sum\"),\n\t\t}\n\tcase ServerTypeRust:\n\t\tfilesToOpen = []string{\n\t\t\tfilepath.Join(workDir, \"Cargo.toml\"),\n\t\t\tfilepath.Join(workDir, \"Cargo.lock\"),\n\t\t}\n\t}\n\n\t// Try to open each file, ignoring errors if they don't exist\n\tfor _, file := range filesToOpen {\n\t\tif _, err := os.Stat(file); err == nil {\n\t\t\t// File exists, try to open it\n\t\t\tif err := c.OpenFile(ctx, file); err != nil {\n\t\t\t\tlogging.Debug(\"Failed to open key config file\", \"file\", file, \"error\", err)\n\t\t\t} else {\n\t\t\t\tlogging.Debug(\"Opened key config file for initialization\", \"file\", file)\n\t\t\t}\n\t\t}\n\t}\n}\n\n// pingServerByType sends a ping request appropriate for the server type\nfunc (c *Client) pingServerByType(ctx context.Context, serverType ServerType) error {\n\tswitch serverType {\n\tcase ServerTypeTypeScript:\n\t\t// For TypeScript, try a document symbol request on an open file\n\t\treturn c.pingTypeScriptServer(ctx)\n\tcase ServerTypeGo:\n\t\t// For Go, workspace/symbol works well\n\t\treturn c.pingWithWorkspaceSymbol(ctx)\n\tcase ServerTypeRust:\n\t\t// For Rust, workspace/symbol works well\n\t\treturn c.pingWithWorkspaceSymbol(ctx)\n\tdefault:\n\t\t// Default ping method\n\t\treturn c.pingWithWorkspaceSymbol(ctx)\n\t}\n}\n\n// pingTypeScriptServer tries to ping a TypeScript server with appropriate methods\nfunc (c *Client) pingTypeScriptServer(ctx context.Context) error {\n\t// First try workspace/symbol which works for many servers\n\tif err := c.pingWithWorkspaceSymbol(ctx); err == nil {\n\t\treturn nil\n\t}\n\n\t// If that fails, try to find an open file and request document symbols\n\tc.openFilesMu.RLock()\n\tdefer c.openFilesMu.RUnlock()\n\n\t// If we have any open files, try to get document symbols for one\n\tfor uri := range c.openFiles {\n\t\tfilePath := strings.TrimPrefix(uri, \"file://\")\n\t\tif strings.HasSuffix(filePath, \".ts\") || strings.HasSuffix(filePath, \".js\") ||\n\t\t\tstrings.HasSuffix(filePath, \".tsx\") || strings.HasSuffix(filePath, \".jsx\") {\n\t\t\tvar symbols []protocol.DocumentSymbol\n\t\t\terr := c.Call(ctx, \"textDocument/documentSymbol\", protocol.DocumentSymbolParams{\n\t\t\t\tTextDocument: protocol.TextDocumentIdentifier{\n\t\t\t\t\tURI: protocol.DocumentUri(uri),\n\t\t\t\t},\n\t\t\t}, &symbols)\n\t\t\tif err == nil {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\t}\n\n\t// If we have no open TypeScript files, try to find and open one\n\tworkDir := config.WorkingDirectory()\n\terr := filepath.WalkDir(workDir, func(path string, d os.DirEntry, err error) error {\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Skip directories and non-TypeScript files\n\t\tif d.IsDir() {\n\t\t\treturn nil\n\t\t}\n\n\t\text := filepath.Ext(path)\n\t\tif ext == \".ts\" || ext == \".js\" || ext == \".tsx\" || ext == \".jsx\" {\n\t\t\t// Found a TypeScript file, try to open it\n\t\t\tif err := c.OpenFile(ctx, path); err == nil {\n\t\t\t\t// Successfully opened, stop walking\n\t\t\t\treturn filepath.SkipAll\n\t\t\t}\n\t\t}\n\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\tlogging.Debug(\"Error walking directory for TypeScript files\", \"error\", err)\n\t}\n\n\t// Final fallback - just try a generic capability\n\treturn c.pingWithServerCapabilities(ctx)\n}\n\n// openTypeScriptFiles finds and opens TypeScript files to help initialize the server\nfunc (c *Client) openTypeScriptFiles(ctx context.Context, workDir string) {\n\tcnf := config.Get()\n\tfilesOpened := 0\n\tmaxFilesToOpen := 5 // Limit to a reasonable number of files\n\n\t// Find and open TypeScript files\n\terr := filepath.WalkDir(workDir, func(path string, d os.DirEntry, err error) error {\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Skip directories and non-TypeScript files\n\t\tif d.IsDir() {\n\t\t\t// Skip common directories to avoid wasting time\n\t\t\tif shouldSkipDir(path) {\n\t\t\t\treturn filepath.SkipDir\n\t\t\t}\n\t\t\treturn nil\n\t\t}\n\n\t\t// Check if we've opened enough files\n\t\tif filesOpened >= maxFilesToOpen {\n\t\t\treturn filepath.SkipAll\n\t\t}\n\n\t\t// Check file extension\n\t\text := filepath.Ext(path)\n\t\tif ext == \".ts\" || ext == \".tsx\" || ext == \".js\" || ext == \".jsx\" {\n\t\t\t// Try to open the file\n\t\t\tif err := c.OpenFile(ctx, path); err == nil {\n\t\t\t\tfilesOpened++\n\t\t\t\tif cnf.DebugLSP {\n\t\t\t\t\tlogging.Debug(\"Opened TypeScript file for initialization\", \"file\", path)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn nil\n\t})\n\n\tif err != nil && cnf.DebugLSP {\n\t\tlogging.Debug(\"Error walking directory for TypeScript files\", \"error\", err)\n\t}\n\n\tif cnf.DebugLSP {\n\t\tlogging.Debug(\"Opened TypeScript files for initialization\", \"count\", filesOpened)\n\t}\n}\n\n// shouldSkipDir returns true if the directory should be skipped during file search\nfunc shouldSkipDir(path string) bool {\n\tdirName := filepath.Base(path)\n\n\t// Skip hidden directories\n\tif strings.HasPrefix(dirName, \".\") {\n\t\treturn true\n\t}\n\n\t// Skip common directories that won't contain relevant source files\n\tskipDirs := map[string]bool{\n\t\t\"node_modules\": true,\n\t\t\"dist\": true,\n\t\t\"build\": true,\n\t\t\"coverage\": true,\n\t\t\"vendor\": true,\n\t\t\"target\": true,\n\t}\n\n\treturn skipDirs[dirName]\n}\n\n// pingWithWorkspaceSymbol tries a workspace/symbol request\nfunc (c *Client) pingWithWorkspaceSymbol(ctx context.Context) error {\n\tvar result []protocol.SymbolInformation\n\treturn c.Call(ctx, \"workspace/symbol\", protocol.WorkspaceSymbolParams{\n\t\tQuery: \"\",\n\t}, &result)\n}\n\n// pingWithServerCapabilities tries to get server capabilities\nfunc (c *Client) pingWithServerCapabilities(ctx context.Context) error {\n\t// This is a very lightweight request that should work for most servers\n\treturn c.Notify(ctx, \"$/cancelRequest\", struct{ ID int }{ID: -1})\n}\n\ntype OpenFileInfo struct {\n\tVersion int32\n\tURI protocol.DocumentUri\n}\n\nfunc (c *Client) OpenFile(ctx context.Context, filepath string) error {\n\turi := fmt.Sprintf(\"file://%s\", filepath)\n\n\tc.openFilesMu.Lock()\n\tif _, exists := c.openFiles[uri]; exists {\n\t\tc.openFilesMu.Unlock()\n\t\treturn nil // Already open\n\t}\n\tc.openFilesMu.Unlock()\n\n\t// Skip files that do not exist or cannot be read\n\tcontent, err := os.ReadFile(filepath)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error reading file: %w\", err)\n\t}\n\n\tparams := protocol.DidOpenTextDocumentParams{\n\t\tTextDocument: protocol.TextDocumentItem{\n\t\t\tURI: protocol.DocumentUri(uri),\n\t\t\tLanguageID: DetectLanguageID(uri),\n\t\t\tVersion: 1,\n\t\t\tText: string(content),\n\t\t},\n\t}\n\n\tif err := c.Notify(ctx, \"textDocument/didOpen\", params); err != nil {\n\t\treturn err\n\t}\n\n\tc.openFilesMu.Lock()\n\tc.openFiles[uri] = &OpenFileInfo{\n\t\tVersion: 1,\n\t\tURI: protocol.DocumentUri(uri),\n\t}\n\tc.openFilesMu.Unlock()\n\n\treturn nil\n}\n\nfunc (c *Client) NotifyChange(ctx context.Context, filepath string) error {\n\turi := fmt.Sprintf(\"file://%s\", filepath)\n\n\tcontent, err := os.ReadFile(filepath)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error reading file: %w\", err)\n\t}\n\n\tc.openFilesMu.Lock()\n\tfileInfo, isOpen := c.openFiles[uri]\n\tif !isOpen {\n\t\tc.openFilesMu.Unlock()\n\t\treturn fmt.Errorf(\"cannot notify change for unopened file: %s\", filepath)\n\t}\n\n\t// Increment version\n\tfileInfo.Version++\n\tversion := fileInfo.Version\n\tc.openFilesMu.Unlock()\n\n\tparams := protocol.DidChangeTextDocumentParams{\n\t\tTextDocument: protocol.VersionedTextDocumentIdentifier{\n\t\t\tTextDocumentIdentifier: protocol.TextDocumentIdentifier{\n\t\t\t\tURI: protocol.DocumentUri(uri),\n\t\t\t},\n\t\t\tVersion: version,\n\t\t},\n\t\tContentChanges: []protocol.TextDocumentContentChangeEvent{\n\t\t\t{\n\t\t\t\tValue: protocol.TextDocumentContentChangeWholeDocument{\n\t\t\t\t\tText: string(content),\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\treturn c.Notify(ctx, \"textDocument/didChange\", params)\n}\n\nfunc (c *Client) CloseFile(ctx context.Context, filepath string) error {\n\tcnf := config.Get()\n\turi := fmt.Sprintf(\"file://%s\", filepath)\n\n\tc.openFilesMu.Lock()\n\tif _, exists := c.openFiles[uri]; !exists {\n\t\tc.openFilesMu.Unlock()\n\t\treturn nil // Already closed\n\t}\n\tc.openFilesMu.Unlock()\n\n\tparams := protocol.DidCloseTextDocumentParams{\n\t\tTextDocument: protocol.TextDocumentIdentifier{\n\t\t\tURI: protocol.DocumentUri(uri),\n\t\t},\n\t}\n\n\tif cnf.DebugLSP {\n\t\tlogging.Debug(\"Closing file\", \"file\", filepath)\n\t}\n\tif err := c.Notify(ctx, \"textDocument/didClose\", params); err != nil {\n\t\treturn err\n\t}\n\n\tc.openFilesMu.Lock()\n\tdelete(c.openFiles, uri)\n\tc.openFilesMu.Unlock()\n\n\treturn nil\n}\n\nfunc (c *Client) IsFileOpen(filepath string) bool {\n\turi := fmt.Sprintf(\"file://%s\", filepath)\n\tc.openFilesMu.RLock()\n\tdefer c.openFilesMu.RUnlock()\n\t_, exists := c.openFiles[uri]\n\treturn exists\n}\n\n// CloseAllFiles closes all currently open files\nfunc (c *Client) CloseAllFiles(ctx context.Context) {\n\tcnf := config.Get()\n\tc.openFilesMu.Lock()\n\tfilesToClose := make([]string, 0, len(c.openFiles))\n\n\t// First collect all URIs that need to be closed\n\tfor uri := range c.openFiles {\n\t\t// Convert URI back to file path by trimming \"file://\" prefix\n\t\tfilePath := strings.TrimPrefix(uri, \"file://\")\n\t\tfilesToClose = append(filesToClose, filePath)\n\t}\n\tc.openFilesMu.Unlock()\n\n\t// Then close them all\n\tfor _, filePath := range filesToClose {\n\t\terr := c.CloseFile(ctx, filePath)\n\t\tif err != nil && cnf.DebugLSP {\n\t\t\tlogging.Warn(\"Error closing file\", \"file\", filePath, \"error\", err)\n\t\t}\n\t}\n\n\tif cnf.DebugLSP {\n\t\tlogging.Debug(\"Closed all files\", \"files\", filesToClose)\n\t}\n}\n\nfunc (c *Client) GetFileDiagnostics(uri protocol.DocumentUri) []protocol.Diagnostic {\n\tc.diagnosticsMu.RLock()\n\tdefer c.diagnosticsMu.RUnlock()\n\n\treturn c.diagnostics[uri]\n}\n\n// GetDiagnostics returns all diagnostics for all files\nfunc (c *Client) GetDiagnostics() map[protocol.DocumentUri][]protocol.Diagnostic {\n\treturn c.diagnostics\n}\n\n// OpenFileOnDemand opens a file only if it's not already open\n// This is used for lazy-loading files when they're actually needed\nfunc (c *Client) OpenFileOnDemand(ctx context.Context, filepath string) error {\n\t// Check if the file is already open\n\tif c.IsFileOpen(filepath) {\n\t\treturn nil\n\t}\n\n\t// Open the file\n\treturn c.OpenFile(ctx, filepath)\n}\n\n// GetDiagnosticsForFile ensures a file is open and returns its diagnostics\n// This is useful for on-demand diagnostics when using lazy loading\nfunc (c *Client) GetDiagnosticsForFile(ctx context.Context, filepath string) ([]protocol.Diagnostic, error) {\n\turi := fmt.Sprintf(\"file://%s\", filepath)\n\tdocumentUri := protocol.DocumentUri(uri)\n\n\t// Make sure the file is open\n\tif !c.IsFileOpen(filepath) {\n\t\tif err := c.OpenFile(ctx, filepath); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to open file for diagnostics: %w\", err)\n\t\t}\n\n\t\t// Give the LSP server a moment to process the file\n\t\ttime.Sleep(100 * time.Millisecond)\n\t}\n\n\t// Get diagnostics\n\tc.diagnosticsMu.RLock()\n\tdiagnostics := c.diagnostics[documentUri]\n\tc.diagnosticsMu.RUnlock()\n\n\treturn diagnostics, nil\n}\n\n// ClearDiagnosticsForURI removes diagnostics for a specific URI from the cache\nfunc (c *Client) ClearDiagnosticsForURI(uri protocol.DocumentUri) {\n\tc.diagnosticsMu.Lock()\n\tdefer c.diagnosticsMu.Unlock()\n\tdelete(c.diagnostics, uri)\n}\n"], ["/opencode/internal/tui/components/dialog/custom_commands.go", "package dialog\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"regexp\"\n\t\"strings\"\n\n\ttea \"github.com/charmbracelet/bubbletea\"\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/tui/util\"\n)\n\n// Command prefix constants\nconst (\n\tUserCommandPrefix = \"user:\"\n\tProjectCommandPrefix = \"project:\"\n)\n\n// namedArgPattern is a regex pattern to find named arguments in the format $NAME\nvar namedArgPattern = regexp.MustCompile(`\\$([A-Z][A-Z0-9_]*)`)\n\n// LoadCustomCommands loads custom commands from both XDG_CONFIG_HOME and project data directory\nfunc LoadCustomCommands() ([]Command, error) {\n\tcfg := config.Get()\n\tif cfg == nil {\n\t\treturn nil, fmt.Errorf(\"config not loaded\")\n\t}\n\n\tvar commands []Command\n\n\t// Load user commands from XDG_CONFIG_HOME/opencode/commands\n\txdgConfigHome := os.Getenv(\"XDG_CONFIG_HOME\")\n\tif xdgConfigHome == \"\" {\n\t\t// Default to ~/.config if XDG_CONFIG_HOME is not set\n\t\thome, err := os.UserHomeDir()\n\t\tif err == nil {\n\t\t\txdgConfigHome = filepath.Join(home, \".config\")\n\t\t}\n\t}\n\n\tif xdgConfigHome != \"\" {\n\t\tuserCommandsDir := filepath.Join(xdgConfigHome, \"opencode\", \"commands\")\n\t\tuserCommands, err := loadCommandsFromDir(userCommandsDir, UserCommandPrefix)\n\t\tif err != nil {\n\t\t\t// Log error but continue - we'll still try to load other commands\n\t\t\tfmt.Printf(\"Warning: failed to load user commands from XDG_CONFIG_HOME: %v\\n\", err)\n\t\t} else {\n\t\t\tcommands = append(commands, userCommands...)\n\t\t}\n\t}\n\n\t// Load commands from $HOME/.opencode/commands\n\thome, err := os.UserHomeDir()\n\tif err == nil {\n\t\thomeCommandsDir := filepath.Join(home, \".opencode\", \"commands\")\n\t\thomeCommands, err := loadCommandsFromDir(homeCommandsDir, UserCommandPrefix)\n\t\tif err != nil {\n\t\t\t// Log error but continue - we'll still try to load other commands\n\t\t\tfmt.Printf(\"Warning: failed to load home commands: %v\\n\", err)\n\t\t} else {\n\t\t\tcommands = append(commands, homeCommands...)\n\t\t}\n\t}\n\n\t// Load project commands from data directory\n\tprojectCommandsDir := filepath.Join(cfg.Data.Directory, \"commands\")\n\tprojectCommands, err := loadCommandsFromDir(projectCommandsDir, ProjectCommandPrefix)\n\tif err != nil {\n\t\t// Log error but return what we have so far\n\t\tfmt.Printf(\"Warning: failed to load project commands: %v\\n\", err)\n\t} else {\n\t\tcommands = append(commands, projectCommands...)\n\t}\n\n\treturn commands, nil\n}\n\n// loadCommandsFromDir loads commands from a specific directory with the given prefix\nfunc loadCommandsFromDir(commandsDir string, prefix string) ([]Command, error) {\n\t// Check if the commands directory exists\n\tif _, err := os.Stat(commandsDir); os.IsNotExist(err) {\n\t\t// Create the commands directory if it doesn't exist\n\t\tif err := os.MkdirAll(commandsDir, 0755); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to create commands directory %s: %w\", commandsDir, err)\n\t\t}\n\t\t// Return empty list since we just created the directory\n\t\treturn []Command{}, nil\n\t}\n\n\tvar commands []Command\n\n\t// Walk through the commands directory and load all .md files\n\terr := filepath.Walk(commandsDir, func(path string, info os.FileInfo, err error) error {\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Skip directories\n\t\tif info.IsDir() {\n\t\t\treturn nil\n\t\t}\n\n\t\t// Only process markdown files\n\t\tif !strings.HasSuffix(strings.ToLower(info.Name()), \".md\") {\n\t\t\treturn nil\n\t\t}\n\n\t\t// Read the file content\n\t\tcontent, err := os.ReadFile(path)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to read command file %s: %w\", path, err)\n\t\t}\n\n\t\t// Get the command ID from the file name without the .md extension\n\t\tcommandID := strings.TrimSuffix(info.Name(), filepath.Ext(info.Name()))\n\n\t\t// Get relative path from commands directory\n\t\trelPath, err := filepath.Rel(commandsDir, path)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to get relative path for %s: %w\", path, err)\n\t\t}\n\n\t\t// Create the command ID from the relative path\n\t\t// Replace directory separators with colons\n\t\tcommandIDPath := strings.ReplaceAll(filepath.Dir(relPath), string(filepath.Separator), \":\")\n\t\tif commandIDPath != \".\" {\n\t\t\tcommandID = commandIDPath + \":\" + commandID\n\t\t}\n\n\t\t// Create a command\n\t\tcommand := Command{\n\t\t\tID: prefix + commandID,\n\t\t\tTitle: prefix + commandID,\n\t\t\tDescription: fmt.Sprintf(\"Custom command from %s\", relPath),\n\t\t\tHandler: func(cmd Command) tea.Cmd {\n\t\t\t\tcommandContent := string(content)\n\n\t\t\t\t// Check for named arguments\n\t\t\t\tmatches := namedArgPattern.FindAllStringSubmatch(commandContent, -1)\n\t\t\t\tif len(matches) > 0 {\n\t\t\t\t\t// Extract unique argument names\n\t\t\t\t\targNames := make([]string, 0)\n\t\t\t\t\targMap := make(map[string]bool)\n\n\t\t\t\t\tfor _, match := range matches {\n\t\t\t\t\t\targName := match[1] // Group 1 is the name without $\n\t\t\t\t\t\tif !argMap[argName] {\n\t\t\t\t\t\t\targMap[argName] = true\n\t\t\t\t\t\t\targNames = append(argNames, argName)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\t// Show multi-arguments dialog for all named arguments\n\t\t\t\t\treturn util.CmdHandler(ShowMultiArgumentsDialogMsg{\n\t\t\t\t\t\tCommandID: cmd.ID,\n\t\t\t\t\t\tContent: commandContent,\n\t\t\t\t\t\tArgNames: argNames,\n\t\t\t\t\t})\n\t\t\t\t}\n\n\t\t\t\t// No arguments needed, run command directly\n\t\t\t\treturn util.CmdHandler(CommandRunCustomMsg{\n\t\t\t\t\tContent: commandContent,\n\t\t\t\t\tArgs: nil, // No arguments\n\t\t\t\t})\n\t\t\t},\n\t\t}\n\n\t\tcommands = append(commands, command)\n\t\treturn nil\n\t})\n\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to load custom commands from %s: %w\", commandsDir, err)\n\t}\n\n\treturn commands, nil\n}\n\n// CommandRunCustomMsg is sent when a custom command is executed\ntype CommandRunCustomMsg struct {\n\tContent string\n\tArgs map[string]string // Map of argument names to values\n}\n"], ["/opencode/internal/app/app.go", "package app\n\nimport (\n\t\"context\"\n\t\"database/sql\"\n\t\"errors\"\n\t\"fmt\"\n\t\"maps\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/db\"\n\t\"github.com/opencode-ai/opencode/internal/format\"\n\t\"github.com/opencode-ai/opencode/internal/history\"\n\t\"github.com/opencode-ai/opencode/internal/llm/agent\"\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n\t\"github.com/opencode-ai/opencode/internal/lsp\"\n\t\"github.com/opencode-ai/opencode/internal/message\"\n\t\"github.com/opencode-ai/opencode/internal/permission\"\n\t\"github.com/opencode-ai/opencode/internal/session\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n)\n\ntype App struct {\n\tSessions session.Service\n\tMessages message.Service\n\tHistory history.Service\n\tPermissions permission.Service\n\n\tCoderAgent agent.Service\n\n\tLSPClients map[string]*lsp.Client\n\n\tclientsMutex sync.RWMutex\n\n\twatcherCancelFuncs []context.CancelFunc\n\tcancelFuncsMutex sync.Mutex\n\twatcherWG sync.WaitGroup\n}\n\nfunc New(ctx context.Context, conn *sql.DB) (*App, error) {\n\tq := db.New(conn)\n\tsessions := session.NewService(q)\n\tmessages := message.NewService(q)\n\tfiles := history.NewService(q, conn)\n\n\tapp := &App{\n\t\tSessions: sessions,\n\t\tMessages: messages,\n\t\tHistory: files,\n\t\tPermissions: permission.NewPermissionService(),\n\t\tLSPClients: make(map[string]*lsp.Client),\n\t}\n\n\t// Initialize theme based on configuration\n\tapp.initTheme()\n\n\t// Initialize LSP clients in the background\n\tgo app.initLSPClients(ctx)\n\n\tvar err error\n\tapp.CoderAgent, err = agent.NewAgent(\n\t\tconfig.AgentCoder,\n\t\tapp.Sessions,\n\t\tapp.Messages,\n\t\tagent.CoderAgentTools(\n\t\t\tapp.Permissions,\n\t\t\tapp.Sessions,\n\t\t\tapp.Messages,\n\t\t\tapp.History,\n\t\t\tapp.LSPClients,\n\t\t),\n\t)\n\tif err != nil {\n\t\tlogging.Error(\"Failed to create coder agent\", err)\n\t\treturn nil, err\n\t}\n\n\treturn app, nil\n}\n\n// initTheme sets the application theme based on the configuration\nfunc (app *App) initTheme() {\n\tcfg := config.Get()\n\tif cfg == nil || cfg.TUI.Theme == \"\" {\n\t\treturn // Use default theme\n\t}\n\n\t// Try to set the theme from config\n\terr := theme.SetTheme(cfg.TUI.Theme)\n\tif err != nil {\n\t\tlogging.Warn(\"Failed to set theme from config, using default theme\", \"theme\", cfg.TUI.Theme, \"error\", err)\n\t} else {\n\t\tlogging.Debug(\"Set theme from config\", \"theme\", cfg.TUI.Theme)\n\t}\n}\n\n// RunNonInteractive handles the execution flow when a prompt is provided via CLI flag.\nfunc (a *App) RunNonInteractive(ctx context.Context, prompt string, outputFormat string, quiet bool) error {\n\tlogging.Info(\"Running in non-interactive mode\")\n\n\t// Start spinner if not in quiet mode\n\tvar spinner *format.Spinner\n\tif !quiet {\n\t\tspinner = format.NewSpinner(\"Thinking...\")\n\t\tspinner.Start()\n\t\tdefer spinner.Stop()\n\t}\n\n\tconst maxPromptLengthForTitle = 100\n\ttitlePrefix := \"Non-interactive: \"\n\tvar titleSuffix string\n\n\tif len(prompt) > maxPromptLengthForTitle {\n\t\ttitleSuffix = prompt[:maxPromptLengthForTitle] + \"...\"\n\t} else {\n\t\ttitleSuffix = prompt\n\t}\n\ttitle := titlePrefix + titleSuffix\n\n\tsess, err := a.Sessions.Create(ctx, title)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to create session for non-interactive mode: %w\", err)\n\t}\n\tlogging.Info(\"Created session for non-interactive run\", \"session_id\", sess.ID)\n\n\t// Automatically approve all permission requests for this non-interactive session\n\ta.Permissions.AutoApproveSession(sess.ID)\n\n\tdone, err := a.CoderAgent.Run(ctx, sess.ID, prompt)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to start agent processing stream: %w\", err)\n\t}\n\n\tresult := <-done\n\tif result.Error != nil {\n\t\tif errors.Is(result.Error, context.Canceled) || errors.Is(result.Error, agent.ErrRequestCancelled) {\n\t\t\tlogging.Info(\"Agent processing cancelled\", \"session_id\", sess.ID)\n\t\t\treturn nil\n\t\t}\n\t\treturn fmt.Errorf(\"agent processing failed: %w\", result.Error)\n\t}\n\n\t// Stop spinner before printing output\n\tif !quiet && spinner != nil {\n\t\tspinner.Stop()\n\t}\n\n\t// Get the text content from the response\n\tcontent := \"No content available\"\n\tif result.Message.Content().String() != \"\" {\n\t\tcontent = result.Message.Content().String()\n\t}\n\n\tfmt.Println(format.FormatOutput(content, outputFormat))\n\n\tlogging.Info(\"Non-interactive run completed\", \"session_id\", sess.ID)\n\n\treturn nil\n}\n\n// Shutdown performs a clean shutdown of the application\nfunc (app *App) Shutdown() {\n\t// Cancel all watcher goroutines\n\tapp.cancelFuncsMutex.Lock()\n\tfor _, cancel := range app.watcherCancelFuncs {\n\t\tcancel()\n\t}\n\tapp.cancelFuncsMutex.Unlock()\n\tapp.watcherWG.Wait()\n\n\t// Perform additional cleanup for LSP clients\n\tapp.clientsMutex.RLock()\n\tclients := make(map[string]*lsp.Client, len(app.LSPClients))\n\tmaps.Copy(clients, app.LSPClients)\n\tapp.clientsMutex.RUnlock()\n\n\tfor name, client := range clients {\n\t\tshutdownCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)\n\t\tif err := client.Shutdown(shutdownCtx); err != nil {\n\t\t\tlogging.Error(\"Failed to shutdown LSP client\", \"name\", name, \"error\", err)\n\t\t}\n\t\tcancel()\n\t}\n}\n"], ["/opencode/internal/llm/provider/copilot.go", "package provider\n\nimport (\n\t\"context\"\n\t\"encoding/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"net/http\"\n\t\"os\"\n\t\"time\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n\t\"github.com/openai/openai-go/shared\"\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/llm/models\"\n\ttoolsPkg \"github.com/opencode-ai/opencode/internal/llm/tools\"\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n\t\"github.com/opencode-ai/opencode/internal/message\"\n)\n\ntype copilotOptions struct {\n\treasoningEffort string\n\textraHeaders map[string]string\n\tbearerToken string\n}\n\ntype CopilotOption func(*copilotOptions)\n\ntype copilotClient struct {\n\tproviderOptions providerClientOptions\n\toptions copilotOptions\n\tclient openai.Client\n\thttpClient *http.Client\n}\n\ntype CopilotClient ProviderClient\n\n// CopilotTokenResponse represents the response from GitHub's token exchange endpoint\ntype CopilotTokenResponse struct {\n\tToken string `json:\"token\"`\n\tExpiresAt int64 `json:\"expires_at\"`\n}\n\nfunc (c *copilotClient) isAnthropicModel() bool {\n\tfor _, modelId := range models.CopilotAnthropicModels {\n\t\tif c.providerOptions.model.ID == modelId {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n// loadGitHubToken loads the GitHub OAuth token from the standard GitHub CLI/Copilot locations\n\n// exchangeGitHubToken exchanges a GitHub token for a Copilot bearer token\nfunc (c *copilotClient) exchangeGitHubToken(githubToken string) (string, error) {\n\treq, err := http.NewRequest(\"GET\", \"https://api.github.com/copilot_internal/v2/token\", nil)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed to create token exchange request: %w\", err)\n\t}\n\n\treq.Header.Set(\"Authorization\", \"Token \"+githubToken)\n\treq.Header.Set(\"User-Agent\", \"OpenCode/1.0\")\n\n\tresp, err := c.httpClient.Do(req)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed to exchange GitHub token: %w\", err)\n\t}\n\tdefer resp.Body.Close()\n\n\tif resp.StatusCode != http.StatusOK {\n\t\tbody, _ := io.ReadAll(resp.Body)\n\t\treturn \"\", fmt.Errorf(\"token exchange failed with status %d: %s\", resp.StatusCode, string(body))\n\t}\n\n\tvar tokenResp CopilotTokenResponse\n\tif err := json.NewDecoder(resp.Body).Decode(&tokenResp); err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed to decode token response: %w\", err)\n\t}\n\n\treturn tokenResp.Token, nil\n}\n\nfunc newCopilotClient(opts providerClientOptions) CopilotClient {\n\tcopilotOpts := copilotOptions{\n\t\treasoningEffort: \"medium\",\n\t}\n\t// Apply copilot-specific options\n\tfor _, o := range opts.copilotOptions {\n\t\to(&copilotOpts)\n\t}\n\n\t// Create HTTP client for token exchange\n\thttpClient := &http.Client{\n\t\tTimeout: 30 * time.Second,\n\t}\n\n\tvar bearerToken string\n\n\t// If bearer token is already provided, use it\n\tif copilotOpts.bearerToken != \"\" {\n\t\tbearerToken = copilotOpts.bearerToken\n\t} else {\n\t\t// Try to get GitHub token from multiple sources\n\t\tvar githubToken string\n\n\t\t// 1. Environment variable\n\t\tgithubToken = os.Getenv(\"GITHUB_TOKEN\")\n\n\t\t// 2. API key from options\n\t\tif githubToken == \"\" {\n\t\t\tgithubToken = opts.apiKey\n\t\t}\n\n\t\t// 3. Standard GitHub CLI/Copilot locations\n\t\tif githubToken == \"\" {\n\t\t\tvar err error\n\t\t\tgithubToken, err = config.LoadGitHubToken()\n\t\t\tif err != nil {\n\t\t\t\tlogging.Debug(\"Failed to load GitHub token from standard locations\", \"error\", err)\n\t\t\t}\n\t\t}\n\n\t\tif githubToken == \"\" {\n\t\t\tlogging.Error(\"GitHub token is required for Copilot provider. Set GITHUB_TOKEN environment variable, configure it in opencode.json, or ensure GitHub CLI/Copilot is properly authenticated.\")\n\t\t\treturn &copilotClient{\n\t\t\t\tproviderOptions: opts,\n\t\t\t\toptions: copilotOpts,\n\t\t\t\thttpClient: httpClient,\n\t\t\t}\n\t\t}\n\n\t\t// Create a temporary client for token exchange\n\t\ttempClient := &copilotClient{\n\t\t\tproviderOptions: opts,\n\t\t\toptions: copilotOpts,\n\t\t\thttpClient: httpClient,\n\t\t}\n\n\t\t// Exchange GitHub token for bearer token\n\t\tvar err error\n\t\tbearerToken, err = tempClient.exchangeGitHubToken(githubToken)\n\t\tif err != nil {\n\t\t\tlogging.Error(\"Failed to exchange GitHub token for Copilot bearer token\", \"error\", err)\n\t\t\treturn &copilotClient{\n\t\t\t\tproviderOptions: opts,\n\t\t\t\toptions: copilotOpts,\n\t\t\t\thttpClient: httpClient,\n\t\t\t}\n\t\t}\n\t}\n\n\tcopilotOpts.bearerToken = bearerToken\n\n\t// GitHub Copilot API base URL\n\tbaseURL := \"https://api.githubcopilot.com\"\n\n\topenaiClientOptions := []option.RequestOption{\n\t\toption.WithBaseURL(baseURL),\n\t\toption.WithAPIKey(bearerToken), // Use bearer token as API key\n\t}\n\n\t// Add GitHub Copilot specific headers\n\topenaiClientOptions = append(openaiClientOptions,\n\t\toption.WithHeader(\"Editor-Version\", \"OpenCode/1.0\"),\n\t\toption.WithHeader(\"Editor-Plugin-Version\", \"OpenCode/1.0\"),\n\t\toption.WithHeader(\"Copilot-Integration-Id\", \"vscode-chat\"),\n\t)\n\n\t// Add any extra headers\n\tif copilotOpts.extraHeaders != nil {\n\t\tfor key, value := range copilotOpts.extraHeaders {\n\t\t\topenaiClientOptions = append(openaiClientOptions, option.WithHeader(key, value))\n\t\t}\n\t}\n\n\tclient := openai.NewClient(openaiClientOptions...)\n\t// logging.Debug(\"Copilot client created\", \"opts\", opts, \"copilotOpts\", copilotOpts, \"model\", opts.model)\n\treturn &copilotClient{\n\t\tproviderOptions: opts,\n\t\toptions: copilotOpts,\n\t\tclient: client,\n\t\thttpClient: httpClient,\n\t}\n}\n\nfunc (c *copilotClient) convertMessages(messages []message.Message) (copilotMessages []openai.ChatCompletionMessageParamUnion) {\n\t// Add system message first\n\tcopilotMessages = append(copilotMessages, openai.SystemMessage(c.providerOptions.systemMessage))\n\n\tfor _, msg := range messages {\n\t\tswitch msg.Role {\n\t\tcase message.User:\n\t\t\tvar content []openai.ChatCompletionContentPartUnionParam\n\t\t\ttextBlock := openai.ChatCompletionContentPartTextParam{Text: msg.Content().String()}\n\t\t\tcontent = append(content, openai.ChatCompletionContentPartUnionParam{OfText: &textBlock})\n\n\t\t\tfor _, binaryContent := range msg.BinaryContent() {\n\t\t\t\timageURL := openai.ChatCompletionContentPartImageImageURLParam{URL: binaryContent.String(models.ProviderCopilot)}\n\t\t\t\timageBlock := openai.ChatCompletionContentPartImageParam{ImageURL: imageURL}\n\t\t\t\tcontent = append(content, openai.ChatCompletionContentPartUnionParam{OfImageURL: &imageBlock})\n\t\t\t}\n\n\t\t\tcopilotMessages = append(copilotMessages, openai.UserMessage(content))\n\n\t\tcase message.Assistant:\n\t\t\tassistantMsg := openai.ChatCompletionAssistantMessageParam{\n\t\t\t\tRole: \"assistant\",\n\t\t\t}\n\n\t\t\tif msg.Content().String() != \"\" {\n\t\t\t\tassistantMsg.Content = openai.ChatCompletionAssistantMessageParamContentUnion{\n\t\t\t\t\tOfString: openai.String(msg.Content().String()),\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif len(msg.ToolCalls()) > 0 {\n\t\t\t\tassistantMsg.ToolCalls = make([]openai.ChatCompletionMessageToolCallParam, len(msg.ToolCalls()))\n\t\t\t\tfor i, call := range msg.ToolCalls() {\n\t\t\t\t\tassistantMsg.ToolCalls[i] = openai.ChatCompletionMessageToolCallParam{\n\t\t\t\t\t\tID: call.ID,\n\t\t\t\t\t\tType: \"function\",\n\t\t\t\t\t\tFunction: openai.ChatCompletionMessageToolCallFunctionParam{\n\t\t\t\t\t\t\tName: call.Name,\n\t\t\t\t\t\t\tArguments: call.Input,\n\t\t\t\t\t\t},\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tcopilotMessages = append(copilotMessages, openai.ChatCompletionMessageParamUnion{\n\t\t\t\tOfAssistant: &assistantMsg,\n\t\t\t})\n\n\t\tcase message.Tool:\n\t\t\tfor _, result := range msg.ToolResults() {\n\t\t\t\tcopilotMessages = append(copilotMessages,\n\t\t\t\t\topenai.ToolMessage(result.Content, result.ToolCallID),\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn\n}\n\nfunc (c *copilotClient) convertTools(tools []toolsPkg.BaseTool) []openai.ChatCompletionToolParam {\n\tcopilotTools := make([]openai.ChatCompletionToolParam, len(tools))\n\n\tfor i, tool := range tools {\n\t\tinfo := tool.Info()\n\t\tcopilotTools[i] = openai.ChatCompletionToolParam{\n\t\t\tFunction: openai.FunctionDefinitionParam{\n\t\t\t\tName: info.Name,\n\t\t\t\tDescription: openai.String(info.Description),\n\t\t\t\tParameters: openai.FunctionParameters{\n\t\t\t\t\t\"type\": \"object\",\n\t\t\t\t\t\"properties\": info.Parameters,\n\t\t\t\t\t\"required\": info.Required,\n\t\t\t\t},\n\t\t\t},\n\t\t}\n\t}\n\n\treturn copilotTools\n}\n\nfunc (c *copilotClient) finishReason(reason string) message.FinishReason {\n\tswitch reason {\n\tcase \"stop\":\n\t\treturn message.FinishReasonEndTurn\n\tcase \"length\":\n\t\treturn message.FinishReasonMaxTokens\n\tcase \"tool_calls\":\n\t\treturn message.FinishReasonToolUse\n\tdefault:\n\t\treturn message.FinishReasonUnknown\n\t}\n}\n\nfunc (c *copilotClient) preparedParams(messages []openai.ChatCompletionMessageParamUnion, tools []openai.ChatCompletionToolParam) openai.ChatCompletionNewParams {\n\tparams := openai.ChatCompletionNewParams{\n\t\tModel: openai.ChatModel(c.providerOptions.model.APIModel),\n\t\tMessages: messages,\n\t\tTools: tools,\n\t}\n\n\tif c.providerOptions.model.CanReason == true {\n\t\tparams.MaxCompletionTokens = openai.Int(c.providerOptions.maxTokens)\n\t\tswitch c.options.reasoningEffort {\n\t\tcase \"low\":\n\t\t\tparams.ReasoningEffort = shared.ReasoningEffortLow\n\t\tcase \"medium\":\n\t\t\tparams.ReasoningEffort = shared.ReasoningEffortMedium\n\t\tcase \"high\":\n\t\t\tparams.ReasoningEffort = shared.ReasoningEffortHigh\n\t\tdefault:\n\t\t\tparams.ReasoningEffort = shared.ReasoningEffortMedium\n\t\t}\n\t} else {\n\t\tparams.MaxTokens = openai.Int(c.providerOptions.maxTokens)\n\t}\n\n\treturn params\n}\n\nfunc (c *copilotClient) send(ctx context.Context, messages []message.Message, tools []toolsPkg.BaseTool) (response *ProviderResponse, err error) {\n\tparams := c.preparedParams(c.convertMessages(messages), c.convertTools(tools))\n\tcfg := config.Get()\n\tvar sessionId string\n\trequestSeqId := (len(messages) + 1) / 2\n\tif cfg.Debug {\n\t\t// jsonData, _ := json.Marshal(params)\n\t\t// logging.Debug(\"Prepared messages\", \"messages\", string(jsonData))\n\t\tif sid, ok := ctx.Value(toolsPkg.SessionIDContextKey).(string); ok {\n\t\t\tsessionId = sid\n\t\t}\n\t\tjsonData, _ := json.Marshal(params)\n\t\tif sessionId != \"\" {\n\t\t\tfilepath := logging.WriteRequestMessageJson(sessionId, requestSeqId, params)\n\t\t\tlogging.Debug(\"Prepared messages\", \"filepath\", filepath)\n\t\t} else {\n\t\t\tlogging.Debug(\"Prepared messages\", \"messages\", string(jsonData))\n\t\t}\n\t}\n\n\tattempts := 0\n\tfor {\n\t\tattempts++\n\t\tcopilotResponse, err := c.client.Chat.Completions.New(\n\t\t\tctx,\n\t\t\tparams,\n\t\t)\n\n\t\t// If there is an error we are going to see if we can retry the call\n\t\tif err != nil {\n\t\t\tretry, after, retryErr := c.shouldRetry(attempts, err)\n\t\t\tif retryErr != nil {\n\t\t\t\treturn nil, retryErr\n\t\t\t}\n\t\t\tif retry {\n\t\t\t\tlogging.WarnPersist(fmt.Sprintf(\"Retrying due to rate limit... attempt %d of %d\", attempts, maxRetries), logging.PersistTimeArg, time.Millisecond*time.Duration(after+100))\n\t\t\t\tselect {\n\t\t\t\tcase <-ctx.Done():\n\t\t\t\t\treturn nil, ctx.Err()\n\t\t\t\tcase <-time.After(time.Duration(after) * time.Millisecond):\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn nil, retryErr\n\t\t}\n\n\t\tcontent := \"\"\n\t\tif copilotResponse.Choices[0].Message.Content != \"\" {\n\t\t\tcontent = copilotResponse.Choices[0].Message.Content\n\t\t}\n\n\t\ttoolCalls := c.toolCalls(*copilotResponse)\n\t\tfinishReason := c.finishReason(string(copilotResponse.Choices[0].FinishReason))\n\n\t\tif len(toolCalls) > 0 {\n\t\t\tfinishReason = message.FinishReasonToolUse\n\t\t}\n\n\t\treturn &ProviderResponse{\n\t\t\tContent: content,\n\t\t\tToolCalls: toolCalls,\n\t\t\tUsage: c.usage(*copilotResponse),\n\t\t\tFinishReason: finishReason,\n\t\t}, nil\n\t}\n}\n\nfunc (c *copilotClient) stream(ctx context.Context, messages []message.Message, tools []toolsPkg.BaseTool) <-chan ProviderEvent {\n\tparams := c.preparedParams(c.convertMessages(messages), c.convertTools(tools))\n\tparams.StreamOptions = openai.ChatCompletionStreamOptionsParam{\n\t\tIncludeUsage: openai.Bool(true),\n\t}\n\n\tcfg := config.Get()\n\tvar sessionId string\n\trequestSeqId := (len(messages) + 1) / 2\n\tif cfg.Debug {\n\t\tif sid, ok := ctx.Value(toolsPkg.SessionIDContextKey).(string); ok {\n\t\t\tsessionId = sid\n\t\t}\n\t\tjsonData, _ := json.Marshal(params)\n\t\tif sessionId != \"\" {\n\t\t\tfilepath := logging.WriteRequestMessageJson(sessionId, requestSeqId, params)\n\t\t\tlogging.Debug(\"Prepared messages\", \"filepath\", filepath)\n\t\t} else {\n\t\t\tlogging.Debug(\"Prepared messages\", \"messages\", string(jsonData))\n\t\t}\n\n\t}\n\n\tattempts := 0\n\teventChan := make(chan ProviderEvent)\n\n\tgo func() {\n\t\tfor {\n\t\t\tattempts++\n\t\t\tcopilotStream := c.client.Chat.Completions.NewStreaming(\n\t\t\t\tctx,\n\t\t\t\tparams,\n\t\t\t)\n\n\t\t\tacc := openai.ChatCompletionAccumulator{}\n\t\t\tcurrentContent := \"\"\n\t\t\ttoolCalls := make([]message.ToolCall, 0)\n\n\t\t\tvar currentToolCallId string\n\t\t\tvar currentToolCall openai.ChatCompletionMessageToolCall\n\t\t\tvar msgToolCalls []openai.ChatCompletionMessageToolCall\n\t\t\tfor copilotStream.Next() {\n\t\t\t\tchunk := copilotStream.Current()\n\t\t\t\tacc.AddChunk(chunk)\n\n\t\t\t\tif cfg.Debug {\n\t\t\t\t\tlogging.AppendToStreamSessionLogJson(sessionId, requestSeqId, chunk)\n\t\t\t\t}\n\n\t\t\t\tfor _, choice := range chunk.Choices {\n\t\t\t\t\tif choice.Delta.Content != \"\" {\n\t\t\t\t\t\teventChan <- ProviderEvent{\n\t\t\t\t\t\t\tType: EventContentDelta,\n\t\t\t\t\t\t\tContent: choice.Delta.Content,\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcurrentContent += choice.Delta.Content\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif c.isAnthropicModel() {\n\t\t\t\t\t// Monkeypatch adapter for Sonnet-4 multi-tool use\n\t\t\t\t\tfor _, choice := range chunk.Choices {\n\t\t\t\t\t\tif choice.Delta.ToolCalls != nil && len(choice.Delta.ToolCalls) > 0 {\n\t\t\t\t\t\t\ttoolCall := choice.Delta.ToolCalls[0]\n\t\t\t\t\t\t\t// Detect tool use start\n\t\t\t\t\t\t\tif currentToolCallId == \"\" {\n\t\t\t\t\t\t\t\tif toolCall.ID != \"\" {\n\t\t\t\t\t\t\t\t\tcurrentToolCallId = toolCall.ID\n\t\t\t\t\t\t\t\t\tcurrentToolCall = openai.ChatCompletionMessageToolCall{\n\t\t\t\t\t\t\t\t\t\tID: toolCall.ID,\n\t\t\t\t\t\t\t\t\t\tType: \"function\",\n\t\t\t\t\t\t\t\t\t\tFunction: openai.ChatCompletionMessageToolCallFunction{\n\t\t\t\t\t\t\t\t\t\t\tName: toolCall.Function.Name,\n\t\t\t\t\t\t\t\t\t\t\tArguments: toolCall.Function.Arguments,\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t// Delta tool use\n\t\t\t\t\t\t\t\tif toolCall.ID == \"\" {\n\t\t\t\t\t\t\t\t\tcurrentToolCall.Function.Arguments += toolCall.Function.Arguments\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t// Detect new tool use\n\t\t\t\t\t\t\t\t\tif toolCall.ID != currentToolCallId {\n\t\t\t\t\t\t\t\t\t\tmsgToolCalls = append(msgToolCalls, currentToolCall)\n\t\t\t\t\t\t\t\t\t\tcurrentToolCallId = toolCall.ID\n\t\t\t\t\t\t\t\t\t\tcurrentToolCall = openai.ChatCompletionMessageToolCall{\n\t\t\t\t\t\t\t\t\t\t\tID: toolCall.ID,\n\t\t\t\t\t\t\t\t\t\t\tType: \"function\",\n\t\t\t\t\t\t\t\t\t\t\tFunction: openai.ChatCompletionMessageToolCallFunction{\n\t\t\t\t\t\t\t\t\t\t\t\tName: toolCall.Function.Name,\n\t\t\t\t\t\t\t\t\t\t\t\tArguments: toolCall.Function.Arguments,\n\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif choice.FinishReason == \"tool_calls\" {\n\t\t\t\t\t\t\tmsgToolCalls = append(msgToolCalls, currentToolCall)\n\t\t\t\t\t\t\tacc.ChatCompletion.Choices[0].Message.ToolCalls = msgToolCalls\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\terr := copilotStream.Err()\n\t\t\tif err == nil || errors.Is(err, io.EOF) {\n\t\t\t\tif cfg.Debug {\n\t\t\t\t\trespFilepath := logging.WriteChatResponseJson(sessionId, requestSeqId, acc.ChatCompletion)\n\t\t\t\t\tlogging.Debug(\"Chat completion response\", \"filepath\", respFilepath)\n\t\t\t\t}\n\t\t\t\t// Stream completed successfully\n\t\t\t\tfinishReason := c.finishReason(string(acc.ChatCompletion.Choices[0].FinishReason))\n\t\t\t\tif len(acc.ChatCompletion.Choices[0].Message.ToolCalls) > 0 {\n\t\t\t\t\ttoolCalls = append(toolCalls, c.toolCalls(acc.ChatCompletion)...)\n\t\t\t\t}\n\t\t\t\tif len(toolCalls) > 0 {\n\t\t\t\t\tfinishReason = message.FinishReasonToolUse\n\t\t\t\t}\n\n\t\t\t\teventChan <- ProviderEvent{\n\t\t\t\t\tType: EventComplete,\n\t\t\t\t\tResponse: &ProviderResponse{\n\t\t\t\t\t\tContent: currentContent,\n\t\t\t\t\t\tToolCalls: toolCalls,\n\t\t\t\t\t\tUsage: c.usage(acc.ChatCompletion),\n\t\t\t\t\t\tFinishReason: finishReason,\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t\tclose(eventChan)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\t// If there is an error we are going to see if we can retry the call\n\t\t\tretry, after, retryErr := c.shouldRetry(attempts, err)\n\t\t\tif retryErr != nil {\n\t\t\t\teventChan <- ProviderEvent{Type: EventError, Error: retryErr}\n\t\t\t\tclose(eventChan)\n\t\t\t\treturn\n\t\t\t}\n\t\t\t// shouldRetry is not catching the max retries...\n\t\t\t// TODO: Figure out why\n\t\t\tif attempts > maxRetries {\n\t\t\t\tlogging.Warn(\"Maximum retry attempts reached for rate limit\", \"attempts\", attempts, \"max_retries\", maxRetries)\n\t\t\t\tretry = false\n\t\t\t}\n\t\t\tif retry {\n\t\t\t\tlogging.WarnPersist(fmt.Sprintf(\"Retrying due to rate limit... attempt %d of %d (paused for %d ms)\", attempts, maxRetries, after), logging.PersistTimeArg, time.Millisecond*time.Duration(after+100))\n\t\t\t\tselect {\n\t\t\t\tcase <-ctx.Done():\n\t\t\t\t\t// context cancelled\n\t\t\t\t\tif ctx.Err() == nil {\n\t\t\t\t\t\teventChan <- ProviderEvent{Type: EventError, Error: ctx.Err()}\n\t\t\t\t\t}\n\t\t\t\t\tclose(eventChan)\n\t\t\t\t\treturn\n\t\t\t\tcase <-time.After(time.Duration(after) * time.Millisecond):\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t\teventChan <- ProviderEvent{Type: EventError, Error: retryErr}\n\t\t\tclose(eventChan)\n\t\t\treturn\n\t\t}\n\t}()\n\n\treturn eventChan\n}\n\nfunc (c *copilotClient) shouldRetry(attempts int, err error) (bool, int64, error) {\n\tvar apierr *openai.Error\n\tif !errors.As(err, &apierr) {\n\t\treturn false, 0, err\n\t}\n\n\t// Check for token expiration (401 Unauthorized)\n\tif apierr.StatusCode == 401 {\n\t\t// Try to refresh the bearer token\n\t\tvar githubToken string\n\n\t\t// 1. Environment variable\n\t\tgithubToken = os.Getenv(\"GITHUB_TOKEN\")\n\n\t\t// 2. API key from options\n\t\tif githubToken == \"\" {\n\t\t\tgithubToken = c.providerOptions.apiKey\n\t\t}\n\n\t\t// 3. Standard GitHub CLI/Copilot locations\n\t\tif githubToken == \"\" {\n\t\t\tvar err error\n\t\t\tgithubToken, err = config.LoadGitHubToken()\n\t\t\tif err != nil {\n\t\t\t\tlogging.Debug(\"Failed to load GitHub token from standard locations during retry\", \"error\", err)\n\t\t\t}\n\t\t}\n\n\t\tif githubToken != \"\" {\n\t\t\tnewBearerToken, tokenErr := c.exchangeGitHubToken(githubToken)\n\t\t\tif tokenErr == nil {\n\t\t\t\tc.options.bearerToken = newBearerToken\n\t\t\t\t// Update the client with the new token\n\t\t\t\t// Note: This is a simplified approach. In a production system,\n\t\t\t\t// you might want to recreate the entire client with the new token\n\t\t\t\tlogging.Info(\"Refreshed Copilot bearer token\")\n\t\t\t\treturn true, 1000, nil // Retry immediately with new token\n\t\t\t}\n\t\t\tlogging.Error(\"Failed to refresh Copilot bearer token\", \"error\", tokenErr)\n\t\t}\n\t\treturn false, 0, fmt.Errorf(\"authentication failed: %w\", err)\n\t}\n\tlogging.Debug(\"Copilot API Error\", \"status\", apierr.StatusCode, \"headers\", apierr.Response.Header, \"body\", apierr.RawJSON())\n\n\tif apierr.StatusCode != 429 && apierr.StatusCode != 500 {\n\t\treturn false, 0, err\n\t}\n\n\tif apierr.StatusCode == 500 {\n\t\tlogging.Warn(\"Copilot API returned 500 error, retrying\", \"error\", err)\n\t}\n\n\tif attempts > maxRetries {\n\t\treturn false, 0, fmt.Errorf(\"maximum retry attempts reached for rate limit: %d retries\", maxRetries)\n\t}\n\n\tretryMs := 0\n\tretryAfterValues := apierr.Response.Header.Values(\"Retry-After\")\n\n\tbackoffMs := 2000 * (1 << (attempts - 1))\n\tjitterMs := int(float64(backoffMs) * 0.2)\n\tretryMs = backoffMs + jitterMs\n\tif len(retryAfterValues) > 0 {\n\t\tif _, err := fmt.Sscanf(retryAfterValues[0], \"%d\", &retryMs); err == nil {\n\t\t\tretryMs = retryMs * 1000\n\t\t}\n\t}\n\treturn true, int64(retryMs), nil\n}\n\nfunc (c *copilotClient) toolCalls(completion openai.ChatCompletion) []message.ToolCall {\n\tvar toolCalls []message.ToolCall\n\n\tif len(completion.Choices) > 0 && len(completion.Choices[0].Message.ToolCalls) > 0 {\n\t\tfor _, call := range completion.Choices[0].Message.ToolCalls {\n\t\t\ttoolCall := message.ToolCall{\n\t\t\t\tID: call.ID,\n\t\t\t\tName: call.Function.Name,\n\t\t\t\tInput: call.Function.Arguments,\n\t\t\t\tType: \"function\",\n\t\t\t\tFinished: true,\n\t\t\t}\n\t\t\ttoolCalls = append(toolCalls, toolCall)\n\t\t}\n\t}\n\n\treturn toolCalls\n}\n\nfunc (c *copilotClient) usage(completion openai.ChatCompletion) TokenUsage {\n\tcachedTokens := completion.Usage.PromptTokensDetails.CachedTokens\n\tinputTokens := completion.Usage.PromptTokens - cachedTokens\n\n\treturn TokenUsage{\n\t\tInputTokens: inputTokens,\n\t\tOutputTokens: completion.Usage.CompletionTokens,\n\t\tCacheCreationTokens: 0, // GitHub Copilot doesn't provide this directly\n\t\tCacheReadTokens: cachedTokens,\n\t}\n}\n\nfunc WithCopilotReasoningEffort(effort string) CopilotOption {\n\treturn func(options *copilotOptions) {\n\t\tdefaultReasoningEffort := \"medium\"\n\t\tswitch effort {\n\t\tcase \"low\", \"medium\", \"high\":\n\t\t\tdefaultReasoningEffort = effort\n\t\tdefault:\n\t\t\tlogging.Warn(\"Invalid reasoning effort, using default: medium\")\n\t\t}\n\t\toptions.reasoningEffort = defaultReasoningEffort\n\t}\n}\n\nfunc WithCopilotExtraHeaders(headers map[string]string) CopilotOption {\n\treturn func(options *copilotOptions) {\n\t\toptions.extraHeaders = headers\n\t}\n}\n\nfunc WithCopilotBearerToken(bearerToken string) CopilotOption {\n\treturn func(options *copilotOptions) {\n\t\toptions.bearerToken = bearerToken\n\t}\n}\n\n"], ["/opencode/internal/lsp/transport.go", "package lsp\n\nimport (\n\t\"bufio\"\n\t\"context\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"strings\"\n\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n)\n\n// Write writes an LSP message to the given writer\nfunc WriteMessage(w io.Writer, msg *Message) error {\n\tdata, err := json.Marshal(msg)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to marshal message: %w\", err)\n\t}\n\tcnf := config.Get()\n\n\tif cnf.DebugLSP {\n\t\tlogging.Debug(\"Sending message to server\", \"method\", msg.Method, \"id\", msg.ID)\n\t}\n\n\t_, err = fmt.Fprintf(w, \"Content-Length: %d\\r\\n\\r\\n\", len(data))\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to write header: %w\", err)\n\t}\n\n\t_, err = w.Write(data)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to write message: %w\", err)\n\t}\n\n\treturn nil\n}\n\n// ReadMessage reads a single LSP message from the given reader\nfunc ReadMessage(r *bufio.Reader) (*Message, error) {\n\tcnf := config.Get()\n\t// Read headers\n\tvar contentLength int\n\tfor {\n\t\tline, err := r.ReadString('\\n')\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to read header: %w\", err)\n\t\t}\n\t\tline = strings.TrimSpace(line)\n\n\t\tif cnf.DebugLSP {\n\t\t\tlogging.Debug(\"Received header\", \"line\", line)\n\t\t}\n\n\t\tif line == \"\" {\n\t\t\tbreak // End of headers\n\t\t}\n\n\t\tif strings.HasPrefix(line, \"Content-Length: \") {\n\t\t\t_, err := fmt.Sscanf(line, \"Content-Length: %d\", &contentLength)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"invalid Content-Length: %w\", err)\n\t\t\t}\n\t\t}\n\t}\n\n\tif cnf.DebugLSP {\n\t\tlogging.Debug(\"Content-Length\", \"length\", contentLength)\n\t}\n\n\t// Read content\n\tcontent := make([]byte, contentLength)\n\t_, err := io.ReadFull(r, content)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to read content: %w\", err)\n\t}\n\n\tif cnf.DebugLSP {\n\t\tlogging.Debug(\"Received content\", \"content\", string(content))\n\t}\n\n\t// Parse message\n\tvar msg Message\n\tif err := json.Unmarshal(content, &msg); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to unmarshal message: %w\", err)\n\t}\n\n\treturn &msg, nil\n}\n\n// handleMessages reads and dispatches messages in a loop\nfunc (c *Client) handleMessages() {\n\tcnf := config.Get()\n\tfor {\n\t\tmsg, err := ReadMessage(c.stdout)\n\t\tif err != nil {\n\t\t\tif cnf.DebugLSP {\n\t\t\t\tlogging.Error(\"Error reading message\", \"error\", err)\n\t\t\t}\n\t\t\treturn\n\t\t}\n\n\t\t// Handle server->client request (has both Method and ID)\n\t\tif msg.Method != \"\" && msg.ID != 0 {\n\t\t\tif cnf.DebugLSP {\n\t\t\t\tlogging.Debug(\"Received request from server\", \"method\", msg.Method, \"id\", msg.ID)\n\t\t\t}\n\n\t\t\tresponse := &Message{\n\t\t\t\tJSONRPC: \"2.0\",\n\t\t\t\tID: msg.ID,\n\t\t\t}\n\n\t\t\t// Look up handler for this method\n\t\t\tc.serverHandlersMu.RLock()\n\t\t\thandler, ok := c.serverRequestHandlers[msg.Method]\n\t\t\tc.serverHandlersMu.RUnlock()\n\n\t\t\tif ok {\n\t\t\t\tresult, err := handler(msg.Params)\n\t\t\t\tif err != nil {\n\t\t\t\t\tresponse.Error = &ResponseError{\n\t\t\t\t\t\tCode: -32603,\n\t\t\t\t\t\tMessage: err.Error(),\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\trawJSON, err := json.Marshal(result)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tresponse.Error = &ResponseError{\n\t\t\t\t\t\t\tCode: -32603,\n\t\t\t\t\t\t\tMessage: fmt.Sprintf(\"failed to marshal response: %v\", err),\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tresponse.Result = rawJSON\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tresponse.Error = &ResponseError{\n\t\t\t\t\tCode: -32601,\n\t\t\t\t\tMessage: fmt.Sprintf(\"method not found: %s\", msg.Method),\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Send response back to server\n\t\t\tif err := WriteMessage(c.stdin, response); err != nil {\n\t\t\t\tlogging.Error(\"Error sending response to server\", \"error\", err)\n\t\t\t}\n\n\t\t\tcontinue\n\t\t}\n\n\t\t// Handle notification (has Method but no ID)\n\t\tif msg.Method != \"\" && msg.ID == 0 {\n\t\t\tc.notificationMu.RLock()\n\t\t\thandler, ok := c.notificationHandlers[msg.Method]\n\t\t\tc.notificationMu.RUnlock()\n\n\t\t\tif ok {\n\t\t\t\tif cnf.DebugLSP {\n\t\t\t\t\tlogging.Debug(\"Handling notification\", \"method\", msg.Method)\n\t\t\t\t}\n\t\t\t\tgo handler(msg.Params)\n\t\t\t} else if cnf.DebugLSP {\n\t\t\t\tlogging.Debug(\"No handler for notification\", \"method\", msg.Method)\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\t// Handle response to our request (has ID but no Method)\n\t\tif msg.ID != 0 && msg.Method == \"\" {\n\t\t\tc.handlersMu.RLock()\n\t\t\tch, ok := c.handlers[msg.ID]\n\t\t\tc.handlersMu.RUnlock()\n\n\t\t\tif ok {\n\t\t\t\tif cnf.DebugLSP {\n\t\t\t\t\tlogging.Debug(\"Received response for request\", \"id\", msg.ID)\n\t\t\t\t}\n\t\t\t\tch <- msg\n\t\t\t\tclose(ch)\n\t\t\t} else if cnf.DebugLSP {\n\t\t\t\tlogging.Debug(\"No handler for response\", \"id\", msg.ID)\n\t\t\t}\n\t\t}\n\t}\n}\n\n// Call makes a request and waits for the response\nfunc (c *Client) Call(ctx context.Context, method string, params any, result any) error {\n\tcnf := config.Get()\n\tid := c.nextID.Add(1)\n\n\tif cnf.DebugLSP {\n\t\tlogging.Debug(\"Making call\", \"method\", method, \"id\", id)\n\t}\n\n\tmsg, err := NewRequest(id, method, params)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to create request: %w\", err)\n\t}\n\n\t// Create response channel\n\tch := make(chan *Message, 1)\n\tc.handlersMu.Lock()\n\tc.handlers[id] = ch\n\tc.handlersMu.Unlock()\n\n\tdefer func() {\n\t\tc.handlersMu.Lock()\n\t\tdelete(c.handlers, id)\n\t\tc.handlersMu.Unlock()\n\t}()\n\n\t// Send request\n\tif err := WriteMessage(c.stdin, msg); err != nil {\n\t\treturn fmt.Errorf(\"failed to send request: %w\", err)\n\t}\n\n\tif cnf.DebugLSP {\n\t\tlogging.Debug(\"Request sent\", \"method\", method, \"id\", id)\n\t}\n\n\t// Wait for response\n\tresp := <-ch\n\n\tif cnf.DebugLSP {\n\t\tlogging.Debug(\"Received response\", \"id\", id)\n\t}\n\n\tif resp.Error != nil {\n\t\treturn fmt.Errorf(\"request failed: %s (code: %d)\", resp.Error.Message, resp.Error.Code)\n\t}\n\n\tif result != nil {\n\t\t// If result is a json.RawMessage, just copy the raw bytes\n\t\tif rawMsg, ok := result.(*json.RawMessage); ok {\n\t\t\t*rawMsg = resp.Result\n\t\t\treturn nil\n\t\t}\n\t\t// Otherwise unmarshal into the provided type\n\t\tif err := json.Unmarshal(resp.Result, result); err != nil {\n\t\t\treturn fmt.Errorf(\"failed to unmarshal result: %w\", err)\n\t\t}\n\t}\n\n\treturn nil\n}\n\n// Notify sends a notification (a request without an ID that doesn't expect a response)\nfunc (c *Client) Notify(ctx context.Context, method string, params any) error {\n\tcnf := config.Get()\n\tif cnf.DebugLSP {\n\t\tlogging.Debug(\"Sending notification\", \"method\", method)\n\t}\n\n\tmsg, err := NewNotification(method, params)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to create notification: %w\", err)\n\t}\n\n\tif err := WriteMessage(c.stdin, msg); err != nil {\n\t\treturn fmt.Errorf(\"failed to send notification: %w\", err)\n\t}\n\n\treturn nil\n}\n\ntype (\n\tNotificationHandler func(params json.RawMessage)\n\tServerRequestHandler func(params json.RawMessage) (any, error)\n)\n"], ["/opencode/internal/history/file.go", "package history\n\nimport (\n\t\"context\"\n\t\"database/sql\"\n\t\"fmt\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/google/uuid\"\n\t\"github.com/opencode-ai/opencode/internal/db\"\n\t\"github.com/opencode-ai/opencode/internal/pubsub\"\n)\n\nconst (\n\tInitialVersion = \"initial\"\n)\n\ntype File struct {\n\tID string\n\tSessionID string\n\tPath string\n\tContent string\n\tVersion string\n\tCreatedAt int64\n\tUpdatedAt int64\n}\n\ntype Service interface {\n\tpubsub.Suscriber[File]\n\tCreate(ctx context.Context, sessionID, path, content string) (File, error)\n\tCreateVersion(ctx context.Context, sessionID, path, content string) (File, error)\n\tGet(ctx context.Context, id string) (File, error)\n\tGetByPathAndSession(ctx context.Context, path, sessionID string) (File, error)\n\tListBySession(ctx context.Context, sessionID string) ([]File, error)\n\tListLatestSessionFiles(ctx context.Context, sessionID string) ([]File, error)\n\tUpdate(ctx context.Context, file File) (File, error)\n\tDelete(ctx context.Context, id string) error\n\tDeleteSessionFiles(ctx context.Context, sessionID string) error\n}\n\ntype service struct {\n\t*pubsub.Broker[File]\n\tdb *sql.DB\n\tq *db.Queries\n}\n\nfunc NewService(q *db.Queries, db *sql.DB) Service {\n\treturn &service{\n\t\tBroker: pubsub.NewBroker[File](),\n\t\tq: q,\n\t\tdb: db,\n\t}\n}\n\nfunc (s *service) Create(ctx context.Context, sessionID, path, content string) (File, error) {\n\treturn s.createWithVersion(ctx, sessionID, path, content, InitialVersion)\n}\n\nfunc (s *service) CreateVersion(ctx context.Context, sessionID, path, content string) (File, error) {\n\t// Get the latest version for this path\n\tfiles, err := s.q.ListFilesByPath(ctx, path)\n\tif err != nil {\n\t\treturn File{}, err\n\t}\n\n\tif len(files) == 0 {\n\t\t// No previous versions, create initial\n\t\treturn s.Create(ctx, sessionID, path, content)\n\t}\n\n\t// Get the latest version\n\tlatestFile := files[0] // Files are ordered by created_at DESC\n\tlatestVersion := latestFile.Version\n\n\t// Generate the next version\n\tvar nextVersion string\n\tif latestVersion == InitialVersion {\n\t\tnextVersion = \"v1\"\n\t} else if strings.HasPrefix(latestVersion, \"v\") {\n\t\tversionNum, err := strconv.Atoi(latestVersion[1:])\n\t\tif err != nil {\n\t\t\t// If we can't parse the version, just use a timestamp-based version\n\t\t\tnextVersion = fmt.Sprintf(\"v%d\", latestFile.CreatedAt)\n\t\t} else {\n\t\t\tnextVersion = fmt.Sprintf(\"v%d\", versionNum+1)\n\t\t}\n\t} else {\n\t\t// If the version format is unexpected, use a timestamp-based version\n\t\tnextVersion = fmt.Sprintf(\"v%d\", latestFile.CreatedAt)\n\t}\n\n\treturn s.createWithVersion(ctx, sessionID, path, content, nextVersion)\n}\n\nfunc (s *service) createWithVersion(ctx context.Context, sessionID, path, content, version string) (File, error) {\n\t// Maximum number of retries for transaction conflicts\n\tconst maxRetries = 3\n\tvar file File\n\tvar err error\n\n\t// Retry loop for transaction conflicts\n\tfor attempt := range maxRetries {\n\t\t// Start a transaction\n\t\ttx, txErr := s.db.Begin()\n\t\tif txErr != nil {\n\t\t\treturn File{}, fmt.Errorf(\"failed to begin transaction: %w\", txErr)\n\t\t}\n\n\t\t// Create a new queries instance with the transaction\n\t\tqtx := s.q.WithTx(tx)\n\n\t\t// Try to create the file within the transaction\n\t\tdbFile, txErr := qtx.CreateFile(ctx, db.CreateFileParams{\n\t\t\tID: uuid.New().String(),\n\t\t\tSessionID: sessionID,\n\t\t\tPath: path,\n\t\t\tContent: content,\n\t\t\tVersion: version,\n\t\t})\n\t\tif txErr != nil {\n\t\t\t// Rollback the transaction\n\t\t\ttx.Rollback()\n\n\t\t\t// Check if this is a uniqueness constraint violation\n\t\t\tif strings.Contains(txErr.Error(), \"UNIQUE constraint failed\") {\n\t\t\t\tif attempt < maxRetries-1 {\n\t\t\t\t\t// If we have retries left, generate a new version and try again\n\t\t\t\t\tif strings.HasPrefix(version, \"v\") {\n\t\t\t\t\t\tversionNum, parseErr := strconv.Atoi(version[1:])\n\t\t\t\t\t\tif parseErr == nil {\n\t\t\t\t\t\t\tversion = fmt.Sprintf(\"v%d\", versionNum+1)\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t// If we can't parse the version, use a timestamp-based version\n\t\t\t\t\tversion = fmt.Sprintf(\"v%d\", time.Now().Unix())\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn File{}, txErr\n\t\t}\n\n\t\t// Commit the transaction\n\t\tif txErr = tx.Commit(); txErr != nil {\n\t\t\treturn File{}, fmt.Errorf(\"failed to commit transaction: %w\", txErr)\n\t\t}\n\n\t\tfile = s.fromDBItem(dbFile)\n\t\ts.Publish(pubsub.CreatedEvent, file)\n\t\treturn file, nil\n\t}\n\n\treturn file, err\n}\n\nfunc (s *service) Get(ctx context.Context, id string) (File, error) {\n\tdbFile, err := s.q.GetFile(ctx, id)\n\tif err != nil {\n\t\treturn File{}, err\n\t}\n\treturn s.fromDBItem(dbFile), nil\n}\n\nfunc (s *service) GetByPathAndSession(ctx context.Context, path, sessionID string) (File, error) {\n\tdbFile, err := s.q.GetFileByPathAndSession(ctx, db.GetFileByPathAndSessionParams{\n\t\tPath: path,\n\t\tSessionID: sessionID,\n\t})\n\tif err != nil {\n\t\treturn File{}, err\n\t}\n\treturn s.fromDBItem(dbFile), nil\n}\n\nfunc (s *service) ListBySession(ctx context.Context, sessionID string) ([]File, error) {\n\tdbFiles, err := s.q.ListFilesBySession(ctx, sessionID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfiles := make([]File, len(dbFiles))\n\tfor i, dbFile := range dbFiles {\n\t\tfiles[i] = s.fromDBItem(dbFile)\n\t}\n\treturn files, nil\n}\n\nfunc (s *service) ListLatestSessionFiles(ctx context.Context, sessionID string) ([]File, error) {\n\tdbFiles, err := s.q.ListLatestSessionFiles(ctx, sessionID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfiles := make([]File, len(dbFiles))\n\tfor i, dbFile := range dbFiles {\n\t\tfiles[i] = s.fromDBItem(dbFile)\n\t}\n\treturn files, nil\n}\n\nfunc (s *service) Update(ctx context.Context, file File) (File, error) {\n\tdbFile, err := s.q.UpdateFile(ctx, db.UpdateFileParams{\n\t\tID: file.ID,\n\t\tContent: file.Content,\n\t\tVersion: file.Version,\n\t})\n\tif err != nil {\n\t\treturn File{}, err\n\t}\n\tupdatedFile := s.fromDBItem(dbFile)\n\ts.Publish(pubsub.UpdatedEvent, updatedFile)\n\treturn updatedFile, nil\n}\n\nfunc (s *service) Delete(ctx context.Context, id string) error {\n\tfile, err := s.Get(ctx, id)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = s.q.DeleteFile(ctx, id)\n\tif err != nil {\n\t\treturn err\n\t}\n\ts.Publish(pubsub.DeletedEvent, file)\n\treturn nil\n}\n\nfunc (s *service) DeleteSessionFiles(ctx context.Context, sessionID string) error {\n\tfiles, err := s.ListBySession(ctx, sessionID)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor _, file := range files {\n\t\terr = s.Delete(ctx, file.ID)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (s *service) fromDBItem(item db.File) File {\n\treturn File{\n\t\tID: item.ID,\n\t\tSessionID: item.SessionID,\n\t\tPath: item.Path,\n\t\tContent: item.Content,\n\t\tVersion: item.Version,\n\t\tCreatedAt: item.CreatedAt,\n\t\tUpdatedAt: item.UpdatedAt,\n\t}\n}\n"], ["/opencode/cmd/root.go", "package cmd\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"os\"\n\t\"sync\"\n\t\"time\"\n\n\ttea \"github.com/charmbracelet/bubbletea\"\n\tzone \"github.com/lrstanley/bubblezone\"\n\t\"github.com/opencode-ai/opencode/internal/app\"\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/db\"\n\t\"github.com/opencode-ai/opencode/internal/format\"\n\t\"github.com/opencode-ai/opencode/internal/llm/agent\"\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n\t\"github.com/opencode-ai/opencode/internal/pubsub\"\n\t\"github.com/opencode-ai/opencode/internal/tui\"\n\t\"github.com/opencode-ai/opencode/internal/version\"\n\t\"github.com/spf13/cobra\"\n)\n\nvar rootCmd = &cobra.Command{\n\tUse: \"opencode\",\n\tShort: \"Terminal-based AI assistant for software development\",\n\tLong: `OpenCode is a powerful terminal-based AI assistant that helps with software development tasks.\nIt provides an interactive chat interface with AI capabilities, code analysis, and LSP integration\nto assist developers in writing, debugging, and understanding code directly from the terminal.`,\n\tExample: `\n # Run in interactive mode\n opencode\n\n # Run with debug logging\n opencode -d\n\n # Run with debug logging in a specific directory\n opencode -d -c /path/to/project\n\n # Print version\n opencode -v\n\n # Run a single non-interactive prompt\n opencode -p \"Explain the use of context in Go\"\n\n # Run a single non-interactive prompt with JSON output format\n opencode -p \"Explain the use of context in Go\" -f json\n `,\n\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t// If the help flag is set, show the help message\n\t\tif cmd.Flag(\"help\").Changed {\n\t\t\tcmd.Help()\n\t\t\treturn nil\n\t\t}\n\t\tif cmd.Flag(\"version\").Changed {\n\t\t\tfmt.Println(version.Version)\n\t\t\treturn nil\n\t\t}\n\n\t\t// Load the config\n\t\tdebug, _ := cmd.Flags().GetBool(\"debug\")\n\t\tcwd, _ := cmd.Flags().GetString(\"cwd\")\n\t\tprompt, _ := cmd.Flags().GetString(\"prompt\")\n\t\toutputFormat, _ := cmd.Flags().GetString(\"output-format\")\n\t\tquiet, _ := cmd.Flags().GetBool(\"quiet\")\n\n\t\t// Validate format option\n\t\tif !format.IsValid(outputFormat) {\n\t\t\treturn fmt.Errorf(\"invalid format option: %s\\n%s\", outputFormat, format.GetHelpText())\n\t\t}\n\n\t\tif cwd != \"\" {\n\t\t\terr := os.Chdir(cwd)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"failed to change directory: %v\", err)\n\t\t\t}\n\t\t}\n\t\tif cwd == \"\" {\n\t\t\tc, err := os.Getwd()\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"failed to get current working directory: %v\", err)\n\t\t\t}\n\t\t\tcwd = c\n\t\t}\n\t\t_, err := config.Load(cwd, debug)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Connect DB, this will also run migrations\n\t\tconn, err := db.Connect()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Create main context for the application\n\t\tctx, cancel := context.WithCancel(context.Background())\n\t\tdefer cancel()\n\n\t\tapp, err := app.New(ctx, conn)\n\t\tif err != nil {\n\t\t\tlogging.Error(\"Failed to create app: %v\", err)\n\t\t\treturn err\n\t\t}\n\t\t// Defer shutdown here so it runs for both interactive and non-interactive modes\n\t\tdefer app.Shutdown()\n\n\t\t// Initialize MCP tools early for both modes\n\t\tinitMCPTools(ctx, app)\n\n\t\t// Non-interactive mode\n\t\tif prompt != \"\" {\n\t\t\t// Run non-interactive flow using the App method\n\t\t\treturn app.RunNonInteractive(ctx, prompt, outputFormat, quiet)\n\t\t}\n\n\t\t// Interactive mode\n\t\t// Set up the TUI\n\t\tzone.NewGlobal()\n\t\tprogram := tea.NewProgram(\n\t\t\ttui.New(app),\n\t\t\ttea.WithAltScreen(),\n\t\t)\n\n\t\t// Setup the subscriptions, this will send services events to the TUI\n\t\tch, cancelSubs := setupSubscriptions(app, ctx)\n\n\t\t// Create a context for the TUI message handler\n\t\ttuiCtx, tuiCancel := context.WithCancel(ctx)\n\t\tvar tuiWg sync.WaitGroup\n\t\ttuiWg.Add(1)\n\n\t\t// Set up message handling for the TUI\n\t\tgo func() {\n\t\t\tdefer tuiWg.Done()\n\t\t\tdefer logging.RecoverPanic(\"TUI-message-handler\", func() {\n\t\t\t\tattemptTUIRecovery(program)\n\t\t\t})\n\n\t\t\tfor {\n\t\t\t\tselect {\n\t\t\t\tcase <-tuiCtx.Done():\n\t\t\t\t\tlogging.Info(\"TUI message handler shutting down\")\n\t\t\t\t\treturn\n\t\t\t\tcase msg, ok := <-ch:\n\t\t\t\t\tif !ok {\n\t\t\t\t\t\tlogging.Info(\"TUI message channel closed\")\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\tprogram.Send(msg)\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\n\t\t// Cleanup function for when the program exits\n\t\tcleanup := func() {\n\t\t\t// Shutdown the app\n\t\t\tapp.Shutdown()\n\n\t\t\t// Cancel subscriptions first\n\t\t\tcancelSubs()\n\n\t\t\t// Then cancel TUI message handler\n\t\t\ttuiCancel()\n\n\t\t\t// Wait for TUI message handler to finish\n\t\t\ttuiWg.Wait()\n\n\t\t\tlogging.Info(\"All goroutines cleaned up\")\n\t\t}\n\n\t\t// Run the TUI\n\t\tresult, err := program.Run()\n\t\tcleanup()\n\n\t\tif err != nil {\n\t\t\tlogging.Error(\"TUI error: %v\", err)\n\t\t\treturn fmt.Errorf(\"TUI error: %v\", err)\n\t\t}\n\n\t\tlogging.Info(\"TUI exited with result: %v\", result)\n\t\treturn nil\n\t},\n}\n\n// attemptTUIRecovery tries to recover the TUI after a panic\nfunc attemptTUIRecovery(program *tea.Program) {\n\tlogging.Info(\"Attempting to recover TUI after panic\")\n\n\t// We could try to restart the TUI or gracefully exit\n\t// For now, we'll just quit the program to avoid further issues\n\tprogram.Quit()\n}\n\nfunc initMCPTools(ctx context.Context, app *app.App) {\n\tgo func() {\n\t\tdefer logging.RecoverPanic(\"MCP-goroutine\", nil)\n\n\t\t// Create a context with timeout for the initial MCP tools fetch\n\t\tctxWithTimeout, cancel := context.WithTimeout(ctx, 30*time.Second)\n\t\tdefer cancel()\n\n\t\t// Set this up once with proper error handling\n\t\tagent.GetMcpTools(ctxWithTimeout, app.Permissions)\n\t\tlogging.Info(\"MCP message handling goroutine exiting\")\n\t}()\n}\n\nfunc setupSubscriber[T any](\n\tctx context.Context,\n\twg *sync.WaitGroup,\n\tname string,\n\tsubscriber func(context.Context) <-chan pubsub.Event[T],\n\toutputCh chan<- tea.Msg,\n) {\n\twg.Add(1)\n\tgo func() {\n\t\tdefer wg.Done()\n\t\tdefer logging.RecoverPanic(fmt.Sprintf(\"subscription-%s\", name), nil)\n\n\t\tsubCh := subscriber(ctx)\n\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase event, ok := <-subCh:\n\t\t\t\tif !ok {\n\t\t\t\t\tlogging.Info(\"subscription channel closed\", \"name\", name)\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tvar msg tea.Msg = event\n\n\t\t\t\tselect {\n\t\t\t\tcase outputCh <- msg:\n\t\t\t\tcase <-time.After(2 * time.Second):\n\t\t\t\t\tlogging.Warn(\"message dropped due to slow consumer\", \"name\", name)\n\t\t\t\tcase <-ctx.Done():\n\t\t\t\t\tlogging.Info(\"subscription cancelled\", \"name\", name)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\tcase <-ctx.Done():\n\t\t\t\tlogging.Info(\"subscription cancelled\", \"name\", name)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}()\n}\n\nfunc setupSubscriptions(app *app.App, parentCtx context.Context) (chan tea.Msg, func()) {\n\tch := make(chan tea.Msg, 100)\n\n\twg := sync.WaitGroup{}\n\tctx, cancel := context.WithCancel(parentCtx) // Inherit from parent context\n\n\tsetupSubscriber(ctx, &wg, \"logging\", logging.Subscribe, ch)\n\tsetupSubscriber(ctx, &wg, \"sessions\", app.Sessions.Subscribe, ch)\n\tsetupSubscriber(ctx, &wg, \"messages\", app.Messages.Subscribe, ch)\n\tsetupSubscriber(ctx, &wg, \"permissions\", app.Permissions.Subscribe, ch)\n\tsetupSubscriber(ctx, &wg, \"coderAgent\", app.CoderAgent.Subscribe, ch)\n\n\tcleanupFunc := func() {\n\t\tlogging.Info(\"Cancelling all subscriptions\")\n\t\tcancel() // Signal all goroutines to stop\n\n\t\twaitCh := make(chan struct{})\n\t\tgo func() {\n\t\t\tdefer logging.RecoverPanic(\"subscription-cleanup\", nil)\n\t\t\twg.Wait()\n\t\t\tclose(waitCh)\n\t\t}()\n\n\t\tselect {\n\t\tcase <-waitCh:\n\t\t\tlogging.Info(\"All subscription goroutines completed successfully\")\n\t\t\tclose(ch) // Only close after all writers are confirmed done\n\t\tcase <-time.After(5 * time.Second):\n\t\t\tlogging.Warn(\"Timed out waiting for some subscription goroutines to complete\")\n\t\t\tclose(ch)\n\t\t}\n\t}\n\treturn ch, cleanupFunc\n}\n\nfunc Execute() {\n\terr := rootCmd.Execute()\n\tif err != nil {\n\t\tos.Exit(1)\n\t}\n}\n\nfunc init() {\n\trootCmd.Flags().BoolP(\"help\", \"h\", false, \"Help\")\n\trootCmd.Flags().BoolP(\"version\", \"v\", false, \"Version\")\n\trootCmd.Flags().BoolP(\"debug\", \"d\", false, \"Debug\")\n\trootCmd.Flags().StringP(\"cwd\", \"c\", \"\", \"Current working directory\")\n\trootCmd.Flags().StringP(\"prompt\", \"p\", \"\", \"Prompt to run in non-interactive mode\")\n\n\t// Add format flag with validation logic\n\trootCmd.Flags().StringP(\"output-format\", \"f\", format.Text.String(),\n\t\t\"Output format for non-interactive mode (text, json)\")\n\n\t// Add quiet flag to hide spinner in non-interactive mode\n\trootCmd.Flags().BoolP(\"quiet\", \"q\", false, \"Hide spinner in non-interactive mode\")\n\n\t// Register custom validation for the format flag\n\trootCmd.RegisterFlagCompletionFunc(\"output-format\", func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {\n\t\treturn format.SupportedFormats, cobra.ShellCompDirectiveNoFileComp\n\t})\n}\n"], ["/opencode/internal/lsp/watcher/watcher.go", "package watcher\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com/bmatcuk/doublestar/v4\"\n\t\"github.com/fsnotify/fsnotify\"\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n\t\"github.com/opencode-ai/opencode/internal/lsp\"\n\t\"github.com/opencode-ai/opencode/internal/lsp/protocol\"\n)\n\n// WorkspaceWatcher manages LSP file watching\ntype WorkspaceWatcher struct {\n\tclient *lsp.Client\n\tworkspacePath string\n\n\tdebounceTime time.Duration\n\tdebounceMap map[string]*time.Timer\n\tdebounceMu sync.Mutex\n\n\t// File watchers registered by the server\n\tregistrations []protocol.FileSystemWatcher\n\tregistrationMu sync.RWMutex\n}\n\n// NewWorkspaceWatcher creates a new workspace watcher\nfunc NewWorkspaceWatcher(client *lsp.Client) *WorkspaceWatcher {\n\treturn &WorkspaceWatcher{\n\t\tclient: client,\n\t\tdebounceTime: 300 * time.Millisecond,\n\t\tdebounceMap: make(map[string]*time.Timer),\n\t\tregistrations: []protocol.FileSystemWatcher{},\n\t}\n}\n\n// AddRegistrations adds file watchers to track\nfunc (w *WorkspaceWatcher) AddRegistrations(ctx context.Context, id string, watchers []protocol.FileSystemWatcher) {\n\tcnf := config.Get()\n\n\tlogging.Debug(\"Adding file watcher registrations\")\n\tw.registrationMu.Lock()\n\tdefer w.registrationMu.Unlock()\n\n\t// Add new watchers\n\tw.registrations = append(w.registrations, watchers...)\n\n\t// Print detailed registration information for debugging\n\tif cnf.DebugLSP {\n\t\tlogging.Debug(\"Adding file watcher registrations\",\n\t\t\t\"id\", id,\n\t\t\t\"watchers\", len(watchers),\n\t\t\t\"total\", len(w.registrations),\n\t\t)\n\n\t\tfor i, watcher := range watchers {\n\t\t\tlogging.Debug(\"Registration\", \"index\", i+1)\n\n\t\t\t// Log the GlobPattern\n\t\t\tswitch v := watcher.GlobPattern.Value.(type) {\n\t\t\tcase string:\n\t\t\t\tlogging.Debug(\"GlobPattern\", \"pattern\", v)\n\t\t\tcase protocol.RelativePattern:\n\t\t\t\tlogging.Debug(\"GlobPattern\", \"pattern\", v.Pattern)\n\n\t\t\t\t// Log BaseURI details\n\t\t\t\tswitch u := v.BaseURI.Value.(type) {\n\t\t\t\tcase string:\n\t\t\t\t\tlogging.Debug(\"BaseURI\", \"baseURI\", u)\n\t\t\t\tcase protocol.DocumentUri:\n\t\t\t\t\tlogging.Debug(\"BaseURI\", \"baseURI\", u)\n\t\t\t\tdefault:\n\t\t\t\t\tlogging.Debug(\"BaseURI\", \"baseURI\", u)\n\t\t\t\t}\n\t\t\tdefault:\n\t\t\t\tlogging.Debug(\"GlobPattern\", \"unknown type\", fmt.Sprintf(\"%T\", v))\n\t\t\t}\n\n\t\t\t// Log WatchKind\n\t\t\twatchKind := protocol.WatchKind(protocol.WatchChange | protocol.WatchCreate | protocol.WatchDelete)\n\t\t\tif watcher.Kind != nil {\n\t\t\t\twatchKind = *watcher.Kind\n\t\t\t}\n\n\t\t\tlogging.Debug(\"WatchKind\", \"kind\", watchKind)\n\t\t}\n\t}\n\n\t// Determine server type for specialized handling\n\tserverName := getServerNameFromContext(ctx)\n\tlogging.Debug(\"Server type detected\", \"serverName\", serverName)\n\n\t// Check if this server has sent file watchers\n\thasFileWatchers := len(watchers) > 0\n\n\t// For servers that need file preloading, we'll use a smart approach\n\tif shouldPreloadFiles(serverName) || !hasFileWatchers {\n\t\tgo func() {\n\t\t\tstartTime := time.Now()\n\t\t\tfilesOpened := 0\n\n\t\t\t// Determine max files to open based on server type\n\t\t\tmaxFilesToOpen := 50 // Default conservative limit\n\n\t\t\tswitch serverName {\n\t\t\tcase \"typescript\", \"typescript-language-server\", \"tsserver\", \"vtsls\":\n\t\t\t\t// TypeScript servers benefit from seeing more files\n\t\t\t\tmaxFilesToOpen = 100\n\t\t\tcase \"java\", \"jdtls\":\n\t\t\t\t// Java servers need to see many files for project model\n\t\t\t\tmaxFilesToOpen = 200\n\t\t\t}\n\n\t\t\t// First, open high-priority files\n\t\t\thighPriorityFilesOpened := w.openHighPriorityFiles(ctx, serverName)\n\t\t\tfilesOpened += highPriorityFilesOpened\n\n\t\t\tif cnf.DebugLSP {\n\t\t\t\tlogging.Debug(\"Opened high-priority files\",\n\t\t\t\t\t\"count\", highPriorityFilesOpened,\n\t\t\t\t\t\"serverName\", serverName)\n\t\t\t}\n\n\t\t\t// If we've already opened enough high-priority files, we might not need more\n\t\t\tif filesOpened >= maxFilesToOpen {\n\t\t\t\tif cnf.DebugLSP {\n\t\t\t\t\tlogging.Debug(\"Reached file limit with high-priority files\",\n\t\t\t\t\t\t\"filesOpened\", filesOpened,\n\t\t\t\t\t\t\"maxFiles\", maxFilesToOpen)\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\t// For the remaining slots, walk the directory and open matching files\n\n\t\t\terr := filepath.WalkDir(w.workspacePath, func(path string, d os.DirEntry, err error) error {\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\n\t\t\t\t// Skip directories that should be excluded\n\t\t\t\tif d.IsDir() {\n\t\t\t\t\tif path != w.workspacePath && shouldExcludeDir(path) {\n\t\t\t\t\t\tif cnf.DebugLSP {\n\t\t\t\t\t\t\tlogging.Debug(\"Skipping excluded directory\", \"path\", path)\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn filepath.SkipDir\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\t// Process files, but limit the total number\n\t\t\t\t\tif filesOpened < maxFilesToOpen {\n\t\t\t\t\t\t// Only process if it's not already open (high-priority files were opened earlier)\n\t\t\t\t\t\tif !w.client.IsFileOpen(path) {\n\t\t\t\t\t\t\tw.openMatchingFile(ctx, path)\n\t\t\t\t\t\t\tfilesOpened++\n\n\t\t\t\t\t\t\t// Add a small delay after every 10 files to prevent overwhelming the server\n\t\t\t\t\t\t\tif filesOpened%10 == 0 {\n\t\t\t\t\t\t\t\ttime.Sleep(50 * time.Millisecond)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// We've reached our limit, stop walking\n\t\t\t\t\t\treturn filepath.SkipAll\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\treturn nil\n\t\t\t})\n\n\t\t\telapsedTime := time.Since(startTime)\n\t\t\tif cnf.DebugLSP {\n\t\t\t\tlogging.Debug(\"Limited workspace scan complete\",\n\t\t\t\t\t\"filesOpened\", filesOpened,\n\t\t\t\t\t\"maxFiles\", maxFilesToOpen,\n\t\t\t\t\t\"elapsedTime\", elapsedTime.Seconds(),\n\t\t\t\t\t\"workspacePath\", w.workspacePath,\n\t\t\t\t)\n\t\t\t}\n\n\t\t\tif err != nil && cnf.DebugLSP {\n\t\t\t\tlogging.Debug(\"Error scanning workspace for files to open\", \"error\", err)\n\t\t\t}\n\t\t}()\n\t} else if cnf.DebugLSP {\n\t\tlogging.Debug(\"Using on-demand file loading for server\", \"server\", serverName)\n\t}\n}\n\n// openHighPriorityFiles opens important files for the server type\n// Returns the number of files opened\nfunc (w *WorkspaceWatcher) openHighPriorityFiles(ctx context.Context, serverName string) int {\n\tcnf := config.Get()\n\tfilesOpened := 0\n\n\t// Define patterns for high-priority files based on server type\n\tvar patterns []string\n\n\tswitch serverName {\n\tcase \"typescript\", \"typescript-language-server\", \"tsserver\", \"vtsls\":\n\t\tpatterns = []string{\n\t\t\t\"**/tsconfig.json\",\n\t\t\t\"**/package.json\",\n\t\t\t\"**/jsconfig.json\",\n\t\t\t\"**/index.ts\",\n\t\t\t\"**/index.js\",\n\t\t\t\"**/main.ts\",\n\t\t\t\"**/main.js\",\n\t\t}\n\tcase \"gopls\":\n\t\tpatterns = []string{\n\t\t\t\"**/go.mod\",\n\t\t\t\"**/go.sum\",\n\t\t\t\"**/main.go\",\n\t\t}\n\tcase \"rust-analyzer\":\n\t\tpatterns = []string{\n\t\t\t\"**/Cargo.toml\",\n\t\t\t\"**/Cargo.lock\",\n\t\t\t\"**/src/lib.rs\",\n\t\t\t\"**/src/main.rs\",\n\t\t}\n\tcase \"python\", \"pyright\", \"pylsp\":\n\t\tpatterns = []string{\n\t\t\t\"**/pyproject.toml\",\n\t\t\t\"**/setup.py\",\n\t\t\t\"**/requirements.txt\",\n\t\t\t\"**/__init__.py\",\n\t\t\t\"**/__main__.py\",\n\t\t}\n\tcase \"clangd\":\n\t\tpatterns = []string{\n\t\t\t\"**/CMakeLists.txt\",\n\t\t\t\"**/Makefile\",\n\t\t\t\"**/compile_commands.json\",\n\t\t}\n\tcase \"java\", \"jdtls\":\n\t\tpatterns = []string{\n\t\t\t\"**/pom.xml\",\n\t\t\t\"**/build.gradle\",\n\t\t\t\"**/src/main/java/**/*.java\",\n\t\t}\n\tdefault:\n\t\t// For unknown servers, use common configuration files\n\t\tpatterns = []string{\n\t\t\t\"**/package.json\",\n\t\t\t\"**/Makefile\",\n\t\t\t\"**/CMakeLists.txt\",\n\t\t\t\"**/.editorconfig\",\n\t\t}\n\t}\n\n\t// For each pattern, find and open matching files\n\tfor _, pattern := range patterns {\n\t\t// Use doublestar.Glob to find files matching the pattern (supports ** patterns)\n\t\tmatches, err := doublestar.Glob(os.DirFS(w.workspacePath), pattern)\n\t\tif err != nil {\n\t\t\tif cnf.DebugLSP {\n\t\t\t\tlogging.Debug(\"Error finding high-priority files\", \"pattern\", pattern, \"error\", err)\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\tfor _, match := range matches {\n\t\t\t// Convert relative path to absolute\n\t\t\tfullPath := filepath.Join(w.workspacePath, match)\n\n\t\t\t// Skip directories and excluded files\n\t\t\tinfo, err := os.Stat(fullPath)\n\t\t\tif err != nil || info.IsDir() || shouldExcludeFile(fullPath) {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// Open the file\n\t\t\tif err := w.client.OpenFile(ctx, fullPath); err != nil {\n\t\t\t\tif cnf.DebugLSP {\n\t\t\t\t\tlogging.Debug(\"Error opening high-priority file\", \"path\", fullPath, \"error\", err)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tfilesOpened++\n\t\t\t\tif cnf.DebugLSP {\n\t\t\t\t\tlogging.Debug(\"Opened high-priority file\", \"path\", fullPath)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Add a small delay to prevent overwhelming the server\n\t\t\ttime.Sleep(20 * time.Millisecond)\n\n\t\t\t// Limit the number of files opened per pattern\n\t\t\tif filesOpened >= 5 && (serverName != \"java\" && serverName != \"jdtls\") {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\treturn filesOpened\n}\n\n// WatchWorkspace sets up file watching for a workspace\nfunc (w *WorkspaceWatcher) WatchWorkspace(ctx context.Context, workspacePath string) {\n\tcnf := config.Get()\n\tw.workspacePath = workspacePath\n\n\t// Store the watcher in the context for later use\n\tctx = context.WithValue(ctx, \"workspaceWatcher\", w)\n\n\t// If the server name isn't already in the context, try to detect it\n\tif _, ok := ctx.Value(\"serverName\").(string); !ok {\n\t\tserverName := getServerNameFromContext(ctx)\n\t\tctx = context.WithValue(ctx, \"serverName\", serverName)\n\t}\n\n\tserverName := getServerNameFromContext(ctx)\n\tlogging.Debug(\"Starting workspace watcher\", \"workspacePath\", workspacePath, \"serverName\", serverName)\n\n\t// Register handler for file watcher registrations from the server\n\tlsp.RegisterFileWatchHandler(func(id string, watchers []protocol.FileSystemWatcher) {\n\t\tw.AddRegistrations(ctx, id, watchers)\n\t})\n\n\twatcher, err := fsnotify.NewWatcher()\n\tif err != nil {\n\t\tlogging.Error(\"Error creating watcher\", \"error\", err)\n\t}\n\tdefer watcher.Close()\n\n\t// Watch the workspace recursively\n\terr = filepath.WalkDir(workspacePath, func(path string, d os.DirEntry, err error) error {\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Skip excluded directories (except workspace root)\n\t\tif d.IsDir() && path != workspacePath {\n\t\t\tif shouldExcludeDir(path) {\n\t\t\t\tif cnf.DebugLSP {\n\t\t\t\t\tlogging.Debug(\"Skipping excluded directory\", \"path\", path)\n\t\t\t\t}\n\t\t\t\treturn filepath.SkipDir\n\t\t\t}\n\t\t}\n\n\t\t// Add directories to watcher\n\t\tif d.IsDir() {\n\t\t\terr = watcher.Add(path)\n\t\t\tif err != nil {\n\t\t\t\tlogging.Error(\"Error watching path\", \"path\", path, \"error\", err)\n\t\t\t}\n\t\t}\n\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\tlogging.Error(\"Error walking workspace\", \"error\", err)\n\t}\n\n\t// Event loop\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn\n\t\tcase event, ok := <-watcher.Events:\n\t\t\tif !ok {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\turi := fmt.Sprintf(\"file://%s\", event.Name)\n\n\t\t\t// Add new directories to the watcher\n\t\t\tif event.Op&fsnotify.Create != 0 {\n\t\t\t\tif info, err := os.Stat(event.Name); err == nil {\n\t\t\t\t\tif info.IsDir() {\n\t\t\t\t\t\t// Skip excluded directories\n\t\t\t\t\t\tif !shouldExcludeDir(event.Name) {\n\t\t\t\t\t\t\tif err := watcher.Add(event.Name); err != nil {\n\t\t\t\t\t\t\t\tlogging.Error(\"Error adding directory to watcher\", \"path\", event.Name, \"error\", err)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// For newly created files\n\t\t\t\t\t\tif !shouldExcludeFile(event.Name) {\n\t\t\t\t\t\t\tw.openMatchingFile(ctx, event.Name)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Debug logging\n\t\t\tif cnf.DebugLSP {\n\t\t\t\tmatched, kind := w.isPathWatched(event.Name)\n\t\t\t\tlogging.Debug(\"File event\",\n\t\t\t\t\t\"path\", event.Name,\n\t\t\t\t\t\"operation\", event.Op.String(),\n\t\t\t\t\t\"watched\", matched,\n\t\t\t\t\t\"kind\", kind,\n\t\t\t\t)\n\n\t\t\t}\n\n\t\t\t// Check if this path should be watched according to server registrations\n\t\t\tif watched, watchKind := w.isPathWatched(event.Name); watched {\n\t\t\t\tswitch {\n\t\t\t\tcase event.Op&fsnotify.Write != 0:\n\t\t\t\t\tif watchKind&protocol.WatchChange != 0 {\n\t\t\t\t\t\tw.debounceHandleFileEvent(ctx, uri, protocol.FileChangeType(protocol.Changed))\n\t\t\t\t\t}\n\t\t\t\tcase event.Op&fsnotify.Create != 0:\n\t\t\t\t\t// Already handled earlier in the event loop\n\t\t\t\t\t// Just send the notification if needed\n\t\t\t\t\tinfo, err := os.Stat(event.Name)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlogging.Error(\"Error getting file info\", \"path\", event.Name, \"error\", err)\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\tif !info.IsDir() && watchKind&protocol.WatchCreate != 0 {\n\t\t\t\t\t\tw.debounceHandleFileEvent(ctx, uri, protocol.FileChangeType(protocol.Created))\n\t\t\t\t\t}\n\t\t\t\tcase event.Op&fsnotify.Remove != 0:\n\t\t\t\t\tif watchKind&protocol.WatchDelete != 0 {\n\t\t\t\t\t\tw.handleFileEvent(ctx, uri, protocol.FileChangeType(protocol.Deleted))\n\t\t\t\t\t}\n\t\t\t\tcase event.Op&fsnotify.Rename != 0:\n\t\t\t\t\t// For renames, first delete\n\t\t\t\t\tif watchKind&protocol.WatchDelete != 0 {\n\t\t\t\t\t\tw.handleFileEvent(ctx, uri, protocol.FileChangeType(protocol.Deleted))\n\t\t\t\t\t}\n\n\t\t\t\t\t// Then check if the new file exists and create an event\n\t\t\t\t\tif info, err := os.Stat(event.Name); err == nil && !info.IsDir() {\n\t\t\t\t\t\tif watchKind&protocol.WatchCreate != 0 {\n\t\t\t\t\t\t\tw.debounceHandleFileEvent(ctx, uri, protocol.FileChangeType(protocol.Created))\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\tcase err, ok := <-watcher.Errors:\n\t\t\tif !ok {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tlogging.Error(\"Error watching file\", \"error\", err)\n\t\t}\n\t}\n}\n\n// isPathWatched checks if a path should be watched based on server registrations\nfunc (w *WorkspaceWatcher) isPathWatched(path string) (bool, protocol.WatchKind) {\n\tw.registrationMu.RLock()\n\tdefer w.registrationMu.RUnlock()\n\n\t// If no explicit registrations, watch everything\n\tif len(w.registrations) == 0 {\n\t\treturn true, protocol.WatchKind(protocol.WatchChange | protocol.WatchCreate | protocol.WatchDelete)\n\t}\n\n\t// Check each registration\n\tfor _, reg := range w.registrations {\n\t\tisMatch := w.matchesPattern(path, reg.GlobPattern)\n\t\tif isMatch {\n\t\t\tkind := protocol.WatchKind(protocol.WatchChange | protocol.WatchCreate | protocol.WatchDelete)\n\t\t\tif reg.Kind != nil {\n\t\t\t\tkind = *reg.Kind\n\t\t\t}\n\t\t\treturn true, kind\n\t\t}\n\t}\n\n\treturn false, 0\n}\n\n// matchesGlob handles advanced glob patterns including ** and alternatives\nfunc matchesGlob(pattern, path string) bool {\n\t// Handle file extension patterns with braces like *.{go,mod,sum}\n\tif strings.Contains(pattern, \"{\") && strings.Contains(pattern, \"}\") {\n\t\t// Extract extensions from pattern like \"*.{go,mod,sum}\"\n\t\tparts := strings.SplitN(pattern, \"{\", 2)\n\t\tif len(parts) == 2 {\n\t\t\tprefix := parts[0]\n\t\t\textPart := strings.SplitN(parts[1], \"}\", 2)\n\t\t\tif len(extPart) == 2 {\n\t\t\t\textensions := strings.Split(extPart[0], \",\")\n\t\t\t\tsuffix := extPart[1]\n\n\t\t\t\t// Check if the path matches any of the extensions\n\t\t\t\tfor _, ext := range extensions {\n\t\t\t\t\textPattern := prefix + ext + suffix\n\t\t\t\t\tisMatch := matchesSimpleGlob(extPattern, path)\n\t\t\t\t\tif isMatch {\n\t\t\t\t\t\treturn true\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t}\n\n\treturn matchesSimpleGlob(pattern, path)\n}\n\n// matchesSimpleGlob handles glob patterns with ** wildcards\nfunc matchesSimpleGlob(pattern, path string) bool {\n\t// Handle special case for **/*.ext pattern (common in LSP)\n\tif strings.HasPrefix(pattern, \"**/\") {\n\t\trest := strings.TrimPrefix(pattern, \"**/\")\n\n\t\t// If the rest is a simple file extension pattern like *.go\n\t\tif strings.HasPrefix(rest, \"*.\") {\n\t\t\text := strings.TrimPrefix(rest, \"*\")\n\t\t\tisMatch := strings.HasSuffix(path, ext)\n\t\t\treturn isMatch\n\t\t}\n\n\t\t// Otherwise, try to check if the path ends with the rest part\n\t\tisMatch := strings.HasSuffix(path, rest)\n\n\t\t// If it matches directly, great!\n\t\tif isMatch {\n\t\t\treturn true\n\t\t}\n\n\t\t// Otherwise, check if any path component matches\n\t\tpathComponents := strings.Split(path, \"/\")\n\t\tfor i := range pathComponents {\n\t\t\tsubPath := strings.Join(pathComponents[i:], \"/\")\n\t\t\tif strings.HasSuffix(subPath, rest) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\n\t\treturn false\n\t}\n\n\t// Handle other ** wildcard pattern cases\n\tif strings.Contains(pattern, \"**\") {\n\t\tparts := strings.Split(pattern, \"**\")\n\n\t\t// Validate the path starts with the first part\n\t\tif !strings.HasPrefix(path, parts[0]) && parts[0] != \"\" {\n\t\t\treturn false\n\t\t}\n\n\t\t// For patterns like \"**/*.go\", just check the suffix\n\t\tif len(parts) == 2 && parts[0] == \"\" {\n\t\t\tisMatch := strings.HasSuffix(path, parts[1])\n\t\t\treturn isMatch\n\t\t}\n\n\t\t// For other patterns, handle middle part\n\t\tremaining := strings.TrimPrefix(path, parts[0])\n\t\tif len(parts) == 2 {\n\t\t\tisMatch := strings.HasSuffix(remaining, parts[1])\n\t\t\treturn isMatch\n\t\t}\n\t}\n\n\t// Handle simple * wildcard for file extension patterns (*.go, *.sum, etc)\n\tif strings.HasPrefix(pattern, \"*.\") {\n\t\text := strings.TrimPrefix(pattern, \"*\")\n\t\tisMatch := strings.HasSuffix(path, ext)\n\t\treturn isMatch\n\t}\n\n\t// Fall back to simple matching for simpler patterns\n\tmatched, err := filepath.Match(pattern, path)\n\tif err != nil {\n\t\tlogging.Error(\"Error matching pattern\", \"pattern\", pattern, \"path\", path, \"error\", err)\n\t\treturn false\n\t}\n\n\treturn matched\n}\n\n// matchesPattern checks if a path matches the glob pattern\nfunc (w *WorkspaceWatcher) matchesPattern(path string, pattern protocol.GlobPattern) bool {\n\tpatternInfo, err := pattern.AsPattern()\n\tif err != nil {\n\t\tlogging.Error(\"Error parsing pattern\", \"pattern\", pattern, \"error\", err)\n\t\treturn false\n\t}\n\n\tbasePath := patternInfo.GetBasePath()\n\tpatternText := patternInfo.GetPattern()\n\n\tpath = filepath.ToSlash(path)\n\n\t// For simple patterns without base path\n\tif basePath == \"\" {\n\t\t// Check if the pattern matches the full path or just the file extension\n\t\tfullPathMatch := matchesGlob(patternText, path)\n\t\tbaseNameMatch := matchesGlob(patternText, filepath.Base(path))\n\n\t\treturn fullPathMatch || baseNameMatch\n\t}\n\n\t// For relative patterns\n\tbasePath = strings.TrimPrefix(basePath, \"file://\")\n\tbasePath = filepath.ToSlash(basePath)\n\n\t// Make path relative to basePath for matching\n\trelPath, err := filepath.Rel(basePath, path)\n\tif err != nil {\n\t\tlogging.Error(\"Error getting relative path\", \"path\", path, \"basePath\", basePath, \"error\", err)\n\t\treturn false\n\t}\n\trelPath = filepath.ToSlash(relPath)\n\n\tisMatch := matchesGlob(patternText, relPath)\n\n\treturn isMatch\n}\n\n// debounceHandleFileEvent handles file events with debouncing to reduce notifications\nfunc (w *WorkspaceWatcher) debounceHandleFileEvent(ctx context.Context, uri string, changeType protocol.FileChangeType) {\n\tw.debounceMu.Lock()\n\tdefer w.debounceMu.Unlock()\n\n\t// Create a unique key based on URI and change type\n\tkey := fmt.Sprintf(\"%s:%d\", uri, changeType)\n\n\t// Cancel existing timer if any\n\tif timer, exists := w.debounceMap[key]; exists {\n\t\ttimer.Stop()\n\t}\n\n\t// Create new timer\n\tw.debounceMap[key] = time.AfterFunc(w.debounceTime, func() {\n\t\tw.handleFileEvent(ctx, uri, changeType)\n\n\t\t// Cleanup timer after execution\n\t\tw.debounceMu.Lock()\n\t\tdelete(w.debounceMap, key)\n\t\tw.debounceMu.Unlock()\n\t})\n}\n\n// handleFileEvent sends file change notifications\nfunc (w *WorkspaceWatcher) handleFileEvent(ctx context.Context, uri string, changeType protocol.FileChangeType) {\n\t// If the file is open and it's a change event, use didChange notification\n\tfilePath := uri[7:] // Remove \"file://\" prefix\n\tif changeType == protocol.FileChangeType(protocol.Deleted) {\n\t\tw.client.ClearDiagnosticsForURI(protocol.DocumentUri(uri))\n\t} else if changeType == protocol.FileChangeType(protocol.Changed) && w.client.IsFileOpen(filePath) {\n\t\terr := w.client.NotifyChange(ctx, filePath)\n\t\tif err != nil {\n\t\t\tlogging.Error(\"Error notifying change\", \"error\", err)\n\t\t}\n\t\treturn\n\t}\n\n\t// Notify LSP server about the file event using didChangeWatchedFiles\n\tif err := w.notifyFileEvent(ctx, uri, changeType); err != nil {\n\t\tlogging.Error(\"Error notifying LSP server about file event\", \"error\", err)\n\t}\n}\n\n// notifyFileEvent sends a didChangeWatchedFiles notification for a file event\nfunc (w *WorkspaceWatcher) notifyFileEvent(ctx context.Context, uri string, changeType protocol.FileChangeType) error {\n\tcnf := config.Get()\n\tif cnf.DebugLSP {\n\t\tlogging.Debug(\"Notifying file event\",\n\t\t\t\"uri\", uri,\n\t\t\t\"changeType\", changeType,\n\t\t)\n\t}\n\n\tparams := protocol.DidChangeWatchedFilesParams{\n\t\tChanges: []protocol.FileEvent{\n\t\t\t{\n\t\t\t\tURI: protocol.DocumentUri(uri),\n\t\t\t\tType: changeType,\n\t\t\t},\n\t\t},\n\t}\n\n\treturn w.client.DidChangeWatchedFiles(ctx, params)\n}\n\n// getServerNameFromContext extracts the server name from the context\n// This is a best-effort function that tries to identify which LSP server we're dealing with\nfunc getServerNameFromContext(ctx context.Context) string {\n\t// First check if the server name is directly stored in the context\n\tif serverName, ok := ctx.Value(\"serverName\").(string); ok && serverName != \"\" {\n\t\treturn strings.ToLower(serverName)\n\t}\n\n\t// Otherwise, try to extract server name from the client command path\n\tif w, ok := ctx.Value(\"workspaceWatcher\").(*WorkspaceWatcher); ok && w != nil && w.client != nil && w.client.Cmd != nil {\n\t\tpath := strings.ToLower(w.client.Cmd.Path)\n\n\t\t// Extract server name from path\n\t\tif strings.Contains(path, \"typescript\") || strings.Contains(path, \"tsserver\") || strings.Contains(path, \"vtsls\") {\n\t\t\treturn \"typescript\"\n\t\t} else if strings.Contains(path, \"gopls\") {\n\t\t\treturn \"gopls\"\n\t\t} else if strings.Contains(path, \"rust-analyzer\") {\n\t\t\treturn \"rust-analyzer\"\n\t\t} else if strings.Contains(path, \"pyright\") || strings.Contains(path, \"pylsp\") || strings.Contains(path, \"python\") {\n\t\t\treturn \"python\"\n\t\t} else if strings.Contains(path, \"clangd\") {\n\t\t\treturn \"clangd\"\n\t\t} else if strings.Contains(path, \"jdtls\") || strings.Contains(path, \"java\") {\n\t\t\treturn \"java\"\n\t\t}\n\n\t\t// Return the base name as fallback\n\t\treturn filepath.Base(path)\n\t}\n\n\treturn \"unknown\"\n}\n\n// shouldPreloadFiles determines if we should preload files for a specific language server\n// Some servers work better with preloaded files, others don't need it\nfunc shouldPreloadFiles(serverName string) bool {\n\t// TypeScript/JavaScript servers typically need some files preloaded\n\t// to properly resolve imports and provide intellisense\n\tswitch serverName {\n\tcase \"typescript\", \"typescript-language-server\", \"tsserver\", \"vtsls\":\n\t\treturn true\n\tcase \"java\", \"jdtls\":\n\t\t// Java servers often need to see source files to build the project model\n\t\treturn true\n\tdefault:\n\t\t// For most servers, we'll use lazy loading by default\n\t\treturn false\n\t}\n}\n\n// Common patterns for directories and files to exclude\n// TODO: make configurable\nvar (\n\texcludedDirNames = map[string]bool{\n\t\t\".git\": true,\n\t\t\"node_modules\": true,\n\t\t\"dist\": true,\n\t\t\"build\": true,\n\t\t\"out\": true,\n\t\t\"bin\": true,\n\t\t\".idea\": true,\n\t\t\".vscode\": true,\n\t\t\".cache\": true,\n\t\t\"coverage\": true,\n\t\t\"target\": true, // Rust build output\n\t\t\"vendor\": true, // Go vendor directory\n\t}\n\n\texcludedFileExtensions = map[string]bool{\n\t\t\".swp\": true,\n\t\t\".swo\": true,\n\t\t\".tmp\": true,\n\t\t\".temp\": true,\n\t\t\".bak\": true,\n\t\t\".log\": true,\n\t\t\".o\": true, // Object files\n\t\t\".so\": true, // Shared libraries\n\t\t\".dylib\": true, // macOS shared libraries\n\t\t\".dll\": true, // Windows shared libraries\n\t\t\".a\": true, // Static libraries\n\t\t\".exe\": true, // Windows executables\n\t\t\".lock\": true, // Lock files\n\t}\n\n\t// Large binary files that shouldn't be opened\n\tlargeBinaryExtensions = map[string]bool{\n\t\t\".png\": true,\n\t\t\".jpg\": true,\n\t\t\".jpeg\": true,\n\t\t\".gif\": true,\n\t\t\".bmp\": true,\n\t\t\".ico\": true,\n\t\t\".zip\": true,\n\t\t\".tar\": true,\n\t\t\".gz\": true,\n\t\t\".rar\": true,\n\t\t\".7z\": true,\n\t\t\".pdf\": true,\n\t\t\".mp3\": true,\n\t\t\".mp4\": true,\n\t\t\".mov\": true,\n\t\t\".wav\": true,\n\t\t\".wasm\": true,\n\t}\n\n\t// Maximum file size to open (5MB)\n\tmaxFileSize int64 = 5 * 1024 * 1024\n)\n\n// shouldExcludeDir returns true if the directory should be excluded from watching/opening\nfunc shouldExcludeDir(dirPath string) bool {\n\tdirName := filepath.Base(dirPath)\n\n\t// Skip dot directories\n\tif strings.HasPrefix(dirName, \".\") {\n\t\treturn true\n\t}\n\n\t// Skip common excluded directories\n\tif excludedDirNames[dirName] {\n\t\treturn true\n\t}\n\n\treturn false\n}\n\n// shouldExcludeFile returns true if the file should be excluded from opening\nfunc shouldExcludeFile(filePath string) bool {\n\tfileName := filepath.Base(filePath)\n\tcnf := config.Get()\n\t// Skip dot files\n\tif strings.HasPrefix(fileName, \".\") {\n\t\treturn true\n\t}\n\n\t// Check file extension\n\text := strings.ToLower(filepath.Ext(filePath))\n\tif excludedFileExtensions[ext] || largeBinaryExtensions[ext] {\n\t\treturn true\n\t}\n\n\t// Skip temporary files\n\tif strings.HasSuffix(filePath, \"~\") {\n\t\treturn true\n\t}\n\n\t// Check file size\n\tinfo, err := os.Stat(filePath)\n\tif err != nil {\n\t\t// If we can't stat the file, skip it\n\t\treturn true\n\t}\n\n\t// Skip large files\n\tif info.Size() > maxFileSize {\n\t\tif cnf.DebugLSP {\n\t\t\tlogging.Debug(\"Skipping large file\",\n\t\t\t\t\"path\", filePath,\n\t\t\t\t\"size\", info.Size(),\n\t\t\t\t\"maxSize\", maxFileSize,\n\t\t\t\t\"debug\", cnf.Debug,\n\t\t\t\t\"sizeMB\", float64(info.Size())/(1024*1024),\n\t\t\t\t\"maxSizeMB\", float64(maxFileSize)/(1024*1024),\n\t\t\t)\n\t\t}\n\t\treturn true\n\t}\n\n\treturn false\n}\n\n// openMatchingFile opens a file if it matches any of the registered patterns\nfunc (w *WorkspaceWatcher) openMatchingFile(ctx context.Context, path string) {\n\tcnf := config.Get()\n\t// Skip directories\n\tinfo, err := os.Stat(path)\n\tif err != nil || info.IsDir() {\n\t\treturn\n\t}\n\n\t// Skip excluded files\n\tif shouldExcludeFile(path) {\n\t\treturn\n\t}\n\n\t// Check if this path should be watched according to server registrations\n\tif watched, _ := w.isPathWatched(path); watched {\n\t\t// Get server name for specialized handling\n\t\tserverName := getServerNameFromContext(ctx)\n\n\t\t// Check if the file is a high-priority file that should be opened immediately\n\t\t// This helps with project initialization for certain language servers\n\t\tif isHighPriorityFile(path, serverName) {\n\t\t\tif cnf.DebugLSP {\n\t\t\t\tlogging.Debug(\"Opening high-priority file\", \"path\", path, \"serverName\", serverName)\n\t\t\t}\n\t\t\tif err := w.client.OpenFile(ctx, path); err != nil && cnf.DebugLSP {\n\t\t\t\tlogging.Error(\"Error opening high-priority file\", \"path\", path, \"error\", err)\n\t\t\t}\n\t\t\treturn\n\t\t}\n\n\t\t// For non-high-priority files, we'll use different strategies based on server type\n\t\tif shouldPreloadFiles(serverName) {\n\t\t\t// For servers that benefit from preloading, open files but with limits\n\n\t\t\t// Check file size - for preloading we're more conservative\n\t\t\tif info.Size() > (1 * 1024 * 1024) { // 1MB limit for preloaded files\n\t\t\t\tif cnf.DebugLSP {\n\t\t\t\t\tlogging.Debug(\"Skipping large file for preloading\", \"path\", path, \"size\", info.Size())\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\t// Check file extension for common source files\n\t\t\text := strings.ToLower(filepath.Ext(path))\n\n\t\t\t// Only preload source files for the specific language\n\t\t\tshouldOpen := false\n\n\t\t\tswitch serverName {\n\t\t\tcase \"typescript\", \"typescript-language-server\", \"tsserver\", \"vtsls\":\n\t\t\t\tshouldOpen = ext == \".ts\" || ext == \".js\" || ext == \".tsx\" || ext == \".jsx\"\n\t\t\tcase \"gopls\":\n\t\t\t\tshouldOpen = ext == \".go\"\n\t\t\tcase \"rust-analyzer\":\n\t\t\t\tshouldOpen = ext == \".rs\"\n\t\t\tcase \"python\", \"pyright\", \"pylsp\":\n\t\t\t\tshouldOpen = ext == \".py\"\n\t\t\tcase \"clangd\":\n\t\t\t\tshouldOpen = ext == \".c\" || ext == \".cpp\" || ext == \".h\" || ext == \".hpp\"\n\t\t\tcase \"java\", \"jdtls\":\n\t\t\t\tshouldOpen = ext == \".java\"\n\t\t\tdefault:\n\t\t\t\t// For unknown servers, be conservative\n\t\t\t\tshouldOpen = false\n\t\t\t}\n\n\t\t\tif shouldOpen {\n\t\t\t\t// Don't need to check if it's already open - the client.OpenFile handles that\n\t\t\t\tif err := w.client.OpenFile(ctx, path); err != nil && cnf.DebugLSP {\n\t\t\t\t\tlogging.Error(\"Error opening file\", \"path\", path, \"error\", err)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\n// isHighPriorityFile determines if a file should be opened immediately\n// regardless of the preloading strategy\nfunc isHighPriorityFile(path string, serverName string) bool {\n\tfileName := filepath.Base(path)\n\text := filepath.Ext(path)\n\n\tswitch serverName {\n\tcase \"typescript\", \"typescript-language-server\", \"tsserver\", \"vtsls\":\n\t\t// For TypeScript, we want to open configuration files immediately\n\t\treturn fileName == \"tsconfig.json\" ||\n\t\t\tfileName == \"package.json\" ||\n\t\t\tfileName == \"jsconfig.json\" ||\n\t\t\t// Also open main entry points\n\t\t\tfileName == \"index.ts\" ||\n\t\t\tfileName == \"index.js\" ||\n\t\t\tfileName == \"main.ts\" ||\n\t\t\tfileName == \"main.js\"\n\tcase \"gopls\":\n\t\t// For Go, we want to open go.mod files immediately\n\t\treturn fileName == \"go.mod\" ||\n\t\t\tfileName == \"go.sum\" ||\n\t\t\t// Also open main.go files\n\t\t\tfileName == \"main.go\"\n\tcase \"rust-analyzer\":\n\t\t// For Rust, we want to open Cargo.toml files immediately\n\t\treturn fileName == \"Cargo.toml\" ||\n\t\t\tfileName == \"Cargo.lock\" ||\n\t\t\t// Also open lib.rs and main.rs\n\t\t\tfileName == \"lib.rs\" ||\n\t\t\tfileName == \"main.rs\"\n\tcase \"python\", \"pyright\", \"pylsp\":\n\t\t// For Python, open key project files\n\t\treturn fileName == \"pyproject.toml\" ||\n\t\t\tfileName == \"setup.py\" ||\n\t\t\tfileName == \"requirements.txt\" ||\n\t\t\tfileName == \"__init__.py\" ||\n\t\t\tfileName == \"__main__.py\"\n\tcase \"clangd\":\n\t\t// For C/C++, open key project files\n\t\treturn fileName == \"CMakeLists.txt\" ||\n\t\t\tfileName == \"Makefile\" ||\n\t\t\tfileName == \"compile_commands.json\"\n\tcase \"java\", \"jdtls\":\n\t\t// For Java, open key project files\n\t\treturn fileName == \"pom.xml\" ||\n\t\t\tfileName == \"build.gradle\" ||\n\t\t\text == \".java\" // Java servers often need to see source files\n\t}\n\n\t// For unknown servers, prioritize common configuration files\n\treturn fileName == \"package.json\" ||\n\t\tfileName == \"Makefile\" ||\n\t\tfileName == \"CMakeLists.txt\" ||\n\t\tfileName == \".editorconfig\"\n}\n"], ["/opencode/internal/llm/agent/agent.go", "package agent\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/llm/models\"\n\t\"github.com/opencode-ai/opencode/internal/llm/prompt\"\n\t\"github.com/opencode-ai/opencode/internal/llm/provider\"\n\t\"github.com/opencode-ai/opencode/internal/llm/tools\"\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n\t\"github.com/opencode-ai/opencode/internal/message\"\n\t\"github.com/opencode-ai/opencode/internal/permission\"\n\t\"github.com/opencode-ai/opencode/internal/pubsub\"\n\t\"github.com/opencode-ai/opencode/internal/session\"\n)\n\n// Common errors\nvar (\n\tErrRequestCancelled = errors.New(\"request cancelled by user\")\n\tErrSessionBusy = errors.New(\"session is currently processing another request\")\n)\n\ntype AgentEventType string\n\nconst (\n\tAgentEventTypeError AgentEventType = \"error\"\n\tAgentEventTypeResponse AgentEventType = \"response\"\n\tAgentEventTypeSummarize AgentEventType = \"summarize\"\n)\n\ntype AgentEvent struct {\n\tType AgentEventType\n\tMessage message.Message\n\tError error\n\n\t// When summarizing\n\tSessionID string\n\tProgress string\n\tDone bool\n}\n\ntype Service interface {\n\tpubsub.Suscriber[AgentEvent]\n\tModel() models.Model\n\tRun(ctx context.Context, sessionID string, content string, attachments ...message.Attachment) (<-chan AgentEvent, error)\n\tCancel(sessionID string)\n\tIsSessionBusy(sessionID string) bool\n\tIsBusy() bool\n\tUpdate(agentName config.AgentName, modelID models.ModelID) (models.Model, error)\n\tSummarize(ctx context.Context, sessionID string) error\n}\n\ntype agent struct {\n\t*pubsub.Broker[AgentEvent]\n\tsessions session.Service\n\tmessages message.Service\n\n\ttools []tools.BaseTool\n\tprovider provider.Provider\n\n\ttitleProvider provider.Provider\n\tsummarizeProvider provider.Provider\n\n\tactiveRequests sync.Map\n}\n\nfunc NewAgent(\n\tagentName config.AgentName,\n\tsessions session.Service,\n\tmessages message.Service,\n\tagentTools []tools.BaseTool,\n) (Service, error) {\n\tagentProvider, err := createAgentProvider(agentName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar titleProvider provider.Provider\n\t// Only generate titles for the coder agent\n\tif agentName == config.AgentCoder {\n\t\ttitleProvider, err = createAgentProvider(config.AgentTitle)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tvar summarizeProvider provider.Provider\n\tif agentName == config.AgentCoder {\n\t\tsummarizeProvider, err = createAgentProvider(config.AgentSummarizer)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tagent := &agent{\n\t\tBroker: pubsub.NewBroker[AgentEvent](),\n\t\tprovider: agentProvider,\n\t\tmessages: messages,\n\t\tsessions: sessions,\n\t\ttools: agentTools,\n\t\ttitleProvider: titleProvider,\n\t\tsummarizeProvider: summarizeProvider,\n\t\tactiveRequests: sync.Map{},\n\t}\n\n\treturn agent, nil\n}\n\nfunc (a *agent) Model() models.Model {\n\treturn a.provider.Model()\n}\n\nfunc (a *agent) Cancel(sessionID string) {\n\t// Cancel regular requests\n\tif cancelFunc, exists := a.activeRequests.LoadAndDelete(sessionID); exists {\n\t\tif cancel, ok := cancelFunc.(context.CancelFunc); ok {\n\t\t\tlogging.InfoPersist(fmt.Sprintf(\"Request cancellation initiated for session: %s\", sessionID))\n\t\t\tcancel()\n\t\t}\n\t}\n\n\t// Also check for summarize requests\n\tif cancelFunc, exists := a.activeRequests.LoadAndDelete(sessionID + \"-summarize\"); exists {\n\t\tif cancel, ok := cancelFunc.(context.CancelFunc); ok {\n\t\t\tlogging.InfoPersist(fmt.Sprintf(\"Summarize cancellation initiated for session: %s\", sessionID))\n\t\t\tcancel()\n\t\t}\n\t}\n}\n\nfunc (a *agent) IsBusy() bool {\n\tbusy := false\n\ta.activeRequests.Range(func(key, value interface{}) bool {\n\t\tif cancelFunc, ok := value.(context.CancelFunc); ok {\n\t\t\tif cancelFunc != nil {\n\t\t\t\tbusy = true\n\t\t\t\treturn false // Stop iterating\n\t\t\t}\n\t\t}\n\t\treturn true // Continue iterating\n\t})\n\treturn busy\n}\n\nfunc (a *agent) IsSessionBusy(sessionID string) bool {\n\t_, busy := a.activeRequests.Load(sessionID)\n\treturn busy\n}\n\nfunc (a *agent) generateTitle(ctx context.Context, sessionID string, content string) error {\n\tif content == \"\" {\n\t\treturn nil\n\t}\n\tif a.titleProvider == nil {\n\t\treturn nil\n\t}\n\tsession, err := a.sessions.Get(ctx, sessionID)\n\tif err != nil {\n\t\treturn err\n\t}\n\tctx = context.WithValue(ctx, tools.SessionIDContextKey, sessionID)\n\tparts := []message.ContentPart{message.TextContent{Text: content}}\n\tresponse, err := a.titleProvider.SendMessages(\n\t\tctx,\n\t\t[]message.Message{\n\t\t\t{\n\t\t\t\tRole: message.User,\n\t\t\t\tParts: parts,\n\t\t\t},\n\t\t},\n\t\tmake([]tools.BaseTool, 0),\n\t)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ttitle := strings.TrimSpace(strings.ReplaceAll(response.Content, \"\\n\", \" \"))\n\tif title == \"\" {\n\t\treturn nil\n\t}\n\n\tsession.Title = title\n\t_, err = a.sessions.Save(ctx, session)\n\treturn err\n}\n\nfunc (a *agent) err(err error) AgentEvent {\n\treturn AgentEvent{\n\t\tType: AgentEventTypeError,\n\t\tError: err,\n\t}\n}\n\nfunc (a *agent) Run(ctx context.Context, sessionID string, content string, attachments ...message.Attachment) (<-chan AgentEvent, error) {\n\tif !a.provider.Model().SupportsAttachments && attachments != nil {\n\t\tattachments = nil\n\t}\n\tevents := make(chan AgentEvent)\n\tif a.IsSessionBusy(sessionID) {\n\t\treturn nil, ErrSessionBusy\n\t}\n\n\tgenCtx, cancel := context.WithCancel(ctx)\n\n\ta.activeRequests.Store(sessionID, cancel)\n\tgo func() {\n\t\tlogging.Debug(\"Request started\", \"sessionID\", sessionID)\n\t\tdefer logging.RecoverPanic(\"agent.Run\", func() {\n\t\t\tevents <- a.err(fmt.Errorf(\"panic while running the agent\"))\n\t\t})\n\t\tvar attachmentParts []message.ContentPart\n\t\tfor _, attachment := range attachments {\n\t\t\tattachmentParts = append(attachmentParts, message.BinaryContent{Path: attachment.FilePath, MIMEType: attachment.MimeType, Data: attachment.Content})\n\t\t}\n\t\tresult := a.processGeneration(genCtx, sessionID, content, attachmentParts)\n\t\tif result.Error != nil && !errors.Is(result.Error, ErrRequestCancelled) && !errors.Is(result.Error, context.Canceled) {\n\t\t\tlogging.ErrorPersist(result.Error.Error())\n\t\t}\n\t\tlogging.Debug(\"Request completed\", \"sessionID\", sessionID)\n\t\ta.activeRequests.Delete(sessionID)\n\t\tcancel()\n\t\ta.Publish(pubsub.CreatedEvent, result)\n\t\tevents <- result\n\t\tclose(events)\n\t}()\n\treturn events, nil\n}\n\nfunc (a *agent) processGeneration(ctx context.Context, sessionID, content string, attachmentParts []message.ContentPart) AgentEvent {\n\tcfg := config.Get()\n\t// List existing messages; if none, start title generation asynchronously.\n\tmsgs, err := a.messages.List(ctx, sessionID)\n\tif err != nil {\n\t\treturn a.err(fmt.Errorf(\"failed to list messages: %w\", err))\n\t}\n\tif len(msgs) == 0 {\n\t\tgo func() {\n\t\t\tdefer logging.RecoverPanic(\"agent.Run\", func() {\n\t\t\t\tlogging.ErrorPersist(\"panic while generating title\")\n\t\t\t})\n\t\t\ttitleErr := a.generateTitle(context.Background(), sessionID, content)\n\t\t\tif titleErr != nil {\n\t\t\t\tlogging.ErrorPersist(fmt.Sprintf(\"failed to generate title: %v\", titleErr))\n\t\t\t}\n\t\t}()\n\t}\n\tsession, err := a.sessions.Get(ctx, sessionID)\n\tif err != nil {\n\t\treturn a.err(fmt.Errorf(\"failed to get session: %w\", err))\n\t}\n\tif session.SummaryMessageID != \"\" {\n\t\tsummaryMsgInex := -1\n\t\tfor i, msg := range msgs {\n\t\t\tif msg.ID == session.SummaryMessageID {\n\t\t\t\tsummaryMsgInex = i\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif summaryMsgInex != -1 {\n\t\t\tmsgs = msgs[summaryMsgInex:]\n\t\t\tmsgs[0].Role = message.User\n\t\t}\n\t}\n\n\tuserMsg, err := a.createUserMessage(ctx, sessionID, content, attachmentParts)\n\tif err != nil {\n\t\treturn a.err(fmt.Errorf(\"failed to create user message: %w\", err))\n\t}\n\t// Append the new user message to the conversation history.\n\tmsgHistory := append(msgs, userMsg)\n\n\tfor {\n\t\t// Check for cancellation before each iteration\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn a.err(ctx.Err())\n\t\tdefault:\n\t\t\t// Continue processing\n\t\t}\n\t\tagentMessage, toolResults, err := a.streamAndHandleEvents(ctx, sessionID, msgHistory)\n\t\tif err != nil {\n\t\t\tif errors.Is(err, context.Canceled) {\n\t\t\t\tagentMessage.AddFinish(message.FinishReasonCanceled)\n\t\t\t\ta.messages.Update(context.Background(), agentMessage)\n\t\t\t\treturn a.err(ErrRequestCancelled)\n\t\t\t}\n\t\t\treturn a.err(fmt.Errorf(\"failed to process events: %w\", err))\n\t\t}\n\t\tif cfg.Debug {\n\t\t\tseqId := (len(msgHistory) + 1) / 2\n\t\t\ttoolResultFilepath := logging.WriteToolResultsJson(sessionID, seqId, toolResults)\n\t\t\tlogging.Info(\"Result\", \"message\", agentMessage.FinishReason(), \"toolResults\", \"{}\", \"filepath\", toolResultFilepath)\n\t\t} else {\n\t\t\tlogging.Info(\"Result\", \"message\", agentMessage.FinishReason(), \"toolResults\", toolResults)\n\t\t}\n\t\tif (agentMessage.FinishReason() == message.FinishReasonToolUse) && toolResults != nil {\n\t\t\t// We are not done, we need to respond with the tool response\n\t\t\tmsgHistory = append(msgHistory, agentMessage, *toolResults)\n\t\t\tcontinue\n\t\t}\n\t\treturn AgentEvent{\n\t\t\tType: AgentEventTypeResponse,\n\t\t\tMessage: agentMessage,\n\t\t\tDone: true,\n\t\t}\n\t}\n}\n\nfunc (a *agent) createUserMessage(ctx context.Context, sessionID, content string, attachmentParts []message.ContentPart) (message.Message, error) {\n\tparts := []message.ContentPart{message.TextContent{Text: content}}\n\tparts = append(parts, attachmentParts...)\n\treturn a.messages.Create(ctx, sessionID, message.CreateMessageParams{\n\t\tRole: message.User,\n\t\tParts: parts,\n\t})\n}\n\nfunc (a *agent) streamAndHandleEvents(ctx context.Context, sessionID string, msgHistory []message.Message) (message.Message, *message.Message, error) {\n\tctx = context.WithValue(ctx, tools.SessionIDContextKey, sessionID)\n\teventChan := a.provider.StreamResponse(ctx, msgHistory, a.tools)\n\n\tassistantMsg, err := a.messages.Create(ctx, sessionID, message.CreateMessageParams{\n\t\tRole: message.Assistant,\n\t\tParts: []message.ContentPart{},\n\t\tModel: a.provider.Model().ID,\n\t})\n\tif err != nil {\n\t\treturn assistantMsg, nil, fmt.Errorf(\"failed to create assistant message: %w\", err)\n\t}\n\n\t// Add the session and message ID into the context if needed by tools.\n\tctx = context.WithValue(ctx, tools.MessageIDContextKey, assistantMsg.ID)\n\n\t// Process each event in the stream.\n\tfor event := range eventChan {\n\t\tif processErr := a.processEvent(ctx, sessionID, &assistantMsg, event); processErr != nil {\n\t\t\ta.finishMessage(ctx, &assistantMsg, message.FinishReasonCanceled)\n\t\t\treturn assistantMsg, nil, processErr\n\t\t}\n\t\tif ctx.Err() != nil {\n\t\t\ta.finishMessage(context.Background(), &assistantMsg, message.FinishReasonCanceled)\n\t\t\treturn assistantMsg, nil, ctx.Err()\n\t\t}\n\t}\n\n\ttoolResults := make([]message.ToolResult, len(assistantMsg.ToolCalls()))\n\ttoolCalls := assistantMsg.ToolCalls()\n\tfor i, toolCall := range toolCalls {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\ta.finishMessage(context.Background(), &assistantMsg, message.FinishReasonCanceled)\n\t\t\t// Make all future tool calls cancelled\n\t\t\tfor j := i; j < len(toolCalls); j++ {\n\t\t\t\ttoolResults[j] = message.ToolResult{\n\t\t\t\t\tToolCallID: toolCalls[j].ID,\n\t\t\t\t\tContent: \"Tool execution canceled by user\",\n\t\t\t\t\tIsError: true,\n\t\t\t\t}\n\t\t\t}\n\t\t\tgoto out\n\t\tdefault:\n\t\t\t// Continue processing\n\t\t\tvar tool tools.BaseTool\n\t\t\tfor _, availableTool := range a.tools {\n\t\t\t\tif availableTool.Info().Name == toolCall.Name {\n\t\t\t\t\ttool = availableTool\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\t// Monkey patch for Copilot Sonnet-4 tool repetition obfuscation\n\t\t\t\t// if strings.HasPrefix(toolCall.Name, availableTool.Info().Name) &&\n\t\t\t\t// \tstrings.HasPrefix(toolCall.Name, availableTool.Info().Name+availableTool.Info().Name) {\n\t\t\t\t// \ttool = availableTool\n\t\t\t\t// \tbreak\n\t\t\t\t// }\n\t\t\t}\n\n\t\t\t// Tool not found\n\t\t\tif tool == nil {\n\t\t\t\ttoolResults[i] = message.ToolResult{\n\t\t\t\t\tToolCallID: toolCall.ID,\n\t\t\t\t\tContent: fmt.Sprintf(\"Tool not found: %s\", toolCall.Name),\n\t\t\t\t\tIsError: true,\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\ttoolResult, toolErr := tool.Run(ctx, tools.ToolCall{\n\t\t\t\tID: toolCall.ID,\n\t\t\t\tName: toolCall.Name,\n\t\t\t\tInput: toolCall.Input,\n\t\t\t})\n\t\t\tif toolErr != nil {\n\t\t\t\tif errors.Is(toolErr, permission.ErrorPermissionDenied) {\n\t\t\t\t\ttoolResults[i] = message.ToolResult{\n\t\t\t\t\t\tToolCallID: toolCall.ID,\n\t\t\t\t\t\tContent: \"Permission denied\",\n\t\t\t\t\t\tIsError: true,\n\t\t\t\t\t}\n\t\t\t\t\tfor j := i + 1; j < len(toolCalls); j++ {\n\t\t\t\t\t\ttoolResults[j] = message.ToolResult{\n\t\t\t\t\t\t\tToolCallID: toolCalls[j].ID,\n\t\t\t\t\t\t\tContent: \"Tool execution canceled by user\",\n\t\t\t\t\t\t\tIsError: true,\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\ta.finishMessage(ctx, &assistantMsg, message.FinishReasonPermissionDenied)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\ttoolResults[i] = message.ToolResult{\n\t\t\t\tToolCallID: toolCall.ID,\n\t\t\t\tContent: toolResult.Content,\n\t\t\t\tMetadata: toolResult.Metadata,\n\t\t\t\tIsError: toolResult.IsError,\n\t\t\t}\n\t\t}\n\t}\nout:\n\tif len(toolResults) == 0 {\n\t\treturn assistantMsg, nil, nil\n\t}\n\tparts := make([]message.ContentPart, 0)\n\tfor _, tr := range toolResults {\n\t\tparts = append(parts, tr)\n\t}\n\tmsg, err := a.messages.Create(context.Background(), assistantMsg.SessionID, message.CreateMessageParams{\n\t\tRole: message.Tool,\n\t\tParts: parts,\n\t})\n\tif err != nil {\n\t\treturn assistantMsg, nil, fmt.Errorf(\"failed to create cancelled tool message: %w\", err)\n\t}\n\n\treturn assistantMsg, &msg, err\n}\n\nfunc (a *agent) finishMessage(ctx context.Context, msg *message.Message, finishReson message.FinishReason) {\n\tmsg.AddFinish(finishReson)\n\t_ = a.messages.Update(ctx, *msg)\n}\n\nfunc (a *agent) processEvent(ctx context.Context, sessionID string, assistantMsg *message.Message, event provider.ProviderEvent) error {\n\tselect {\n\tcase <-ctx.Done():\n\t\treturn ctx.Err()\n\tdefault:\n\t\t// Continue processing.\n\t}\n\n\tswitch event.Type {\n\tcase provider.EventThinkingDelta:\n\t\tassistantMsg.AppendReasoningContent(event.Content)\n\t\treturn a.messages.Update(ctx, *assistantMsg)\n\tcase provider.EventContentDelta:\n\t\tassistantMsg.AppendContent(event.Content)\n\t\treturn a.messages.Update(ctx, *assistantMsg)\n\tcase provider.EventToolUseStart:\n\t\tassistantMsg.AddToolCall(*event.ToolCall)\n\t\treturn a.messages.Update(ctx, *assistantMsg)\n\t// TODO: see how to handle this\n\t// case provider.EventToolUseDelta:\n\t// \ttm := time.Unix(assistantMsg.UpdatedAt, 0)\n\t// \tassistantMsg.AppendToolCallInput(event.ToolCall.ID, event.ToolCall.Input)\n\t// \tif time.Since(tm) > 1000*time.Millisecond {\n\t// \t\terr := a.messages.Update(ctx, *assistantMsg)\n\t// \t\tassistantMsg.UpdatedAt = time.Now().Unix()\n\t// \t\treturn err\n\t// \t}\n\tcase provider.EventToolUseStop:\n\t\tassistantMsg.FinishToolCall(event.ToolCall.ID)\n\t\treturn a.messages.Update(ctx, *assistantMsg)\n\tcase provider.EventError:\n\t\tif errors.Is(event.Error, context.Canceled) {\n\t\t\tlogging.InfoPersist(fmt.Sprintf(\"Event processing canceled for session: %s\", sessionID))\n\t\t\treturn context.Canceled\n\t\t}\n\t\tlogging.ErrorPersist(event.Error.Error())\n\t\treturn event.Error\n\tcase provider.EventComplete:\n\t\tassistantMsg.SetToolCalls(event.Response.ToolCalls)\n\t\tassistantMsg.AddFinish(event.Response.FinishReason)\n\t\tif err := a.messages.Update(ctx, *assistantMsg); err != nil {\n\t\t\treturn fmt.Errorf(\"failed to update message: %w\", err)\n\t\t}\n\t\treturn a.TrackUsage(ctx, sessionID, a.provider.Model(), event.Response.Usage)\n\t}\n\n\treturn nil\n}\n\nfunc (a *agent) TrackUsage(ctx context.Context, sessionID string, model models.Model, usage provider.TokenUsage) error {\n\tsess, err := a.sessions.Get(ctx, sessionID)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to get session: %w\", err)\n\t}\n\n\tcost := model.CostPer1MInCached/1e6*float64(usage.CacheCreationTokens) +\n\t\tmodel.CostPer1MOutCached/1e6*float64(usage.CacheReadTokens) +\n\t\tmodel.CostPer1MIn/1e6*float64(usage.InputTokens) +\n\t\tmodel.CostPer1MOut/1e6*float64(usage.OutputTokens)\n\n\tsess.Cost += cost\n\tsess.CompletionTokens = usage.OutputTokens + usage.CacheReadTokens\n\tsess.PromptTokens = usage.InputTokens + usage.CacheCreationTokens\n\n\t_, err = a.sessions.Save(ctx, sess)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to save session: %w\", err)\n\t}\n\treturn nil\n}\n\nfunc (a *agent) Update(agentName config.AgentName, modelID models.ModelID) (models.Model, error) {\n\tif a.IsBusy() {\n\t\treturn models.Model{}, fmt.Errorf(\"cannot change model while processing requests\")\n\t}\n\n\tif err := config.UpdateAgentModel(agentName, modelID); err != nil {\n\t\treturn models.Model{}, fmt.Errorf(\"failed to update config: %w\", err)\n\t}\n\n\tprovider, err := createAgentProvider(agentName)\n\tif err != nil {\n\t\treturn models.Model{}, fmt.Errorf(\"failed to create provider for model %s: %w\", modelID, err)\n\t}\n\n\ta.provider = provider\n\n\treturn a.provider.Model(), nil\n}\n\nfunc (a *agent) Summarize(ctx context.Context, sessionID string) error {\n\tif a.summarizeProvider == nil {\n\t\treturn fmt.Errorf(\"summarize provider not available\")\n\t}\n\n\t// Check if session is busy\n\tif a.IsSessionBusy(sessionID) {\n\t\treturn ErrSessionBusy\n\t}\n\n\t// Create a new context with cancellation\n\tsummarizeCtx, cancel := context.WithCancel(ctx)\n\n\t// Store the cancel function in activeRequests to allow cancellation\n\ta.activeRequests.Store(sessionID+\"-summarize\", cancel)\n\n\tgo func() {\n\t\tdefer a.activeRequests.Delete(sessionID + \"-summarize\")\n\t\tdefer cancel()\n\t\tevent := AgentEvent{\n\t\t\tType: AgentEventTypeSummarize,\n\t\t\tProgress: \"Starting summarization...\",\n\t\t}\n\n\t\ta.Publish(pubsub.CreatedEvent, event)\n\t\t// Get all messages from the session\n\t\tmsgs, err := a.messages.List(summarizeCtx, sessionID)\n\t\tif err != nil {\n\t\t\tevent = AgentEvent{\n\t\t\t\tType: AgentEventTypeError,\n\t\t\t\tError: fmt.Errorf(\"failed to list messages: %w\", err),\n\t\t\t\tDone: true,\n\t\t\t}\n\t\t\ta.Publish(pubsub.CreatedEvent, event)\n\t\t\treturn\n\t\t}\n\t\tsummarizeCtx = context.WithValue(summarizeCtx, tools.SessionIDContextKey, sessionID)\n\n\t\tif len(msgs) == 0 {\n\t\t\tevent = AgentEvent{\n\t\t\t\tType: AgentEventTypeError,\n\t\t\t\tError: fmt.Errorf(\"no messages to summarize\"),\n\t\t\t\tDone: true,\n\t\t\t}\n\t\t\ta.Publish(pubsub.CreatedEvent, event)\n\t\t\treturn\n\t\t}\n\n\t\tevent = AgentEvent{\n\t\t\tType: AgentEventTypeSummarize,\n\t\t\tProgress: \"Analyzing conversation...\",\n\t\t}\n\t\ta.Publish(pubsub.CreatedEvent, event)\n\n\t\t// Add a system message to guide the summarization\n\t\tsummarizePrompt := \"Provide a detailed but concise summary of our conversation above. Focus on information that would be helpful for continuing the conversation, including what we did, what we're doing, which files we're working on, and what we're going to do next.\"\n\n\t\t// Create a new message with the summarize prompt\n\t\tpromptMsg := message.Message{\n\t\t\tRole: message.User,\n\t\t\tParts: []message.ContentPart{message.TextContent{Text: summarizePrompt}},\n\t\t}\n\n\t\t// Append the prompt to the messages\n\t\tmsgsWithPrompt := append(msgs, promptMsg)\n\n\t\tevent = AgentEvent{\n\t\t\tType: AgentEventTypeSummarize,\n\t\t\tProgress: \"Generating summary...\",\n\t\t}\n\n\t\ta.Publish(pubsub.CreatedEvent, event)\n\n\t\t// Send the messages to the summarize provider\n\t\tresponse, err := a.summarizeProvider.SendMessages(\n\t\t\tsummarizeCtx,\n\t\t\tmsgsWithPrompt,\n\t\t\tmake([]tools.BaseTool, 0),\n\t\t)\n\t\tif err != nil {\n\t\t\tevent = AgentEvent{\n\t\t\t\tType: AgentEventTypeError,\n\t\t\t\tError: fmt.Errorf(\"failed to summarize: %w\", err),\n\t\t\t\tDone: true,\n\t\t\t}\n\t\t\ta.Publish(pubsub.CreatedEvent, event)\n\t\t\treturn\n\t\t}\n\n\t\tsummary := strings.TrimSpace(response.Content)\n\t\tif summary == \"\" {\n\t\t\tevent = AgentEvent{\n\t\t\t\tType: AgentEventTypeError,\n\t\t\t\tError: fmt.Errorf(\"empty summary returned\"),\n\t\t\t\tDone: true,\n\t\t\t}\n\t\t\ta.Publish(pubsub.CreatedEvent, event)\n\t\t\treturn\n\t\t}\n\t\tevent = AgentEvent{\n\t\t\tType: AgentEventTypeSummarize,\n\t\t\tProgress: \"Creating new session...\",\n\t\t}\n\n\t\ta.Publish(pubsub.CreatedEvent, event)\n\t\toldSession, err := a.sessions.Get(summarizeCtx, sessionID)\n\t\tif err != nil {\n\t\t\tevent = AgentEvent{\n\t\t\t\tType: AgentEventTypeError,\n\t\t\t\tError: fmt.Errorf(\"failed to get session: %w\", err),\n\t\t\t\tDone: true,\n\t\t\t}\n\n\t\t\ta.Publish(pubsub.CreatedEvent, event)\n\t\t\treturn\n\t\t}\n\t\t// Create a message in the new session with the summary\n\t\tmsg, err := a.messages.Create(summarizeCtx, oldSession.ID, message.CreateMessageParams{\n\t\t\tRole: message.Assistant,\n\t\t\tParts: []message.ContentPart{\n\t\t\t\tmessage.TextContent{Text: summary},\n\t\t\t\tmessage.Finish{\n\t\t\t\t\tReason: message.FinishReasonEndTurn,\n\t\t\t\t\tTime: time.Now().Unix(),\n\t\t\t\t},\n\t\t\t},\n\t\t\tModel: a.summarizeProvider.Model().ID,\n\t\t})\n\t\tif err != nil {\n\t\t\tevent = AgentEvent{\n\t\t\t\tType: AgentEventTypeError,\n\t\t\t\tError: fmt.Errorf(\"failed to create summary message: %w\", err),\n\t\t\t\tDone: true,\n\t\t\t}\n\n\t\t\ta.Publish(pubsub.CreatedEvent, event)\n\t\t\treturn\n\t\t}\n\t\toldSession.SummaryMessageID = msg.ID\n\t\toldSession.CompletionTokens = response.Usage.OutputTokens\n\t\toldSession.PromptTokens = 0\n\t\tmodel := a.summarizeProvider.Model()\n\t\tusage := response.Usage\n\t\tcost := model.CostPer1MInCached/1e6*float64(usage.CacheCreationTokens) +\n\t\t\tmodel.CostPer1MOutCached/1e6*float64(usage.CacheReadTokens) +\n\t\t\tmodel.CostPer1MIn/1e6*float64(usage.InputTokens) +\n\t\t\tmodel.CostPer1MOut/1e6*float64(usage.OutputTokens)\n\t\toldSession.Cost += cost\n\t\t_, err = a.sessions.Save(summarizeCtx, oldSession)\n\t\tif err != nil {\n\t\t\tevent = AgentEvent{\n\t\t\t\tType: AgentEventTypeError,\n\t\t\t\tError: fmt.Errorf(\"failed to save session: %w\", err),\n\t\t\t\tDone: true,\n\t\t\t}\n\t\t\ta.Publish(pubsub.CreatedEvent, event)\n\t\t}\n\n\t\tevent = AgentEvent{\n\t\t\tType: AgentEventTypeSummarize,\n\t\t\tSessionID: oldSession.ID,\n\t\t\tProgress: \"Summary complete\",\n\t\t\tDone: true,\n\t\t}\n\t\ta.Publish(pubsub.CreatedEvent, event)\n\t\t// Send final success event with the new session ID\n\t}()\n\n\treturn nil\n}\n\nfunc createAgentProvider(agentName config.AgentName) (provider.Provider, error) {\n\tcfg := config.Get()\n\tagentConfig, ok := cfg.Agents[agentName]\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"agent %s not found\", agentName)\n\t}\n\tmodel, ok := models.SupportedModels[agentConfig.Model]\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"model %s not supported\", agentConfig.Model)\n\t}\n\n\tproviderCfg, ok := cfg.Providers[model.Provider]\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"provider %s not supported\", model.Provider)\n\t}\n\tif providerCfg.Disabled {\n\t\treturn nil, fmt.Errorf(\"provider %s is not enabled\", model.Provider)\n\t}\n\tmaxTokens := model.DefaultMaxTokens\n\tif agentConfig.MaxTokens > 0 {\n\t\tmaxTokens = agentConfig.MaxTokens\n\t}\n\topts := []provider.ProviderClientOption{\n\t\tprovider.WithAPIKey(providerCfg.APIKey),\n\t\tprovider.WithModel(model),\n\t\tprovider.WithSystemMessage(prompt.GetAgentPrompt(agentName, model.Provider)),\n\t\tprovider.WithMaxTokens(maxTokens),\n\t}\n\tif model.Provider == models.ProviderOpenAI || model.Provider == models.ProviderLocal && model.CanReason {\n\t\topts = append(\n\t\t\topts,\n\t\t\tprovider.WithOpenAIOptions(\n\t\t\t\tprovider.WithReasoningEffort(agentConfig.ReasoningEffort),\n\t\t\t),\n\t\t)\n\t} else if model.Provider == models.ProviderAnthropic && model.CanReason && agentName == config.AgentCoder {\n\t\topts = append(\n\t\t\topts,\n\t\t\tprovider.WithAnthropicOptions(\n\t\t\t\tprovider.WithAnthropicShouldThinkFn(provider.DefaultShouldThinkFn),\n\t\t\t),\n\t\t)\n\t}\n\tagentProvider, err := provider.NewProvider(\n\t\tmodel.Provider,\n\t\topts...,\n\t)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"could not create provider: %v\", err)\n\t}\n\n\treturn agentProvider, nil\n}\n"], ["/opencode/internal/lsp/util/edit.go", "package util\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"os\"\n\t\"sort\"\n\t\"strings\"\n\n\t\"github.com/opencode-ai/opencode/internal/lsp/protocol\"\n)\n\nfunc applyTextEdits(uri protocol.DocumentUri, edits []protocol.TextEdit) error {\n\tpath := strings.TrimPrefix(string(uri), \"file://\")\n\n\t// Read the file content\n\tcontent, err := os.ReadFile(path)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to read file: %w\", err)\n\t}\n\n\t// Detect line ending style\n\tvar lineEnding string\n\tif bytes.Contains(content, []byte(\"\\r\\n\")) {\n\t\tlineEnding = \"\\r\\n\"\n\t} else {\n\t\tlineEnding = \"\\n\"\n\t}\n\n\t// Track if file ends with a newline\n\tendsWithNewline := len(content) > 0 && bytes.HasSuffix(content, []byte(lineEnding))\n\n\t// Split into lines without the endings\n\tlines := strings.Split(string(content), lineEnding)\n\n\t// Check for overlapping edits\n\tfor i, edit1 := range edits {\n\t\tfor j := i + 1; j < len(edits); j++ {\n\t\t\tif rangesOverlap(edit1.Range, edits[j].Range) {\n\t\t\t\treturn fmt.Errorf(\"overlapping edits detected between edit %d and %d\", i, j)\n\t\t\t}\n\t\t}\n\t}\n\n\t// Sort edits in reverse order\n\tsortedEdits := make([]protocol.TextEdit, len(edits))\n\tcopy(sortedEdits, edits)\n\tsort.Slice(sortedEdits, func(i, j int) bool {\n\t\tif sortedEdits[i].Range.Start.Line != sortedEdits[j].Range.Start.Line {\n\t\t\treturn sortedEdits[i].Range.Start.Line > sortedEdits[j].Range.Start.Line\n\t\t}\n\t\treturn sortedEdits[i].Range.Start.Character > sortedEdits[j].Range.Start.Character\n\t})\n\n\t// Apply each edit\n\tfor _, edit := range sortedEdits {\n\t\tnewLines, err := applyTextEdit(lines, edit)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to apply edit: %w\", err)\n\t\t}\n\t\tlines = newLines\n\t}\n\n\t// Join lines with proper line endings\n\tvar newContent strings.Builder\n\tfor i, line := range lines {\n\t\tif i > 0 {\n\t\t\tnewContent.WriteString(lineEnding)\n\t\t}\n\t\tnewContent.WriteString(line)\n\t}\n\n\t// Only add a newline if the original file had one and we haven't already added it\n\tif endsWithNewline && !strings.HasSuffix(newContent.String(), lineEnding) {\n\t\tnewContent.WriteString(lineEnding)\n\t}\n\n\tif err := os.WriteFile(path, []byte(newContent.String()), 0o644); err != nil {\n\t\treturn fmt.Errorf(\"failed to write file: %w\", err)\n\t}\n\n\treturn nil\n}\n\nfunc applyTextEdit(lines []string, edit protocol.TextEdit) ([]string, error) {\n\tstartLine := int(edit.Range.Start.Line)\n\tendLine := int(edit.Range.End.Line)\n\tstartChar := int(edit.Range.Start.Character)\n\tendChar := int(edit.Range.End.Character)\n\n\t// Validate positions\n\tif startLine < 0 || startLine >= len(lines) {\n\t\treturn nil, fmt.Errorf(\"invalid start line: %d\", startLine)\n\t}\n\tif endLine < 0 || endLine >= len(lines) {\n\t\tendLine = len(lines) - 1\n\t}\n\n\t// Create result slice with initial capacity\n\tresult := make([]string, 0, len(lines))\n\n\t// Copy lines before edit\n\tresult = append(result, lines[:startLine]...)\n\n\t// Get the prefix of the start line\n\tstartLineContent := lines[startLine]\n\tif startChar < 0 || startChar > len(startLineContent) {\n\t\tstartChar = len(startLineContent)\n\t}\n\tprefix := startLineContent[:startChar]\n\n\t// Get the suffix of the end line\n\tendLineContent := lines[endLine]\n\tif endChar < 0 || endChar > len(endLineContent) {\n\t\tendChar = len(endLineContent)\n\t}\n\tsuffix := endLineContent[endChar:]\n\n\t// Handle the edit\n\tif edit.NewText == \"\" {\n\t\tif prefix+suffix != \"\" {\n\t\t\tresult = append(result, prefix+suffix)\n\t\t}\n\t} else {\n\t\t// Split new text into lines, being careful not to add extra newlines\n\t\t// newLines := strings.Split(strings.TrimRight(edit.NewText, \"\\n\"), \"\\n\")\n\t\tnewLines := strings.Split(edit.NewText, \"\\n\")\n\n\t\tif len(newLines) == 1 {\n\t\t\t// Single line change\n\t\t\tresult = append(result, prefix+newLines[0]+suffix)\n\t\t} else {\n\t\t\t// Multi-line change\n\t\t\tresult = append(result, prefix+newLines[0])\n\t\t\tresult = append(result, newLines[1:len(newLines)-1]...)\n\t\t\tresult = append(result, newLines[len(newLines)-1]+suffix)\n\t\t}\n\t}\n\n\t// Add remaining lines\n\tif endLine+1 < len(lines) {\n\t\tresult = append(result, lines[endLine+1:]...)\n\t}\n\n\treturn result, nil\n}\n\n// applyDocumentChange applies a DocumentChange (create/rename/delete operations)\nfunc applyDocumentChange(change protocol.DocumentChange) error {\n\tif change.CreateFile != nil {\n\t\tpath := strings.TrimPrefix(string(change.CreateFile.URI), \"file://\")\n\t\tif change.CreateFile.Options != nil {\n\t\t\tif change.CreateFile.Options.Overwrite {\n\t\t\t\t// Proceed with overwrite\n\t\t\t} else if change.CreateFile.Options.IgnoreIfExists {\n\t\t\t\tif _, err := os.Stat(path); err == nil {\n\t\t\t\t\treturn nil // File exists and we're ignoring it\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif err := os.WriteFile(path, []byte(\"\"), 0o644); err != nil {\n\t\t\treturn fmt.Errorf(\"failed to create file: %w\", err)\n\t\t}\n\t}\n\n\tif change.DeleteFile != nil {\n\t\tpath := strings.TrimPrefix(string(change.DeleteFile.URI), \"file://\")\n\t\tif change.DeleteFile.Options != nil && change.DeleteFile.Options.Recursive {\n\t\t\tif err := os.RemoveAll(path); err != nil {\n\t\t\t\treturn fmt.Errorf(\"failed to delete directory recursively: %w\", err)\n\t\t\t}\n\t\t} else {\n\t\t\tif err := os.Remove(path); err != nil {\n\t\t\t\treturn fmt.Errorf(\"failed to delete file: %w\", err)\n\t\t\t}\n\t\t}\n\t}\n\n\tif change.RenameFile != nil {\n\t\toldPath := strings.TrimPrefix(string(change.RenameFile.OldURI), \"file://\")\n\t\tnewPath := strings.TrimPrefix(string(change.RenameFile.NewURI), \"file://\")\n\t\tif change.RenameFile.Options != nil {\n\t\t\tif !change.RenameFile.Options.Overwrite {\n\t\t\t\tif _, err := os.Stat(newPath); err == nil {\n\t\t\t\t\treturn fmt.Errorf(\"target file already exists and overwrite is not allowed: %s\", newPath)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif err := os.Rename(oldPath, newPath); err != nil {\n\t\t\treturn fmt.Errorf(\"failed to rename file: %w\", err)\n\t\t}\n\t}\n\n\tif change.TextDocumentEdit != nil {\n\t\ttextEdits := make([]protocol.TextEdit, len(change.TextDocumentEdit.Edits))\n\t\tfor i, edit := range change.TextDocumentEdit.Edits {\n\t\t\tvar err error\n\t\t\ttextEdits[i], err = edit.AsTextEdit()\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"invalid edit type: %w\", err)\n\t\t\t}\n\t\t}\n\t\treturn applyTextEdits(change.TextDocumentEdit.TextDocument.URI, textEdits)\n\t}\n\n\treturn nil\n}\n\n// ApplyWorkspaceEdit applies the given WorkspaceEdit to the filesystem\nfunc ApplyWorkspaceEdit(edit protocol.WorkspaceEdit) error {\n\t// Handle Changes field\n\tfor uri, textEdits := range edit.Changes {\n\t\tif err := applyTextEdits(uri, textEdits); err != nil {\n\t\t\treturn fmt.Errorf(\"failed to apply text edits: %w\", err)\n\t\t}\n\t}\n\n\t// Handle DocumentChanges field\n\tfor _, change := range edit.DocumentChanges {\n\t\tif err := applyDocumentChange(change); err != nil {\n\t\t\treturn fmt.Errorf(\"failed to apply document change: %w\", err)\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc rangesOverlap(r1, r2 protocol.Range) bool {\n\tif r1.Start.Line > r2.End.Line || r2.Start.Line > r1.End.Line {\n\t\treturn false\n\t}\n\tif r1.Start.Line == r2.End.Line && r1.Start.Character > r2.End.Character {\n\t\treturn false\n\t}\n\tif r2.Start.Line == r1.End.Line && r2.Start.Character > r1.End.Character {\n\t\treturn false\n\t}\n\treturn true\n}\n"], ["/opencode/internal/completions/files-folders.go", "package completions\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"os/exec\"\n\t\"path/filepath\"\n\n\t\"github.com/lithammer/fuzzysearch/fuzzy\"\n\t\"github.com/opencode-ai/opencode/internal/fileutil\"\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n\t\"github.com/opencode-ai/opencode/internal/tui/components/dialog\"\n)\n\ntype filesAndFoldersContextGroup struct {\n\tprefix string\n}\n\nfunc (cg *filesAndFoldersContextGroup) GetId() string {\n\treturn cg.prefix\n}\n\nfunc (cg *filesAndFoldersContextGroup) GetEntry() dialog.CompletionItemI {\n\treturn dialog.NewCompletionItem(dialog.CompletionItem{\n\t\tTitle: \"Files & Folders\",\n\t\tValue: \"files\",\n\t})\n}\n\nfunc processNullTerminatedOutput(outputBytes []byte) []string {\n\tif len(outputBytes) > 0 && outputBytes[len(outputBytes)-1] == 0 {\n\t\toutputBytes = outputBytes[:len(outputBytes)-1]\n\t}\n\n\tif len(outputBytes) == 0 {\n\t\treturn []string{}\n\t}\n\n\tsplit := bytes.Split(outputBytes, []byte{0})\n\tmatches := make([]string, 0, len(split))\n\n\tfor _, p := range split {\n\t\tif len(p) == 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\tpath := string(p)\n\t\tpath = filepath.Join(\".\", path)\n\n\t\tif !fileutil.SkipHidden(path) {\n\t\t\tmatches = append(matches, path)\n\t\t}\n\t}\n\n\treturn matches\n}\n\nfunc (cg *filesAndFoldersContextGroup) getFiles(query string) ([]string, error) {\n\tcmdRg := fileutil.GetRgCmd(\"\") // No glob pattern for this use case\n\tcmdFzf := fileutil.GetFzfCmd(query)\n\n\tvar matches []string\n\t// Case 1: Both rg and fzf available\n\tif cmdRg != nil && cmdFzf != nil {\n\t\trgPipe, err := cmdRg.StdoutPipe()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to get rg stdout pipe: %w\", err)\n\t\t}\n\t\tdefer rgPipe.Close()\n\n\t\tcmdFzf.Stdin = rgPipe\n\t\tvar fzfOut bytes.Buffer\n\t\tvar fzfErr bytes.Buffer\n\t\tcmdFzf.Stdout = &fzfOut\n\t\tcmdFzf.Stderr = &fzfErr\n\n\t\tif err := cmdFzf.Start(); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to start fzf: %w\", err)\n\t\t}\n\n\t\terrRg := cmdRg.Run()\n\t\terrFzf := cmdFzf.Wait()\n\n\t\tif errRg != nil {\n\t\t\tlogging.Warn(fmt.Sprintf(\"rg command failed during pipe: %v\", errRg))\n\t\t}\n\n\t\tif errFzf != nil {\n\t\t\tif exitErr, ok := errFzf.(*exec.ExitError); ok && exitErr.ExitCode() == 1 {\n\t\t\t\treturn []string{}, nil // No matches from fzf\n\t\t\t}\n\t\t\treturn nil, fmt.Errorf(\"fzf command failed: %w\\nStderr: %s\", errFzf, fzfErr.String())\n\t\t}\n\n\t\tmatches = processNullTerminatedOutput(fzfOut.Bytes())\n\n\t\t// Case 2: Only rg available\n\t} else if cmdRg != nil {\n\t\tlogging.Debug(\"Using Ripgrep with fuzzy match fallback for file completions\")\n\t\tvar rgOut bytes.Buffer\n\t\tvar rgErr bytes.Buffer\n\t\tcmdRg.Stdout = &rgOut\n\t\tcmdRg.Stderr = &rgErr\n\n\t\tif err := cmdRg.Run(); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"rg command failed: %w\\nStderr: %s\", err, rgErr.String())\n\t\t}\n\n\t\tallFiles := processNullTerminatedOutput(rgOut.Bytes())\n\t\tmatches = fuzzy.Find(query, allFiles)\n\n\t\t// Case 3: Only fzf available\n\t} else if cmdFzf != nil {\n\t\tlogging.Debug(\"Using FZF with doublestar fallback for file completions\")\n\t\tfiles, _, err := fileutil.GlobWithDoublestar(\"**/*\", \".\", 0)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to list files for fzf: %w\", err)\n\t\t}\n\n\t\tallFiles := make([]string, 0, len(files))\n\t\tfor _, file := range files {\n\t\t\tif !fileutil.SkipHidden(file) {\n\t\t\t\tallFiles = append(allFiles, file)\n\t\t\t}\n\t\t}\n\n\t\tvar fzfIn bytes.Buffer\n\t\tfor _, file := range allFiles {\n\t\t\tfzfIn.WriteString(file)\n\t\t\tfzfIn.WriteByte(0)\n\t\t}\n\n\t\tcmdFzf.Stdin = &fzfIn\n\t\tvar fzfOut bytes.Buffer\n\t\tvar fzfErr bytes.Buffer\n\t\tcmdFzf.Stdout = &fzfOut\n\t\tcmdFzf.Stderr = &fzfErr\n\n\t\tif err := cmdFzf.Run(); err != nil {\n\t\t\tif exitErr, ok := err.(*exec.ExitError); ok && exitErr.ExitCode() == 1 {\n\t\t\t\treturn []string{}, nil\n\t\t\t}\n\t\t\treturn nil, fmt.Errorf(\"fzf command failed: %w\\nStderr: %s\", err, fzfErr.String())\n\t\t}\n\n\t\tmatches = processNullTerminatedOutput(fzfOut.Bytes())\n\n\t\t// Case 4: Fallback to doublestar with fuzzy match\n\t} else {\n\t\tlogging.Debug(\"Using doublestar with fuzzy match for file completions\")\n\t\tallFiles, _, err := fileutil.GlobWithDoublestar(\"**/*\", \".\", 0)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to glob files: %w\", err)\n\t\t}\n\n\t\tfilteredFiles := make([]string, 0, len(allFiles))\n\t\tfor _, file := range allFiles {\n\t\t\tif !fileutil.SkipHidden(file) {\n\t\t\t\tfilteredFiles = append(filteredFiles, file)\n\t\t\t}\n\t\t}\n\n\t\tmatches = fuzzy.Find(query, filteredFiles)\n\t}\n\n\treturn matches, nil\n}\n\nfunc (cg *filesAndFoldersContextGroup) GetChildEntries(query string) ([]dialog.CompletionItemI, error) {\n\tmatches, err := cg.getFiles(query)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\titems := make([]dialog.CompletionItemI, 0, len(matches))\n\tfor _, file := range matches {\n\t\titem := dialog.NewCompletionItem(dialog.CompletionItem{\n\t\t\tTitle: file,\n\t\t\tValue: file,\n\t\t})\n\t\titems = append(items, item)\n\t}\n\n\treturn items, nil\n}\n\nfunc NewFileAndFolderContextGroup() dialog.CompletionProvider {\n\treturn &filesAndFoldersContextGroup{\n\t\tprefix: \"file\",\n\t}\n}\n"], ["/opencode/internal/logging/logger.go", "package logging\n\nimport (\n\t\"fmt\"\n\t\"log/slog\"\n\t\"os\"\n\t// \"path/filepath\"\n\t\"encoding/json\"\n\t\"runtime\"\n\t\"runtime/debug\"\n\t\"sync\"\n\t\"time\"\n)\n\nfunc getCaller() string {\n\tvar caller string\n\tif _, file, line, ok := runtime.Caller(2); ok {\n\t\t// caller = fmt.Sprintf(\"%s:%d\", filepath.Base(file), line)\n\t\tcaller = fmt.Sprintf(\"%s:%d\", file, line)\n\t} else {\n\t\tcaller = \"unknown\"\n\t}\n\treturn caller\n}\nfunc Info(msg string, args ...any) {\n\tsource := getCaller()\n\tslog.Info(msg, append([]any{\"source\", source}, args...)...)\n}\n\nfunc Debug(msg string, args ...any) {\n\t// slog.Debug(msg, args...)\n\tsource := getCaller()\n\tslog.Debug(msg, append([]any{\"source\", source}, args...)...)\n}\n\nfunc Warn(msg string, args ...any) {\n\tslog.Warn(msg, args...)\n}\n\nfunc Error(msg string, args ...any) {\n\tslog.Error(msg, args...)\n}\n\nfunc InfoPersist(msg string, args ...any) {\n\targs = append(args, persistKeyArg, true)\n\tslog.Info(msg, args...)\n}\n\nfunc DebugPersist(msg string, args ...any) {\n\targs = append(args, persistKeyArg, true)\n\tslog.Debug(msg, args...)\n}\n\nfunc WarnPersist(msg string, args ...any) {\n\targs = append(args, persistKeyArg, true)\n\tslog.Warn(msg, args...)\n}\n\nfunc ErrorPersist(msg string, args ...any) {\n\targs = append(args, persistKeyArg, true)\n\tslog.Error(msg, args...)\n}\n\n// RecoverPanic is a common function to handle panics gracefully.\n// It logs the error, creates a panic log file with stack trace,\n// and executes an optional cleanup function before returning.\nfunc RecoverPanic(name string, cleanup func()) {\n\tif r := recover(); r != nil {\n\t\t// Log the panic\n\t\tErrorPersist(fmt.Sprintf(\"Panic in %s: %v\", name, r))\n\n\t\t// Create a timestamped panic log file\n\t\ttimestamp := time.Now().Format(\"20060102-150405\")\n\t\tfilename := fmt.Sprintf(\"opencode-panic-%s-%s.log\", name, timestamp)\n\n\t\tfile, err := os.Create(filename)\n\t\tif err != nil {\n\t\t\tErrorPersist(fmt.Sprintf(\"Failed to create panic log: %v\", err))\n\t\t} else {\n\t\t\tdefer file.Close()\n\n\t\t\t// Write panic information and stack trace\n\t\t\tfmt.Fprintf(file, \"Panic in %s: %v\\n\\n\", name, r)\n\t\t\tfmt.Fprintf(file, \"Time: %s\\n\\n\", time.Now().Format(time.RFC3339))\n\t\t\tfmt.Fprintf(file, \"Stack Trace:\\n%s\\n\", debug.Stack())\n\n\t\t\tInfoPersist(fmt.Sprintf(\"Panic details written to %s\", filename))\n\t\t}\n\n\t\t// Execute cleanup function if provided\n\t\tif cleanup != nil {\n\t\t\tcleanup()\n\t\t}\n\t}\n}\n\n// Message Logging for Debug\nvar MessageDir string\n\nfunc GetSessionPrefix(sessionId string) string {\n\treturn sessionId[:8]\n}\n\nvar sessionLogMutex sync.Mutex\n\nfunc AppendToSessionLogFile(sessionId string, filename string, content string) string {\n\tif MessageDir == \"\" || sessionId == \"\" {\n\t\treturn \"\"\n\t}\n\tsessionPrefix := GetSessionPrefix(sessionId)\n\n\tsessionLogMutex.Lock()\n\tdefer sessionLogMutex.Unlock()\n\n\tsessionPath := fmt.Sprintf(\"%s/%s\", MessageDir, sessionPrefix)\n\tif _, err := os.Stat(sessionPath); os.IsNotExist(err) {\n\t\tif err := os.MkdirAll(sessionPath, 0o766); err != nil {\n\t\t\tError(\"Failed to create session directory\", \"dirpath\", sessionPath, \"error\", err)\n\t\t\treturn \"\"\n\t\t}\n\t}\n\n\tfilePath := fmt.Sprintf(\"%s/%s\", sessionPath, filename)\n\n\tf, err := os.OpenFile(filePath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)\n\tif err != nil {\n\t\tError(\"Failed to open session log file\", \"filepath\", filePath, \"error\", err)\n\t\treturn \"\"\n\t}\n\tdefer f.Close()\n\n\t// Append chunk to file\n\t_, err = f.WriteString(content)\n\tif err != nil {\n\t\tError(\"Failed to write chunk to session log file\", \"filepath\", filePath, \"error\", err)\n\t\treturn \"\"\n\t}\n\treturn filePath\n}\n\nfunc WriteRequestMessageJson(sessionId string, requestSeqId int, message any) string {\n\tif MessageDir == \"\" || sessionId == \"\" || requestSeqId <= 0 {\n\t\treturn \"\"\n\t}\n\tmsgJson, err := json.Marshal(message)\n\tif err != nil {\n\t\tError(\"Failed to marshal message\", \"session_id\", sessionId, \"request_seq_id\", requestSeqId, \"error\", err)\n\t\treturn \"\"\n\t}\n\treturn WriteRequestMessage(sessionId, requestSeqId, string(msgJson))\n}\n\nfunc WriteRequestMessage(sessionId string, requestSeqId int, message string) string {\n\tif MessageDir == \"\" || sessionId == \"\" || requestSeqId <= 0 {\n\t\treturn \"\"\n\t}\n\tfilename := fmt.Sprintf(\"%d_request.json\", requestSeqId)\n\n\treturn AppendToSessionLogFile(sessionId, filename, message)\n}\n\nfunc AppendToStreamSessionLogJson(sessionId string, requestSeqId int, jsonableChunk any) string {\n\tif MessageDir == \"\" || sessionId == \"\" || requestSeqId <= 0 {\n\t\treturn \"\"\n\t}\n\tchunkJson, err := json.Marshal(jsonableChunk)\n\tif err != nil {\n\t\tError(\"Failed to marshal message\", \"session_id\", sessionId, \"request_seq_id\", requestSeqId, \"error\", err)\n\t\treturn \"\"\n\t}\n\treturn AppendToStreamSessionLog(sessionId, requestSeqId, string(chunkJson))\n}\n\nfunc AppendToStreamSessionLog(sessionId string, requestSeqId int, chunk string) string {\n\tif MessageDir == \"\" || sessionId == \"\" || requestSeqId <= 0 {\n\t\treturn \"\"\n\t}\n\tfilename := fmt.Sprintf(\"%d_response_stream.log\", requestSeqId)\n\treturn AppendToSessionLogFile(sessionId, filename, chunk)\n}\n\nfunc WriteChatResponseJson(sessionId string, requestSeqId int, response any) string {\n\tif MessageDir == \"\" || sessionId == \"\" || requestSeqId <= 0 {\n\t\treturn \"\"\n\t}\n\tresponseJson, err := json.Marshal(response)\n\tif err != nil {\n\t\tError(\"Failed to marshal response\", \"session_id\", sessionId, \"request_seq_id\", requestSeqId, \"error\", err)\n\t\treturn \"\"\n\t}\n\tfilename := fmt.Sprintf(\"%d_response.json\", requestSeqId)\n\n\treturn AppendToSessionLogFile(sessionId, filename, string(responseJson))\n}\n\nfunc WriteToolResultsJson(sessionId string, requestSeqId int, toolResults any) string {\n\tif MessageDir == \"\" || sessionId == \"\" || requestSeqId <= 0 {\n\t\treturn \"\"\n\t}\n\ttoolResultsJson, err := json.Marshal(toolResults)\n\tif err != nil {\n\t\tError(\"Failed to marshal tool results\", \"session_id\", sessionId, \"request_seq_id\", requestSeqId, \"error\", err)\n\t\treturn \"\"\n\t}\n\tfilename := fmt.Sprintf(\"%d_tool_results.json\", requestSeqId)\n\treturn AppendToSessionLogFile(sessionId, filename, string(toolResultsJson))\n}\n"], ["/opencode/internal/tui/components/dialog/filepicker.go", "package dialog\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"sort\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/charmbracelet/bubbles/key\"\n\t\"github.com/charmbracelet/bubbles/textinput\"\n\t\"github.com/charmbracelet/bubbles/viewport\"\n\ttea \"github.com/charmbracelet/bubbletea\"\n\t\"github.com/charmbracelet/lipgloss\"\n\t\"github.com/opencode-ai/opencode/internal/app\"\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n\t\"github.com/opencode-ai/opencode/internal/message\"\n\t\"github.com/opencode-ai/opencode/internal/tui/image\"\n\t\"github.com/opencode-ai/opencode/internal/tui/styles\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n\t\"github.com/opencode-ai/opencode/internal/tui/util\"\n)\n\nconst (\n\tmaxAttachmentSize = int64(5 * 1024 * 1024) // 5MB\n\tdownArrow = \"down\"\n\tupArrow = \"up\"\n)\n\ntype FilePrickerKeyMap struct {\n\tEnter key.Binding\n\tDown key.Binding\n\tUp key.Binding\n\tForward key.Binding\n\tBackward key.Binding\n\tOpenFilePicker key.Binding\n\tEsc key.Binding\n\tInsertCWD key.Binding\n}\n\nvar filePickerKeyMap = FilePrickerKeyMap{\n\tEnter: key.NewBinding(\n\t\tkey.WithKeys(\"enter\"),\n\t\tkey.WithHelp(\"enter\", \"select file/enter directory\"),\n\t),\n\tDown: key.NewBinding(\n\t\tkey.WithKeys(\"j\", downArrow),\n\t\tkey.WithHelp(\"↓/j\", \"down\"),\n\t),\n\tUp: key.NewBinding(\n\t\tkey.WithKeys(\"k\", upArrow),\n\t\tkey.WithHelp(\"↑/k\", \"up\"),\n\t),\n\tForward: key.NewBinding(\n\t\tkey.WithKeys(\"l\"),\n\t\tkey.WithHelp(\"l\", \"enter directory\"),\n\t),\n\tBackward: key.NewBinding(\n\t\tkey.WithKeys(\"h\", \"backspace\"),\n\t\tkey.WithHelp(\"h/backspace\", \"go back\"),\n\t),\n\tOpenFilePicker: key.NewBinding(\n\t\tkey.WithKeys(\"ctrl+f\"),\n\t\tkey.WithHelp(\"ctrl+f\", \"open file picker\"),\n\t),\n\tEsc: key.NewBinding(\n\t\tkey.WithKeys(\"esc\"),\n\t\tkey.WithHelp(\"esc\", \"close/exit\"),\n\t),\n\tInsertCWD: key.NewBinding(\n\t\tkey.WithKeys(\"i\"),\n\t\tkey.WithHelp(\"i\", \"manual path input\"),\n\t),\n}\n\ntype filepickerCmp struct {\n\tbasePath string\n\twidth int\n\theight int\n\tcursor int\n\terr error\n\tcursorChain stack\n\tviewport viewport.Model\n\tdirs []os.DirEntry\n\tcwdDetails *DirNode\n\tselectedFile string\n\tcwd textinput.Model\n\tShowFilePicker bool\n\tapp *app.App\n}\n\ntype DirNode struct {\n\tparent *DirNode\n\tchild *DirNode\n\tdirectory string\n}\ntype stack []int\n\nfunc (s stack) Push(v int) stack {\n\treturn append(s, v)\n}\n\nfunc (s stack) Pop() (stack, int) {\n\tl := len(s)\n\treturn s[:l-1], s[l-1]\n}\n\ntype AttachmentAddedMsg struct {\n\tAttachment message.Attachment\n}\n\nfunc (f *filepickerCmp) Init() tea.Cmd {\n\treturn nil\n}\n\nfunc (f *filepickerCmp) Update(msg tea.Msg) (tea.Model, tea.Cmd) {\n\tvar cmd tea.Cmd\n\tswitch msg := msg.(type) {\n\tcase tea.WindowSizeMsg:\n\t\tf.width = 60\n\t\tf.height = 20\n\t\tf.viewport.Width = 80\n\t\tf.viewport.Height = 22\n\t\tf.cursor = 0\n\t\tf.getCurrentFileBelowCursor()\n\tcase tea.KeyMsg:\n\t\tif f.cwd.Focused() {\n\t\t\tf.cwd, cmd = f.cwd.Update(msg)\n\t\t}\n\t\tswitch {\n\t\tcase key.Matches(msg, filePickerKeyMap.InsertCWD):\n\t\t\tf.cwd.Focus()\n\t\t\treturn f, cmd\n\t\tcase key.Matches(msg, filePickerKeyMap.Esc):\n\t\t\tif f.cwd.Focused() {\n\t\t\t\tf.cwd.Blur()\n\t\t\t}\n\t\tcase key.Matches(msg, filePickerKeyMap.Down):\n\t\t\tif !f.cwd.Focused() || msg.String() == downArrow {\n\t\t\t\tif f.cursor < len(f.dirs)-1 {\n\t\t\t\t\tf.cursor++\n\t\t\t\t\tf.getCurrentFileBelowCursor()\n\t\t\t\t}\n\t\t\t}\n\t\tcase key.Matches(msg, filePickerKeyMap.Up):\n\t\t\tif !f.cwd.Focused() || msg.String() == upArrow {\n\t\t\t\tif f.cursor > 0 {\n\t\t\t\t\tf.cursor--\n\t\t\t\t\tf.getCurrentFileBelowCursor()\n\t\t\t\t}\n\t\t\t}\n\t\tcase key.Matches(msg, filePickerKeyMap.Enter):\n\t\t\tvar path string\n\t\t\tvar isPathDir bool\n\t\t\tif f.cwd.Focused() {\n\t\t\t\tpath = f.cwd.Value()\n\t\t\t\tfileInfo, err := os.Stat(path)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlogging.ErrorPersist(\"Invalid path\")\n\t\t\t\t\treturn f, cmd\n\t\t\t\t}\n\t\t\t\tisPathDir = fileInfo.IsDir()\n\t\t\t} else {\n\t\t\t\tpath = filepath.Join(f.cwdDetails.directory, \"/\", f.dirs[f.cursor].Name())\n\t\t\t\tisPathDir = f.dirs[f.cursor].IsDir()\n\t\t\t}\n\t\t\tif isPathDir {\n\t\t\t\tnewWorkingDir := DirNode{parent: f.cwdDetails, directory: path}\n\t\t\t\tf.cwdDetails.child = &newWorkingDir\n\t\t\t\tf.cwdDetails = f.cwdDetails.child\n\t\t\t\tf.cursorChain = f.cursorChain.Push(f.cursor)\n\t\t\t\tf.dirs = readDir(f.cwdDetails.directory, false)\n\t\t\t\tf.cursor = 0\n\t\t\t\tf.cwd.SetValue(f.cwdDetails.directory)\n\t\t\t\tf.getCurrentFileBelowCursor()\n\t\t\t} else {\n\t\t\t\tf.selectedFile = path\n\t\t\t\treturn f.addAttachmentToMessage()\n\t\t\t}\n\t\tcase key.Matches(msg, filePickerKeyMap.Esc):\n\t\t\tif !f.cwd.Focused() {\n\t\t\t\tf.cursorChain = make(stack, 0)\n\t\t\t\tf.cursor = 0\n\t\t\t} else {\n\t\t\t\tf.cwd.Blur()\n\t\t\t}\n\t\tcase key.Matches(msg, filePickerKeyMap.Forward):\n\t\t\tif !f.cwd.Focused() {\n\t\t\t\tif f.dirs[f.cursor].IsDir() {\n\t\t\t\t\tpath := filepath.Join(f.cwdDetails.directory, \"/\", f.dirs[f.cursor].Name())\n\t\t\t\t\tnewWorkingDir := DirNode{parent: f.cwdDetails, directory: path}\n\t\t\t\t\tf.cwdDetails.child = &newWorkingDir\n\t\t\t\t\tf.cwdDetails = f.cwdDetails.child\n\t\t\t\t\tf.cursorChain = f.cursorChain.Push(f.cursor)\n\t\t\t\t\tf.dirs = readDir(f.cwdDetails.directory, false)\n\t\t\t\t\tf.cursor = 0\n\t\t\t\t\tf.cwd.SetValue(f.cwdDetails.directory)\n\t\t\t\t\tf.getCurrentFileBelowCursor()\n\t\t\t\t}\n\t\t\t}\n\t\tcase key.Matches(msg, filePickerKeyMap.Backward):\n\t\t\tif !f.cwd.Focused() {\n\t\t\t\tif len(f.cursorChain) != 0 && f.cwdDetails.parent != nil {\n\t\t\t\t\tf.cursorChain, f.cursor = f.cursorChain.Pop()\n\t\t\t\t\tf.cwdDetails = f.cwdDetails.parent\n\t\t\t\t\tf.cwdDetails.child = nil\n\t\t\t\t\tf.dirs = readDir(f.cwdDetails.directory, false)\n\t\t\t\t\tf.cwd.SetValue(f.cwdDetails.directory)\n\t\t\t\t\tf.getCurrentFileBelowCursor()\n\t\t\t\t}\n\t\t\t}\n\t\tcase key.Matches(msg, filePickerKeyMap.OpenFilePicker):\n\t\t\tf.dirs = readDir(f.cwdDetails.directory, false)\n\t\t\tf.cursor = 0\n\t\t\tf.getCurrentFileBelowCursor()\n\t\t}\n\t}\n\treturn f, cmd\n}\n\nfunc (f *filepickerCmp) addAttachmentToMessage() (tea.Model, tea.Cmd) {\n\tmodeInfo := GetSelectedModel(config.Get())\n\tif !modeInfo.SupportsAttachments {\n\t\tlogging.ErrorPersist(fmt.Sprintf(\"Model %s doesn't support attachments\", modeInfo.Name))\n\t\treturn f, nil\n\t}\n\n\tselectedFilePath := f.selectedFile\n\tif !isExtSupported(selectedFilePath) {\n\t\tlogging.ErrorPersist(\"Unsupported file\")\n\t\treturn f, nil\n\t}\n\n\tisFileLarge, err := image.ValidateFileSize(selectedFilePath, maxAttachmentSize)\n\tif err != nil {\n\t\tlogging.ErrorPersist(\"unable to read the image\")\n\t\treturn f, nil\n\t}\n\tif isFileLarge {\n\t\tlogging.ErrorPersist(\"file too large, max 5MB\")\n\t\treturn f, nil\n\t}\n\n\tcontent, err := os.ReadFile(selectedFilePath)\n\tif err != nil {\n\t\tlogging.ErrorPersist(\"Unable read selected file\")\n\t\treturn f, nil\n\t}\n\n\tmimeBufferSize := min(512, len(content))\n\tmimeType := http.DetectContentType(content[:mimeBufferSize])\n\tfileName := filepath.Base(selectedFilePath)\n\tattachment := message.Attachment{FilePath: selectedFilePath, FileName: fileName, MimeType: mimeType, Content: content}\n\tf.selectedFile = \"\"\n\treturn f, util.CmdHandler(AttachmentAddedMsg{attachment})\n}\n\nfunc (f *filepickerCmp) View() string {\n\tt := theme.CurrentTheme()\n\tconst maxVisibleDirs = 20\n\tconst maxWidth = 80\n\n\tadjustedWidth := maxWidth\n\tfor _, file := range f.dirs {\n\t\tif len(file.Name()) > adjustedWidth-4 { // Account for padding\n\t\t\tadjustedWidth = len(file.Name()) + 4\n\t\t}\n\t}\n\tadjustedWidth = max(30, min(adjustedWidth, f.width-15)) + 1\n\n\tfiles := make([]string, 0, maxVisibleDirs)\n\tstartIdx := 0\n\n\tif len(f.dirs) > maxVisibleDirs {\n\t\thalfVisible := maxVisibleDirs / 2\n\t\tif f.cursor >= halfVisible && f.cursor < len(f.dirs)-halfVisible {\n\t\t\tstartIdx = f.cursor - halfVisible\n\t\t} else if f.cursor >= len(f.dirs)-halfVisible {\n\t\t\tstartIdx = len(f.dirs) - maxVisibleDirs\n\t\t}\n\t}\n\n\tendIdx := min(startIdx+maxVisibleDirs, len(f.dirs))\n\n\tfor i := startIdx; i < endIdx; i++ {\n\t\tfile := f.dirs[i]\n\t\titemStyle := styles.BaseStyle().Width(adjustedWidth)\n\n\t\tif i == f.cursor {\n\t\t\titemStyle = itemStyle.\n\t\t\t\tBackground(t.Primary()).\n\t\t\t\tForeground(t.Background()).\n\t\t\t\tBold(true)\n\t\t}\n\t\tfilename := file.Name()\n\n\t\tif len(filename) > adjustedWidth-4 {\n\t\t\tfilename = filename[:adjustedWidth-7] + \"...\"\n\t\t}\n\t\tif file.IsDir() {\n\t\t\tfilename = filename + \"/\"\n\t\t}\n\t\t// No need to reassign filename if it's not changing\n\n\t\tfiles = append(files, itemStyle.Padding(0, 1).Render(filename))\n\t}\n\n\t// Pad to always show exactly 21 lines\n\tfor len(files) < maxVisibleDirs {\n\t\tfiles = append(files, styles.BaseStyle().Width(adjustedWidth).Render(\"\"))\n\t}\n\n\tcurrentPath := styles.BaseStyle().\n\t\tHeight(1).\n\t\tWidth(adjustedWidth).\n\t\tRender(f.cwd.View())\n\n\tviewportstyle := lipgloss.NewStyle().\n\t\tWidth(f.viewport.Width).\n\t\tBackground(t.Background()).\n\t\tBorder(lipgloss.RoundedBorder()).\n\t\tBorderForeground(t.TextMuted()).\n\t\tBorderBackground(t.Background()).\n\t\tPadding(2).\n\t\tRender(f.viewport.View())\n\tvar insertExitText string\n\tif f.IsCWDFocused() {\n\t\tinsertExitText = \"Press esc to exit typing path\"\n\t} else {\n\t\tinsertExitText = \"Press i to start typing path\"\n\t}\n\n\tcontent := lipgloss.JoinVertical(\n\t\tlipgloss.Left,\n\t\tcurrentPath,\n\t\tstyles.BaseStyle().Width(adjustedWidth).Render(\"\"),\n\t\tstyles.BaseStyle().Width(adjustedWidth).Render(lipgloss.JoinVertical(lipgloss.Left, files...)),\n\t\tstyles.BaseStyle().Width(adjustedWidth).Render(\"\"),\n\t\tstyles.BaseStyle().Foreground(t.TextMuted()).Width(adjustedWidth).Render(insertExitText),\n\t)\n\n\tf.cwd.SetValue(f.cwd.Value())\n\tcontentStyle := styles.BaseStyle().Padding(1, 2).\n\t\tBorder(lipgloss.RoundedBorder()).\n\t\tBorderBackground(t.Background()).\n\t\tBorderForeground(t.TextMuted()).\n\t\tWidth(lipgloss.Width(content) + 4)\n\n\treturn lipgloss.JoinHorizontal(lipgloss.Center, contentStyle.Render(content), viewportstyle)\n}\n\ntype FilepickerCmp interface {\n\ttea.Model\n\tToggleFilepicker(showFilepicker bool)\n\tIsCWDFocused() bool\n}\n\nfunc (f *filepickerCmp) ToggleFilepicker(showFilepicker bool) {\n\tf.ShowFilePicker = showFilepicker\n}\n\nfunc (f *filepickerCmp) IsCWDFocused() bool {\n\treturn f.cwd.Focused()\n}\n\nfunc NewFilepickerCmp(app *app.App) FilepickerCmp {\n\thomepath, err := os.UserHomeDir()\n\tif err != nil {\n\t\tlogging.Error(\"error loading user files\")\n\t\treturn nil\n\t}\n\tbaseDir := DirNode{parent: nil, directory: homepath}\n\tdirs := readDir(homepath, false)\n\tviewport := viewport.New(0, 0)\n\tcurrentDirectory := textinput.New()\n\tcurrentDirectory.CharLimit = 200\n\tcurrentDirectory.Width = 44\n\tcurrentDirectory.Cursor.Blink = true\n\tcurrentDirectory.SetValue(baseDir.directory)\n\treturn &filepickerCmp{cwdDetails: &baseDir, dirs: dirs, cursorChain: make(stack, 0), viewport: viewport, cwd: currentDirectory, app: app}\n}\n\nfunc (f *filepickerCmp) getCurrentFileBelowCursor() {\n\tif len(f.dirs) == 0 || f.cursor < 0 || f.cursor >= len(f.dirs) {\n\t\tlogging.Error(fmt.Sprintf(\"Invalid cursor position. Dirs length: %d, Cursor: %d\", len(f.dirs), f.cursor))\n\t\tf.viewport.SetContent(\"Preview unavailable\")\n\t\treturn\n\t}\n\n\tdir := f.dirs[f.cursor]\n\tfilename := dir.Name()\n\tif !dir.IsDir() && isExtSupported(filename) {\n\t\tfullPath := f.cwdDetails.directory + \"/\" + dir.Name()\n\n\t\tgo func() {\n\t\t\timageString, err := image.ImagePreview(f.viewport.Width-4, fullPath)\n\t\t\tif err != nil {\n\t\t\t\tlogging.Error(err.Error())\n\t\t\t\tf.viewport.SetContent(\"Preview unavailable\")\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tf.viewport.SetContent(imageString)\n\t\t}()\n\t} else {\n\t\tf.viewport.SetContent(\"Preview unavailable\")\n\t}\n}\n\nfunc readDir(path string, showHidden bool) []os.DirEntry {\n\tlogging.Info(fmt.Sprintf(\"Reading directory: %s\", path))\n\n\tentriesChan := make(chan []os.DirEntry, 1)\n\terrChan := make(chan error, 1)\n\n\tgo func() {\n\t\tdirEntries, err := os.ReadDir(path)\n\t\tif err != nil {\n\t\t\tlogging.ErrorPersist(err.Error())\n\t\t\terrChan <- err\n\t\t\treturn\n\t\t}\n\t\tentriesChan <- dirEntries\n\t}()\n\n\tselect {\n\tcase dirEntries := <-entriesChan:\n\t\tsort.Slice(dirEntries, func(i, j int) bool {\n\t\t\tif dirEntries[i].IsDir() == dirEntries[j].IsDir() {\n\t\t\t\treturn dirEntries[i].Name() < dirEntries[j].Name()\n\t\t\t}\n\t\t\treturn dirEntries[i].IsDir()\n\t\t})\n\n\t\tif showHidden {\n\t\t\treturn dirEntries\n\t\t}\n\n\t\tvar sanitizedDirEntries []os.DirEntry\n\t\tfor _, dirEntry := range dirEntries {\n\t\t\tisHidden, _ := IsHidden(dirEntry.Name())\n\t\t\tif !isHidden {\n\t\t\t\tif dirEntry.IsDir() || isExtSupported(dirEntry.Name()) {\n\t\t\t\t\tsanitizedDirEntries = append(sanitizedDirEntries, dirEntry)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn sanitizedDirEntries\n\n\tcase err := <-errChan:\n\t\tlogging.ErrorPersist(fmt.Sprintf(\"Error reading directory %s\", path), err)\n\t\treturn []os.DirEntry{}\n\n\tcase <-time.After(5 * time.Second):\n\t\tlogging.ErrorPersist(fmt.Sprintf(\"Timeout reading directory %s\", path), nil)\n\t\treturn []os.DirEntry{}\n\t}\n}\n\nfunc IsHidden(file string) (bool, error) {\n\treturn strings.HasPrefix(file, \".\"), nil\n}\n\nfunc isExtSupported(path string) bool {\n\text := strings.ToLower(filepath.Ext(path))\n\treturn (ext == \".jpg\" || ext == \".jpeg\" || ext == \".webp\" || ext == \".png\")\n}\n"], ["/opencode/internal/db/db.go", "// Code generated by sqlc. DO NOT EDIT.\n// versions:\n// sqlc v1.29.0\n\npackage db\n\nimport (\n\t\"context\"\n\t\"database/sql\"\n\t\"fmt\"\n)\n\ntype DBTX interface {\n\tExecContext(context.Context, string, ...interface{}) (sql.Result, error)\n\tPrepareContext(context.Context, string) (*sql.Stmt, error)\n\tQueryContext(context.Context, string, ...interface{}) (*sql.Rows, error)\n\tQueryRowContext(context.Context, string, ...interface{}) *sql.Row\n}\n\nfunc New(db DBTX) *Queries {\n\treturn &Queries{db: db}\n}\n\nfunc Prepare(ctx context.Context, db DBTX) (*Queries, error) {\n\tq := Queries{db: db}\n\tvar err error\n\tif q.createFileStmt, err = db.PrepareContext(ctx, createFile); err != nil {\n\t\treturn nil, fmt.Errorf(\"error preparing query CreateFile: %w\", err)\n\t}\n\tif q.createMessageStmt, err = db.PrepareContext(ctx, createMessage); err != nil {\n\t\treturn nil, fmt.Errorf(\"error preparing query CreateMessage: %w\", err)\n\t}\n\tif q.createSessionStmt, err = db.PrepareContext(ctx, createSession); err != nil {\n\t\treturn nil, fmt.Errorf(\"error preparing query CreateSession: %w\", err)\n\t}\n\tif q.deleteFileStmt, err = db.PrepareContext(ctx, deleteFile); err != nil {\n\t\treturn nil, fmt.Errorf(\"error preparing query DeleteFile: %w\", err)\n\t}\n\tif q.deleteMessageStmt, err = db.PrepareContext(ctx, deleteMessage); err != nil {\n\t\treturn nil, fmt.Errorf(\"error preparing query DeleteMessage: %w\", err)\n\t}\n\tif q.deleteSessionStmt, err = db.PrepareContext(ctx, deleteSession); err != nil {\n\t\treturn nil, fmt.Errorf(\"error preparing query DeleteSession: %w\", err)\n\t}\n\tif q.deleteSessionFilesStmt, err = db.PrepareContext(ctx, deleteSessionFiles); err != nil {\n\t\treturn nil, fmt.Errorf(\"error preparing query DeleteSessionFiles: %w\", err)\n\t}\n\tif q.deleteSessionMessagesStmt, err = db.PrepareContext(ctx, deleteSessionMessages); err != nil {\n\t\treturn nil, fmt.Errorf(\"error preparing query DeleteSessionMessages: %w\", err)\n\t}\n\tif q.getFileStmt, err = db.PrepareContext(ctx, getFile); err != nil {\n\t\treturn nil, fmt.Errorf(\"error preparing query GetFile: %w\", err)\n\t}\n\tif q.getFileByPathAndSessionStmt, err = db.PrepareContext(ctx, getFileByPathAndSession); err != nil {\n\t\treturn nil, fmt.Errorf(\"error preparing query GetFileByPathAndSession: %w\", err)\n\t}\n\tif q.getMessageStmt, err = db.PrepareContext(ctx, getMessage); err != nil {\n\t\treturn nil, fmt.Errorf(\"error preparing query GetMessage: %w\", err)\n\t}\n\tif q.getSessionByIDStmt, err = db.PrepareContext(ctx, getSessionByID); err != nil {\n\t\treturn nil, fmt.Errorf(\"error preparing query GetSessionByID: %w\", err)\n\t}\n\tif q.listFilesByPathStmt, err = db.PrepareContext(ctx, listFilesByPath); err != nil {\n\t\treturn nil, fmt.Errorf(\"error preparing query ListFilesByPath: %w\", err)\n\t}\n\tif q.listFilesBySessionStmt, err = db.PrepareContext(ctx, listFilesBySession); err != nil {\n\t\treturn nil, fmt.Errorf(\"error preparing query ListFilesBySession: %w\", err)\n\t}\n\tif q.listLatestSessionFilesStmt, err = db.PrepareContext(ctx, listLatestSessionFiles); err != nil {\n\t\treturn nil, fmt.Errorf(\"error preparing query ListLatestSessionFiles: %w\", err)\n\t}\n\tif q.listMessagesBySessionStmt, err = db.PrepareContext(ctx, listMessagesBySession); err != nil {\n\t\treturn nil, fmt.Errorf(\"error preparing query ListMessagesBySession: %w\", err)\n\t}\n\tif q.listNewFilesStmt, err = db.PrepareContext(ctx, listNewFiles); err != nil {\n\t\treturn nil, fmt.Errorf(\"error preparing query ListNewFiles: %w\", err)\n\t}\n\tif q.listSessionsStmt, err = db.PrepareContext(ctx, listSessions); err != nil {\n\t\treturn nil, fmt.Errorf(\"error preparing query ListSessions: %w\", err)\n\t}\n\tif q.updateFileStmt, err = db.PrepareContext(ctx, updateFile); err != nil {\n\t\treturn nil, fmt.Errorf(\"error preparing query UpdateFile: %w\", err)\n\t}\n\tif q.updateMessageStmt, err = db.PrepareContext(ctx, updateMessage); err != nil {\n\t\treturn nil, fmt.Errorf(\"error preparing query UpdateMessage: %w\", err)\n\t}\n\tif q.updateSessionStmt, err = db.PrepareContext(ctx, updateSession); err != nil {\n\t\treturn nil, fmt.Errorf(\"error preparing query UpdateSession: %w\", err)\n\t}\n\treturn &q, nil\n}\n\nfunc (q *Queries) Close() error {\n\tvar err error\n\tif q.createFileStmt != nil {\n\t\tif cerr := q.createFileStmt.Close(); cerr != nil {\n\t\t\terr = fmt.Errorf(\"error closing createFileStmt: %w\", cerr)\n\t\t}\n\t}\n\tif q.createMessageStmt != nil {\n\t\tif cerr := q.createMessageStmt.Close(); cerr != nil {\n\t\t\terr = fmt.Errorf(\"error closing createMessageStmt: %w\", cerr)\n\t\t}\n\t}\n\tif q.createSessionStmt != nil {\n\t\tif cerr := q.createSessionStmt.Close(); cerr != nil {\n\t\t\terr = fmt.Errorf(\"error closing createSessionStmt: %w\", cerr)\n\t\t}\n\t}\n\tif q.deleteFileStmt != nil {\n\t\tif cerr := q.deleteFileStmt.Close(); cerr != nil {\n\t\t\terr = fmt.Errorf(\"error closing deleteFileStmt: %w\", cerr)\n\t\t}\n\t}\n\tif q.deleteMessageStmt != nil {\n\t\tif cerr := q.deleteMessageStmt.Close(); cerr != nil {\n\t\t\terr = fmt.Errorf(\"error closing deleteMessageStmt: %w\", cerr)\n\t\t}\n\t}\n\tif q.deleteSessionStmt != nil {\n\t\tif cerr := q.deleteSessionStmt.Close(); cerr != nil {\n\t\t\terr = fmt.Errorf(\"error closing deleteSessionStmt: %w\", cerr)\n\t\t}\n\t}\n\tif q.deleteSessionFilesStmt != nil {\n\t\tif cerr := q.deleteSessionFilesStmt.Close(); cerr != nil {\n\t\t\terr = fmt.Errorf(\"error closing deleteSessionFilesStmt: %w\", cerr)\n\t\t}\n\t}\n\tif q.deleteSessionMessagesStmt != nil {\n\t\tif cerr := q.deleteSessionMessagesStmt.Close(); cerr != nil {\n\t\t\terr = fmt.Errorf(\"error closing deleteSessionMessagesStmt: %w\", cerr)\n\t\t}\n\t}\n\tif q.getFileStmt != nil {\n\t\tif cerr := q.getFileStmt.Close(); cerr != nil {\n\t\t\terr = fmt.Errorf(\"error closing getFileStmt: %w\", cerr)\n\t\t}\n\t}\n\tif q.getFileByPathAndSessionStmt != nil {\n\t\tif cerr := q.getFileByPathAndSessionStmt.Close(); cerr != nil {\n\t\t\terr = fmt.Errorf(\"error closing getFileByPathAndSessionStmt: %w\", cerr)\n\t\t}\n\t}\n\tif q.getMessageStmt != nil {\n\t\tif cerr := q.getMessageStmt.Close(); cerr != nil {\n\t\t\terr = fmt.Errorf(\"error closing getMessageStmt: %w\", cerr)\n\t\t}\n\t}\n\tif q.getSessionByIDStmt != nil {\n\t\tif cerr := q.getSessionByIDStmt.Close(); cerr != nil {\n\t\t\terr = fmt.Errorf(\"error closing getSessionByIDStmt: %w\", cerr)\n\t\t}\n\t}\n\tif q.listFilesByPathStmt != nil {\n\t\tif cerr := q.listFilesByPathStmt.Close(); cerr != nil {\n\t\t\terr = fmt.Errorf(\"error closing listFilesByPathStmt: %w\", cerr)\n\t\t}\n\t}\n\tif q.listFilesBySessionStmt != nil {\n\t\tif cerr := q.listFilesBySessionStmt.Close(); cerr != nil {\n\t\t\terr = fmt.Errorf(\"error closing listFilesBySessionStmt: %w\", cerr)\n\t\t}\n\t}\n\tif q.listLatestSessionFilesStmt != nil {\n\t\tif cerr := q.listLatestSessionFilesStmt.Close(); cerr != nil {\n\t\t\terr = fmt.Errorf(\"error closing listLatestSessionFilesStmt: %w\", cerr)\n\t\t}\n\t}\n\tif q.listMessagesBySessionStmt != nil {\n\t\tif cerr := q.listMessagesBySessionStmt.Close(); cerr != nil {\n\t\t\terr = fmt.Errorf(\"error closing listMessagesBySessionStmt: %w\", cerr)\n\t\t}\n\t}\n\tif q.listNewFilesStmt != nil {\n\t\tif cerr := q.listNewFilesStmt.Close(); cerr != nil {\n\t\t\terr = fmt.Errorf(\"error closing listNewFilesStmt: %w\", cerr)\n\t\t}\n\t}\n\tif q.listSessionsStmt != nil {\n\t\tif cerr := q.listSessionsStmt.Close(); cerr != nil {\n\t\t\terr = fmt.Errorf(\"error closing listSessionsStmt: %w\", cerr)\n\t\t}\n\t}\n\tif q.updateFileStmt != nil {\n\t\tif cerr := q.updateFileStmt.Close(); cerr != nil {\n\t\t\terr = fmt.Errorf(\"error closing updateFileStmt: %w\", cerr)\n\t\t}\n\t}\n\tif q.updateMessageStmt != nil {\n\t\tif cerr := q.updateMessageStmt.Close(); cerr != nil {\n\t\t\terr = fmt.Errorf(\"error closing updateMessageStmt: %w\", cerr)\n\t\t}\n\t}\n\tif q.updateSessionStmt != nil {\n\t\tif cerr := q.updateSessionStmt.Close(); cerr != nil {\n\t\t\terr = fmt.Errorf(\"error closing updateSessionStmt: %w\", cerr)\n\t\t}\n\t}\n\treturn err\n}\n\nfunc (q *Queries) exec(ctx context.Context, stmt *sql.Stmt, query string, args ...interface{}) (sql.Result, error) {\n\tswitch {\n\tcase stmt != nil && q.tx != nil:\n\t\treturn q.tx.StmtContext(ctx, stmt).ExecContext(ctx, args...)\n\tcase stmt != nil:\n\t\treturn stmt.ExecContext(ctx, args...)\n\tdefault:\n\t\treturn q.db.ExecContext(ctx, query, args...)\n\t}\n}\n\nfunc (q *Queries) query(ctx context.Context, stmt *sql.Stmt, query string, args ...interface{}) (*sql.Rows, error) {\n\tswitch {\n\tcase stmt != nil && q.tx != nil:\n\t\treturn q.tx.StmtContext(ctx, stmt).QueryContext(ctx, args...)\n\tcase stmt != nil:\n\t\treturn stmt.QueryContext(ctx, args...)\n\tdefault:\n\t\treturn q.db.QueryContext(ctx, query, args...)\n\t}\n}\n\nfunc (q *Queries) queryRow(ctx context.Context, stmt *sql.Stmt, query string, args ...interface{}) *sql.Row {\n\tswitch {\n\tcase stmt != nil && q.tx != nil:\n\t\treturn q.tx.StmtContext(ctx, stmt).QueryRowContext(ctx, args...)\n\tcase stmt != nil:\n\t\treturn stmt.QueryRowContext(ctx, args...)\n\tdefault:\n\t\treturn q.db.QueryRowContext(ctx, query, args...)\n\t}\n}\n\ntype Queries struct {\n\tdb DBTX\n\ttx *sql.Tx\n\tcreateFileStmt *sql.Stmt\n\tcreateMessageStmt *sql.Stmt\n\tcreateSessionStmt *sql.Stmt\n\tdeleteFileStmt *sql.Stmt\n\tdeleteMessageStmt *sql.Stmt\n\tdeleteSessionStmt *sql.Stmt\n\tdeleteSessionFilesStmt *sql.Stmt\n\tdeleteSessionMessagesStmt *sql.Stmt\n\tgetFileStmt *sql.Stmt\n\tgetFileByPathAndSessionStmt *sql.Stmt\n\tgetMessageStmt *sql.Stmt\n\tgetSessionByIDStmt *sql.Stmt\n\tlistFilesByPathStmt *sql.Stmt\n\tlistFilesBySessionStmt *sql.Stmt\n\tlistLatestSessionFilesStmt *sql.Stmt\n\tlistMessagesBySessionStmt *sql.Stmt\n\tlistNewFilesStmt *sql.Stmt\n\tlistSessionsStmt *sql.Stmt\n\tupdateFileStmt *sql.Stmt\n\tupdateMessageStmt *sql.Stmt\n\tupdateSessionStmt *sql.Stmt\n}\n\nfunc (q *Queries) WithTx(tx *sql.Tx) *Queries {\n\treturn &Queries{\n\t\tdb: tx,\n\t\ttx: tx,\n\t\tcreateFileStmt: q.createFileStmt,\n\t\tcreateMessageStmt: q.createMessageStmt,\n\t\tcreateSessionStmt: q.createSessionStmt,\n\t\tdeleteFileStmt: q.deleteFileStmt,\n\t\tdeleteMessageStmt: q.deleteMessageStmt,\n\t\tdeleteSessionStmt: q.deleteSessionStmt,\n\t\tdeleteSessionFilesStmt: q.deleteSessionFilesStmt,\n\t\tdeleteSessionMessagesStmt: q.deleteSessionMessagesStmt,\n\t\tgetFileStmt: q.getFileStmt,\n\t\tgetFileByPathAndSessionStmt: q.getFileByPathAndSessionStmt,\n\t\tgetMessageStmt: q.getMessageStmt,\n\t\tgetSessionByIDStmt: q.getSessionByIDStmt,\n\t\tlistFilesByPathStmt: q.listFilesByPathStmt,\n\t\tlistFilesBySessionStmt: q.listFilesBySessionStmt,\n\t\tlistLatestSessionFilesStmt: q.listLatestSessionFilesStmt,\n\t\tlistMessagesBySessionStmt: q.listMessagesBySessionStmt,\n\t\tlistNewFilesStmt: q.listNewFilesStmt,\n\t\tlistSessionsStmt: q.listSessionsStmt,\n\t\tupdateFileStmt: q.updateFileStmt,\n\t\tupdateMessageStmt: q.updateMessageStmt,\n\t\tupdateSessionStmt: q.updateSessionStmt,\n\t}\n}\n"], ["/opencode/internal/llm/models/local.go", "package models\n\nimport (\n\t\"cmp\"\n\t\"encoding/json\"\n\t\"net/http\"\n\t\"net/url\"\n\t\"os\"\n\t\"regexp\"\n\t\"strings\"\n\t\"unicode\"\n\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n\t\"github.com/spf13/viper\"\n)\n\nconst (\n\tProviderLocal ModelProvider = \"local\"\n\n\tlocalModelsPath = \"v1/models\"\n\tlmStudioBetaModelsPath = \"api/v0/models\"\n)\n\nfunc init() {\n\tif endpoint := os.Getenv(\"LOCAL_ENDPOINT\"); endpoint != \"\" {\n\t\tlocalEndpoint, err := url.Parse(endpoint)\n\t\tif err != nil {\n\t\t\tlogging.Debug(\"Failed to parse local endpoint\",\n\t\t\t\t\"error\", err,\n\t\t\t\t\"endpoint\", endpoint,\n\t\t\t)\n\t\t\treturn\n\t\t}\n\n\t\tload := func(url *url.URL, path string) []localModel {\n\t\t\turl.Path = path\n\t\t\treturn listLocalModels(url.String())\n\t\t}\n\n\t\tmodels := load(localEndpoint, lmStudioBetaModelsPath)\n\n\t\tif len(models) == 0 {\n\t\t\tmodels = load(localEndpoint, localModelsPath)\n\t\t}\n\n\t\tif len(models) == 0 {\n\t\t\tlogging.Debug(\"No local models found\",\n\t\t\t\t\"endpoint\", endpoint,\n\t\t\t)\n\t\t\treturn\n\t\t}\n\n\t\tloadLocalModels(models)\n\n\t\tviper.SetDefault(\"providers.local.apiKey\", \"dummy\")\n\t\tProviderPopularity[ProviderLocal] = 0\n\t}\n}\n\ntype localModelList struct {\n\tData []localModel `json:\"data\"`\n}\n\ntype localModel struct {\n\tID string `json:\"id\"`\n\tObject string `json:\"object\"`\n\tType string `json:\"type\"`\n\tPublisher string `json:\"publisher\"`\n\tArch string `json:\"arch\"`\n\tCompatibilityType string `json:\"compatibility_type\"`\n\tQuantization string `json:\"quantization\"`\n\tState string `json:\"state\"`\n\tMaxContextLength int64 `json:\"max_context_length\"`\n\tLoadedContextLength int64 `json:\"loaded_context_length\"`\n}\n\nfunc listLocalModels(modelsEndpoint string) []localModel {\n\tres, err := http.Get(modelsEndpoint)\n\tif err != nil {\n\t\tlogging.Debug(\"Failed to list local models\",\n\t\t\t\"error\", err,\n\t\t\t\"endpoint\", modelsEndpoint,\n\t\t)\n\t\treturn []localModel{}\n\t}\n\tdefer res.Body.Close()\n\n\tif res.StatusCode != http.StatusOK {\n\t\tlogging.Debug(\"Failed to list local models\",\n\t\t\t\"status\", res.StatusCode,\n\t\t\t\"endpoint\", modelsEndpoint,\n\t\t)\n\t\treturn []localModel{}\n\t}\n\n\tvar modelList localModelList\n\tif err = json.NewDecoder(res.Body).Decode(&modelList); err != nil {\n\t\tlogging.Debug(\"Failed to list local models\",\n\t\t\t\"error\", err,\n\t\t\t\"endpoint\", modelsEndpoint,\n\t\t)\n\t\treturn []localModel{}\n\t}\n\n\tvar supportedModels []localModel\n\tfor _, model := range modelList.Data {\n\t\tif strings.HasSuffix(modelsEndpoint, lmStudioBetaModelsPath) {\n\t\t\tif model.Object != \"model\" || model.Type != \"llm\" {\n\t\t\t\tlogging.Debug(\"Skipping unsupported LMStudio model\",\n\t\t\t\t\t\"endpoint\", modelsEndpoint,\n\t\t\t\t\t\"id\", model.ID,\n\t\t\t\t\t\"object\", model.Object,\n\t\t\t\t\t\"type\", model.Type,\n\t\t\t\t)\n\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\n\t\tsupportedModels = append(supportedModels, model)\n\t}\n\n\treturn supportedModels\n}\n\nfunc loadLocalModels(models []localModel) {\n\tfor i, m := range models {\n\t\tmodel := convertLocalModel(m)\n\t\tSupportedModels[model.ID] = model\n\n\t\tif i == 0 || m.State == \"loaded\" {\n\t\t\tviper.SetDefault(\"agents.coder.model\", model.ID)\n\t\t\tviper.SetDefault(\"agents.summarizer.model\", model.ID)\n\t\t\tviper.SetDefault(\"agents.task.model\", model.ID)\n\t\t\tviper.SetDefault(\"agents.title.model\", model.ID)\n\t\t}\n\t}\n}\n\nfunc convertLocalModel(model localModel) Model {\n\treturn Model{\n\t\tID: ModelID(\"local.\" + model.ID),\n\t\tName: friendlyModelName(model.ID),\n\t\tProvider: ProviderLocal,\n\t\tAPIModel: model.ID,\n\t\tContextWindow: cmp.Or(model.LoadedContextLength, 4096),\n\t\tDefaultMaxTokens: cmp.Or(model.LoadedContextLength, 4096),\n\t\tCanReason: true,\n\t\tSupportsAttachments: true,\n\t}\n}\n\nvar modelInfoRegex = regexp.MustCompile(`(?i)^([a-z0-9]+)(?:[-_]?([rv]?\\d[\\.\\d]*))?(?:[-_]?([a-z]+))?.*`)\n\nfunc friendlyModelName(modelID string) string {\n\tmainID := modelID\n\ttag := \"\"\n\n\tif slash := strings.LastIndex(mainID, \"/\"); slash != -1 {\n\t\tmainID = mainID[slash+1:]\n\t}\n\n\tif at := strings.Index(modelID, \"@\"); at != -1 {\n\t\tmainID = modelID[:at]\n\t\ttag = modelID[at+1:]\n\t}\n\n\tmatch := modelInfoRegex.FindStringSubmatch(mainID)\n\tif match == nil {\n\t\treturn modelID\n\t}\n\n\tcapitalize := func(s string) string {\n\t\tif s == \"\" {\n\t\t\treturn \"\"\n\t\t}\n\t\trunes := []rune(s)\n\t\trunes[0] = unicode.ToUpper(runes[0])\n\t\treturn string(runes)\n\t}\n\n\tfamily := capitalize(match[1])\n\tversion := \"\"\n\tlabel := \"\"\n\n\tif len(match) > 2 && match[2] != \"\" {\n\t\tversion = strings.ToUpper(match[2])\n\t}\n\n\tif len(match) > 3 && match[3] != \"\" {\n\t\tlabel = capitalize(match[3])\n\t}\n\n\tvar parts []string\n\tif family != \"\" {\n\t\tparts = append(parts, family)\n\t}\n\tif version != \"\" {\n\t\tparts = append(parts, version)\n\t}\n\tif label != \"\" {\n\t\tparts = append(parts, label)\n\t}\n\tif tag != \"\" {\n\t\tparts = append(parts, tag)\n\t}\n\n\treturn strings.Join(parts, \" \")\n}\n"], ["/opencode/internal/fileutil/fileutil.go", "package fileutil\n\nimport (\n\t\"fmt\"\n\t\"io/fs\"\n\t\"os\"\n\t\"os/exec\"\n\t\"path/filepath\"\n\t\"sort\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/bmatcuk/doublestar/v4\"\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n)\n\nvar (\n\trgPath string\n\tfzfPath string\n)\n\nfunc init() {\n\tvar err error\n\trgPath, err = exec.LookPath(\"rg\")\n\tif err != nil {\n\t\tlogging.Warn(\"Ripgrep (rg) not found in $PATH. Some features might be limited or slower.\")\n\t\trgPath = \"\"\n\t}\n\tfzfPath, err = exec.LookPath(\"fzf\")\n\tif err != nil {\n\t\tlogging.Warn(\"FZF not found in $PATH. Some features might be limited or slower.\")\n\t\tfzfPath = \"\"\n\t}\n}\n\nfunc GetRgCmd(globPattern string) *exec.Cmd {\n\tif rgPath == \"\" {\n\t\treturn nil\n\t}\n\trgArgs := []string{\n\t\t\"--files\",\n\t\t\"-L\",\n\t\t\"--null\",\n\t}\n\tif globPattern != \"\" {\n\t\tif !filepath.IsAbs(globPattern) && !strings.HasPrefix(globPattern, \"/\") {\n\t\t\tglobPattern = \"/\" + globPattern\n\t\t}\n\t\trgArgs = append(rgArgs, \"--glob\", globPattern)\n\t}\n\tcmd := exec.Command(rgPath, rgArgs...)\n\tcmd.Dir = \".\"\n\treturn cmd\n}\n\nfunc GetFzfCmd(query string) *exec.Cmd {\n\tif fzfPath == \"\" {\n\t\treturn nil\n\t}\n\tfzfArgs := []string{\n\t\t\"--filter\",\n\t\tquery,\n\t\t\"--read0\",\n\t\t\"--print0\",\n\t}\n\tcmd := exec.Command(fzfPath, fzfArgs...)\n\tcmd.Dir = \".\"\n\treturn cmd\n}\n\ntype FileInfo struct {\n\tPath string\n\tModTime time.Time\n}\n\nfunc SkipHidden(path string) bool {\n\t// Check for hidden files (starting with a dot)\n\tbase := filepath.Base(path)\n\tif base != \".\" && strings.HasPrefix(base, \".\") {\n\t\treturn true\n\t}\n\n\tcommonIgnoredDirs := map[string]bool{\n\t\t\".opencode\": true,\n\t\t\"node_modules\": true,\n\t\t\"vendor\": true,\n\t\t\"dist\": true,\n\t\t\"build\": true,\n\t\t\"target\": true,\n\t\t\".git\": true,\n\t\t\".idea\": true,\n\t\t\".vscode\": true,\n\t\t\"__pycache__\": true,\n\t\t\"bin\": true,\n\t\t\"obj\": true,\n\t\t\"out\": true,\n\t\t\"coverage\": true,\n\t\t\"tmp\": true,\n\t\t\"temp\": true,\n\t\t\"logs\": true,\n\t\t\"generated\": true,\n\t\t\"bower_components\": true,\n\t\t\"jspm_packages\": true,\n\t}\n\n\tparts := strings.Split(path, string(os.PathSeparator))\n\tfor _, part := range parts {\n\t\tif commonIgnoredDirs[part] {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc GlobWithDoublestar(pattern, searchPath string, limit int) ([]string, bool, error) {\n\tfsys := os.DirFS(searchPath)\n\trelPattern := strings.TrimPrefix(pattern, \"/\")\n\tvar matches []FileInfo\n\n\terr := doublestar.GlobWalk(fsys, relPattern, func(path string, d fs.DirEntry) error {\n\t\tif d.IsDir() {\n\t\t\treturn nil\n\t\t}\n\t\tif SkipHidden(path) {\n\t\t\treturn nil\n\t\t}\n\t\tinfo, err := d.Info()\n\t\tif err != nil {\n\t\t\treturn nil\n\t\t}\n\t\tabsPath := path\n\t\tif !strings.HasPrefix(absPath, searchPath) && searchPath != \".\" {\n\t\t\tabsPath = filepath.Join(searchPath, absPath)\n\t\t} else if !strings.HasPrefix(absPath, \"/\") && searchPath == \".\" {\n\t\t\tabsPath = filepath.Join(searchPath, absPath) // Ensure relative paths are joined correctly\n\t\t}\n\n\t\tmatches = append(matches, FileInfo{Path: absPath, ModTime: info.ModTime()})\n\t\tif limit > 0 && len(matches) >= limit*2 {\n\t\t\treturn fs.SkipAll\n\t\t}\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\treturn nil, false, fmt.Errorf(\"glob walk error: %w\", err)\n\t}\n\n\tsort.Slice(matches, func(i, j int) bool {\n\t\treturn matches[i].ModTime.After(matches[j].ModTime)\n\t})\n\n\ttruncated := false\n\tif limit > 0 && len(matches) > limit {\n\t\tmatches = matches[:limit]\n\t\ttruncated = true\n\t}\n\n\tresults := make([]string, len(matches))\n\tfor i, m := range matches {\n\t\tresults[i] = m.Path\n\t}\n\treturn results, truncated, nil\n}\n"], ["/opencode/internal/message/message.go", "package message\n\nimport (\n\t\"context\"\n\t\"database/sql\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com/google/uuid\"\n\t\"github.com/opencode-ai/opencode/internal/db\"\n\t\"github.com/opencode-ai/opencode/internal/llm/models\"\n\t\"github.com/opencode-ai/opencode/internal/pubsub\"\n)\n\ntype CreateMessageParams struct {\n\tRole MessageRole\n\tParts []ContentPart\n\tModel models.ModelID\n}\n\ntype Service interface {\n\tpubsub.Suscriber[Message]\n\tCreate(ctx context.Context, sessionID string, params CreateMessageParams) (Message, error)\n\tUpdate(ctx context.Context, message Message) error\n\tGet(ctx context.Context, id string) (Message, error)\n\tList(ctx context.Context, sessionID string) ([]Message, error)\n\tDelete(ctx context.Context, id string) error\n\tDeleteSessionMessages(ctx context.Context, sessionID string) error\n}\n\ntype service struct {\n\t*pubsub.Broker[Message]\n\tq db.Querier\n}\n\nfunc NewService(q db.Querier) Service {\n\treturn &service{\n\t\tBroker: pubsub.NewBroker[Message](),\n\t\tq: q,\n\t}\n}\n\nfunc (s *service) Delete(ctx context.Context, id string) error {\n\tmessage, err := s.Get(ctx, id)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = s.q.DeleteMessage(ctx, message.ID)\n\tif err != nil {\n\t\treturn err\n\t}\n\ts.Publish(pubsub.DeletedEvent, message)\n\treturn nil\n}\n\nfunc (s *service) Create(ctx context.Context, sessionID string, params CreateMessageParams) (Message, error) {\n\tif params.Role != Assistant {\n\t\tparams.Parts = append(params.Parts, Finish{\n\t\t\tReason: \"stop\",\n\t\t})\n\t}\n\tpartsJSON, err := marshallParts(params.Parts)\n\tif err != nil {\n\t\treturn Message{}, err\n\t}\n\tdbMessage, err := s.q.CreateMessage(ctx, db.CreateMessageParams{\n\t\tID: uuid.New().String(),\n\t\tSessionID: sessionID,\n\t\tRole: string(params.Role),\n\t\tParts: string(partsJSON),\n\t\tModel: sql.NullString{String: string(params.Model), Valid: true},\n\t})\n\tif err != nil {\n\t\treturn Message{}, err\n\t}\n\tmessage, err := s.fromDBItem(dbMessage)\n\tif err != nil {\n\t\treturn Message{}, err\n\t}\n\ts.Publish(pubsub.CreatedEvent, message)\n\treturn message, nil\n}\n\nfunc (s *service) DeleteSessionMessages(ctx context.Context, sessionID string) error {\n\tmessages, err := s.List(ctx, sessionID)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor _, message := range messages {\n\t\tif message.SessionID == sessionID {\n\t\t\terr = s.Delete(ctx, message.ID)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (s *service) Update(ctx context.Context, message Message) error {\n\tparts, err := marshallParts(message.Parts)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfinishedAt := sql.NullInt64{}\n\tif f := message.FinishPart(); f != nil {\n\t\tfinishedAt.Int64 = f.Time\n\t\tfinishedAt.Valid = true\n\t}\n\terr = s.q.UpdateMessage(ctx, db.UpdateMessageParams{\n\t\tID: message.ID,\n\t\tParts: string(parts),\n\t\tFinishedAt: finishedAt,\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\tmessage.UpdatedAt = time.Now().Unix()\n\ts.Publish(pubsub.UpdatedEvent, message)\n\treturn nil\n}\n\nfunc (s *service) Get(ctx context.Context, id string) (Message, error) {\n\tdbMessage, err := s.q.GetMessage(ctx, id)\n\tif err != nil {\n\t\treturn Message{}, err\n\t}\n\treturn s.fromDBItem(dbMessage)\n}\n\nfunc (s *service) List(ctx context.Context, sessionID string) ([]Message, error) {\n\tdbMessages, err := s.q.ListMessagesBySession(ctx, sessionID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tmessages := make([]Message, len(dbMessages))\n\tfor i, dbMessage := range dbMessages {\n\t\tmessages[i], err = s.fromDBItem(dbMessage)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn messages, nil\n}\n\nfunc (s *service) fromDBItem(item db.Message) (Message, error) {\n\tparts, err := unmarshallParts([]byte(item.Parts))\n\tif err != nil {\n\t\treturn Message{}, err\n\t}\n\treturn Message{\n\t\tID: item.ID,\n\t\tSessionID: item.SessionID,\n\t\tRole: MessageRole(item.Role),\n\t\tParts: parts,\n\t\tModel: models.ModelID(item.Model.String),\n\t\tCreatedAt: item.CreatedAt,\n\t\tUpdatedAt: item.UpdatedAt,\n\t}, nil\n}\n\ntype partType string\n\nconst (\n\treasoningType partType = \"reasoning\"\n\ttextType partType = \"text\"\n\timageURLType partType = \"image_url\"\n\tbinaryType partType = \"binary\"\n\ttoolCallType partType = \"tool_call\"\n\ttoolResultType partType = \"tool_result\"\n\tfinishType partType = \"finish\"\n)\n\ntype partWrapper struct {\n\tType partType `json:\"type\"`\n\tData ContentPart `json:\"data\"`\n}\n\nfunc marshallParts(parts []ContentPart) ([]byte, error) {\n\twrappedParts := make([]partWrapper, len(parts))\n\n\tfor i, part := range parts {\n\t\tvar typ partType\n\n\t\tswitch part.(type) {\n\t\tcase ReasoningContent:\n\t\t\ttyp = reasoningType\n\t\tcase TextContent:\n\t\t\ttyp = textType\n\t\tcase ImageURLContent:\n\t\t\ttyp = imageURLType\n\t\tcase BinaryContent:\n\t\t\ttyp = binaryType\n\t\tcase ToolCall:\n\t\t\ttyp = toolCallType\n\t\tcase ToolResult:\n\t\t\ttyp = toolResultType\n\t\tcase Finish:\n\t\t\ttyp = finishType\n\t\tdefault:\n\t\t\treturn nil, fmt.Errorf(\"unknown part type: %T\", part)\n\t\t}\n\n\t\twrappedParts[i] = partWrapper{\n\t\t\tType: typ,\n\t\t\tData: part,\n\t\t}\n\t}\n\treturn json.Marshal(wrappedParts)\n}\n\nfunc unmarshallParts(data []byte) ([]ContentPart, error) {\n\ttemp := []json.RawMessage{}\n\n\tif err := json.Unmarshal(data, &temp); err != nil {\n\t\treturn nil, err\n\t}\n\n\tparts := make([]ContentPart, 0)\n\n\tfor _, rawPart := range temp {\n\t\tvar wrapper struct {\n\t\t\tType partType `json:\"type\"`\n\t\t\tData json.RawMessage `json:\"data\"`\n\t\t}\n\n\t\tif err := json.Unmarshal(rawPart, &wrapper); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tswitch wrapper.Type {\n\t\tcase reasoningType:\n\t\t\tpart := ReasoningContent{}\n\t\t\tif err := json.Unmarshal(wrapper.Data, &part); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tparts = append(parts, part)\n\t\tcase textType:\n\t\t\tpart := TextContent{}\n\t\t\tif err := json.Unmarshal(wrapper.Data, &part); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tparts = append(parts, part)\n\t\tcase imageURLType:\n\t\t\tpart := ImageURLContent{}\n\t\t\tif err := json.Unmarshal(wrapper.Data, &part); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\tcase binaryType:\n\t\t\tpart := BinaryContent{}\n\t\t\tif err := json.Unmarshal(wrapper.Data, &part); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tparts = append(parts, part)\n\t\tcase toolCallType:\n\t\t\tpart := ToolCall{}\n\t\t\tif err := json.Unmarshal(wrapper.Data, &part); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tparts = append(parts, part)\n\t\tcase toolResultType:\n\t\t\tpart := ToolResult{}\n\t\t\tif err := json.Unmarshal(wrapper.Data, &part); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tparts = append(parts, part)\n\t\tcase finishType:\n\t\t\tpart := Finish{}\n\t\t\tif err := json.Unmarshal(wrapper.Data, &part); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tparts = append(parts, part)\n\t\tdefault:\n\t\t\treturn nil, fmt.Errorf(\"unknown part type: %s\", wrapper.Type)\n\t\t}\n\n\t}\n\n\treturn parts, nil\n}\n"], ["/opencode/internal/llm/provider/anthropic.go", "package provider\n\nimport (\n\t\"context\"\n\t\"encoding/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/anthropics/anthropic-sdk-go\"\n\t\"github.com/anthropics/anthropic-sdk-go/bedrock\"\n\t\"github.com/anthropics/anthropic-sdk-go/option\"\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/llm/models\"\n\ttoolsPkg \"github.com/opencode-ai/opencode/internal/llm/tools\"\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n\t\"github.com/opencode-ai/opencode/internal/message\"\n)\n\ntype anthropicOptions struct {\n\tuseBedrock bool\n\tdisableCache bool\n\tshouldThink func(userMessage string) bool\n}\n\ntype AnthropicOption func(*anthropicOptions)\n\ntype anthropicClient struct {\n\tproviderOptions providerClientOptions\n\toptions anthropicOptions\n\tclient anthropic.Client\n}\n\ntype AnthropicClient ProviderClient\n\nfunc newAnthropicClient(opts providerClientOptions) AnthropicClient {\n\tanthropicOpts := anthropicOptions{}\n\tfor _, o := range opts.anthropicOptions {\n\t\to(&anthropicOpts)\n\t}\n\n\tanthropicClientOptions := []option.RequestOption{}\n\tif opts.apiKey != \"\" {\n\t\tanthropicClientOptions = append(anthropicClientOptions, option.WithAPIKey(opts.apiKey))\n\t}\n\tif anthropicOpts.useBedrock {\n\t\tanthropicClientOptions = append(anthropicClientOptions, bedrock.WithLoadDefaultConfig(context.Background()))\n\t}\n\n\tclient := anthropic.NewClient(anthropicClientOptions...)\n\treturn &anthropicClient{\n\t\tproviderOptions: opts,\n\t\toptions: anthropicOpts,\n\t\tclient: client,\n\t}\n}\n\nfunc (a *anthropicClient) convertMessages(messages []message.Message) (anthropicMessages []anthropic.MessageParam) {\n\tfor i, msg := range messages {\n\t\tcache := false\n\t\tif i > len(messages)-3 {\n\t\t\tcache = true\n\t\t}\n\t\tswitch msg.Role {\n\t\tcase message.User:\n\t\t\tcontent := anthropic.NewTextBlock(msg.Content().String())\n\t\t\tif cache && !a.options.disableCache {\n\t\t\t\tcontent.OfText.CacheControl = anthropic.CacheControlEphemeralParam{\n\t\t\t\t\tType: \"ephemeral\",\n\t\t\t\t}\n\t\t\t}\n\t\t\tvar contentBlocks []anthropic.ContentBlockParamUnion\n\t\t\tcontentBlocks = append(contentBlocks, content)\n\t\t\tfor _, binaryContent := range msg.BinaryContent() {\n\t\t\t\tbase64Image := binaryContent.String(models.ProviderAnthropic)\n\t\t\t\timageBlock := anthropic.NewImageBlockBase64(binaryContent.MIMEType, base64Image)\n\t\t\t\tcontentBlocks = append(contentBlocks, imageBlock)\n\t\t\t}\n\t\t\tanthropicMessages = append(anthropicMessages, anthropic.NewUserMessage(contentBlocks...))\n\n\t\tcase message.Assistant:\n\t\t\tblocks := []anthropic.ContentBlockParamUnion{}\n\t\t\tif msg.Content().String() != \"\" {\n\t\t\t\tcontent := anthropic.NewTextBlock(msg.Content().String())\n\t\t\t\tif cache && !a.options.disableCache {\n\t\t\t\t\tcontent.OfText.CacheControl = anthropic.CacheControlEphemeralParam{\n\t\t\t\t\t\tType: \"ephemeral\",\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tblocks = append(blocks, content)\n\t\t\t}\n\n\t\t\tfor _, toolCall := range msg.ToolCalls() {\n\t\t\t\tvar inputMap map[string]any\n\t\t\t\terr := json.Unmarshal([]byte(toolCall.Input), &inputMap)\n\t\t\t\tif err != nil {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tblocks = append(blocks, anthropic.NewToolUseBlock(toolCall.ID, inputMap, toolCall.Name))\n\t\t\t}\n\n\t\t\tif len(blocks) == 0 {\n\t\t\t\tlogging.Warn(\"There is a message without content, investigate, this should not happen\")\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tanthropicMessages = append(anthropicMessages, anthropic.NewAssistantMessage(blocks...))\n\n\t\tcase message.Tool:\n\t\t\tresults := make([]anthropic.ContentBlockParamUnion, len(msg.ToolResults()))\n\t\t\tfor i, toolResult := range msg.ToolResults() {\n\t\t\t\tresults[i] = anthropic.NewToolResultBlock(toolResult.ToolCallID, toolResult.Content, toolResult.IsError)\n\t\t\t}\n\t\t\tanthropicMessages = append(anthropicMessages, anthropic.NewUserMessage(results...))\n\t\t}\n\t}\n\treturn\n}\n\nfunc (a *anthropicClient) convertTools(tools []toolsPkg.BaseTool) []anthropic.ToolUnionParam {\n\tanthropicTools := make([]anthropic.ToolUnionParam, len(tools))\n\n\tfor i, tool := range tools {\n\t\tinfo := tool.Info()\n\t\ttoolParam := anthropic.ToolParam{\n\t\t\tName: info.Name,\n\t\t\tDescription: anthropic.String(info.Description),\n\t\t\tInputSchema: anthropic.ToolInputSchemaParam{\n\t\t\t\tProperties: info.Parameters,\n\t\t\t\t// TODO: figure out how we can tell claude the required fields?\n\t\t\t},\n\t\t}\n\n\t\tif i == len(tools)-1 && !a.options.disableCache {\n\t\t\ttoolParam.CacheControl = anthropic.CacheControlEphemeralParam{\n\t\t\t\tType: \"ephemeral\",\n\t\t\t}\n\t\t}\n\n\t\tanthropicTools[i] = anthropic.ToolUnionParam{OfTool: &toolParam}\n\t}\n\n\treturn anthropicTools\n}\n\nfunc (a *anthropicClient) finishReason(reason string) message.FinishReason {\n\tswitch reason {\n\tcase \"end_turn\":\n\t\treturn message.FinishReasonEndTurn\n\tcase \"max_tokens\":\n\t\treturn message.FinishReasonMaxTokens\n\tcase \"tool_use\":\n\t\treturn message.FinishReasonToolUse\n\tcase \"stop_sequence\":\n\t\treturn message.FinishReasonEndTurn\n\tdefault:\n\t\treturn message.FinishReasonUnknown\n\t}\n}\n\nfunc (a *anthropicClient) preparedMessages(messages []anthropic.MessageParam, tools []anthropic.ToolUnionParam) anthropic.MessageNewParams {\n\tvar thinkingParam anthropic.ThinkingConfigParamUnion\n\tlastMessage := messages[len(messages)-1]\n\tisUser := lastMessage.Role == anthropic.MessageParamRoleUser\n\tmessageContent := \"\"\n\ttemperature := anthropic.Float(0)\n\tif isUser {\n\t\tfor _, m := range lastMessage.Content {\n\t\t\tif m.OfText != nil && m.OfText.Text != \"\" {\n\t\t\t\tmessageContent = m.OfText.Text\n\t\t\t}\n\t\t}\n\t\tif messageContent != \"\" && a.options.shouldThink != nil && a.options.shouldThink(messageContent) {\n\t\t\tthinkingParam = anthropic.ThinkingConfigParamOfEnabled(int64(float64(a.providerOptions.maxTokens) * 0.8))\n\t\t\ttemperature = anthropic.Float(1)\n\t\t}\n\t}\n\n\treturn anthropic.MessageNewParams{\n\t\tModel: anthropic.Model(a.providerOptions.model.APIModel),\n\t\tMaxTokens: a.providerOptions.maxTokens,\n\t\tTemperature: temperature,\n\t\tMessages: messages,\n\t\tTools: tools,\n\t\tThinking: thinkingParam,\n\t\tSystem: []anthropic.TextBlockParam{\n\t\t\t{\n\t\t\t\tText: a.providerOptions.systemMessage,\n\t\t\t\tCacheControl: anthropic.CacheControlEphemeralParam{\n\t\t\t\t\tType: \"ephemeral\",\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n}\n\nfunc (a *anthropicClient) send(ctx context.Context, messages []message.Message, tools []toolsPkg.BaseTool) (resposne *ProviderResponse, err error) {\n\tpreparedMessages := a.preparedMessages(a.convertMessages(messages), a.convertTools(tools))\n\tcfg := config.Get()\n\tif cfg.Debug {\n\t\tjsonData, _ := json.Marshal(preparedMessages)\n\t\tlogging.Debug(\"Prepared messages\", \"messages\", string(jsonData))\n\t}\n\n\tattempts := 0\n\tfor {\n\t\tattempts++\n\t\tanthropicResponse, err := a.client.Messages.New(\n\t\t\tctx,\n\t\t\tpreparedMessages,\n\t\t)\n\t\t// If there is an error we are going to see if we can retry the call\n\t\tif err != nil {\n\t\t\tlogging.Error(\"Error in Anthropic API call\", \"error\", err)\n\t\t\tretry, after, retryErr := a.shouldRetry(attempts, err)\n\t\t\tif retryErr != nil {\n\t\t\t\treturn nil, retryErr\n\t\t\t}\n\t\t\tif retry {\n\t\t\t\tlogging.WarnPersist(fmt.Sprintf(\"Retrying due to rate limit... attempt %d of %d\", attempts, maxRetries), logging.PersistTimeArg, time.Millisecond*time.Duration(after+100))\n\t\t\t\tselect {\n\t\t\t\tcase <-ctx.Done():\n\t\t\t\t\treturn nil, ctx.Err()\n\t\t\t\tcase <-time.After(time.Duration(after) * time.Millisecond):\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn nil, retryErr\n\t\t}\n\n\t\tcontent := \"\"\n\t\tfor _, block := range anthropicResponse.Content {\n\t\t\tif text, ok := block.AsAny().(anthropic.TextBlock); ok {\n\t\t\t\tcontent += text.Text\n\t\t\t}\n\t\t}\n\n\t\treturn &ProviderResponse{\n\t\t\tContent: content,\n\t\t\tToolCalls: a.toolCalls(*anthropicResponse),\n\t\t\tUsage: a.usage(*anthropicResponse),\n\t\t}, nil\n\t}\n}\n\nfunc (a *anthropicClient) stream(ctx context.Context, messages []message.Message, tools []toolsPkg.BaseTool) <-chan ProviderEvent {\n\tpreparedMessages := a.preparedMessages(a.convertMessages(messages), a.convertTools(tools))\n\tcfg := config.Get()\n\n\tvar sessionId string\n\trequestSeqId := (len(messages) + 1) / 2\n\tif cfg.Debug {\n\t\tif sid, ok := ctx.Value(toolsPkg.SessionIDContextKey).(string); ok {\n\t\t\tsessionId = sid\n\t\t}\n\t\tjsonData, _ := json.Marshal(preparedMessages)\n\t\tif sessionId != \"\" {\n\t\t\tfilepath := logging.WriteRequestMessageJson(sessionId, requestSeqId, preparedMessages)\n\t\t\tlogging.Debug(\"Prepared messages\", \"filepath\", filepath)\n\t\t} else {\n\t\t\tlogging.Debug(\"Prepared messages\", \"messages\", string(jsonData))\n\t\t}\n\n\t}\n\tattempts := 0\n\teventChan := make(chan ProviderEvent)\n\tgo func() {\n\t\tfor {\n\t\t\tattempts++\n\t\t\tanthropicStream := a.client.Messages.NewStreaming(\n\t\t\t\tctx,\n\t\t\t\tpreparedMessages,\n\t\t\t)\n\t\t\taccumulatedMessage := anthropic.Message{}\n\n\t\t\tcurrentToolCallID := \"\"\n\t\t\tfor anthropicStream.Next() {\n\t\t\t\tevent := anthropicStream.Current()\n\t\t\t\terr := accumulatedMessage.Accumulate(event)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlogging.Warn(\"Error accumulating message\", \"error\", err)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tswitch event := event.AsAny().(type) {\n\t\t\t\tcase anthropic.ContentBlockStartEvent:\n\t\t\t\t\tif event.ContentBlock.Type == \"text\" {\n\t\t\t\t\t\teventChan <- ProviderEvent{Type: EventContentStart}\n\t\t\t\t\t} else if event.ContentBlock.Type == \"tool_use\" {\n\t\t\t\t\t\tcurrentToolCallID = event.ContentBlock.ID\n\t\t\t\t\t\teventChan <- ProviderEvent{\n\t\t\t\t\t\t\tType: EventToolUseStart,\n\t\t\t\t\t\t\tToolCall: &message.ToolCall{\n\t\t\t\t\t\t\t\tID: event.ContentBlock.ID,\n\t\t\t\t\t\t\t\tName: event.ContentBlock.Name,\n\t\t\t\t\t\t\t\tFinished: false,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\tcase anthropic.ContentBlockDeltaEvent:\n\t\t\t\t\tif event.Delta.Type == \"thinking_delta\" && event.Delta.Thinking != \"\" {\n\t\t\t\t\t\teventChan <- ProviderEvent{\n\t\t\t\t\t\t\tType: EventThinkingDelta,\n\t\t\t\t\t\t\tThinking: event.Delta.Thinking,\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if event.Delta.Type == \"text_delta\" && event.Delta.Text != \"\" {\n\t\t\t\t\t\teventChan <- ProviderEvent{\n\t\t\t\t\t\t\tType: EventContentDelta,\n\t\t\t\t\t\t\tContent: event.Delta.Text,\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if event.Delta.Type == \"input_json_delta\" {\n\t\t\t\t\t\tif currentToolCallID != \"\" {\n\t\t\t\t\t\t\teventChan <- ProviderEvent{\n\t\t\t\t\t\t\t\tType: EventToolUseDelta,\n\t\t\t\t\t\t\t\tToolCall: &message.ToolCall{\n\t\t\t\t\t\t\t\t\tID: currentToolCallID,\n\t\t\t\t\t\t\t\t\tFinished: false,\n\t\t\t\t\t\t\t\t\tInput: event.Delta.JSON.PartialJSON.Raw(),\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\tcase anthropic.ContentBlockStopEvent:\n\t\t\t\t\tif currentToolCallID != \"\" {\n\t\t\t\t\t\teventChan <- ProviderEvent{\n\t\t\t\t\t\t\tType: EventToolUseStop,\n\t\t\t\t\t\t\tToolCall: &message.ToolCall{\n\t\t\t\t\t\t\t\tID: currentToolCallID,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcurrentToolCallID = \"\"\n\t\t\t\t\t} else {\n\t\t\t\t\t\teventChan <- ProviderEvent{Type: EventContentStop}\n\t\t\t\t\t}\n\n\t\t\t\tcase anthropic.MessageStopEvent:\n\t\t\t\t\tcontent := \"\"\n\t\t\t\t\tfor _, block := range accumulatedMessage.Content {\n\t\t\t\t\t\tif text, ok := block.AsAny().(anthropic.TextBlock); ok {\n\t\t\t\t\t\t\tcontent += text.Text\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\teventChan <- ProviderEvent{\n\t\t\t\t\t\tType: EventComplete,\n\t\t\t\t\t\tResponse: &ProviderResponse{\n\t\t\t\t\t\t\tContent: content,\n\t\t\t\t\t\t\tToolCalls: a.toolCalls(accumulatedMessage),\n\t\t\t\t\t\t\tUsage: a.usage(accumulatedMessage),\n\t\t\t\t\t\t\tFinishReason: a.finishReason(string(accumulatedMessage.StopReason)),\n\t\t\t\t\t\t},\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\terr := anthropicStream.Err()\n\t\t\tif err == nil || errors.Is(err, io.EOF) {\n\t\t\t\tclose(eventChan)\n\t\t\t\treturn\n\t\t\t}\n\t\t\t// If there is an error we are going to see if we can retry the call\n\t\t\tretry, after, retryErr := a.shouldRetry(attempts, err)\n\t\t\tif retryErr != nil {\n\t\t\t\teventChan <- ProviderEvent{Type: EventError, Error: retryErr}\n\t\t\t\tclose(eventChan)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif retry {\n\t\t\t\tlogging.WarnPersist(fmt.Sprintf(\"Retrying due to rate limit... attempt %d of %d\", attempts, maxRetries), logging.PersistTimeArg, time.Millisecond*time.Duration(after+100))\n\t\t\t\tselect {\n\t\t\t\tcase <-ctx.Done():\n\t\t\t\t\t// context cancelled\n\t\t\t\t\tif ctx.Err() != nil {\n\t\t\t\t\t\teventChan <- ProviderEvent{Type: EventError, Error: ctx.Err()}\n\t\t\t\t\t}\n\t\t\t\t\tclose(eventChan)\n\t\t\t\t\treturn\n\t\t\t\tcase <-time.After(time.Duration(after) * time.Millisecond):\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t\tif ctx.Err() != nil {\n\t\t\t\teventChan <- ProviderEvent{Type: EventError, Error: ctx.Err()}\n\t\t\t}\n\n\t\t\tclose(eventChan)\n\t\t\treturn\n\t\t}\n\t}()\n\treturn eventChan\n}\n\nfunc (a *anthropicClient) shouldRetry(attempts int, err error) (bool, int64, error) {\n\tvar apierr *anthropic.Error\n\tif !errors.As(err, &apierr) {\n\t\treturn false, 0, err\n\t}\n\n\tif apierr.StatusCode != 429 && apierr.StatusCode != 529 {\n\t\treturn false, 0, err\n\t}\n\n\tif attempts > maxRetries {\n\t\treturn false, 0, fmt.Errorf(\"maximum retry attempts reached for rate limit: %d retries\", maxRetries)\n\t}\n\n\tretryMs := 0\n\tretryAfterValues := apierr.Response.Header.Values(\"Retry-After\")\n\n\tbackoffMs := 2000 * (1 << (attempts - 1))\n\tjitterMs := int(float64(backoffMs) * 0.2)\n\tretryMs = backoffMs + jitterMs\n\tif len(retryAfterValues) > 0 {\n\t\tif _, err := fmt.Sscanf(retryAfterValues[0], \"%d\", &retryMs); err == nil {\n\t\t\tretryMs = retryMs * 1000\n\t\t}\n\t}\n\treturn true, int64(retryMs), nil\n}\n\nfunc (a *anthropicClient) toolCalls(msg anthropic.Message) []message.ToolCall {\n\tvar toolCalls []message.ToolCall\n\n\tfor _, block := range msg.Content {\n\t\tswitch variant := block.AsAny().(type) {\n\t\tcase anthropic.ToolUseBlock:\n\t\t\ttoolCall := message.ToolCall{\n\t\t\t\tID: variant.ID,\n\t\t\t\tName: variant.Name,\n\t\t\t\tInput: string(variant.Input),\n\t\t\t\tType: string(variant.Type),\n\t\t\t\tFinished: true,\n\t\t\t}\n\t\t\ttoolCalls = append(toolCalls, toolCall)\n\t\t}\n\t}\n\n\treturn toolCalls\n}\n\nfunc (a *anthropicClient) usage(msg anthropic.Message) TokenUsage {\n\treturn TokenUsage{\n\t\tInputTokens: msg.Usage.InputTokens,\n\t\tOutputTokens: msg.Usage.OutputTokens,\n\t\tCacheCreationTokens: msg.Usage.CacheCreationInputTokens,\n\t\tCacheReadTokens: msg.Usage.CacheReadInputTokens,\n\t}\n}\n\nfunc WithAnthropicBedrock(useBedrock bool) AnthropicOption {\n\treturn func(options *anthropicOptions) {\n\t\toptions.useBedrock = useBedrock\n\t}\n}\n\nfunc WithAnthropicDisableCache() AnthropicOption {\n\treturn func(options *anthropicOptions) {\n\t\toptions.disableCache = true\n\t}\n}\n\nfunc DefaultShouldThinkFn(s string) bool {\n\treturn strings.Contains(strings.ToLower(s), \"think\")\n}\n\nfunc WithAnthropicShouldThinkFn(fn func(string) bool) AnthropicOption {\n\treturn func(options *anthropicOptions) {\n\t\toptions.shouldThink = fn\n\t}\n}\n"], ["/opencode/internal/llm/agent/mcp-tools.go", "package agent\n\nimport (\n\t\"context\"\n\t\"encoding/json\"\n\t\"fmt\"\n\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/llm/tools\"\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n\t\"github.com/opencode-ai/opencode/internal/permission\"\n\t\"github.com/opencode-ai/opencode/internal/version\"\n\n\t\"github.com/mark3labs/mcp-go/client\"\n\t\"github.com/mark3labs/mcp-go/mcp\"\n)\n\ntype mcpTool struct {\n\tmcpName string\n\ttool mcp.Tool\n\tmcpConfig config.MCPServer\n\tpermissions permission.Service\n}\n\ntype MCPClient interface {\n\tInitialize(\n\t\tctx context.Context,\n\t\trequest mcp.InitializeRequest,\n\t) (*mcp.InitializeResult, error)\n\tListTools(ctx context.Context, request mcp.ListToolsRequest) (*mcp.ListToolsResult, error)\n\tCallTool(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error)\n\tClose() error\n}\n\nfunc (b *mcpTool) Info() tools.ToolInfo {\n\trequired := b.tool.InputSchema.Required\n\tif required == nil {\n\t\trequired = make([]string, 0)\n\t}\n\treturn tools.ToolInfo{\n\t\tName: fmt.Sprintf(\"%s_%s\", b.mcpName, b.tool.Name),\n\t\tDescription: b.tool.Description,\n\t\tParameters: b.tool.InputSchema.Properties,\n\t\tRequired: required,\n\t}\n}\n\nfunc runTool(ctx context.Context, c MCPClient, toolName string, input string) (tools.ToolResponse, error) {\n\tdefer c.Close()\n\tinitRequest := mcp.InitializeRequest{}\n\tinitRequest.Params.ProtocolVersion = mcp.LATEST_PROTOCOL_VERSION\n\tinitRequest.Params.ClientInfo = mcp.Implementation{\n\t\tName: \"OpenCode\",\n\t\tVersion: version.Version,\n\t}\n\n\t_, err := c.Initialize(ctx, initRequest)\n\tif err != nil {\n\t\treturn tools.NewTextErrorResponse(err.Error()), nil\n\t}\n\n\ttoolRequest := mcp.CallToolRequest{}\n\ttoolRequest.Params.Name = toolName\n\tvar args map[string]any\n\tif err = json.Unmarshal([]byte(input), &args); err != nil {\n\t\treturn tools.NewTextErrorResponse(fmt.Sprintf(\"error parsing parameters: %s\", err)), nil\n\t}\n\ttoolRequest.Params.Arguments = args\n\tresult, err := c.CallTool(ctx, toolRequest)\n\tif err != nil {\n\t\treturn tools.NewTextErrorResponse(err.Error()), nil\n\t}\n\n\toutput := \"\"\n\tfor _, v := range result.Content {\n\t\tif v, ok := v.(mcp.TextContent); ok {\n\t\t\toutput = v.Text\n\t\t} else {\n\t\t\toutput = fmt.Sprintf(\"%v\", v)\n\t\t}\n\t}\n\n\treturn tools.NewTextResponse(output), nil\n}\n\nfunc (b *mcpTool) Run(ctx context.Context, params tools.ToolCall) (tools.ToolResponse, error) {\n\tsessionID, messageID := tools.GetContextValues(ctx)\n\tif sessionID == \"\" || messageID == \"\" {\n\t\treturn tools.ToolResponse{}, fmt.Errorf(\"session ID and message ID are required for creating a new file\")\n\t}\n\tpermissionDescription := fmt.Sprintf(\"execute %s with the following parameters: %s\", b.Info().Name, params.Input)\n\tp := b.permissions.Request(\n\t\tpermission.CreatePermissionRequest{\n\t\t\tSessionID: sessionID,\n\t\t\tPath: config.WorkingDirectory(),\n\t\t\tToolName: b.Info().Name,\n\t\t\tAction: \"execute\",\n\t\t\tDescription: permissionDescription,\n\t\t\tParams: params.Input,\n\t\t},\n\t)\n\tif !p {\n\t\treturn tools.NewTextErrorResponse(\"permission denied\"), nil\n\t}\n\n\tswitch b.mcpConfig.Type {\n\tcase config.MCPStdio:\n\t\tc, err := client.NewStdioMCPClient(\n\t\t\tb.mcpConfig.Command,\n\t\t\tb.mcpConfig.Env,\n\t\t\tb.mcpConfig.Args...,\n\t\t)\n\t\tif err != nil {\n\t\t\treturn tools.NewTextErrorResponse(err.Error()), nil\n\t\t}\n\t\treturn runTool(ctx, c, b.tool.Name, params.Input)\n\tcase config.MCPSse:\n\t\tc, err := client.NewSSEMCPClient(\n\t\t\tb.mcpConfig.URL,\n\t\t\tclient.WithHeaders(b.mcpConfig.Headers),\n\t\t)\n\t\tif err != nil {\n\t\t\treturn tools.NewTextErrorResponse(err.Error()), nil\n\t\t}\n\t\treturn runTool(ctx, c, b.tool.Name, params.Input)\n\t}\n\n\treturn tools.NewTextErrorResponse(\"invalid mcp type\"), nil\n}\n\nfunc NewMcpTool(name string, tool mcp.Tool, permissions permission.Service, mcpConfig config.MCPServer) tools.BaseTool {\n\treturn &mcpTool{\n\t\tmcpName: name,\n\t\ttool: tool,\n\t\tmcpConfig: mcpConfig,\n\t\tpermissions: permissions,\n\t}\n}\n\nvar mcpTools []tools.BaseTool\n\nfunc getTools(ctx context.Context, name string, m config.MCPServer, permissions permission.Service, c MCPClient) []tools.BaseTool {\n\tvar stdioTools []tools.BaseTool\n\tinitRequest := mcp.InitializeRequest{}\n\tinitRequest.Params.ProtocolVersion = mcp.LATEST_PROTOCOL_VERSION\n\tinitRequest.Params.ClientInfo = mcp.Implementation{\n\t\tName: \"OpenCode\",\n\t\tVersion: version.Version,\n\t}\n\n\t_, err := c.Initialize(ctx, initRequest)\n\tif err != nil {\n\t\tlogging.Error(\"error initializing mcp client\", \"error\", err)\n\t\treturn stdioTools\n\t}\n\ttoolsRequest := mcp.ListToolsRequest{}\n\ttools, err := c.ListTools(ctx, toolsRequest)\n\tif err != nil {\n\t\tlogging.Error(\"error listing tools\", \"error\", err)\n\t\treturn stdioTools\n\t}\n\tfor _, t := range tools.Tools {\n\t\tstdioTools = append(stdioTools, NewMcpTool(name, t, permissions, m))\n\t}\n\tdefer c.Close()\n\treturn stdioTools\n}\n\nfunc GetMcpTools(ctx context.Context, permissions permission.Service) []tools.BaseTool {\n\tif len(mcpTools) > 0 {\n\t\treturn mcpTools\n\t}\n\tfor name, m := range config.Get().MCPServers {\n\t\tswitch m.Type {\n\t\tcase config.MCPStdio:\n\t\t\tc, err := client.NewStdioMCPClient(\n\t\t\t\tm.Command,\n\t\t\t\tm.Env,\n\t\t\t\tm.Args...,\n\t\t\t)\n\t\t\tif err != nil {\n\t\t\t\tlogging.Error(\"error creating mcp client\", \"error\", err)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tmcpTools = append(mcpTools, getTools(ctx, name, m, permissions, c)...)\n\t\tcase config.MCPSse:\n\t\t\tc, err := client.NewSSEMCPClient(\n\t\t\t\tm.URL,\n\t\t\t\tclient.WithHeaders(m.Headers),\n\t\t\t)\n\t\t\tif err != nil {\n\t\t\t\tlogging.Error(\"error creating mcp client\", \"error\", err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tmcpTools = append(mcpTools, getTools(ctx, name, m, permissions, c)...)\n\t\t}\n\t}\n\n\treturn mcpTools\n}\n"], ["/opencode/internal/tui/components/chat/sidebar.go", "package chat\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"sort\"\n\t\"strings\"\n\n\ttea \"github.com/charmbracelet/bubbletea\"\n\t\"github.com/charmbracelet/lipgloss\"\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/diff\"\n\t\"github.com/opencode-ai/opencode/internal/history\"\n\t\"github.com/opencode-ai/opencode/internal/pubsub\"\n\t\"github.com/opencode-ai/opencode/internal/session\"\n\t\"github.com/opencode-ai/opencode/internal/tui/styles\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n)\n\ntype sidebarCmp struct {\n\twidth, height int\n\tsession session.Session\n\thistory history.Service\n\tmodFiles map[string]struct {\n\t\tadditions int\n\t\tremovals int\n\t}\n}\n\nfunc (m *sidebarCmp) Init() tea.Cmd {\n\tif m.history != nil {\n\t\tctx := context.Background()\n\t\t// Subscribe to file events\n\t\tfilesCh := m.history.Subscribe(ctx)\n\n\t\t// Initialize the modified files map\n\t\tm.modFiles = make(map[string]struct {\n\t\t\tadditions int\n\t\t\tremovals int\n\t\t})\n\n\t\t// Load initial files and calculate diffs\n\t\tm.loadModifiedFiles(ctx)\n\n\t\t// Return a command that will send file events to the Update method\n\t\treturn func() tea.Msg {\n\t\t\treturn <-filesCh\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (m *sidebarCmp) Update(msg tea.Msg) (tea.Model, tea.Cmd) {\n\tswitch msg := msg.(type) {\n\tcase SessionSelectedMsg:\n\t\tif msg.ID != m.session.ID {\n\t\t\tm.session = msg\n\t\t\tctx := context.Background()\n\t\t\tm.loadModifiedFiles(ctx)\n\t\t}\n\tcase pubsub.Event[session.Session]:\n\t\tif msg.Type == pubsub.UpdatedEvent {\n\t\t\tif m.session.ID == msg.Payload.ID {\n\t\t\t\tm.session = msg.Payload\n\t\t\t}\n\t\t}\n\tcase pubsub.Event[history.File]:\n\t\tif msg.Payload.SessionID == m.session.ID {\n\t\t\t// Process the individual file change instead of reloading all files\n\t\t\tctx := context.Background()\n\t\t\tm.processFileChanges(ctx, msg.Payload)\n\n\t\t\t// Return a command to continue receiving events\n\t\t\treturn m, func() tea.Msg {\n\t\t\t\tctx := context.Background()\n\t\t\t\tfilesCh := m.history.Subscribe(ctx)\n\t\t\t\treturn <-filesCh\n\t\t\t}\n\t\t}\n\t}\n\treturn m, nil\n}\n\nfunc (m *sidebarCmp) View() string {\n\tbaseStyle := styles.BaseStyle()\n\n\treturn baseStyle.\n\t\tWidth(m.width).\n\t\tPaddingLeft(4).\n\t\tPaddingRight(2).\n\t\tHeight(m.height - 1).\n\t\tRender(\n\t\t\tlipgloss.JoinVertical(\n\t\t\t\tlipgloss.Top,\n\t\t\t\theader(m.width),\n\t\t\t\t\" \",\n\t\t\t\tm.sessionSection(),\n\t\t\t\t\" \",\n\t\t\t\tlspsConfigured(m.width),\n\t\t\t\t\" \",\n\t\t\t\tm.modifiedFiles(),\n\t\t\t),\n\t\t)\n}\n\nfunc (m *sidebarCmp) sessionSection() string {\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\n\tsessionKey := baseStyle.\n\t\tForeground(t.Primary()).\n\t\tBold(true).\n\t\tRender(\"Session\")\n\n\tsessionValue := baseStyle.\n\t\tForeground(t.Text()).\n\t\tWidth(m.width - lipgloss.Width(sessionKey)).\n\t\tRender(fmt.Sprintf(\": %s\", m.session.Title))\n\n\treturn lipgloss.JoinHorizontal(\n\t\tlipgloss.Left,\n\t\tsessionKey,\n\t\tsessionValue,\n\t)\n}\n\nfunc (m *sidebarCmp) modifiedFile(filePath string, additions, removals int) string {\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\n\tstats := \"\"\n\tif additions > 0 && removals > 0 {\n\t\tadditionsStr := baseStyle.\n\t\t\tForeground(t.Success()).\n\t\t\tPaddingLeft(1).\n\t\t\tRender(fmt.Sprintf(\"+%d\", additions))\n\n\t\tremovalsStr := baseStyle.\n\t\t\tForeground(t.Error()).\n\t\t\tPaddingLeft(1).\n\t\t\tRender(fmt.Sprintf(\"-%d\", removals))\n\n\t\tcontent := lipgloss.JoinHorizontal(lipgloss.Left, additionsStr, removalsStr)\n\t\tstats = baseStyle.Width(lipgloss.Width(content)).Render(content)\n\t} else if additions > 0 {\n\t\tadditionsStr := fmt.Sprintf(\" %s\", baseStyle.\n\t\t\tPaddingLeft(1).\n\t\t\tForeground(t.Success()).\n\t\t\tRender(fmt.Sprintf(\"+%d\", additions)))\n\t\tstats = baseStyle.Width(lipgloss.Width(additionsStr)).Render(additionsStr)\n\t} else if removals > 0 {\n\t\tremovalsStr := fmt.Sprintf(\" %s\", baseStyle.\n\t\t\tPaddingLeft(1).\n\t\t\tForeground(t.Error()).\n\t\t\tRender(fmt.Sprintf(\"-%d\", removals)))\n\t\tstats = baseStyle.Width(lipgloss.Width(removalsStr)).Render(removalsStr)\n\t}\n\n\tfilePathStr := baseStyle.Render(filePath)\n\n\treturn baseStyle.\n\t\tWidth(m.width).\n\t\tRender(\n\t\t\tlipgloss.JoinHorizontal(\n\t\t\t\tlipgloss.Left,\n\t\t\t\tfilePathStr,\n\t\t\t\tstats,\n\t\t\t),\n\t\t)\n}\n\nfunc (m *sidebarCmp) modifiedFiles() string {\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\n\tmodifiedFiles := baseStyle.\n\t\tWidth(m.width).\n\t\tForeground(t.Primary()).\n\t\tBold(true).\n\t\tRender(\"Modified Files:\")\n\n\t// If no modified files, show a placeholder message\n\tif m.modFiles == nil || len(m.modFiles) == 0 {\n\t\tmessage := \"No modified files\"\n\t\tremainingWidth := m.width - lipgloss.Width(message)\n\t\tif remainingWidth > 0 {\n\t\t\tmessage += strings.Repeat(\" \", remainingWidth)\n\t\t}\n\t\treturn baseStyle.\n\t\t\tWidth(m.width).\n\t\t\tRender(\n\t\t\t\tlipgloss.JoinVertical(\n\t\t\t\t\tlipgloss.Top,\n\t\t\t\t\tmodifiedFiles,\n\t\t\t\t\tbaseStyle.Foreground(t.TextMuted()).Render(message),\n\t\t\t\t),\n\t\t\t)\n\t}\n\n\t// Sort file paths alphabetically for consistent ordering\n\tvar paths []string\n\tfor path := range m.modFiles {\n\t\tpaths = append(paths, path)\n\t}\n\tsort.Strings(paths)\n\n\t// Create views for each file in sorted order\n\tvar fileViews []string\n\tfor _, path := range paths {\n\t\tstats := m.modFiles[path]\n\t\tfileViews = append(fileViews, m.modifiedFile(path, stats.additions, stats.removals))\n\t}\n\n\treturn baseStyle.\n\t\tWidth(m.width).\n\t\tRender(\n\t\t\tlipgloss.JoinVertical(\n\t\t\t\tlipgloss.Top,\n\t\t\t\tmodifiedFiles,\n\t\t\t\tlipgloss.JoinVertical(\n\t\t\t\t\tlipgloss.Left,\n\t\t\t\t\tfileViews...,\n\t\t\t\t),\n\t\t\t),\n\t\t)\n}\n\nfunc (m *sidebarCmp) SetSize(width, height int) tea.Cmd {\n\tm.width = width\n\tm.height = height\n\treturn nil\n}\n\nfunc (m *sidebarCmp) GetSize() (int, int) {\n\treturn m.width, m.height\n}\n\nfunc NewSidebarCmp(session session.Session, history history.Service) tea.Model {\n\treturn &sidebarCmp{\n\t\tsession: session,\n\t\thistory: history,\n\t}\n}\n\nfunc (m *sidebarCmp) loadModifiedFiles(ctx context.Context) {\n\tif m.history == nil || m.session.ID == \"\" {\n\t\treturn\n\t}\n\n\t// Get all latest files for this session\n\tlatestFiles, err := m.history.ListLatestSessionFiles(ctx, m.session.ID)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t// Get all files for this session (to find initial versions)\n\tallFiles, err := m.history.ListBySession(ctx, m.session.ID)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t// Clear the existing map to rebuild it\n\tm.modFiles = make(map[string]struct {\n\t\tadditions int\n\t\tremovals int\n\t})\n\n\t// Process each latest file\n\tfor _, file := range latestFiles {\n\t\t// Skip if this is the initial version (no changes to show)\n\t\tif file.Version == history.InitialVersion {\n\t\t\tcontinue\n\t\t}\n\n\t\t// Find the initial version for this specific file\n\t\tvar initialVersion history.File\n\t\tfor _, v := range allFiles {\n\t\t\tif v.Path == file.Path && v.Version == history.InitialVersion {\n\t\t\t\tinitialVersion = v\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\t// Skip if we can't find the initial version\n\t\tif initialVersion.ID == \"\" {\n\t\t\tcontinue\n\t\t}\n\t\tif initialVersion.Content == file.Content {\n\t\t\tcontinue\n\t\t}\n\n\t\t// Calculate diff between initial and latest version\n\t\t_, additions, removals := diff.GenerateDiff(initialVersion.Content, file.Content, file.Path)\n\n\t\t// Only add to modified files if there are changes\n\t\tif additions > 0 || removals > 0 {\n\t\t\t// Remove working directory prefix from file path\n\t\t\tdisplayPath := file.Path\n\t\t\tworkingDir := config.WorkingDirectory()\n\t\t\tdisplayPath = strings.TrimPrefix(displayPath, workingDir)\n\t\t\tdisplayPath = strings.TrimPrefix(displayPath, \"/\")\n\n\t\t\tm.modFiles[displayPath] = struct {\n\t\t\t\tadditions int\n\t\t\t\tremovals int\n\t\t\t}{\n\t\t\t\tadditions: additions,\n\t\t\t\tremovals: removals,\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc (m *sidebarCmp) processFileChanges(ctx context.Context, file history.File) {\n\t// Skip if this is the initial version (no changes to show)\n\tif file.Version == history.InitialVersion {\n\t\treturn\n\t}\n\n\t// Find the initial version for this file\n\tinitialVersion, err := m.findInitialVersion(ctx, file.Path)\n\tif err != nil || initialVersion.ID == \"\" {\n\t\treturn\n\t}\n\n\t// Skip if content hasn't changed\n\tif initialVersion.Content == file.Content {\n\t\t// If this file was previously modified but now matches the initial version,\n\t\t// remove it from the modified files list\n\t\tdisplayPath := getDisplayPath(file.Path)\n\t\tdelete(m.modFiles, displayPath)\n\t\treturn\n\t}\n\n\t// Calculate diff between initial and latest version\n\t_, additions, removals := diff.GenerateDiff(initialVersion.Content, file.Content, file.Path)\n\n\t// Only add to modified files if there are changes\n\tif additions > 0 || removals > 0 {\n\t\tdisplayPath := getDisplayPath(file.Path)\n\t\tm.modFiles[displayPath] = struct {\n\t\t\tadditions int\n\t\t\tremovals int\n\t\t}{\n\t\t\tadditions: additions,\n\t\t\tremovals: removals,\n\t\t}\n\t} else {\n\t\t// If no changes, remove from modified files\n\t\tdisplayPath := getDisplayPath(file.Path)\n\t\tdelete(m.modFiles, displayPath)\n\t}\n}\n\n// Helper function to find the initial version of a file\nfunc (m *sidebarCmp) findInitialVersion(ctx context.Context, path string) (history.File, error) {\n\t// Get all versions of this file for the session\n\tfileVersions, err := m.history.ListBySession(ctx, m.session.ID)\n\tif err != nil {\n\t\treturn history.File{}, err\n\t}\n\n\t// Find the initial version\n\tfor _, v := range fileVersions {\n\t\tif v.Path == path && v.Version == history.InitialVersion {\n\t\t\treturn v, nil\n\t\t}\n\t}\n\n\treturn history.File{}, fmt.Errorf(\"initial version not found\")\n}\n\n// Helper function to get the display path for a file\nfunc getDisplayPath(path string) string {\n\tworkingDir := config.WorkingDirectory()\n\tdisplayPath := strings.TrimPrefix(path, workingDir)\n\treturn strings.TrimPrefix(displayPath, \"/\")\n}\n"], ["/opencode/internal/llm/provider/gemini.go", "package provider\n\nimport (\n\t\"context\"\n\t\"encoding/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/google/uuid\"\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/llm/tools\"\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n\t\"github.com/opencode-ai/opencode/internal/message\"\n\t\"google.golang.org/genai\"\n)\n\ntype geminiOptions struct {\n\tdisableCache bool\n}\n\ntype GeminiOption func(*geminiOptions)\n\ntype geminiClient struct {\n\tproviderOptions providerClientOptions\n\toptions geminiOptions\n\tclient *genai.Client\n}\n\ntype GeminiClient ProviderClient\n\nfunc newGeminiClient(opts providerClientOptions) GeminiClient {\n\tgeminiOpts := geminiOptions{}\n\tfor _, o := range opts.geminiOptions {\n\t\to(&geminiOpts)\n\t}\n\n\tclient, err := genai.NewClient(context.Background(), &genai.ClientConfig{APIKey: opts.apiKey, Backend: genai.BackendGeminiAPI})\n\tif err != nil {\n\t\tlogging.Error(\"Failed to create Gemini client\", \"error\", err)\n\t\treturn nil\n\t}\n\n\treturn &geminiClient{\n\t\tproviderOptions: opts,\n\t\toptions: geminiOpts,\n\t\tclient: client,\n\t}\n}\n\nfunc (g *geminiClient) convertMessages(messages []message.Message) []*genai.Content {\n\tvar history []*genai.Content\n\tfor _, msg := range messages {\n\t\tswitch msg.Role {\n\t\tcase message.User:\n\t\t\tvar parts []*genai.Part\n\t\t\tparts = append(parts, &genai.Part{Text: msg.Content().String()})\n\t\t\tfor _, binaryContent := range msg.BinaryContent() {\n\t\t\t\timageFormat := strings.Split(binaryContent.MIMEType, \"/\")\n\t\t\t\tparts = append(parts, &genai.Part{InlineData: &genai.Blob{\n\t\t\t\t\tMIMEType: imageFormat[1],\n\t\t\t\t\tData: binaryContent.Data,\n\t\t\t\t}})\n\t\t\t}\n\t\t\thistory = append(history, &genai.Content{\n\t\t\t\tParts: parts,\n\t\t\t\tRole: \"user\",\n\t\t\t})\n\t\tcase message.Assistant:\n\t\t\tvar assistantParts []*genai.Part\n\n\t\t\tif msg.Content().String() != \"\" {\n\t\t\t\tassistantParts = append(assistantParts, &genai.Part{Text: msg.Content().String()})\n\t\t\t}\n\n\t\t\tif len(msg.ToolCalls()) > 0 {\n\t\t\t\tfor _, call := range msg.ToolCalls() {\n\t\t\t\t\targs, _ := parseJsonToMap(call.Input)\n\t\t\t\t\tassistantParts = append(assistantParts, &genai.Part{\n\t\t\t\t\t\tFunctionCall: &genai.FunctionCall{\n\t\t\t\t\t\t\tName: call.Name,\n\t\t\t\t\t\t\tArgs: args,\n\t\t\t\t\t\t},\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif len(assistantParts) > 0 {\n\t\t\t\thistory = append(history, &genai.Content{\n\t\t\t\t\tRole: \"model\",\n\t\t\t\t\tParts: assistantParts,\n\t\t\t\t})\n\t\t\t}\n\n\t\tcase message.Tool:\n\t\t\tfor _, result := range msg.ToolResults() {\n\t\t\t\tresponse := map[string]interface{}{\"result\": result.Content}\n\t\t\t\tparsed, err := parseJsonToMap(result.Content)\n\t\t\t\tif err == nil {\n\t\t\t\t\tresponse = parsed\n\t\t\t\t}\n\n\t\t\t\tvar toolCall message.ToolCall\n\t\t\t\tfor _, m := range messages {\n\t\t\t\t\tif m.Role == message.Assistant {\n\t\t\t\t\t\tfor _, call := range m.ToolCalls() {\n\t\t\t\t\t\t\tif call.ID == result.ToolCallID {\n\t\t\t\t\t\t\t\ttoolCall = call\n\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\thistory = append(history, &genai.Content{\n\t\t\t\t\tParts: []*genai.Part{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tFunctionResponse: &genai.FunctionResponse{\n\t\t\t\t\t\t\t\tName: toolCall.Name,\n\t\t\t\t\t\t\t\tResponse: response,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\tRole: \"function\",\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\t}\n\n\treturn history\n}\n\nfunc (g *geminiClient) convertTools(tools []tools.BaseTool) []*genai.Tool {\n\tgeminiTool := &genai.Tool{}\n\tgeminiTool.FunctionDeclarations = make([]*genai.FunctionDeclaration, 0, len(tools))\n\n\tfor _, tool := range tools {\n\t\tinfo := tool.Info()\n\t\tdeclaration := &genai.FunctionDeclaration{\n\t\t\tName: info.Name,\n\t\t\tDescription: info.Description,\n\t\t\tParameters: &genai.Schema{\n\t\t\t\tType: genai.TypeObject,\n\t\t\t\tProperties: convertSchemaProperties(info.Parameters),\n\t\t\t\tRequired: info.Required,\n\t\t\t},\n\t\t}\n\n\t\tgeminiTool.FunctionDeclarations = append(geminiTool.FunctionDeclarations, declaration)\n\t}\n\n\treturn []*genai.Tool{geminiTool}\n}\n\nfunc (g *geminiClient) finishReason(reason genai.FinishReason) message.FinishReason {\n\tswitch {\n\tcase reason == genai.FinishReasonStop:\n\t\treturn message.FinishReasonEndTurn\n\tcase reason == genai.FinishReasonMaxTokens:\n\t\treturn message.FinishReasonMaxTokens\n\tdefault:\n\t\treturn message.FinishReasonUnknown\n\t}\n}\n\nfunc (g *geminiClient) send(ctx context.Context, messages []message.Message, tools []tools.BaseTool) (*ProviderResponse, error) {\n\t// Convert messages\n\tgeminiMessages := g.convertMessages(messages)\n\n\tcfg := config.Get()\n\tif cfg.Debug {\n\t\tjsonData, _ := json.Marshal(geminiMessages)\n\t\tlogging.Debug(\"Prepared messages\", \"messages\", string(jsonData))\n\t}\n\n\thistory := geminiMessages[:len(geminiMessages)-1] // All but last message\n\tlastMsg := geminiMessages[len(geminiMessages)-1]\n\tconfig := &genai.GenerateContentConfig{\n\t\tMaxOutputTokens: int32(g.providerOptions.maxTokens),\n\t\tSystemInstruction: &genai.Content{\n\t\t\tParts: []*genai.Part{{Text: g.providerOptions.systemMessage}},\n\t\t},\n\t}\n\tif len(tools) > 0 {\n\t\tconfig.Tools = g.convertTools(tools)\n\t}\n\tchat, _ := g.client.Chats.Create(ctx, g.providerOptions.model.APIModel, config, history)\n\n\tattempts := 0\n\tfor {\n\t\tattempts++\n\t\tvar toolCalls []message.ToolCall\n\n\t\tvar lastMsgParts []genai.Part\n\t\tfor _, part := range lastMsg.Parts {\n\t\t\tlastMsgParts = append(lastMsgParts, *part)\n\t\t}\n\t\tresp, err := chat.SendMessage(ctx, lastMsgParts...)\n\t\t// If there is an error we are going to see if we can retry the call\n\t\tif err != nil {\n\t\t\tretry, after, retryErr := g.shouldRetry(attempts, err)\n\t\t\tif retryErr != nil {\n\t\t\t\treturn nil, retryErr\n\t\t\t}\n\t\t\tif retry {\n\t\t\t\tlogging.WarnPersist(fmt.Sprintf(\"Retrying due to rate limit... attempt %d of %d\", attempts, maxRetries), logging.PersistTimeArg, time.Millisecond*time.Duration(after+100))\n\t\t\t\tselect {\n\t\t\t\tcase <-ctx.Done():\n\t\t\t\t\treturn nil, ctx.Err()\n\t\t\t\tcase <-time.After(time.Duration(after) * time.Millisecond):\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn nil, retryErr\n\t\t}\n\n\t\tcontent := \"\"\n\n\t\tif len(resp.Candidates) > 0 && resp.Candidates[0].Content != nil {\n\t\t\tfor _, part := range resp.Candidates[0].Content.Parts {\n\t\t\t\tswitch {\n\t\t\t\tcase part.Text != \"\":\n\t\t\t\t\tcontent = string(part.Text)\n\t\t\t\tcase part.FunctionCall != nil:\n\t\t\t\t\tid := \"call_\" + uuid.New().String()\n\t\t\t\t\targs, _ := json.Marshal(part.FunctionCall.Args)\n\t\t\t\t\ttoolCalls = append(toolCalls, message.ToolCall{\n\t\t\t\t\t\tID: id,\n\t\t\t\t\t\tName: part.FunctionCall.Name,\n\t\t\t\t\t\tInput: string(args),\n\t\t\t\t\t\tType: \"function\",\n\t\t\t\t\t\tFinished: true,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tfinishReason := message.FinishReasonEndTurn\n\t\tif len(resp.Candidates) > 0 {\n\t\t\tfinishReason = g.finishReason(resp.Candidates[0].FinishReason)\n\t\t}\n\t\tif len(toolCalls) > 0 {\n\t\t\tfinishReason = message.FinishReasonToolUse\n\t\t}\n\n\t\treturn &ProviderResponse{\n\t\t\tContent: content,\n\t\t\tToolCalls: toolCalls,\n\t\t\tUsage: g.usage(resp),\n\t\t\tFinishReason: finishReason,\n\t\t}, nil\n\t}\n}\n\nfunc (g *geminiClient) stream(ctx context.Context, messages []message.Message, tools []tools.BaseTool) <-chan ProviderEvent {\n\t// Convert messages\n\tgeminiMessages := g.convertMessages(messages)\n\n\tcfg := config.Get()\n\tif cfg.Debug {\n\t\tjsonData, _ := json.Marshal(geminiMessages)\n\t\tlogging.Debug(\"Prepared messages\", \"messages\", string(jsonData))\n\t}\n\n\thistory := geminiMessages[:len(geminiMessages)-1] // All but last message\n\tlastMsg := geminiMessages[len(geminiMessages)-1]\n\tconfig := &genai.GenerateContentConfig{\n\t\tMaxOutputTokens: int32(g.providerOptions.maxTokens),\n\t\tSystemInstruction: &genai.Content{\n\t\t\tParts: []*genai.Part{{Text: g.providerOptions.systemMessage}},\n\t\t},\n\t}\n\tif len(tools) > 0 {\n\t\tconfig.Tools = g.convertTools(tools)\n\t}\n\tchat, _ := g.client.Chats.Create(ctx, g.providerOptions.model.APIModel, config, history)\n\n\tattempts := 0\n\teventChan := make(chan ProviderEvent)\n\n\tgo func() {\n\t\tdefer close(eventChan)\n\n\t\tfor {\n\t\t\tattempts++\n\n\t\t\tcurrentContent := \"\"\n\t\t\ttoolCalls := []message.ToolCall{}\n\t\t\tvar finalResp *genai.GenerateContentResponse\n\n\t\t\teventChan <- ProviderEvent{Type: EventContentStart}\n\n\t\t\tvar lastMsgParts []genai.Part\n\n\t\t\tfor _, part := range lastMsg.Parts {\n\t\t\t\tlastMsgParts = append(lastMsgParts, *part)\n\t\t\t}\n\t\t\tfor resp, err := range chat.SendMessageStream(ctx, lastMsgParts...) {\n\t\t\t\tif err != nil {\n\t\t\t\t\tretry, after, retryErr := g.shouldRetry(attempts, err)\n\t\t\t\t\tif retryErr != nil {\n\t\t\t\t\t\teventChan <- ProviderEvent{Type: EventError, Error: retryErr}\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\tif retry {\n\t\t\t\t\t\tlogging.WarnPersist(fmt.Sprintf(\"Retrying due to rate limit... attempt %d of %d\", attempts, maxRetries), logging.PersistTimeArg, time.Millisecond*time.Duration(after+100))\n\t\t\t\t\t\tselect {\n\t\t\t\t\t\tcase <-ctx.Done():\n\t\t\t\t\t\t\tif ctx.Err() != nil {\n\t\t\t\t\t\t\t\teventChan <- ProviderEvent{Type: EventError, Error: ctx.Err()}\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\treturn\n\t\t\t\t\t\tcase <-time.After(time.Duration(after) * time.Millisecond):\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\teventChan <- ProviderEvent{Type: EventError, Error: err}\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tfinalResp = resp\n\n\t\t\t\tif len(resp.Candidates) > 0 && resp.Candidates[0].Content != nil {\n\t\t\t\t\tfor _, part := range resp.Candidates[0].Content.Parts {\n\t\t\t\t\t\tswitch {\n\t\t\t\t\t\tcase part.Text != \"\":\n\t\t\t\t\t\t\tdelta := string(part.Text)\n\t\t\t\t\t\t\tif delta != \"\" {\n\t\t\t\t\t\t\t\teventChan <- ProviderEvent{\n\t\t\t\t\t\t\t\t\tType: EventContentDelta,\n\t\t\t\t\t\t\t\t\tContent: delta,\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tcurrentContent += delta\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\tcase part.FunctionCall != nil:\n\t\t\t\t\t\t\tid := \"call_\" + uuid.New().String()\n\t\t\t\t\t\t\targs, _ := json.Marshal(part.FunctionCall.Args)\n\t\t\t\t\t\t\tnewCall := message.ToolCall{\n\t\t\t\t\t\t\t\tID: id,\n\t\t\t\t\t\t\t\tName: part.FunctionCall.Name,\n\t\t\t\t\t\t\t\tInput: string(args),\n\t\t\t\t\t\t\t\tType: \"function\",\n\t\t\t\t\t\t\t\tFinished: true,\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tisNew := true\n\t\t\t\t\t\t\tfor _, existing := range toolCalls {\n\t\t\t\t\t\t\t\tif existing.Name == newCall.Name && existing.Input == newCall.Input {\n\t\t\t\t\t\t\t\t\tisNew = false\n\t\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif isNew {\n\t\t\t\t\t\t\t\ttoolCalls = append(toolCalls, newCall)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\teventChan <- ProviderEvent{Type: EventContentStop}\n\n\t\t\tif finalResp != nil {\n\n\t\t\t\tfinishReason := message.FinishReasonEndTurn\n\t\t\t\tif len(finalResp.Candidates) > 0 {\n\t\t\t\t\tfinishReason = g.finishReason(finalResp.Candidates[0].FinishReason)\n\t\t\t\t}\n\t\t\t\tif len(toolCalls) > 0 {\n\t\t\t\t\tfinishReason = message.FinishReasonToolUse\n\t\t\t\t}\n\t\t\t\teventChan <- ProviderEvent{\n\t\t\t\t\tType: EventComplete,\n\t\t\t\t\tResponse: &ProviderResponse{\n\t\t\t\t\t\tContent: currentContent,\n\t\t\t\t\t\tToolCalls: toolCalls,\n\t\t\t\t\t\tUsage: g.usage(finalResp),\n\t\t\t\t\t\tFinishReason: finishReason,\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\n\t\t}\n\t}()\n\n\treturn eventChan\n}\n\nfunc (g *geminiClient) shouldRetry(attempts int, err error) (bool, int64, error) {\n\t// Check if error is a rate limit error\n\tif attempts > maxRetries {\n\t\treturn false, 0, fmt.Errorf(\"maximum retry attempts reached for rate limit: %d retries\", maxRetries)\n\t}\n\n\t// Gemini doesn't have a standard error type we can check against\n\t// So we'll check the error message for rate limit indicators\n\tif errors.Is(err, io.EOF) {\n\t\treturn false, 0, err\n\t}\n\n\terrMsg := err.Error()\n\tisRateLimit := false\n\n\t// Check for common rate limit error messages\n\tif contains(errMsg, \"rate limit\", \"quota exceeded\", \"too many requests\") {\n\t\tisRateLimit = true\n\t}\n\n\tif !isRateLimit {\n\t\treturn false, 0, err\n\t}\n\n\t// Calculate backoff with jitter\n\tbackoffMs := 2000 * (1 << (attempts - 1))\n\tjitterMs := int(float64(backoffMs) * 0.2)\n\tretryMs := backoffMs + jitterMs\n\n\treturn true, int64(retryMs), nil\n}\n\nfunc (g *geminiClient) toolCalls(resp *genai.GenerateContentResponse) []message.ToolCall {\n\tvar toolCalls []message.ToolCall\n\n\tif len(resp.Candidates) > 0 && resp.Candidates[0].Content != nil {\n\t\tfor _, part := range resp.Candidates[0].Content.Parts {\n\t\t\tif part.FunctionCall != nil {\n\t\t\t\tid := \"call_\" + uuid.New().String()\n\t\t\t\targs, _ := json.Marshal(part.FunctionCall.Args)\n\t\t\t\ttoolCalls = append(toolCalls, message.ToolCall{\n\t\t\t\t\tID: id,\n\t\t\t\t\tName: part.FunctionCall.Name,\n\t\t\t\t\tInput: string(args),\n\t\t\t\t\tType: \"function\",\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\t}\n\n\treturn toolCalls\n}\n\nfunc (g *geminiClient) usage(resp *genai.GenerateContentResponse) TokenUsage {\n\tif resp == nil || resp.UsageMetadata == nil {\n\t\treturn TokenUsage{}\n\t}\n\n\treturn TokenUsage{\n\t\tInputTokens: int64(resp.UsageMetadata.PromptTokenCount),\n\t\tOutputTokens: int64(resp.UsageMetadata.CandidatesTokenCount),\n\t\tCacheCreationTokens: 0, // Not directly provided by Gemini\n\t\tCacheReadTokens: int64(resp.UsageMetadata.CachedContentTokenCount),\n\t}\n}\n\nfunc WithGeminiDisableCache() GeminiOption {\n\treturn func(options *geminiOptions) {\n\t\toptions.disableCache = true\n\t}\n}\n\n// Helper functions\nfunc parseJsonToMap(jsonStr string) (map[string]interface{}, error) {\n\tvar result map[string]interface{}\n\terr := json.Unmarshal([]byte(jsonStr), &result)\n\treturn result, err\n}\n\nfunc convertSchemaProperties(parameters map[string]interface{}) map[string]*genai.Schema {\n\tproperties := make(map[string]*genai.Schema)\n\n\tfor name, param := range parameters {\n\t\tproperties[name] = convertToSchema(param)\n\t}\n\n\treturn properties\n}\n\nfunc convertToSchema(param interface{}) *genai.Schema {\n\tschema := &genai.Schema{Type: genai.TypeString}\n\n\tparamMap, ok := param.(map[string]interface{})\n\tif !ok {\n\t\treturn schema\n\t}\n\n\tif desc, ok := paramMap[\"description\"].(string); ok {\n\t\tschema.Description = desc\n\t}\n\n\ttypeVal, hasType := paramMap[\"type\"]\n\tif !hasType {\n\t\treturn schema\n\t}\n\n\ttypeStr, ok := typeVal.(string)\n\tif !ok {\n\t\treturn schema\n\t}\n\n\tschema.Type = mapJSONTypeToGenAI(typeStr)\n\n\tswitch typeStr {\n\tcase \"array\":\n\t\tschema.Items = processArrayItems(paramMap)\n\tcase \"object\":\n\t\tif props, ok := paramMap[\"properties\"].(map[string]interface{}); ok {\n\t\t\tschema.Properties = convertSchemaProperties(props)\n\t\t}\n\t}\n\n\treturn schema\n}\n\nfunc processArrayItems(paramMap map[string]interface{}) *genai.Schema {\n\titems, ok := paramMap[\"items\"].(map[string]interface{})\n\tif !ok {\n\t\treturn nil\n\t}\n\n\treturn convertToSchema(items)\n}\n\nfunc mapJSONTypeToGenAI(jsonType string) genai.Type {\n\tswitch jsonType {\n\tcase \"string\":\n\t\treturn genai.TypeString\n\tcase \"number\":\n\t\treturn genai.TypeNumber\n\tcase \"integer\":\n\t\treturn genai.TypeInteger\n\tcase \"boolean\":\n\t\treturn genai.TypeBoolean\n\tcase \"array\":\n\t\treturn genai.TypeArray\n\tcase \"object\":\n\t\treturn genai.TypeObject\n\tdefault:\n\t\treturn genai.TypeString // Default to string for unknown types\n\t}\n}\n\nfunc contains(s string, substrs ...string) bool {\n\tfor _, substr := range substrs {\n\t\tif strings.Contains(strings.ToLower(s), strings.ToLower(substr)) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n"], ["/opencode/internal/llm/provider/openai.go", "package provider\n\nimport (\n\t\"context\"\n\t\"encoding/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"time\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n\t\"github.com/openai/openai-go/shared\"\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/llm/models\"\n\t\"github.com/opencode-ai/opencode/internal/llm/tools\"\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n\t\"github.com/opencode-ai/opencode/internal/message\"\n)\n\ntype openaiOptions struct {\n\tbaseURL string\n\tdisableCache bool\n\treasoningEffort string\n\textraHeaders map[string]string\n}\n\ntype OpenAIOption func(*openaiOptions)\n\ntype openaiClient struct {\n\tproviderOptions providerClientOptions\n\toptions openaiOptions\n\tclient openai.Client\n}\n\ntype OpenAIClient ProviderClient\n\nfunc newOpenAIClient(opts providerClientOptions) OpenAIClient {\n\topenaiOpts := openaiOptions{\n\t\treasoningEffort: \"medium\",\n\t}\n\tfor _, o := range opts.openaiOptions {\n\t\to(&openaiOpts)\n\t}\n\n\topenaiClientOptions := []option.RequestOption{}\n\tif opts.apiKey != \"\" {\n\t\topenaiClientOptions = append(openaiClientOptions, option.WithAPIKey(opts.apiKey))\n\t}\n\tif openaiOpts.baseURL != \"\" {\n\t\topenaiClientOptions = append(openaiClientOptions, option.WithBaseURL(openaiOpts.baseURL))\n\t}\n\n\tif openaiOpts.extraHeaders != nil {\n\t\tfor key, value := range openaiOpts.extraHeaders {\n\t\t\topenaiClientOptions = append(openaiClientOptions, option.WithHeader(key, value))\n\t\t}\n\t}\n\n\tclient := openai.NewClient(openaiClientOptions...)\n\treturn &openaiClient{\n\t\tproviderOptions: opts,\n\t\toptions: openaiOpts,\n\t\tclient: client,\n\t}\n}\n\nfunc (o *openaiClient) convertMessages(messages []message.Message) (openaiMessages []openai.ChatCompletionMessageParamUnion) {\n\t// Add system message first\n\topenaiMessages = append(openaiMessages, openai.SystemMessage(o.providerOptions.systemMessage))\n\n\tfor _, msg := range messages {\n\t\tswitch msg.Role {\n\t\tcase message.User:\n\t\t\tvar content []openai.ChatCompletionContentPartUnionParam\n\t\t\ttextBlock := openai.ChatCompletionContentPartTextParam{Text: msg.Content().String()}\n\t\t\tcontent = append(content, openai.ChatCompletionContentPartUnionParam{OfText: &textBlock})\n\t\t\tfor _, binaryContent := range msg.BinaryContent() {\n\t\t\t\timageURL := openai.ChatCompletionContentPartImageImageURLParam{URL: binaryContent.String(models.ProviderOpenAI)}\n\t\t\t\timageBlock := openai.ChatCompletionContentPartImageParam{ImageURL: imageURL}\n\n\t\t\t\tcontent = append(content, openai.ChatCompletionContentPartUnionParam{OfImageURL: &imageBlock})\n\t\t\t}\n\n\t\t\topenaiMessages = append(openaiMessages, openai.UserMessage(content))\n\n\t\tcase message.Assistant:\n\t\t\tassistantMsg := openai.ChatCompletionAssistantMessageParam{\n\t\t\t\tRole: \"assistant\",\n\t\t\t}\n\n\t\t\tif msg.Content().String() != \"\" {\n\t\t\t\tassistantMsg.Content = openai.ChatCompletionAssistantMessageParamContentUnion{\n\t\t\t\t\tOfString: openai.String(msg.Content().String()),\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif len(msg.ToolCalls()) > 0 {\n\t\t\t\tassistantMsg.ToolCalls = make([]openai.ChatCompletionMessageToolCallParam, len(msg.ToolCalls()))\n\t\t\t\tfor i, call := range msg.ToolCalls() {\n\t\t\t\t\tassistantMsg.ToolCalls[i] = openai.ChatCompletionMessageToolCallParam{\n\t\t\t\t\t\tID: call.ID,\n\t\t\t\t\t\tType: \"function\",\n\t\t\t\t\t\tFunction: openai.ChatCompletionMessageToolCallFunctionParam{\n\t\t\t\t\t\t\tName: call.Name,\n\t\t\t\t\t\t\tArguments: call.Input,\n\t\t\t\t\t\t},\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\topenaiMessages = append(openaiMessages, openai.ChatCompletionMessageParamUnion{\n\t\t\t\tOfAssistant: &assistantMsg,\n\t\t\t})\n\n\t\tcase message.Tool:\n\t\t\tfor _, result := range msg.ToolResults() {\n\t\t\t\topenaiMessages = append(openaiMessages,\n\t\t\t\t\topenai.ToolMessage(result.Content, result.ToolCallID),\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn\n}\n\nfunc (o *openaiClient) convertTools(tools []tools.BaseTool) []openai.ChatCompletionToolParam {\n\topenaiTools := make([]openai.ChatCompletionToolParam, len(tools))\n\n\tfor i, tool := range tools {\n\t\tinfo := tool.Info()\n\t\topenaiTools[i] = openai.ChatCompletionToolParam{\n\t\t\tFunction: openai.FunctionDefinitionParam{\n\t\t\t\tName: info.Name,\n\t\t\t\tDescription: openai.String(info.Description),\n\t\t\t\tParameters: openai.FunctionParameters{\n\t\t\t\t\t\"type\": \"object\",\n\t\t\t\t\t\"properties\": info.Parameters,\n\t\t\t\t\t\"required\": info.Required,\n\t\t\t\t},\n\t\t\t},\n\t\t}\n\t}\n\n\treturn openaiTools\n}\n\nfunc (o *openaiClient) finishReason(reason string) message.FinishReason {\n\tswitch reason {\n\tcase \"stop\":\n\t\treturn message.FinishReasonEndTurn\n\tcase \"length\":\n\t\treturn message.FinishReasonMaxTokens\n\tcase \"tool_calls\":\n\t\treturn message.FinishReasonToolUse\n\tdefault:\n\t\treturn message.FinishReasonUnknown\n\t}\n}\n\nfunc (o *openaiClient) preparedParams(messages []openai.ChatCompletionMessageParamUnion, tools []openai.ChatCompletionToolParam) openai.ChatCompletionNewParams {\n\tparams := openai.ChatCompletionNewParams{\n\t\tModel: openai.ChatModel(o.providerOptions.model.APIModel),\n\t\tMessages: messages,\n\t\tTools: tools,\n\t}\n\n\tif o.providerOptions.model.CanReason == true {\n\t\tparams.MaxCompletionTokens = openai.Int(o.providerOptions.maxTokens)\n\t\tswitch o.options.reasoningEffort {\n\t\tcase \"low\":\n\t\t\tparams.ReasoningEffort = shared.ReasoningEffortLow\n\t\tcase \"medium\":\n\t\t\tparams.ReasoningEffort = shared.ReasoningEffortMedium\n\t\tcase \"high\":\n\t\t\tparams.ReasoningEffort = shared.ReasoningEffortHigh\n\t\tdefault:\n\t\t\tparams.ReasoningEffort = shared.ReasoningEffortMedium\n\t\t}\n\t} else {\n\t\tparams.MaxTokens = openai.Int(o.providerOptions.maxTokens)\n\t}\n\n\treturn params\n}\n\nfunc (o *openaiClient) send(ctx context.Context, messages []message.Message, tools []tools.BaseTool) (response *ProviderResponse, err error) {\n\tparams := o.preparedParams(o.convertMessages(messages), o.convertTools(tools))\n\tcfg := config.Get()\n\tif cfg.Debug {\n\t\tjsonData, _ := json.Marshal(params)\n\t\tlogging.Debug(\"Prepared messages\", \"messages\", string(jsonData))\n\t}\n\tattempts := 0\n\tfor {\n\t\tattempts++\n\t\topenaiResponse, err := o.client.Chat.Completions.New(\n\t\t\tctx,\n\t\t\tparams,\n\t\t)\n\t\t// If there is an error we are going to see if we can retry the call\n\t\tif err != nil {\n\t\t\tretry, after, retryErr := o.shouldRetry(attempts, err)\n\t\t\tif retryErr != nil {\n\t\t\t\treturn nil, retryErr\n\t\t\t}\n\t\t\tif retry {\n\t\t\t\tlogging.WarnPersist(fmt.Sprintf(\"Retrying due to rate limit... attempt %d of %d\", attempts, maxRetries), logging.PersistTimeArg, time.Millisecond*time.Duration(after+100))\n\t\t\t\tselect {\n\t\t\t\tcase <-ctx.Done():\n\t\t\t\t\treturn nil, ctx.Err()\n\t\t\t\tcase <-time.After(time.Duration(after) * time.Millisecond):\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn nil, retryErr\n\t\t}\n\n\t\tcontent := \"\"\n\t\tif openaiResponse.Choices[0].Message.Content != \"\" {\n\t\t\tcontent = openaiResponse.Choices[0].Message.Content\n\t\t}\n\n\t\ttoolCalls := o.toolCalls(*openaiResponse)\n\t\tfinishReason := o.finishReason(string(openaiResponse.Choices[0].FinishReason))\n\n\t\tif len(toolCalls) > 0 {\n\t\t\tfinishReason = message.FinishReasonToolUse\n\t\t}\n\n\t\treturn &ProviderResponse{\n\t\t\tContent: content,\n\t\t\tToolCalls: toolCalls,\n\t\t\tUsage: o.usage(*openaiResponse),\n\t\t\tFinishReason: finishReason,\n\t\t}, nil\n\t}\n}\n\nfunc (o *openaiClient) stream(ctx context.Context, messages []message.Message, tools []tools.BaseTool) <-chan ProviderEvent {\n\tparams := o.preparedParams(o.convertMessages(messages), o.convertTools(tools))\n\tparams.StreamOptions = openai.ChatCompletionStreamOptionsParam{\n\t\tIncludeUsage: openai.Bool(true),\n\t}\n\n\tcfg := config.Get()\n\tif cfg.Debug {\n\t\tjsonData, _ := json.Marshal(params)\n\t\tlogging.Debug(\"Prepared messages\", \"messages\", string(jsonData))\n\t}\n\n\tattempts := 0\n\teventChan := make(chan ProviderEvent)\n\n\tgo func() {\n\t\tfor {\n\t\t\tattempts++\n\t\t\topenaiStream := o.client.Chat.Completions.NewStreaming(\n\t\t\t\tctx,\n\t\t\t\tparams,\n\t\t\t)\n\n\t\t\tacc := openai.ChatCompletionAccumulator{}\n\t\t\tcurrentContent := \"\"\n\t\t\ttoolCalls := make([]message.ToolCall, 0)\n\n\t\t\tfor openaiStream.Next() {\n\t\t\t\tchunk := openaiStream.Current()\n\t\t\t\tacc.AddChunk(chunk)\n\n\t\t\t\tfor _, choice := range chunk.Choices {\n\t\t\t\t\tif choice.Delta.Content != \"\" {\n\t\t\t\t\t\teventChan <- ProviderEvent{\n\t\t\t\t\t\t\tType: EventContentDelta,\n\t\t\t\t\t\t\tContent: choice.Delta.Content,\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcurrentContent += choice.Delta.Content\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\terr := openaiStream.Err()\n\t\t\tif err == nil || errors.Is(err, io.EOF) {\n\t\t\t\t// Stream completed successfully\n\t\t\t\tfinishReason := o.finishReason(string(acc.ChatCompletion.Choices[0].FinishReason))\n\t\t\t\tif len(acc.ChatCompletion.Choices[0].Message.ToolCalls) > 0 {\n\t\t\t\t\ttoolCalls = append(toolCalls, o.toolCalls(acc.ChatCompletion)...)\n\t\t\t\t}\n\t\t\t\tif len(toolCalls) > 0 {\n\t\t\t\t\tfinishReason = message.FinishReasonToolUse\n\t\t\t\t}\n\n\t\t\t\teventChan <- ProviderEvent{\n\t\t\t\t\tType: EventComplete,\n\t\t\t\t\tResponse: &ProviderResponse{\n\t\t\t\t\t\tContent: currentContent,\n\t\t\t\t\t\tToolCalls: toolCalls,\n\t\t\t\t\t\tUsage: o.usage(acc.ChatCompletion),\n\t\t\t\t\t\tFinishReason: finishReason,\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t\tclose(eventChan)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\t// If there is an error we are going to see if we can retry the call\n\t\t\tretry, after, retryErr := o.shouldRetry(attempts, err)\n\t\t\tif retryErr != nil {\n\t\t\t\teventChan <- ProviderEvent{Type: EventError, Error: retryErr}\n\t\t\t\tclose(eventChan)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif retry {\n\t\t\t\tlogging.WarnPersist(fmt.Sprintf(\"Retrying due to rate limit... attempt %d of %d\", attempts, maxRetries), logging.PersistTimeArg, time.Millisecond*time.Duration(after+100))\n\t\t\t\tselect {\n\t\t\t\tcase <-ctx.Done():\n\t\t\t\t\t// context cancelled\n\t\t\t\t\tif ctx.Err() == nil {\n\t\t\t\t\t\teventChan <- ProviderEvent{Type: EventError, Error: ctx.Err()}\n\t\t\t\t\t}\n\t\t\t\t\tclose(eventChan)\n\t\t\t\t\treturn\n\t\t\t\tcase <-time.After(time.Duration(after) * time.Millisecond):\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t\teventChan <- ProviderEvent{Type: EventError, Error: retryErr}\n\t\t\tclose(eventChan)\n\t\t\treturn\n\t\t}\n\t}()\n\n\treturn eventChan\n}\n\nfunc (o *openaiClient) shouldRetry(attempts int, err error) (bool, int64, error) {\n\tvar apierr *openai.Error\n\tif !errors.As(err, &apierr) {\n\t\treturn false, 0, err\n\t}\n\n\tif apierr.StatusCode != 429 && apierr.StatusCode != 500 {\n\t\treturn false, 0, err\n\t}\n\n\tif attempts > maxRetries {\n\t\treturn false, 0, fmt.Errorf(\"maximum retry attempts reached for rate limit: %d retries\", maxRetries)\n\t}\n\n\tretryMs := 0\n\tretryAfterValues := apierr.Response.Header.Values(\"Retry-After\")\n\n\tbackoffMs := 2000 * (1 << (attempts - 1))\n\tjitterMs := int(float64(backoffMs) * 0.2)\n\tretryMs = backoffMs + jitterMs\n\tif len(retryAfterValues) > 0 {\n\t\tif _, err := fmt.Sscanf(retryAfterValues[0], \"%d\", &retryMs); err == nil {\n\t\t\tretryMs = retryMs * 1000\n\t\t}\n\t}\n\treturn true, int64(retryMs), nil\n}\n\nfunc (o *openaiClient) toolCalls(completion openai.ChatCompletion) []message.ToolCall {\n\tvar toolCalls []message.ToolCall\n\n\tif len(completion.Choices) > 0 && len(completion.Choices[0].Message.ToolCalls) > 0 {\n\t\tfor _, call := range completion.Choices[0].Message.ToolCalls {\n\t\t\ttoolCall := message.ToolCall{\n\t\t\t\tID: call.ID,\n\t\t\t\tName: call.Function.Name,\n\t\t\t\tInput: call.Function.Arguments,\n\t\t\t\tType: \"function\",\n\t\t\t\tFinished: true,\n\t\t\t}\n\t\t\ttoolCalls = append(toolCalls, toolCall)\n\t\t}\n\t}\n\n\treturn toolCalls\n}\n\nfunc (o *openaiClient) usage(completion openai.ChatCompletion) TokenUsage {\n\tcachedTokens := completion.Usage.PromptTokensDetails.CachedTokens\n\tinputTokens := completion.Usage.PromptTokens - cachedTokens\n\n\treturn TokenUsage{\n\t\tInputTokens: inputTokens,\n\t\tOutputTokens: completion.Usage.CompletionTokens,\n\t\tCacheCreationTokens: 0, // OpenAI doesn't provide this directly\n\t\tCacheReadTokens: cachedTokens,\n\t}\n}\n\nfunc WithOpenAIBaseURL(baseURL string) OpenAIOption {\n\treturn func(options *openaiOptions) {\n\t\toptions.baseURL = baseURL\n\t}\n}\n\nfunc WithOpenAIExtraHeaders(headers map[string]string) OpenAIOption {\n\treturn func(options *openaiOptions) {\n\t\toptions.extraHeaders = headers\n\t}\n}\n\nfunc WithOpenAIDisableCache() OpenAIOption {\n\treturn func(options *openaiOptions) {\n\t\toptions.disableCache = true\n\t}\n}\n\nfunc WithReasoningEffort(effort string) OpenAIOption {\n\treturn func(options *openaiOptions) {\n\t\tdefaultReasoningEffort := \"medium\"\n\t\tswitch effort {\n\t\tcase \"low\", \"medium\", \"high\":\n\t\t\tdefaultReasoningEffort = effort\n\t\tdefault:\n\t\t\tlogging.Warn(\"Invalid reasoning effort, using default: medium\")\n\t\t}\n\t\toptions.reasoningEffort = defaultReasoningEffort\n\t}\n}\n"], ["/opencode/internal/llm/prompt/prompt.go", "package prompt\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"strings\"\n\t\"sync\"\n\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/llm/models\"\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n)\n\nfunc GetAgentPrompt(agentName config.AgentName, provider models.ModelProvider) string {\n\tbasePrompt := \"\"\n\tswitch agentName {\n\tcase config.AgentCoder:\n\t\tbasePrompt = CoderPrompt(provider)\n\tcase config.AgentTitle:\n\t\tbasePrompt = TitlePrompt(provider)\n\tcase config.AgentTask:\n\t\tbasePrompt = TaskPrompt(provider)\n\tcase config.AgentSummarizer:\n\t\tbasePrompt = SummarizerPrompt(provider)\n\tdefault:\n\t\tbasePrompt = \"You are a helpful assistant\"\n\t}\n\n\tif agentName == config.AgentCoder || agentName == config.AgentTask {\n\t\t// Add context from project-specific instruction files if they exist\n\t\tcontextContent := getContextFromPaths()\n\t\tlogging.Debug(\"Context content\", \"Context\", contextContent)\n\t\tif contextContent != \"\" {\n\t\t\treturn fmt.Sprintf(\"%s\\n\\n# Project-Specific Context\\n Make sure to follow the instructions in the context below\\n%s\", basePrompt, contextContent)\n\t\t}\n\t}\n\treturn basePrompt\n}\n\nvar (\n\tonceContext sync.Once\n\tcontextContent string\n)\n\nfunc getContextFromPaths() string {\n\tonceContext.Do(func() {\n\t\tvar (\n\t\t\tcfg = config.Get()\n\t\t\tworkDir = cfg.WorkingDir\n\t\t\tcontextPaths = cfg.ContextPaths\n\t\t)\n\n\t\tcontextContent = processContextPaths(workDir, contextPaths)\n\t})\n\n\treturn contextContent\n}\n\nfunc processContextPaths(workDir string, paths []string) string {\n\tvar (\n\t\twg sync.WaitGroup\n\t\tresultCh = make(chan string)\n\t)\n\n\t// Track processed files to avoid duplicates\n\tprocessedFiles := make(map[string]bool)\n\tvar processedMutex sync.Mutex\n\n\tfor _, path := range paths {\n\t\twg.Add(1)\n\t\tgo func(p string) {\n\t\t\tdefer wg.Done()\n\n\t\t\tif strings.HasSuffix(p, \"/\") {\n\t\t\t\tfilepath.WalkDir(filepath.Join(workDir, p), func(path string, d os.DirEntry, err error) error {\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn err\n\t\t\t\t\t}\n\t\t\t\t\tif !d.IsDir() {\n\t\t\t\t\t\t// Check if we've already processed this file (case-insensitive)\n\t\t\t\t\t\tprocessedMutex.Lock()\n\t\t\t\t\t\tlowerPath := strings.ToLower(path)\n\t\t\t\t\t\tif !processedFiles[lowerPath] {\n\t\t\t\t\t\t\tprocessedFiles[lowerPath] = true\n\t\t\t\t\t\t\tprocessedMutex.Unlock()\n\n\t\t\t\t\t\t\tif result := processFile(path); result != \"\" {\n\t\t\t\t\t\t\t\tresultCh <- result\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tprocessedMutex.Unlock()\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\treturn nil\n\t\t\t\t})\n\t\t\t} else {\n\t\t\t\tfullPath := filepath.Join(workDir, p)\n\n\t\t\t\t// Check if we've already processed this file (case-insensitive)\n\t\t\t\tprocessedMutex.Lock()\n\t\t\t\tlowerPath := strings.ToLower(fullPath)\n\t\t\t\tif !processedFiles[lowerPath] {\n\t\t\t\t\tprocessedFiles[lowerPath] = true\n\t\t\t\t\tprocessedMutex.Unlock()\n\n\t\t\t\t\tresult := processFile(fullPath)\n\t\t\t\t\tif result != \"\" {\n\t\t\t\t\t\tresultCh <- result\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tprocessedMutex.Unlock()\n\t\t\t\t}\n\t\t\t}\n\t\t}(path)\n\t}\n\n\tgo func() {\n\t\twg.Wait()\n\t\tclose(resultCh)\n\t}()\n\n\tresults := make([]string, 0)\n\tfor result := range resultCh {\n\t\tresults = append(results, result)\n\t}\n\n\treturn strings.Join(results, \"\\n\")\n}\n\nfunc processFile(filePath string) string {\n\tcontent, err := os.ReadFile(filePath)\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\treturn \"# From:\" + filePath + \"\\n\" + string(content)\n}\n"], ["/opencode/internal/llm/agent/agent-tool.go", "package agent\n\nimport (\n\t\"context\"\n\t\"encoding/json\"\n\t\"fmt\"\n\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/llm/tools\"\n\t\"github.com/opencode-ai/opencode/internal/lsp\"\n\t\"github.com/opencode-ai/opencode/internal/message\"\n\t\"github.com/opencode-ai/opencode/internal/session\"\n)\n\ntype agentTool struct {\n\tsessions session.Service\n\tmessages message.Service\n\tlspClients map[string]*lsp.Client\n}\n\nconst (\n\tAgentToolName = \"agent\"\n)\n\ntype AgentParams struct {\n\tPrompt string `json:\"prompt\"`\n}\n\nfunc (b *agentTool) Info() tools.ToolInfo {\n\treturn tools.ToolInfo{\n\t\tName: AgentToolName,\n\t\tDescription: \"Launch a new agent that has access to the following tools: GlobTool, GrepTool, LS, View. When you are searching for a keyword or file and are not confident that you will find the right match on the first try, use the Agent tool to perform the search for you. For example:\\n\\n- If you are searching for a keyword like \\\"config\\\" or \\\"logger\\\", or for questions like \\\"which file does X?\\\", the Agent tool is strongly recommended\\n- If you want to read a specific file path, use the View or GlobTool tool instead of the Agent tool, to find the match more quickly\\n- If you are searching for a specific class definition like \\\"class Foo\\\", use the GlobTool tool instead, to find the match more quickly\\n\\nUsage notes:\\n1. Launch multiple agents concurrently whenever possible, to maximize performance; to do that, use a single message with multiple tool uses\\n2. When the agent is done, it will return a single message back to you. The result returned by the agent is not visible to the user. To show the user the result, you should send a text message back to the user with a concise summary of the result.\\n3. Each agent invocation is stateless. You will not be able to send additional messages to the agent, nor will the agent be able to communicate with you outside of its final report. Therefore, your prompt should contain a highly detailed task description for the agent to perform autonomously and you should specify exactly what information the agent should return back to you in its final and only message to you.\\n4. The agent's outputs should generally be trusted\\n5. IMPORTANT: The agent can not use Bash, Replace, Edit, so can not modify files. If you want to use these tools, use them directly instead of going through the agent.\",\n\t\tParameters: map[string]any{\n\t\t\t\"prompt\": map[string]any{\n\t\t\t\t\"type\": \"string\",\n\t\t\t\t\"description\": \"The task for the agent to perform\",\n\t\t\t},\n\t\t},\n\t\tRequired: []string{\"prompt\"},\n\t}\n}\n\nfunc (b *agentTool) Run(ctx context.Context, call tools.ToolCall) (tools.ToolResponse, error) {\n\tvar params AgentParams\n\tif err := json.Unmarshal([]byte(call.Input), ¶ms); err != nil {\n\t\treturn tools.NewTextErrorResponse(fmt.Sprintf(\"error parsing parameters: %s\", err)), nil\n\t}\n\tif params.Prompt == \"\" {\n\t\treturn tools.NewTextErrorResponse(\"prompt is required\"), nil\n\t}\n\n\tsessionID, messageID := tools.GetContextValues(ctx)\n\tif sessionID == \"\" || messageID == \"\" {\n\t\treturn tools.ToolResponse{}, fmt.Errorf(\"session_id and message_id are required\")\n\t}\n\n\tagent, err := NewAgent(config.AgentTask, b.sessions, b.messages, TaskAgentTools(b.lspClients))\n\tif err != nil {\n\t\treturn tools.ToolResponse{}, fmt.Errorf(\"error creating agent: %s\", err)\n\t}\n\n\tsession, err := b.sessions.CreateTaskSession(ctx, call.ID, sessionID, \"New Agent Session\")\n\tif err != nil {\n\t\treturn tools.ToolResponse{}, fmt.Errorf(\"error creating session: %s\", err)\n\t}\n\n\tdone, err := agent.Run(ctx, session.ID, params.Prompt)\n\tif err != nil {\n\t\treturn tools.ToolResponse{}, fmt.Errorf(\"error generating agent: %s\", err)\n\t}\n\tresult := <-done\n\tif result.Error != nil {\n\t\treturn tools.ToolResponse{}, fmt.Errorf(\"error generating agent: %s\", result.Error)\n\t}\n\n\tresponse := result.Message\n\tif response.Role != message.Assistant {\n\t\treturn tools.NewTextErrorResponse(\"no response\"), nil\n\t}\n\n\tupdatedSession, err := b.sessions.Get(ctx, session.ID)\n\tif err != nil {\n\t\treturn tools.ToolResponse{}, fmt.Errorf(\"error getting session: %s\", err)\n\t}\n\tparentSession, err := b.sessions.Get(ctx, sessionID)\n\tif err != nil {\n\t\treturn tools.ToolResponse{}, fmt.Errorf(\"error getting parent session: %s\", err)\n\t}\n\n\tparentSession.Cost += updatedSession.Cost\n\n\t_, err = b.sessions.Save(ctx, parentSession)\n\tif err != nil {\n\t\treturn tools.ToolResponse{}, fmt.Errorf(\"error saving parent session: %s\", err)\n\t}\n\treturn tools.NewTextResponse(response.Content().String()), nil\n}\n\nfunc NewAgentTool(\n\tSessions session.Service,\n\tMessages message.Service,\n\tLspClients map[string]*lsp.Client,\n) tools.BaseTool {\n\treturn &agentTool{\n\t\tsessions: Sessions,\n\t\tmessages: Messages,\n\t\tlspClients: LspClients,\n\t}\n}\n"], ["/opencode/internal/tui/components/chat/editor.go", "package chat\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"os/exec\"\n\t\"slices\"\n\t\"strings\"\n\t\"unicode\"\n\n\t\"github.com/charmbracelet/bubbles/key\"\n\t\"github.com/charmbracelet/bubbles/textarea\"\n\ttea \"github.com/charmbracelet/bubbletea\"\n\t\"github.com/charmbracelet/lipgloss\"\n\t\"github.com/opencode-ai/opencode/internal/app\"\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n\t\"github.com/opencode-ai/opencode/internal/message\"\n\t\"github.com/opencode-ai/opencode/internal/session\"\n\t\"github.com/opencode-ai/opencode/internal/tui/components/dialog\"\n\t\"github.com/opencode-ai/opencode/internal/tui/layout\"\n\t\"github.com/opencode-ai/opencode/internal/tui/styles\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n\t\"github.com/opencode-ai/opencode/internal/tui/util\"\n)\n\ntype editorCmp struct {\n\twidth int\n\theight int\n\tapp *app.App\n\tsession session.Session\n\ttextarea textarea.Model\n\tattachments []message.Attachment\n\tdeleteMode bool\n}\n\ntype EditorKeyMaps struct {\n\tSend key.Binding\n\tOpenEditor key.Binding\n}\n\ntype bluredEditorKeyMaps struct {\n\tSend key.Binding\n\tFocus key.Binding\n\tOpenEditor key.Binding\n}\ntype DeleteAttachmentKeyMaps struct {\n\tAttachmentDeleteMode key.Binding\n\tEscape key.Binding\n\tDeleteAllAttachments key.Binding\n}\n\nvar editorMaps = EditorKeyMaps{\n\tSend: key.NewBinding(\n\t\tkey.WithKeys(\"enter\", \"ctrl+s\"),\n\t\tkey.WithHelp(\"enter\", \"send message\"),\n\t),\n\tOpenEditor: key.NewBinding(\n\t\tkey.WithKeys(\"ctrl+e\"),\n\t\tkey.WithHelp(\"ctrl+e\", \"open editor\"),\n\t),\n}\n\nvar DeleteKeyMaps = DeleteAttachmentKeyMaps{\n\tAttachmentDeleteMode: key.NewBinding(\n\t\tkey.WithKeys(\"ctrl+r\"),\n\t\tkey.WithHelp(\"ctrl+r+{i}\", \"delete attachment at index i\"),\n\t),\n\tEscape: key.NewBinding(\n\t\tkey.WithKeys(\"esc\"),\n\t\tkey.WithHelp(\"esc\", \"cancel delete mode\"),\n\t),\n\tDeleteAllAttachments: key.NewBinding(\n\t\tkey.WithKeys(\"r\"),\n\t\tkey.WithHelp(\"ctrl+r+r\", \"delete all attchments\"),\n\t),\n}\n\nconst (\n\tmaxAttachments = 5\n)\n\nfunc (m *editorCmp) openEditor() tea.Cmd {\n\teditor := os.Getenv(\"EDITOR\")\n\tif editor == \"\" {\n\t\teditor = \"nvim\"\n\t}\n\n\ttmpfile, err := os.CreateTemp(\"\", \"msg_*.md\")\n\tif err != nil {\n\t\treturn util.ReportError(err)\n\t}\n\ttmpfile.Close()\n\tc := exec.Command(editor, tmpfile.Name()) //nolint:gosec\n\tc.Stdin = os.Stdin\n\tc.Stdout = os.Stdout\n\tc.Stderr = os.Stderr\n\treturn tea.ExecProcess(c, func(err error) tea.Msg {\n\t\tif err != nil {\n\t\t\treturn util.ReportError(err)\n\t\t}\n\t\tcontent, err := os.ReadFile(tmpfile.Name())\n\t\tif err != nil {\n\t\t\treturn util.ReportError(err)\n\t\t}\n\t\tif len(content) == 0 {\n\t\t\treturn util.ReportWarn(\"Message is empty\")\n\t\t}\n\t\tos.Remove(tmpfile.Name())\n\t\tattachments := m.attachments\n\t\tm.attachments = nil\n\t\treturn SendMsg{\n\t\t\tText: string(content),\n\t\t\tAttachments: attachments,\n\t\t}\n\t})\n}\n\nfunc (m *editorCmp) Init() tea.Cmd {\n\treturn textarea.Blink\n}\n\nfunc (m *editorCmp) send() tea.Cmd {\n\tif m.app.CoderAgent.IsSessionBusy(m.session.ID) {\n\t\treturn util.ReportWarn(\"Agent is working, please wait...\")\n\t}\n\n\tvalue := m.textarea.Value()\n\tm.textarea.Reset()\n\tattachments := m.attachments\n\n\tm.attachments = nil\n\tif value == \"\" {\n\t\treturn nil\n\t}\n\treturn tea.Batch(\n\t\tutil.CmdHandler(SendMsg{\n\t\t\tText: value,\n\t\t\tAttachments: attachments,\n\t\t}),\n\t)\n}\n\nfunc (m *editorCmp) Update(msg tea.Msg) (tea.Model, tea.Cmd) {\n\tvar cmd tea.Cmd\n\tswitch msg := msg.(type) {\n\tcase dialog.ThemeChangedMsg:\n\t\tm.textarea = CreateTextArea(&m.textarea)\n\tcase dialog.CompletionSelectedMsg:\n\t\texistingValue := m.textarea.Value()\n\t\tmodifiedValue := strings.Replace(existingValue, msg.SearchString, msg.CompletionValue, 1)\n\n\t\tm.textarea.SetValue(modifiedValue)\n\t\treturn m, nil\n\tcase SessionSelectedMsg:\n\t\tif msg.ID != m.session.ID {\n\t\t\tm.session = msg\n\t\t}\n\t\treturn m, nil\n\tcase dialog.AttachmentAddedMsg:\n\t\tif len(m.attachments) >= maxAttachments {\n\t\t\tlogging.ErrorPersist(fmt.Sprintf(\"cannot add more than %d images\", maxAttachments))\n\t\t\treturn m, cmd\n\t\t}\n\t\tm.attachments = append(m.attachments, msg.Attachment)\n\tcase tea.KeyMsg:\n\t\tif key.Matches(msg, DeleteKeyMaps.AttachmentDeleteMode) {\n\t\t\tm.deleteMode = true\n\t\t\treturn m, nil\n\t\t}\n\t\tif key.Matches(msg, DeleteKeyMaps.DeleteAllAttachments) && m.deleteMode {\n\t\t\tm.deleteMode = false\n\t\t\tm.attachments = nil\n\t\t\treturn m, nil\n\t\t}\n\t\tif m.deleteMode && len(msg.Runes) > 0 && unicode.IsDigit(msg.Runes[0]) {\n\t\t\tnum := int(msg.Runes[0] - '0')\n\t\t\tm.deleteMode = false\n\t\t\tif num < 10 && len(m.attachments) > num {\n\t\t\t\tif num == 0 {\n\t\t\t\t\tm.attachments = m.attachments[num+1:]\n\t\t\t\t} else {\n\t\t\t\t\tm.attachments = slices.Delete(m.attachments, num, num+1)\n\t\t\t\t}\n\t\t\t\treturn m, nil\n\t\t\t}\n\t\t}\n\t\tif key.Matches(msg, messageKeys.PageUp) || key.Matches(msg, messageKeys.PageDown) ||\n\t\t\tkey.Matches(msg, messageKeys.HalfPageUp) || key.Matches(msg, messageKeys.HalfPageDown) {\n\t\t\treturn m, nil\n\t\t}\n\t\tif key.Matches(msg, editorMaps.OpenEditor) {\n\t\t\tif m.app.CoderAgent.IsSessionBusy(m.session.ID) {\n\t\t\t\treturn m, util.ReportWarn(\"Agent is working, please wait...\")\n\t\t\t}\n\t\t\treturn m, m.openEditor()\n\t\t}\n\t\tif key.Matches(msg, DeleteKeyMaps.Escape) {\n\t\t\tm.deleteMode = false\n\t\t\treturn m, nil\n\t\t}\n\t\t// Hanlde Enter key\n\t\tif m.textarea.Focused() && key.Matches(msg, editorMaps.Send) {\n\t\t\tvalue := m.textarea.Value()\n\t\t\tif len(value) > 0 && value[len(value)-1] == '\\\\' {\n\t\t\t\t// If the last character is a backslash, remove it and add a newline\n\t\t\t\tm.textarea.SetValue(value[:len(value)-1] + \"\\n\")\n\t\t\t\treturn m, nil\n\t\t\t} else {\n\t\t\t\t// Otherwise, send the message\n\t\t\t\treturn m, m.send()\n\t\t\t}\n\t\t}\n\n\t}\n\tm.textarea, cmd = m.textarea.Update(msg)\n\treturn m, cmd\n}\n\nfunc (m *editorCmp) View() string {\n\tt := theme.CurrentTheme()\n\n\t// Style the prompt with theme colors\n\tstyle := lipgloss.NewStyle().\n\t\tPadding(0, 0, 0, 1).\n\t\tBold(true).\n\t\tForeground(t.Primary())\n\n\tif len(m.attachments) == 0 {\n\t\treturn lipgloss.JoinHorizontal(lipgloss.Top, style.Render(\">\"), m.textarea.View())\n\t}\n\tm.textarea.SetHeight(m.height - 1)\n\treturn lipgloss.JoinVertical(lipgloss.Top,\n\t\tm.attachmentsContent(),\n\t\tlipgloss.JoinHorizontal(lipgloss.Top, style.Render(\">\"),\n\t\t\tm.textarea.View()),\n\t)\n}\n\nfunc (m *editorCmp) SetSize(width, height int) tea.Cmd {\n\tm.width = width\n\tm.height = height\n\tm.textarea.SetWidth(width - 3) // account for the prompt and padding right\n\tm.textarea.SetHeight(height)\n\tm.textarea.SetWidth(width)\n\treturn nil\n}\n\nfunc (m *editorCmp) GetSize() (int, int) {\n\treturn m.textarea.Width(), m.textarea.Height()\n}\n\nfunc (m *editorCmp) attachmentsContent() string {\n\tvar styledAttachments []string\n\tt := theme.CurrentTheme()\n\tattachmentStyles := styles.BaseStyle().\n\t\tMarginLeft(1).\n\t\tBackground(t.TextMuted()).\n\t\tForeground(t.Text())\n\tfor i, attachment := range m.attachments {\n\t\tvar filename string\n\t\tif len(attachment.FileName) > 10 {\n\t\t\tfilename = fmt.Sprintf(\" %s %s...\", styles.DocumentIcon, attachment.FileName[0:7])\n\t\t} else {\n\t\t\tfilename = fmt.Sprintf(\" %s %s\", styles.DocumentIcon, attachment.FileName)\n\t\t}\n\t\tif m.deleteMode {\n\t\t\tfilename = fmt.Sprintf(\"%d%s\", i, filename)\n\t\t}\n\t\tstyledAttachments = append(styledAttachments, attachmentStyles.Render(filename))\n\t}\n\tcontent := lipgloss.JoinHorizontal(lipgloss.Left, styledAttachments...)\n\treturn content\n}\n\nfunc (m *editorCmp) BindingKeys() []key.Binding {\n\tbindings := []key.Binding{}\n\tbindings = append(bindings, layout.KeyMapToSlice(editorMaps)...)\n\tbindings = append(bindings, layout.KeyMapToSlice(DeleteKeyMaps)...)\n\treturn bindings\n}\n\nfunc CreateTextArea(existing *textarea.Model) textarea.Model {\n\tt := theme.CurrentTheme()\n\tbgColor := t.Background()\n\ttextColor := t.Text()\n\ttextMutedColor := t.TextMuted()\n\n\tta := textarea.New()\n\tta.BlurredStyle.Base = styles.BaseStyle().Background(bgColor).Foreground(textColor)\n\tta.BlurredStyle.CursorLine = styles.BaseStyle().Background(bgColor)\n\tta.BlurredStyle.Placeholder = styles.BaseStyle().Background(bgColor).Foreground(textMutedColor)\n\tta.BlurredStyle.Text = styles.BaseStyle().Background(bgColor).Foreground(textColor)\n\tta.FocusedStyle.Base = styles.BaseStyle().Background(bgColor).Foreground(textColor)\n\tta.FocusedStyle.CursorLine = styles.BaseStyle().Background(bgColor)\n\tta.FocusedStyle.Placeholder = styles.BaseStyle().Background(bgColor).Foreground(textMutedColor)\n\tta.FocusedStyle.Text = styles.BaseStyle().Background(bgColor).Foreground(textColor)\n\n\tta.Prompt = \" \"\n\tta.ShowLineNumbers = false\n\tta.CharLimit = -1\n\n\tif existing != nil {\n\t\tta.SetValue(existing.Value())\n\t\tta.SetWidth(existing.Width())\n\t\tta.SetHeight(existing.Height())\n\t}\n\n\tta.Focus()\n\treturn ta\n}\n\nfunc NewEditorCmp(app *app.App) tea.Model {\n\tta := CreateTextArea(nil)\n\treturn &editorCmp{\n\t\tapp: app,\n\t\ttextarea: ta,\n\t}\n}\n"], ["/opencode/internal/config/init.go", "package config\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"path/filepath\"\n)\n\nconst (\n\t// InitFlagFilename is the name of the file that indicates whether the project has been initialized\n\tInitFlagFilename = \"init\"\n)\n\n// ProjectInitFlag represents the initialization status for a project directory\ntype ProjectInitFlag struct {\n\tInitialized bool `json:\"initialized\"`\n}\n\n// ShouldShowInitDialog checks if the initialization dialog should be shown for the current directory\nfunc ShouldShowInitDialog() (bool, error) {\n\tif cfg == nil {\n\t\treturn false, fmt.Errorf(\"config not loaded\")\n\t}\n\n\t// Create the flag file path\n\tflagFilePath := filepath.Join(cfg.Data.Directory, InitFlagFilename)\n\n\t// Check if the flag file exists\n\t_, err := os.Stat(flagFilePath)\n\tif err == nil {\n\t\t// File exists, don't show the dialog\n\t\treturn false, nil\n\t}\n\n\t// If the error is not \"file not found\", return the error\n\tif !os.IsNotExist(err) {\n\t\treturn false, fmt.Errorf(\"failed to check init flag file: %w\", err)\n\t}\n\n\t// File doesn't exist, show the dialog\n\treturn true, nil\n}\n\n// MarkProjectInitialized marks the current project as initialized\nfunc MarkProjectInitialized() error {\n\tif cfg == nil {\n\t\treturn fmt.Errorf(\"config not loaded\")\n\t}\n\t// Create the flag file path\n\tflagFilePath := filepath.Join(cfg.Data.Directory, InitFlagFilename)\n\n\t// Create an empty file to mark the project as initialized\n\tfile, err := os.Create(flagFilePath)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to create init flag file: %w\", err)\n\t}\n\tdefer file.Close()\n\n\treturn nil\n}\n\n"], ["/opencode/internal/tui/components/dialog/permission.go", "package dialog\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\n\t\"github.com/charmbracelet/bubbles/key\"\n\t\"github.com/charmbracelet/bubbles/viewport\"\n\ttea \"github.com/charmbracelet/bubbletea\"\n\t\"github.com/charmbracelet/lipgloss\"\n\t\"github.com/opencode-ai/opencode/internal/diff\"\n\t\"github.com/opencode-ai/opencode/internal/llm/tools\"\n\t\"github.com/opencode-ai/opencode/internal/permission\"\n\t\"github.com/opencode-ai/opencode/internal/tui/layout\"\n\t\"github.com/opencode-ai/opencode/internal/tui/styles\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n\t\"github.com/opencode-ai/opencode/internal/tui/util\"\n)\n\ntype PermissionAction string\n\n// Permission responses\nconst (\n\tPermissionAllow PermissionAction = \"allow\"\n\tPermissionAllowForSession PermissionAction = \"allow_session\"\n\tPermissionDeny PermissionAction = \"deny\"\n)\n\n// PermissionResponseMsg represents the user's response to a permission request\ntype PermissionResponseMsg struct {\n\tPermission permission.PermissionRequest\n\tAction PermissionAction\n}\n\n// PermissionDialogCmp interface for permission dialog component\ntype PermissionDialogCmp interface {\n\ttea.Model\n\tlayout.Bindings\n\tSetPermissions(permission permission.PermissionRequest) tea.Cmd\n}\n\ntype permissionsMapping struct {\n\tLeft key.Binding\n\tRight key.Binding\n\tEnterSpace key.Binding\n\tAllow key.Binding\n\tAllowSession key.Binding\n\tDeny key.Binding\n\tTab key.Binding\n}\n\nvar permissionsKeys = permissionsMapping{\n\tLeft: key.NewBinding(\n\t\tkey.WithKeys(\"left\"),\n\t\tkey.WithHelp(\"←\", \"switch options\"),\n\t),\n\tRight: key.NewBinding(\n\t\tkey.WithKeys(\"right\"),\n\t\tkey.WithHelp(\"→\", \"switch options\"),\n\t),\n\tEnterSpace: key.NewBinding(\n\t\tkey.WithKeys(\"enter\", \" \"),\n\t\tkey.WithHelp(\"enter/space\", \"confirm\"),\n\t),\n\tAllow: key.NewBinding(\n\t\tkey.WithKeys(\"a\"),\n\t\tkey.WithHelp(\"a\", \"allow\"),\n\t),\n\tAllowSession: key.NewBinding(\n\t\tkey.WithKeys(\"s\"),\n\t\tkey.WithHelp(\"s\", \"allow for session\"),\n\t),\n\tDeny: key.NewBinding(\n\t\tkey.WithKeys(\"d\"),\n\t\tkey.WithHelp(\"d\", \"deny\"),\n\t),\n\tTab: key.NewBinding(\n\t\tkey.WithKeys(\"tab\"),\n\t\tkey.WithHelp(\"tab\", \"switch options\"),\n\t),\n}\n\n// permissionDialogCmp is the implementation of PermissionDialog\ntype permissionDialogCmp struct {\n\twidth int\n\theight int\n\tpermission permission.PermissionRequest\n\twindowSize tea.WindowSizeMsg\n\tcontentViewPort viewport.Model\n\tselectedOption int // 0: Allow, 1: Allow for session, 2: Deny\n\n\tdiffCache map[string]string\n\tmarkdownCache map[string]string\n}\n\nfunc (p *permissionDialogCmp) Init() tea.Cmd {\n\treturn p.contentViewPort.Init()\n}\n\nfunc (p *permissionDialogCmp) Update(msg tea.Msg) (tea.Model, tea.Cmd) {\n\tvar cmds []tea.Cmd\n\n\tswitch msg := msg.(type) {\n\tcase tea.WindowSizeMsg:\n\t\tp.windowSize = msg\n\t\tcmd := p.SetSize()\n\t\tcmds = append(cmds, cmd)\n\t\tp.markdownCache = make(map[string]string)\n\t\tp.diffCache = make(map[string]string)\n\tcase tea.KeyMsg:\n\t\tswitch {\n\t\tcase key.Matches(msg, permissionsKeys.Right) || key.Matches(msg, permissionsKeys.Tab):\n\t\t\tp.selectedOption = (p.selectedOption + 1) % 3\n\t\t\treturn p, nil\n\t\tcase key.Matches(msg, permissionsKeys.Left):\n\t\t\tp.selectedOption = (p.selectedOption + 2) % 3\n\t\tcase key.Matches(msg, permissionsKeys.EnterSpace):\n\t\t\treturn p, p.selectCurrentOption()\n\t\tcase key.Matches(msg, permissionsKeys.Allow):\n\t\t\treturn p, util.CmdHandler(PermissionResponseMsg{Action: PermissionAllow, Permission: p.permission})\n\t\tcase key.Matches(msg, permissionsKeys.AllowSession):\n\t\t\treturn p, util.CmdHandler(PermissionResponseMsg{Action: PermissionAllowForSession, Permission: p.permission})\n\t\tcase key.Matches(msg, permissionsKeys.Deny):\n\t\t\treturn p, util.CmdHandler(PermissionResponseMsg{Action: PermissionDeny, Permission: p.permission})\n\t\tdefault:\n\t\t\t// Pass other keys to viewport\n\t\t\tviewPort, cmd := p.contentViewPort.Update(msg)\n\t\t\tp.contentViewPort = viewPort\n\t\t\tcmds = append(cmds, cmd)\n\t\t}\n\t}\n\n\treturn p, tea.Batch(cmds...)\n}\n\nfunc (p *permissionDialogCmp) selectCurrentOption() tea.Cmd {\n\tvar action PermissionAction\n\n\tswitch p.selectedOption {\n\tcase 0:\n\t\taction = PermissionAllow\n\tcase 1:\n\t\taction = PermissionAllowForSession\n\tcase 2:\n\t\taction = PermissionDeny\n\t}\n\n\treturn util.CmdHandler(PermissionResponseMsg{Action: action, Permission: p.permission})\n}\n\nfunc (p *permissionDialogCmp) renderButtons() string {\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\n\tallowStyle := baseStyle\n\tallowSessionStyle := baseStyle\n\tdenyStyle := baseStyle\n\tspacerStyle := baseStyle.Background(t.Background())\n\n\t// Style the selected button\n\tswitch p.selectedOption {\n\tcase 0:\n\t\tallowStyle = allowStyle.Background(t.Primary()).Foreground(t.Background())\n\t\tallowSessionStyle = allowSessionStyle.Background(t.Background()).Foreground(t.Primary())\n\t\tdenyStyle = denyStyle.Background(t.Background()).Foreground(t.Primary())\n\tcase 1:\n\t\tallowStyle = allowStyle.Background(t.Background()).Foreground(t.Primary())\n\t\tallowSessionStyle = allowSessionStyle.Background(t.Primary()).Foreground(t.Background())\n\t\tdenyStyle = denyStyle.Background(t.Background()).Foreground(t.Primary())\n\tcase 2:\n\t\tallowStyle = allowStyle.Background(t.Background()).Foreground(t.Primary())\n\t\tallowSessionStyle = allowSessionStyle.Background(t.Background()).Foreground(t.Primary())\n\t\tdenyStyle = denyStyle.Background(t.Primary()).Foreground(t.Background())\n\t}\n\n\tallowButton := allowStyle.Padding(0, 1).Render(\"Allow (a)\")\n\tallowSessionButton := allowSessionStyle.Padding(0, 1).Render(\"Allow for session (s)\")\n\tdenyButton := denyStyle.Padding(0, 1).Render(\"Deny (d)\")\n\n\tcontent := lipgloss.JoinHorizontal(\n\t\tlipgloss.Left,\n\t\tallowButton,\n\t\tspacerStyle.Render(\" \"),\n\t\tallowSessionButton,\n\t\tspacerStyle.Render(\" \"),\n\t\tdenyButton,\n\t\tspacerStyle.Render(\" \"),\n\t)\n\n\tremainingWidth := p.width - lipgloss.Width(content)\n\tif remainingWidth > 0 {\n\t\tcontent = spacerStyle.Render(strings.Repeat(\" \", remainingWidth)) + content\n\t}\n\treturn content\n}\n\nfunc (p *permissionDialogCmp) renderHeader() string {\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\n\ttoolKey := baseStyle.Foreground(t.TextMuted()).Bold(true).Render(\"Tool\")\n\ttoolValue := baseStyle.\n\t\tForeground(t.Text()).\n\t\tWidth(p.width - lipgloss.Width(toolKey)).\n\t\tRender(fmt.Sprintf(\": %s\", p.permission.ToolName))\n\n\tpathKey := baseStyle.Foreground(t.TextMuted()).Bold(true).Render(\"Path\")\n\tpathValue := baseStyle.\n\t\tForeground(t.Text()).\n\t\tWidth(p.width - lipgloss.Width(pathKey)).\n\t\tRender(fmt.Sprintf(\": %s\", p.permission.Path))\n\n\theaderParts := []string{\n\t\tlipgloss.JoinHorizontal(\n\t\t\tlipgloss.Left,\n\t\t\ttoolKey,\n\t\t\ttoolValue,\n\t\t),\n\t\tbaseStyle.Render(strings.Repeat(\" \", p.width)),\n\t\tlipgloss.JoinHorizontal(\n\t\t\tlipgloss.Left,\n\t\t\tpathKey,\n\t\t\tpathValue,\n\t\t),\n\t\tbaseStyle.Render(strings.Repeat(\" \", p.width)),\n\t}\n\n\t// Add tool-specific header information\n\tswitch p.permission.ToolName {\n\tcase tools.BashToolName:\n\t\theaderParts = append(headerParts, baseStyle.Foreground(t.TextMuted()).Width(p.width).Bold(true).Render(\"Command\"))\n\tcase tools.EditToolName:\n\t\tparams := p.permission.Params.(tools.EditPermissionsParams)\n\t\tfileKey := baseStyle.Foreground(t.TextMuted()).Bold(true).Render(\"File\")\n\t\tfilePath := baseStyle.\n\t\t\tForeground(t.Text()).\n\t\t\tWidth(p.width - lipgloss.Width(fileKey)).\n\t\t\tRender(fmt.Sprintf(\": %s\", params.FilePath))\n\t\theaderParts = append(headerParts,\n\t\t\tlipgloss.JoinHorizontal(\n\t\t\t\tlipgloss.Left,\n\t\t\t\tfileKey,\n\t\t\t\tfilePath,\n\t\t\t),\n\t\t\tbaseStyle.Render(strings.Repeat(\" \", p.width)),\n\t\t)\n\n\tcase tools.WriteToolName:\n\t\tparams := p.permission.Params.(tools.WritePermissionsParams)\n\t\tfileKey := baseStyle.Foreground(t.TextMuted()).Bold(true).Render(\"File\")\n\t\tfilePath := baseStyle.\n\t\t\tForeground(t.Text()).\n\t\t\tWidth(p.width - lipgloss.Width(fileKey)).\n\t\t\tRender(fmt.Sprintf(\": %s\", params.FilePath))\n\t\theaderParts = append(headerParts,\n\t\t\tlipgloss.JoinHorizontal(\n\t\t\t\tlipgloss.Left,\n\t\t\t\tfileKey,\n\t\t\t\tfilePath,\n\t\t\t),\n\t\t\tbaseStyle.Render(strings.Repeat(\" \", p.width)),\n\t\t)\n\tcase tools.FetchToolName:\n\t\theaderParts = append(headerParts, baseStyle.Foreground(t.TextMuted()).Width(p.width).Bold(true).Render(\"URL\"))\n\t}\n\n\treturn lipgloss.NewStyle().Background(t.Background()).Render(lipgloss.JoinVertical(lipgloss.Left, headerParts...))\n}\n\nfunc (p *permissionDialogCmp) renderBashContent() string {\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\n\tif pr, ok := p.permission.Params.(tools.BashPermissionsParams); ok {\n\t\tcontent := fmt.Sprintf(\"```bash\\n%s\\n```\", pr.Command)\n\n\t\t// Use the cache for markdown rendering\n\t\trenderedContent := p.GetOrSetMarkdown(p.permission.ID, func() (string, error) {\n\t\t\tr := styles.GetMarkdownRenderer(p.width - 10)\n\t\t\ts, err := r.Render(content)\n\t\t\treturn styles.ForceReplaceBackgroundWithLipgloss(s, t.Background()), err\n\t\t})\n\n\t\tfinalContent := baseStyle.\n\t\t\tWidth(p.contentViewPort.Width).\n\t\t\tRender(renderedContent)\n\t\tp.contentViewPort.SetContent(finalContent)\n\t\treturn p.styleViewport()\n\t}\n\treturn \"\"\n}\n\nfunc (p *permissionDialogCmp) renderEditContent() string {\n\tif pr, ok := p.permission.Params.(tools.EditPermissionsParams); ok {\n\t\tdiff := p.GetOrSetDiff(p.permission.ID, func() (string, error) {\n\t\t\treturn diff.FormatDiff(pr.Diff, diff.WithTotalWidth(p.contentViewPort.Width))\n\t\t})\n\n\t\tp.contentViewPort.SetContent(diff)\n\t\treturn p.styleViewport()\n\t}\n\treturn \"\"\n}\n\nfunc (p *permissionDialogCmp) renderPatchContent() string {\n\tif pr, ok := p.permission.Params.(tools.EditPermissionsParams); ok {\n\t\tdiff := p.GetOrSetDiff(p.permission.ID, func() (string, error) {\n\t\t\treturn diff.FormatDiff(pr.Diff, diff.WithTotalWidth(p.contentViewPort.Width))\n\t\t})\n\n\t\tp.contentViewPort.SetContent(diff)\n\t\treturn p.styleViewport()\n\t}\n\treturn \"\"\n}\n\nfunc (p *permissionDialogCmp) renderWriteContent() string {\n\tif pr, ok := p.permission.Params.(tools.WritePermissionsParams); ok {\n\t\t// Use the cache for diff rendering\n\t\tdiff := p.GetOrSetDiff(p.permission.ID, func() (string, error) {\n\t\t\treturn diff.FormatDiff(pr.Diff, diff.WithTotalWidth(p.contentViewPort.Width))\n\t\t})\n\n\t\tp.contentViewPort.SetContent(diff)\n\t\treturn p.styleViewport()\n\t}\n\treturn \"\"\n}\n\nfunc (p *permissionDialogCmp) renderFetchContent() string {\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\n\tif pr, ok := p.permission.Params.(tools.FetchPermissionsParams); ok {\n\t\tcontent := fmt.Sprintf(\"```bash\\n%s\\n```\", pr.URL)\n\n\t\t// Use the cache for markdown rendering\n\t\trenderedContent := p.GetOrSetMarkdown(p.permission.ID, func() (string, error) {\n\t\t\tr := styles.GetMarkdownRenderer(p.width - 10)\n\t\t\ts, err := r.Render(content)\n\t\t\treturn styles.ForceReplaceBackgroundWithLipgloss(s, t.Background()), err\n\t\t})\n\n\t\tfinalContent := baseStyle.\n\t\t\tWidth(p.contentViewPort.Width).\n\t\t\tRender(renderedContent)\n\t\tp.contentViewPort.SetContent(finalContent)\n\t\treturn p.styleViewport()\n\t}\n\treturn \"\"\n}\n\nfunc (p *permissionDialogCmp) renderDefaultContent() string {\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\n\tcontent := p.permission.Description\n\n\t// Use the cache for markdown rendering\n\trenderedContent := p.GetOrSetMarkdown(p.permission.ID, func() (string, error) {\n\t\tr := styles.GetMarkdownRenderer(p.width - 10)\n\t\ts, err := r.Render(content)\n\t\treturn styles.ForceReplaceBackgroundWithLipgloss(s, t.Background()), err\n\t})\n\n\tfinalContent := baseStyle.\n\t\tWidth(p.contentViewPort.Width).\n\t\tRender(renderedContent)\n\tp.contentViewPort.SetContent(finalContent)\n\n\tif renderedContent == \"\" {\n\t\treturn \"\"\n\t}\n\n\treturn p.styleViewport()\n}\n\nfunc (p *permissionDialogCmp) styleViewport() string {\n\tt := theme.CurrentTheme()\n\tcontentStyle := lipgloss.NewStyle().\n\t\tBackground(t.Background())\n\n\treturn contentStyle.Render(p.contentViewPort.View())\n}\n\nfunc (p *permissionDialogCmp) render() string {\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\n\ttitle := baseStyle.\n\t\tBold(true).\n\t\tWidth(p.width - 4).\n\t\tForeground(t.Primary()).\n\t\tRender(\"Permission Required\")\n\t// Render header\n\theaderContent := p.renderHeader()\n\t// Render buttons\n\tbuttons := p.renderButtons()\n\n\t// Calculate content height dynamically based on window size\n\tp.contentViewPort.Height = p.height - lipgloss.Height(headerContent) - lipgloss.Height(buttons) - 2 - lipgloss.Height(title)\n\tp.contentViewPort.Width = p.width - 4\n\n\t// Render content based on tool type\n\tvar contentFinal string\n\tswitch p.permission.ToolName {\n\tcase tools.BashToolName:\n\t\tcontentFinal = p.renderBashContent()\n\tcase tools.EditToolName:\n\t\tcontentFinal = p.renderEditContent()\n\tcase tools.PatchToolName:\n\t\tcontentFinal = p.renderPatchContent()\n\tcase tools.WriteToolName:\n\t\tcontentFinal = p.renderWriteContent()\n\tcase tools.FetchToolName:\n\t\tcontentFinal = p.renderFetchContent()\n\tdefault:\n\t\tcontentFinal = p.renderDefaultContent()\n\t}\n\n\tcontent := lipgloss.JoinVertical(\n\t\tlipgloss.Top,\n\t\ttitle,\n\t\tbaseStyle.Render(strings.Repeat(\" \", lipgloss.Width(title))),\n\t\theaderContent,\n\t\tcontentFinal,\n\t\tbuttons,\n\t\tbaseStyle.Render(strings.Repeat(\" \", p.width-4)),\n\t)\n\n\treturn baseStyle.\n\t\tPadding(1, 0, 0, 1).\n\t\tBorder(lipgloss.RoundedBorder()).\n\t\tBorderBackground(t.Background()).\n\t\tBorderForeground(t.TextMuted()).\n\t\tWidth(p.width).\n\t\tHeight(p.height).\n\t\tRender(\n\t\t\tcontent,\n\t\t)\n}\n\nfunc (p *permissionDialogCmp) View() string {\n\treturn p.render()\n}\n\nfunc (p *permissionDialogCmp) BindingKeys() []key.Binding {\n\treturn layout.KeyMapToSlice(permissionsKeys)\n}\n\nfunc (p *permissionDialogCmp) SetSize() tea.Cmd {\n\tif p.permission.ID == \"\" {\n\t\treturn nil\n\t}\n\tswitch p.permission.ToolName {\n\tcase tools.BashToolName:\n\t\tp.width = int(float64(p.windowSize.Width) * 0.4)\n\t\tp.height = int(float64(p.windowSize.Height) * 0.3)\n\tcase tools.EditToolName:\n\t\tp.width = int(float64(p.windowSize.Width) * 0.8)\n\t\tp.height = int(float64(p.windowSize.Height) * 0.8)\n\tcase tools.WriteToolName:\n\t\tp.width = int(float64(p.windowSize.Width) * 0.8)\n\t\tp.height = int(float64(p.windowSize.Height) * 0.8)\n\tcase tools.FetchToolName:\n\t\tp.width = int(float64(p.windowSize.Width) * 0.4)\n\t\tp.height = int(float64(p.windowSize.Height) * 0.3)\n\tdefault:\n\t\tp.width = int(float64(p.windowSize.Width) * 0.7)\n\t\tp.height = int(float64(p.windowSize.Height) * 0.5)\n\t}\n\treturn nil\n}\n\nfunc (p *permissionDialogCmp) SetPermissions(permission permission.PermissionRequest) tea.Cmd {\n\tp.permission = permission\n\treturn p.SetSize()\n}\n\n// Helper to get or set cached diff content\nfunc (c *permissionDialogCmp) GetOrSetDiff(key string, generator func() (string, error)) string {\n\tif cached, ok := c.diffCache[key]; ok {\n\t\treturn cached\n\t}\n\n\tcontent, err := generator()\n\tif err != nil {\n\t\treturn fmt.Sprintf(\"Error formatting diff: %v\", err)\n\t}\n\n\tc.diffCache[key] = content\n\n\treturn content\n}\n\n// Helper to get or set cached markdown content\nfunc (c *permissionDialogCmp) GetOrSetMarkdown(key string, generator func() (string, error)) string {\n\tif cached, ok := c.markdownCache[key]; ok {\n\t\treturn cached\n\t}\n\n\tcontent, err := generator()\n\tif err != nil {\n\t\treturn fmt.Sprintf(\"Error rendering markdown: %v\", err)\n\t}\n\n\tc.markdownCache[key] = content\n\n\treturn content\n}\n\nfunc NewPermissionDialogCmp() PermissionDialogCmp {\n\t// Create viewport for content\n\tcontentViewport := viewport.New(0, 0)\n\n\treturn &permissionDialogCmp{\n\t\tcontentViewPort: contentViewport,\n\t\tselectedOption: 0, // Default to \"Allow\"\n\t\tdiffCache: make(map[string]string),\n\t\tmarkdownCache: make(map[string]string),\n\t}\n}\n"], ["/opencode/internal/lsp/protocol/uri.go", "// Copyright 2023 The Go Authors. All rights reserved.\n// Use of this source code is governed by a BSD-style\n// license that can be found in the LICENSE file.\n\npackage protocol\n\n// This file declares URI, DocumentUri, and its methods.\n//\n// For the LSP definition of these types, see\n// https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#uri\n\nimport (\n\t\"fmt\"\n\t\"net/url\"\n\t\"path/filepath\"\n\t\"strings\"\n\t\"unicode\"\n)\n\n// A DocumentUri is the URI of a client editor document.\n//\n// According to the LSP specification:\n//\n//\tCare should be taken to handle encoding in URIs. For\n//\texample, some clients (such as VS Code) may encode colons\n//\tin drive letters while others do not. The URIs below are\n//\tboth valid, but clients and servers should be consistent\n//\twith the form they use themselves to ensure the other party\n//\tdoesn’t interpret them as distinct URIs. Clients and\n//\tservers should not assume that each other are encoding the\n//\tsame way (for example a client encoding colons in drive\n//\tletters cannot assume server responses will have encoded\n//\tcolons). The same applies to casing of drive letters - one\n//\tparty should not assume the other party will return paths\n//\twith drive letters cased the same as it.\n//\n//\tfile:///c:/project/readme.md\n//\tfile:///C%3A/project/readme.md\n//\n// This is done during JSON unmarshalling;\n// see [DocumentUri.UnmarshalText] for details.\ntype DocumentUri string\n\n// A URI is an arbitrary URL (e.g. https), not necessarily a file.\ntype URI = string\n\n// UnmarshalText implements decoding of DocumentUri values.\n//\n// In particular, it implements a systematic correction of various odd\n// features of the definition of DocumentUri in the LSP spec that\n// appear to be workarounds for bugs in VS Code. For example, it may\n// URI-encode the URI itself, so that colon becomes %3A, and it may\n// send file://foo.go URIs that have two slashes (not three) and no\n// hostname.\n//\n// We use UnmarshalText, not UnmarshalJSON, because it is called even\n// for non-addressable values such as keys and values of map[K]V,\n// where there is no pointer of type *K or *V on which to call\n// UnmarshalJSON. (See Go issue #28189 for more detail.)\n//\n// Non-empty DocumentUris are valid \"file\"-scheme URIs.\n// The empty DocumentUri is valid.\nfunc (uri *DocumentUri) UnmarshalText(data []byte) (err error) {\n\t*uri, err = ParseDocumentUri(string(data))\n\treturn\n}\n\n// Path returns the file path for the given URI.\n//\n// DocumentUri(\"\").Path() returns the empty string.\n//\n// Path panics if called on a URI that is not a valid filename.\nfunc (uri DocumentUri) Path() string {\n\tfilename, err := filename(uri)\n\tif err != nil {\n\t\t// e.g. ParseRequestURI failed.\n\t\t//\n\t\t// This can only affect DocumentUris created by\n\t\t// direct string manipulation; all DocumentUris\n\t\t// received from the client pass through\n\t\t// ParseRequestURI, which ensures validity.\n\t\tpanic(err)\n\t}\n\treturn filepath.FromSlash(filename)\n}\n\n// Dir returns the URI for the directory containing the receiver.\nfunc (uri DocumentUri) Dir() DocumentUri {\n\t// This function could be more efficiently implemented by avoiding any call\n\t// to Path(), but at least consolidates URI manipulation.\n\treturn URIFromPath(uri.DirPath())\n}\n\n// DirPath returns the file path to the directory containing this URI, which\n// must be a file URI.\nfunc (uri DocumentUri) DirPath() string {\n\treturn filepath.Dir(uri.Path())\n}\n\nfunc filename(uri DocumentUri) (string, error) {\n\tif uri == \"\" {\n\t\treturn \"\", nil\n\t}\n\n\t// This conservative check for the common case\n\t// of a simple non-empty absolute POSIX filename\n\t// avoids the allocation of a net.URL.\n\tif strings.HasPrefix(string(uri), \"file:///\") {\n\t\trest := string(uri)[len(\"file://\"):] // leave one slash\n\t\tfor i := range len(rest) {\n\t\t\tb := rest[i]\n\t\t\t// Reject these cases:\n\t\t\tif b < ' ' || b == 0x7f || // control character\n\t\t\t\tb == '%' || b == '+' || // URI escape\n\t\t\t\tb == ':' || // Windows drive letter\n\t\t\t\tb == '@' || b == '&' || b == '?' { // authority or query\n\t\t\t\tgoto slow\n\t\t\t}\n\t\t}\n\t\treturn rest, nil\n\t}\nslow:\n\n\tu, err := url.ParseRequestURI(string(uri))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tif u.Scheme != fileScheme {\n\t\treturn \"\", fmt.Errorf(\"only file URIs are supported, got %q from %q\", u.Scheme, uri)\n\t}\n\t// If the URI is a Windows URI, we trim the leading \"/\" and uppercase\n\t// the drive letter, which will never be case sensitive.\n\tif isWindowsDriveURIPath(u.Path) {\n\t\tu.Path = strings.ToUpper(string(u.Path[1])) + u.Path[2:]\n\t}\n\n\treturn u.Path, nil\n}\n\n// ParseDocumentUri interprets a string as a DocumentUri, applying VS\n// Code workarounds; see [DocumentUri.UnmarshalText] for details.\nfunc ParseDocumentUri(s string) (DocumentUri, error) {\n\tif s == \"\" {\n\t\treturn \"\", nil\n\t}\n\n\tif !strings.HasPrefix(s, \"file://\") {\n\t\treturn \"\", fmt.Errorf(\"DocumentUri scheme is not 'file': %s\", s)\n\t}\n\n\t// VS Code sends URLs with only two slashes,\n\t// which are invalid. golang/go#39789.\n\tif !strings.HasPrefix(s, \"file:///\") {\n\t\ts = \"file:///\" + s[len(\"file://\"):]\n\t}\n\n\t// Even though the input is a URI, it may not be in canonical form. VS Code\n\t// in particular over-escapes :, @, etc. Unescape and re-encode to canonicalize.\n\tpath, err := url.PathUnescape(s[len(\"file://\"):])\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t// File URIs from Windows may have lowercase drive letters.\n\t// Since drive letters are guaranteed to be case insensitive,\n\t// we change them to uppercase to remain consistent.\n\t// For example, file:///c:/x/y/z becomes file:///C:/x/y/z.\n\tif isWindowsDriveURIPath(path) {\n\t\tpath = path[:1] + strings.ToUpper(string(path[1])) + path[2:]\n\t}\n\tu := url.URL{Scheme: fileScheme, Path: path}\n\treturn DocumentUri(u.String()), nil\n}\n\n// URIFromPath returns DocumentUri for the supplied file path.\n// Given \"\", it returns \"\".\nfunc URIFromPath(path string) DocumentUri {\n\tif path == \"\" {\n\t\treturn \"\"\n\t}\n\tif !isWindowsDrivePath(path) {\n\t\tif abs, err := filepath.Abs(path); err == nil {\n\t\t\tpath = abs\n\t\t}\n\t}\n\t// Check the file path again, in case it became absolute.\n\tif isWindowsDrivePath(path) {\n\t\tpath = \"/\" + strings.ToUpper(string(path[0])) + path[1:]\n\t}\n\tpath = filepath.ToSlash(path)\n\tu := url.URL{\n\t\tScheme: fileScheme,\n\t\tPath: path,\n\t}\n\treturn DocumentUri(u.String())\n}\n\nconst fileScheme = \"file\"\n\n// isWindowsDrivePath returns true if the file path is of the form used by\n// Windows. We check if the path begins with a drive letter, followed by a \":\".\n// For example: C:/x/y/z.\nfunc isWindowsDrivePath(path string) bool {\n\tif len(path) < 3 {\n\t\treturn false\n\t}\n\treturn unicode.IsLetter(rune(path[0])) && path[1] == ':'\n}\n\n// isWindowsDriveURIPath returns true if the file URI is of the format used by\n// Windows URIs. The url.Parse package does not specially handle Windows paths\n// (see golang/go#6027), so we check if the URI path has a drive prefix (e.g. \"/C:\").\nfunc isWindowsDriveURIPath(uri string) bool {\n\tif len(uri) < 4 {\n\t\treturn false\n\t}\n\treturn uri[0] == '/' && unicode.IsLetter(rune(uri[1])) && uri[2] == ':'\n}\n"], ["/opencode/internal/diff/patch.go", "package diff\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"strings\"\n)\n\ntype ActionType string\n\nconst (\n\tActionAdd ActionType = \"add\"\n\tActionDelete ActionType = \"delete\"\n\tActionUpdate ActionType = \"update\"\n)\n\ntype FileChange struct {\n\tType ActionType\n\tOldContent *string\n\tNewContent *string\n\tMovePath *string\n}\n\ntype Commit struct {\n\tChanges map[string]FileChange\n}\n\ntype Chunk struct {\n\tOrigIndex int // line index of the first line in the original file\n\tDelLines []string // lines to delete\n\tInsLines []string // lines to insert\n}\n\ntype PatchAction struct {\n\tType ActionType\n\tNewFile *string\n\tChunks []Chunk\n\tMovePath *string\n}\n\ntype Patch struct {\n\tActions map[string]PatchAction\n}\n\ntype DiffError struct {\n\tmessage string\n}\n\nfunc (e DiffError) Error() string {\n\treturn e.message\n}\n\n// Helper functions for error handling\nfunc NewDiffError(message string) DiffError {\n\treturn DiffError{message: message}\n}\n\nfunc fileError(action, reason, path string) DiffError {\n\treturn NewDiffError(fmt.Sprintf(\"%s File Error: %s: %s\", action, reason, path))\n}\n\nfunc contextError(index int, context string, isEOF bool) DiffError {\n\tprefix := \"Invalid Context\"\n\tif isEOF {\n\t\tprefix = \"Invalid EOF Context\"\n\t}\n\treturn NewDiffError(fmt.Sprintf(\"%s %d:\\n%s\", prefix, index, context))\n}\n\ntype Parser struct {\n\tcurrentFiles map[string]string\n\tlines []string\n\tindex int\n\tpatch Patch\n\tfuzz int\n}\n\nfunc NewParser(currentFiles map[string]string, lines []string) *Parser {\n\treturn &Parser{\n\t\tcurrentFiles: currentFiles,\n\t\tlines: lines,\n\t\tindex: 0,\n\t\tpatch: Patch{Actions: make(map[string]PatchAction, len(currentFiles))},\n\t\tfuzz: 0,\n\t}\n}\n\nfunc (p *Parser) isDone(prefixes []string) bool {\n\tif p.index >= len(p.lines) {\n\t\treturn true\n\t}\n\tfor _, prefix := range prefixes {\n\t\tif strings.HasPrefix(p.lines[p.index], prefix) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc (p *Parser) startsWith(prefix any) bool {\n\tvar prefixes []string\n\tswitch v := prefix.(type) {\n\tcase string:\n\t\tprefixes = []string{v}\n\tcase []string:\n\t\tprefixes = v\n\t}\n\n\tfor _, pfx := range prefixes {\n\t\tif strings.HasPrefix(p.lines[p.index], pfx) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc (p *Parser) readStr(prefix string, returnEverything bool) string {\n\tif p.index >= len(p.lines) {\n\t\treturn \"\" // Changed from panic to return empty string for safer operation\n\t}\n\tif strings.HasPrefix(p.lines[p.index], prefix) {\n\t\tvar text string\n\t\tif returnEverything {\n\t\t\ttext = p.lines[p.index]\n\t\t} else {\n\t\t\ttext = p.lines[p.index][len(prefix):]\n\t\t}\n\t\tp.index++\n\t\treturn text\n\t}\n\treturn \"\"\n}\n\nfunc (p *Parser) Parse() error {\n\tendPatchPrefixes := []string{\"*** End Patch\"}\n\n\tfor !p.isDone(endPatchPrefixes) {\n\t\tpath := p.readStr(\"*** Update File: \", false)\n\t\tif path != \"\" {\n\t\t\tif _, exists := p.patch.Actions[path]; exists {\n\t\t\t\treturn fileError(\"Update\", \"Duplicate Path\", path)\n\t\t\t}\n\t\t\tmoveTo := p.readStr(\"*** Move to: \", false)\n\t\t\tif _, exists := p.currentFiles[path]; !exists {\n\t\t\t\treturn fileError(\"Update\", \"Missing File\", path)\n\t\t\t}\n\t\t\ttext := p.currentFiles[path]\n\t\t\taction, err := p.parseUpdateFile(text)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif moveTo != \"\" {\n\t\t\t\taction.MovePath = &moveTo\n\t\t\t}\n\t\t\tp.patch.Actions[path] = action\n\t\t\tcontinue\n\t\t}\n\n\t\tpath = p.readStr(\"*** Delete File: \", false)\n\t\tif path != \"\" {\n\t\t\tif _, exists := p.patch.Actions[path]; exists {\n\t\t\t\treturn fileError(\"Delete\", \"Duplicate Path\", path)\n\t\t\t}\n\t\t\tif _, exists := p.currentFiles[path]; !exists {\n\t\t\t\treturn fileError(\"Delete\", \"Missing File\", path)\n\t\t\t}\n\t\t\tp.patch.Actions[path] = PatchAction{Type: ActionDelete, Chunks: []Chunk{}}\n\t\t\tcontinue\n\t\t}\n\n\t\tpath = p.readStr(\"*** Add File: \", false)\n\t\tif path != \"\" {\n\t\t\tif _, exists := p.patch.Actions[path]; exists {\n\t\t\t\treturn fileError(\"Add\", \"Duplicate Path\", path)\n\t\t\t}\n\t\t\tif _, exists := p.currentFiles[path]; exists {\n\t\t\t\treturn fileError(\"Add\", \"File already exists\", path)\n\t\t\t}\n\t\t\taction, err := p.parseAddFile()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tp.patch.Actions[path] = action\n\t\t\tcontinue\n\t\t}\n\n\t\treturn NewDiffError(fmt.Sprintf(\"Unknown Line: %s\", p.lines[p.index]))\n\t}\n\n\tif !p.startsWith(\"*** End Patch\") {\n\t\treturn NewDiffError(\"Missing End Patch\")\n\t}\n\tp.index++\n\n\treturn nil\n}\n\nfunc (p *Parser) parseUpdateFile(text string) (PatchAction, error) {\n\taction := PatchAction{Type: ActionUpdate, Chunks: []Chunk{}}\n\tfileLines := strings.Split(text, \"\\n\")\n\tindex := 0\n\n\tendPrefixes := []string{\n\t\t\"*** End Patch\",\n\t\t\"*** Update File:\",\n\t\t\"*** Delete File:\",\n\t\t\"*** Add File:\",\n\t\t\"*** End of File\",\n\t}\n\n\tfor !p.isDone(endPrefixes) {\n\t\tdefStr := p.readStr(\"@@ \", false)\n\t\tsectionStr := \"\"\n\t\tif defStr == \"\" && p.index < len(p.lines) && p.lines[p.index] == \"@@\" {\n\t\t\tsectionStr = p.lines[p.index]\n\t\t\tp.index++\n\t\t}\n\t\tif defStr == \"\" && sectionStr == \"\" && index != 0 {\n\t\t\treturn action, NewDiffError(fmt.Sprintf(\"Invalid Line:\\n%s\", p.lines[p.index]))\n\t\t}\n\t\tif strings.TrimSpace(defStr) != \"\" {\n\t\t\tfound := false\n\t\t\tfor i := range fileLines[:index] {\n\t\t\t\tif fileLines[i] == defStr {\n\t\t\t\t\tfound = true\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif !found {\n\t\t\t\tfor i := index; i < len(fileLines); i++ {\n\t\t\t\t\tif fileLines[i] == defStr {\n\t\t\t\t\t\tindex = i + 1\n\t\t\t\t\t\tfound = true\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif !found {\n\t\t\t\tfor i := range fileLines[:index] {\n\t\t\t\t\tif strings.TrimSpace(fileLines[i]) == strings.TrimSpace(defStr) {\n\t\t\t\t\t\tfound = true\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif !found {\n\t\t\t\tfor i := index; i < len(fileLines); i++ {\n\t\t\t\t\tif strings.TrimSpace(fileLines[i]) == strings.TrimSpace(defStr) {\n\t\t\t\t\t\tindex = i + 1\n\t\t\t\t\t\tp.fuzz++\n\t\t\t\t\t\tfound = true\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tnextChunkContext, chunks, endPatchIndex, eof := peekNextSection(p.lines, p.index)\n\t\tnewIndex, fuzz := findContext(fileLines, nextChunkContext, index, eof)\n\t\tif newIndex == -1 {\n\t\t\tctxText := strings.Join(nextChunkContext, \"\\n\")\n\t\t\treturn action, contextError(index, ctxText, eof)\n\t\t}\n\t\tp.fuzz += fuzz\n\n\t\tfor _, ch := range chunks {\n\t\t\tch.OrigIndex += newIndex\n\t\t\taction.Chunks = append(action.Chunks, ch)\n\t\t}\n\t\tindex = newIndex + len(nextChunkContext)\n\t\tp.index = endPatchIndex\n\t}\n\treturn action, nil\n}\n\nfunc (p *Parser) parseAddFile() (PatchAction, error) {\n\tlines := make([]string, 0, 16) // Preallocate space for better performance\n\tendPrefixes := []string{\n\t\t\"*** End Patch\",\n\t\t\"*** Update File:\",\n\t\t\"*** Delete File:\",\n\t\t\"*** Add File:\",\n\t}\n\n\tfor !p.isDone(endPrefixes) {\n\t\ts := p.readStr(\"\", true)\n\t\tif !strings.HasPrefix(s, \"+\") {\n\t\t\treturn PatchAction{}, NewDiffError(fmt.Sprintf(\"Invalid Add File Line: %s\", s))\n\t\t}\n\t\tlines = append(lines, s[1:])\n\t}\n\n\tnewFile := strings.Join(lines, \"\\n\")\n\treturn PatchAction{\n\t\tType: ActionAdd,\n\t\tNewFile: &newFile,\n\t\tChunks: []Chunk{},\n\t}, nil\n}\n\n// Refactored to use a matcher function for each comparison type\nfunc findContextCore(lines []string, context []string, start int) (int, int) {\n\tif len(context) == 0 {\n\t\treturn start, 0\n\t}\n\n\t// Try exact match\n\tif idx, fuzz := tryFindMatch(lines, context, start, func(a, b string) bool {\n\t\treturn a == b\n\t}); idx >= 0 {\n\t\treturn idx, fuzz\n\t}\n\n\t// Try trimming right whitespace\n\tif idx, fuzz := tryFindMatch(lines, context, start, func(a, b string) bool {\n\t\treturn strings.TrimRight(a, \" \\t\") == strings.TrimRight(b, \" \\t\")\n\t}); idx >= 0 {\n\t\treturn idx, fuzz\n\t}\n\n\t// Try trimming all whitespace\n\tif idx, fuzz := tryFindMatch(lines, context, start, func(a, b string) bool {\n\t\treturn strings.TrimSpace(a) == strings.TrimSpace(b)\n\t}); idx >= 0 {\n\t\treturn idx, fuzz\n\t}\n\n\treturn -1, 0\n}\n\n// Helper function to DRY up the match logic\nfunc tryFindMatch(lines []string, context []string, start int,\n\tcompareFunc func(string, string) bool,\n) (int, int) {\n\tfor i := start; i < len(lines); i++ {\n\t\tif i+len(context) <= len(lines) {\n\t\t\tmatch := true\n\t\t\tfor j := range context {\n\t\t\t\tif !compareFunc(lines[i+j], context[j]) {\n\t\t\t\t\tmatch = false\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\tif match {\n\t\t\t\t// Return fuzz level: 0 for exact, 1 for trimRight, 100 for trimSpace\n\t\t\t\tvar fuzz int\n\t\t\t\tif compareFunc(\"a \", \"a\") && !compareFunc(\"a\", \"b\") {\n\t\t\t\t\tfuzz = 1\n\t\t\t\t} else if compareFunc(\"a \", \"a\") {\n\t\t\t\t\tfuzz = 100\n\t\t\t\t}\n\t\t\t\treturn i, fuzz\n\t\t\t}\n\t\t}\n\t}\n\treturn -1, 0\n}\n\nfunc findContext(lines []string, context []string, start int, eof bool) (int, int) {\n\tif eof {\n\t\tnewIndex, fuzz := findContextCore(lines, context, len(lines)-len(context))\n\t\tif newIndex != -1 {\n\t\t\treturn newIndex, fuzz\n\t\t}\n\t\tnewIndex, fuzz = findContextCore(lines, context, start)\n\t\treturn newIndex, fuzz + 10000\n\t}\n\treturn findContextCore(lines, context, start)\n}\n\nfunc peekNextSection(lines []string, initialIndex int) ([]string, []Chunk, int, bool) {\n\tindex := initialIndex\n\told := make([]string, 0, 32) // Preallocate for better performance\n\tdelLines := make([]string, 0, 8)\n\tinsLines := make([]string, 0, 8)\n\tchunks := make([]Chunk, 0, 4)\n\tmode := \"keep\"\n\n\t// End conditions for the section\n\tendSectionConditions := func(s string) bool {\n\t\treturn strings.HasPrefix(s, \"@@\") ||\n\t\t\tstrings.HasPrefix(s, \"*** End Patch\") ||\n\t\t\tstrings.HasPrefix(s, \"*** Update File:\") ||\n\t\t\tstrings.HasPrefix(s, \"*** Delete File:\") ||\n\t\t\tstrings.HasPrefix(s, \"*** Add File:\") ||\n\t\t\tstrings.HasPrefix(s, \"*** End of File\") ||\n\t\t\ts == \"***\" ||\n\t\t\tstrings.HasPrefix(s, \"***\")\n\t}\n\n\tfor index < len(lines) {\n\t\ts := lines[index]\n\t\tif endSectionConditions(s) {\n\t\t\tbreak\n\t\t}\n\t\tindex++\n\t\tlastMode := mode\n\t\tline := s\n\n\t\tif len(line) > 0 {\n\t\t\tswitch line[0] {\n\t\t\tcase '+':\n\t\t\t\tmode = \"add\"\n\t\t\tcase '-':\n\t\t\t\tmode = \"delete\"\n\t\t\tcase ' ':\n\t\t\t\tmode = \"keep\"\n\t\t\tdefault:\n\t\t\t\tmode = \"keep\"\n\t\t\t\tline = \" \" + line\n\t\t\t}\n\t\t} else {\n\t\t\tmode = \"keep\"\n\t\t\tline = \" \"\n\t\t}\n\n\t\tline = line[1:]\n\t\tif mode == \"keep\" && lastMode != mode {\n\t\t\tif len(insLines) > 0 || len(delLines) > 0 {\n\t\t\t\tchunks = append(chunks, Chunk{\n\t\t\t\t\tOrigIndex: len(old) - len(delLines),\n\t\t\t\t\tDelLines: delLines,\n\t\t\t\t\tInsLines: insLines,\n\t\t\t\t})\n\t\t\t}\n\t\t\tdelLines = make([]string, 0, 8)\n\t\t\tinsLines = make([]string, 0, 8)\n\t\t}\n\t\tswitch mode {\n\t\tcase \"delete\":\n\t\t\tdelLines = append(delLines, line)\n\t\t\told = append(old, line)\n\t\tcase \"add\":\n\t\t\tinsLines = append(insLines, line)\n\t\tdefault:\n\t\t\told = append(old, line)\n\t\t}\n\t}\n\n\tif len(insLines) > 0 || len(delLines) > 0 {\n\t\tchunks = append(chunks, Chunk{\n\t\t\tOrigIndex: len(old) - len(delLines),\n\t\t\tDelLines: delLines,\n\t\t\tInsLines: insLines,\n\t\t})\n\t}\n\n\tif index < len(lines) && lines[index] == \"*** End of File\" {\n\t\tindex++\n\t\treturn old, chunks, index, true\n\t}\n\treturn old, chunks, index, false\n}\n\nfunc TextToPatch(text string, orig map[string]string) (Patch, int, error) {\n\ttext = strings.TrimSpace(text)\n\tlines := strings.Split(text, \"\\n\")\n\tif len(lines) < 2 || !strings.HasPrefix(lines[0], \"*** Begin Patch\") || lines[len(lines)-1] != \"*** End Patch\" {\n\t\treturn Patch{}, 0, NewDiffError(\"Invalid patch text\")\n\t}\n\tparser := NewParser(orig, lines)\n\tparser.index = 1\n\tif err := parser.Parse(); err != nil {\n\t\treturn Patch{}, 0, err\n\t}\n\treturn parser.patch, parser.fuzz, nil\n}\n\nfunc IdentifyFilesNeeded(text string) []string {\n\ttext = strings.TrimSpace(text)\n\tlines := strings.Split(text, \"\\n\")\n\tresult := make(map[string]bool)\n\n\tfor _, line := range lines {\n\t\tif strings.HasPrefix(line, \"*** Update File: \") {\n\t\t\tresult[line[len(\"*** Update File: \"):]] = true\n\t\t}\n\t\tif strings.HasPrefix(line, \"*** Delete File: \") {\n\t\t\tresult[line[len(\"*** Delete File: \"):]] = true\n\t\t}\n\t}\n\n\tfiles := make([]string, 0, len(result))\n\tfor file := range result {\n\t\tfiles = append(files, file)\n\t}\n\treturn files\n}\n\nfunc IdentifyFilesAdded(text string) []string {\n\ttext = strings.TrimSpace(text)\n\tlines := strings.Split(text, \"\\n\")\n\tresult := make(map[string]bool)\n\n\tfor _, line := range lines {\n\t\tif strings.HasPrefix(line, \"*** Add File: \") {\n\t\t\tresult[line[len(\"*** Add File: \"):]] = true\n\t\t}\n\t}\n\n\tfiles := make([]string, 0, len(result))\n\tfor file := range result {\n\t\tfiles = append(files, file)\n\t}\n\treturn files\n}\n\nfunc getUpdatedFile(text string, action PatchAction, path string) (string, error) {\n\tif action.Type != ActionUpdate {\n\t\treturn \"\", errors.New(\"expected UPDATE action\")\n\t}\n\torigLines := strings.Split(text, \"\\n\")\n\tdestLines := make([]string, 0, len(origLines)) // Preallocate with capacity\n\torigIndex := 0\n\n\tfor _, chunk := range action.Chunks {\n\t\tif chunk.OrigIndex > len(origLines) {\n\t\t\treturn \"\", NewDiffError(fmt.Sprintf(\"%s: chunk.orig_index %d > len(lines) %d\", path, chunk.OrigIndex, len(origLines)))\n\t\t}\n\t\tif origIndex > chunk.OrigIndex {\n\t\t\treturn \"\", NewDiffError(fmt.Sprintf(\"%s: orig_index %d > chunk.orig_index %d\", path, origIndex, chunk.OrigIndex))\n\t\t}\n\t\tdestLines = append(destLines, origLines[origIndex:chunk.OrigIndex]...)\n\t\tdelta := chunk.OrigIndex - origIndex\n\t\torigIndex += delta\n\n\t\tif len(chunk.InsLines) > 0 {\n\t\t\tdestLines = append(destLines, chunk.InsLines...)\n\t\t}\n\t\torigIndex += len(chunk.DelLines)\n\t}\n\n\tdestLines = append(destLines, origLines[origIndex:]...)\n\treturn strings.Join(destLines, \"\\n\"), nil\n}\n\nfunc PatchToCommit(patch Patch, orig map[string]string) (Commit, error) {\n\tcommit := Commit{Changes: make(map[string]FileChange, len(patch.Actions))}\n\tfor pathKey, action := range patch.Actions {\n\t\tswitch action.Type {\n\t\tcase ActionDelete:\n\t\t\toldContent := orig[pathKey]\n\t\t\tcommit.Changes[pathKey] = FileChange{\n\t\t\t\tType: ActionDelete,\n\t\t\t\tOldContent: &oldContent,\n\t\t\t}\n\t\tcase ActionAdd:\n\t\t\tcommit.Changes[pathKey] = FileChange{\n\t\t\t\tType: ActionAdd,\n\t\t\t\tNewContent: action.NewFile,\n\t\t\t}\n\t\tcase ActionUpdate:\n\t\t\tnewContent, err := getUpdatedFile(orig[pathKey], action, pathKey)\n\t\t\tif err != nil {\n\t\t\t\treturn Commit{}, err\n\t\t\t}\n\t\t\toldContent := orig[pathKey]\n\t\t\tfileChange := FileChange{\n\t\t\t\tType: ActionUpdate,\n\t\t\t\tOldContent: &oldContent,\n\t\t\t\tNewContent: &newContent,\n\t\t\t}\n\t\t\tif action.MovePath != nil {\n\t\t\t\tfileChange.MovePath = action.MovePath\n\t\t\t}\n\t\t\tcommit.Changes[pathKey] = fileChange\n\t\t}\n\t}\n\treturn commit, nil\n}\n\nfunc AssembleChanges(orig map[string]string, updatedFiles map[string]string) Commit {\n\tcommit := Commit{Changes: make(map[string]FileChange, len(updatedFiles))}\n\tfor p, newContent := range updatedFiles {\n\t\toldContent, exists := orig[p]\n\t\tif exists && oldContent == newContent {\n\t\t\tcontinue\n\t\t}\n\n\t\tif exists && newContent != \"\" {\n\t\t\tcommit.Changes[p] = FileChange{\n\t\t\t\tType: ActionUpdate,\n\t\t\t\tOldContent: &oldContent,\n\t\t\t\tNewContent: &newContent,\n\t\t\t}\n\t\t} else if newContent != \"\" {\n\t\t\tcommit.Changes[p] = FileChange{\n\t\t\t\tType: ActionAdd,\n\t\t\t\tNewContent: &newContent,\n\t\t\t}\n\t\t} else if exists {\n\t\t\tcommit.Changes[p] = FileChange{\n\t\t\t\tType: ActionDelete,\n\t\t\t\tOldContent: &oldContent,\n\t\t\t}\n\t\t} else {\n\t\t\treturn commit // Changed from panic to simply return current commit\n\t\t}\n\t}\n\treturn commit\n}\n\nfunc LoadFiles(paths []string, openFn func(string) (string, error)) (map[string]string, error) {\n\torig := make(map[string]string, len(paths))\n\tfor _, p := range paths {\n\t\tcontent, err := openFn(p)\n\t\tif err != nil {\n\t\t\treturn nil, fileError(\"Open\", \"File not found\", p)\n\t\t}\n\t\torig[p] = content\n\t}\n\treturn orig, nil\n}\n\nfunc ApplyCommit(commit Commit, writeFn func(string, string) error, removeFn func(string) error) error {\n\tfor p, change := range commit.Changes {\n\t\tswitch change.Type {\n\t\tcase ActionDelete:\n\t\t\tif err := removeFn(p); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\tcase ActionAdd:\n\t\t\tif change.NewContent == nil {\n\t\t\t\treturn NewDiffError(fmt.Sprintf(\"Add action for %s has nil new_content\", p))\n\t\t\t}\n\t\t\tif err := writeFn(p, *change.NewContent); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\tcase ActionUpdate:\n\t\t\tif change.NewContent == nil {\n\t\t\t\treturn NewDiffError(fmt.Sprintf(\"Update action for %s has nil new_content\", p))\n\t\t\t}\n\t\t\tif change.MovePath != nil {\n\t\t\t\tif err := writeFn(*change.MovePath, *change.NewContent); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tif err := removeFn(p); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif err := writeFn(p, *change.NewContent); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc ProcessPatch(text string, openFn func(string) (string, error), writeFn func(string, string) error, removeFn func(string) error) (string, error) {\n\tif !strings.HasPrefix(text, \"*** Begin Patch\") {\n\t\treturn \"\", NewDiffError(\"Patch must start with *** Begin Patch\")\n\t}\n\tpaths := IdentifyFilesNeeded(text)\n\torig, err := LoadFiles(paths, openFn)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tpatch, fuzz, err := TextToPatch(text, orig)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif fuzz > 0 {\n\t\treturn \"\", NewDiffError(fmt.Sprintf(\"Patch contains fuzzy matches (fuzz level: %d)\", fuzz))\n\t}\n\n\tcommit, err := PatchToCommit(patch, orig)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif err := ApplyCommit(commit, writeFn, removeFn); err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn \"Patch applied successfully\", nil\n}\n\nfunc OpenFile(p string) (string, error) {\n\tdata, err := os.ReadFile(p)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn string(data), nil\n}\n\nfunc WriteFile(p string, content string) error {\n\tif filepath.IsAbs(p) {\n\t\treturn NewDiffError(\"We do not support absolute paths.\")\n\t}\n\n\tdir := filepath.Dir(p)\n\tif dir != \".\" {\n\t\tif err := os.MkdirAll(dir, 0o755); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn os.WriteFile(p, []byte(content), 0o644)\n}\n\nfunc RemoveFile(p string) error {\n\treturn os.Remove(p)\n}\n\nfunc ValidatePatch(patchText string, files map[string]string) (bool, string, error) {\n\tif !strings.HasPrefix(patchText, \"*** Begin Patch\") {\n\t\treturn false, \"Patch must start with *** Begin Patch\", nil\n\t}\n\n\tneededFiles := IdentifyFilesNeeded(patchText)\n\tfor _, filePath := range neededFiles {\n\t\tif _, exists := files[filePath]; !exists {\n\t\t\treturn false, fmt.Sprintf(\"File not found: %s\", filePath), nil\n\t\t}\n\t}\n\n\tpatch, fuzz, err := TextToPatch(patchText, files)\n\tif err != nil {\n\t\treturn false, err.Error(), nil\n\t}\n\n\tif fuzz > 0 {\n\t\treturn false, fmt.Sprintf(\"Patch contains fuzzy matches (fuzz level: %d)\", fuzz), nil\n\t}\n\n\t_, err = PatchToCommit(patch, files)\n\tif err != nil {\n\t\treturn false, err.Error(), nil\n\t}\n\n\treturn true, \"Patch is valid\", nil\n}\n"], ["/opencode/internal/tui/tui.go", "package tui\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"strings\"\n\n\t\"github.com/charmbracelet/bubbles/key\"\n\ttea \"github.com/charmbracelet/bubbletea\"\n\t\"github.com/charmbracelet/lipgloss\"\n\t\"github.com/opencode-ai/opencode/internal/app\"\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/llm/agent\"\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n\t\"github.com/opencode-ai/opencode/internal/permission\"\n\t\"github.com/opencode-ai/opencode/internal/pubsub\"\n\t\"github.com/opencode-ai/opencode/internal/session\"\n\t\"github.com/opencode-ai/opencode/internal/tui/components/chat\"\n\t\"github.com/opencode-ai/opencode/internal/tui/components/core\"\n\t\"github.com/opencode-ai/opencode/internal/tui/components/dialog\"\n\t\"github.com/opencode-ai/opencode/internal/tui/layout\"\n\t\"github.com/opencode-ai/opencode/internal/tui/page\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n\t\"github.com/opencode-ai/opencode/internal/tui/util\"\n)\n\ntype keyMap struct {\n\tLogs key.Binding\n\tQuit key.Binding\n\tHelp key.Binding\n\tSwitchSession key.Binding\n\tCommands key.Binding\n\tFilepicker key.Binding\n\tModels key.Binding\n\tSwitchTheme key.Binding\n}\n\ntype startCompactSessionMsg struct{}\n\nconst (\n\tquitKey = \"q\"\n)\n\nvar keys = keyMap{\n\tLogs: key.NewBinding(\n\t\tkey.WithKeys(\"ctrl+l\"),\n\t\tkey.WithHelp(\"ctrl+l\", \"logs\"),\n\t),\n\n\tQuit: key.NewBinding(\n\t\tkey.WithKeys(\"ctrl+c\"),\n\t\tkey.WithHelp(\"ctrl+c\", \"quit\"),\n\t),\n\tHelp: key.NewBinding(\n\t\tkey.WithKeys(\"ctrl+_\", \"ctrl+h\"),\n\t\tkey.WithHelp(\"ctrl+?\", \"toggle help\"),\n\t),\n\n\tSwitchSession: key.NewBinding(\n\t\tkey.WithKeys(\"ctrl+s\"),\n\t\tkey.WithHelp(\"ctrl+s\", \"switch session\"),\n\t),\n\n\tCommands: key.NewBinding(\n\t\tkey.WithKeys(\"ctrl+k\"),\n\t\tkey.WithHelp(\"ctrl+k\", \"commands\"),\n\t),\n\tFilepicker: key.NewBinding(\n\t\tkey.WithKeys(\"ctrl+f\"),\n\t\tkey.WithHelp(\"ctrl+f\", \"select files to upload\"),\n\t),\n\tModels: key.NewBinding(\n\t\tkey.WithKeys(\"ctrl+o\"),\n\t\tkey.WithHelp(\"ctrl+o\", \"model selection\"),\n\t),\n\n\tSwitchTheme: key.NewBinding(\n\t\tkey.WithKeys(\"ctrl+t\"),\n\t\tkey.WithHelp(\"ctrl+t\", \"switch theme\"),\n\t),\n}\n\nvar helpEsc = key.NewBinding(\n\tkey.WithKeys(\"?\"),\n\tkey.WithHelp(\"?\", \"toggle help\"),\n)\n\nvar returnKey = key.NewBinding(\n\tkey.WithKeys(\"esc\"),\n\tkey.WithHelp(\"esc\", \"close\"),\n)\n\nvar logsKeyReturnKey = key.NewBinding(\n\tkey.WithKeys(\"esc\", \"backspace\", quitKey),\n\tkey.WithHelp(\"esc/q\", \"go back\"),\n)\n\ntype appModel struct {\n\twidth, height int\n\tcurrentPage page.PageID\n\tpreviousPage page.PageID\n\tpages map[page.PageID]tea.Model\n\tloadedPages map[page.PageID]bool\n\tstatus core.StatusCmp\n\tapp *app.App\n\tselectedSession session.Session\n\n\tshowPermissions bool\n\tpermissions dialog.PermissionDialogCmp\n\n\tshowHelp bool\n\thelp dialog.HelpCmp\n\n\tshowQuit bool\n\tquit dialog.QuitDialog\n\n\tshowSessionDialog bool\n\tsessionDialog dialog.SessionDialog\n\n\tshowCommandDialog bool\n\tcommandDialog dialog.CommandDialog\n\tcommands []dialog.Command\n\n\tshowModelDialog bool\n\tmodelDialog dialog.ModelDialog\n\n\tshowInitDialog bool\n\tinitDialog dialog.InitDialogCmp\n\n\tshowFilepicker bool\n\tfilepicker dialog.FilepickerCmp\n\n\tshowThemeDialog bool\n\tthemeDialog dialog.ThemeDialog\n\n\tshowMultiArgumentsDialog bool\n\tmultiArgumentsDialog dialog.MultiArgumentsDialogCmp\n\n\tisCompacting bool\n\tcompactingMessage string\n}\n\nfunc (a appModel) Init() tea.Cmd {\n\tvar cmds []tea.Cmd\n\tcmd := a.pages[a.currentPage].Init()\n\ta.loadedPages[a.currentPage] = true\n\tcmds = append(cmds, cmd)\n\tcmd = a.status.Init()\n\tcmds = append(cmds, cmd)\n\tcmd = a.quit.Init()\n\tcmds = append(cmds, cmd)\n\tcmd = a.help.Init()\n\tcmds = append(cmds, cmd)\n\tcmd = a.sessionDialog.Init()\n\tcmds = append(cmds, cmd)\n\tcmd = a.commandDialog.Init()\n\tcmds = append(cmds, cmd)\n\tcmd = a.modelDialog.Init()\n\tcmds = append(cmds, cmd)\n\tcmd = a.initDialog.Init()\n\tcmds = append(cmds, cmd)\n\tcmd = a.filepicker.Init()\n\tcmds = append(cmds, cmd)\n\tcmd = a.themeDialog.Init()\n\tcmds = append(cmds, cmd)\n\n\t// Check if we should show the init dialog\n\tcmds = append(cmds, func() tea.Msg {\n\t\tshouldShow, err := config.ShouldShowInitDialog()\n\t\tif err != nil {\n\t\t\treturn util.InfoMsg{\n\t\t\t\tType: util.InfoTypeError,\n\t\t\t\tMsg: \"Failed to check init status: \" + err.Error(),\n\t\t\t}\n\t\t}\n\t\treturn dialog.ShowInitDialogMsg{Show: shouldShow}\n\t})\n\n\treturn tea.Batch(cmds...)\n}\n\nfunc (a appModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {\n\tvar cmds []tea.Cmd\n\tvar cmd tea.Cmd\n\tswitch msg := msg.(type) {\n\tcase tea.WindowSizeMsg:\n\t\tmsg.Height -= 1 // Make space for the status bar\n\t\ta.width, a.height = msg.Width, msg.Height\n\n\t\ts, _ := a.status.Update(msg)\n\t\ta.status = s.(core.StatusCmp)\n\t\ta.pages[a.currentPage], cmd = a.pages[a.currentPage].Update(msg)\n\t\tcmds = append(cmds, cmd)\n\n\t\tprm, permCmd := a.permissions.Update(msg)\n\t\ta.permissions = prm.(dialog.PermissionDialogCmp)\n\t\tcmds = append(cmds, permCmd)\n\n\t\thelp, helpCmd := a.help.Update(msg)\n\t\ta.help = help.(dialog.HelpCmp)\n\t\tcmds = append(cmds, helpCmd)\n\n\t\tsession, sessionCmd := a.sessionDialog.Update(msg)\n\t\ta.sessionDialog = session.(dialog.SessionDialog)\n\t\tcmds = append(cmds, sessionCmd)\n\n\t\tcommand, commandCmd := a.commandDialog.Update(msg)\n\t\ta.commandDialog = command.(dialog.CommandDialog)\n\t\tcmds = append(cmds, commandCmd)\n\n\t\tfilepicker, filepickerCmd := a.filepicker.Update(msg)\n\t\ta.filepicker = filepicker.(dialog.FilepickerCmp)\n\t\tcmds = append(cmds, filepickerCmd)\n\n\t\ta.initDialog.SetSize(msg.Width, msg.Height)\n\n\t\tif a.showMultiArgumentsDialog {\n\t\t\ta.multiArgumentsDialog.SetSize(msg.Width, msg.Height)\n\t\t\targs, argsCmd := a.multiArgumentsDialog.Update(msg)\n\t\t\ta.multiArgumentsDialog = args.(dialog.MultiArgumentsDialogCmp)\n\t\t\tcmds = append(cmds, argsCmd, a.multiArgumentsDialog.Init())\n\t\t}\n\n\t\treturn a, tea.Batch(cmds...)\n\t// Status\n\tcase util.InfoMsg:\n\t\ts, cmd := a.status.Update(msg)\n\t\ta.status = s.(core.StatusCmp)\n\t\tcmds = append(cmds, cmd)\n\t\treturn a, tea.Batch(cmds...)\n\tcase pubsub.Event[logging.LogMessage]:\n\t\tif msg.Payload.Persist {\n\t\t\tswitch msg.Payload.Level {\n\t\t\tcase \"error\":\n\t\t\t\ts, cmd := a.status.Update(util.InfoMsg{\n\t\t\t\t\tType: util.InfoTypeError,\n\t\t\t\t\tMsg: msg.Payload.Message,\n\t\t\t\t\tTTL: msg.Payload.PersistTime,\n\t\t\t\t})\n\t\t\t\ta.status = s.(core.StatusCmp)\n\t\t\t\tcmds = append(cmds, cmd)\n\t\t\tcase \"info\":\n\t\t\t\ts, cmd := a.status.Update(util.InfoMsg{\n\t\t\t\t\tType: util.InfoTypeInfo,\n\t\t\t\t\tMsg: msg.Payload.Message,\n\t\t\t\t\tTTL: msg.Payload.PersistTime,\n\t\t\t\t})\n\t\t\t\ta.status = s.(core.StatusCmp)\n\t\t\t\tcmds = append(cmds, cmd)\n\n\t\t\tcase \"warn\":\n\t\t\t\ts, cmd := a.status.Update(util.InfoMsg{\n\t\t\t\t\tType: util.InfoTypeWarn,\n\t\t\t\t\tMsg: msg.Payload.Message,\n\t\t\t\t\tTTL: msg.Payload.PersistTime,\n\t\t\t\t})\n\n\t\t\t\ta.status = s.(core.StatusCmp)\n\t\t\t\tcmds = append(cmds, cmd)\n\t\t\tdefault:\n\t\t\t\ts, cmd := a.status.Update(util.InfoMsg{\n\t\t\t\t\tType: util.InfoTypeInfo,\n\t\t\t\t\tMsg: msg.Payload.Message,\n\t\t\t\t\tTTL: msg.Payload.PersistTime,\n\t\t\t\t})\n\t\t\t\ta.status = s.(core.StatusCmp)\n\t\t\t\tcmds = append(cmds, cmd)\n\t\t\t}\n\t\t}\n\tcase util.ClearStatusMsg:\n\t\ts, _ := a.status.Update(msg)\n\t\ta.status = s.(core.StatusCmp)\n\n\t// Permission\n\tcase pubsub.Event[permission.PermissionRequest]:\n\t\ta.showPermissions = true\n\t\treturn a, a.permissions.SetPermissions(msg.Payload)\n\tcase dialog.PermissionResponseMsg:\n\t\tvar cmd tea.Cmd\n\t\tswitch msg.Action {\n\t\tcase dialog.PermissionAllow:\n\t\t\ta.app.Permissions.Grant(msg.Permission)\n\t\tcase dialog.PermissionAllowForSession:\n\t\t\ta.app.Permissions.GrantPersistant(msg.Permission)\n\t\tcase dialog.PermissionDeny:\n\t\t\ta.app.Permissions.Deny(msg.Permission)\n\t\t}\n\t\ta.showPermissions = false\n\t\treturn a, cmd\n\n\tcase page.PageChangeMsg:\n\t\treturn a, a.moveToPage(msg.ID)\n\n\tcase dialog.CloseQuitMsg:\n\t\ta.showQuit = false\n\t\treturn a, nil\n\n\tcase dialog.CloseSessionDialogMsg:\n\t\ta.showSessionDialog = false\n\t\treturn a, nil\n\n\tcase dialog.CloseCommandDialogMsg:\n\t\ta.showCommandDialog = false\n\t\treturn a, nil\n\n\tcase startCompactSessionMsg:\n\t\t// Start compacting the current session\n\t\ta.isCompacting = true\n\t\ta.compactingMessage = \"Starting summarization...\"\n\n\t\tif a.selectedSession.ID == \"\" {\n\t\t\ta.isCompacting = false\n\t\t\treturn a, util.ReportWarn(\"No active session to summarize\")\n\t\t}\n\n\t\t// Start the summarization process\n\t\treturn a, func() tea.Msg {\n\t\t\tctx := context.Background()\n\t\t\ta.app.CoderAgent.Summarize(ctx, a.selectedSession.ID)\n\t\t\treturn nil\n\t\t}\n\n\tcase pubsub.Event[agent.AgentEvent]:\n\t\tpayload := msg.Payload\n\t\tif payload.Error != nil {\n\t\t\ta.isCompacting = false\n\t\t\treturn a, util.ReportError(payload.Error)\n\t\t}\n\n\t\ta.compactingMessage = payload.Progress\n\n\t\tif payload.Done && payload.Type == agent.AgentEventTypeSummarize {\n\t\t\ta.isCompacting = false\n\t\t\treturn a, util.ReportInfo(\"Session summarization complete\")\n\t\t} else if payload.Done && payload.Type == agent.AgentEventTypeResponse && a.selectedSession.ID != \"\" {\n\t\t\tmodel := a.app.CoderAgent.Model()\n\t\t\tcontextWindow := model.ContextWindow\n\t\t\ttokens := a.selectedSession.CompletionTokens + a.selectedSession.PromptTokens\n\t\t\tif (tokens >= int64(float64(contextWindow)*0.95)) && config.Get().AutoCompact {\n\t\t\t\treturn a, util.CmdHandler(startCompactSessionMsg{})\n\t\t\t}\n\t\t}\n\t\t// Continue listening for events\n\t\treturn a, nil\n\n\tcase dialog.CloseThemeDialogMsg:\n\t\ta.showThemeDialog = false\n\t\treturn a, nil\n\n\tcase dialog.ThemeChangedMsg:\n\t\ta.pages[a.currentPage], cmd = a.pages[a.currentPage].Update(msg)\n\t\ta.showThemeDialog = false\n\t\treturn a, tea.Batch(cmd, util.ReportInfo(\"Theme changed to: \"+msg.ThemeName))\n\n\tcase dialog.CloseModelDialogMsg:\n\t\ta.showModelDialog = false\n\t\treturn a, nil\n\n\tcase dialog.ModelSelectedMsg:\n\t\ta.showModelDialog = false\n\n\t\tmodel, err := a.app.CoderAgent.Update(config.AgentCoder, msg.Model.ID)\n\t\tif err != nil {\n\t\t\treturn a, util.ReportError(err)\n\t\t}\n\n\t\treturn a, util.ReportInfo(fmt.Sprintf(\"Model changed to %s\", model.Name))\n\n\tcase dialog.ShowInitDialogMsg:\n\t\ta.showInitDialog = msg.Show\n\t\treturn a, nil\n\n\tcase dialog.CloseInitDialogMsg:\n\t\ta.showInitDialog = false\n\t\tif msg.Initialize {\n\t\t\t// Run the initialization command\n\t\t\tfor _, cmd := range a.commands {\n\t\t\t\tif cmd.ID == \"init\" {\n\t\t\t\t\t// Mark the project as initialized\n\t\t\t\t\tif err := config.MarkProjectInitialized(); err != nil {\n\t\t\t\t\t\treturn a, util.ReportError(err)\n\t\t\t\t\t}\n\t\t\t\t\treturn a, cmd.Handler(cmd)\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\t// Mark the project as initialized without running the command\n\t\t\tif err := config.MarkProjectInitialized(); err != nil {\n\t\t\t\treturn a, util.ReportError(err)\n\t\t\t}\n\t\t}\n\t\treturn a, nil\n\n\tcase chat.SessionSelectedMsg:\n\t\ta.selectedSession = msg\n\t\ta.sessionDialog.SetSelectedSession(msg.ID)\n\n\tcase pubsub.Event[session.Session]:\n\t\tif msg.Type == pubsub.UpdatedEvent && msg.Payload.ID == a.selectedSession.ID {\n\t\t\ta.selectedSession = msg.Payload\n\t\t}\n\tcase dialog.SessionSelectedMsg:\n\t\ta.showSessionDialog = false\n\t\tif a.currentPage == page.ChatPage {\n\t\t\treturn a, util.CmdHandler(chat.SessionSelectedMsg(msg.Session))\n\t\t}\n\t\treturn a, nil\n\n\tcase dialog.CommandSelectedMsg:\n\t\ta.showCommandDialog = false\n\t\t// Execute the command handler if available\n\t\tif msg.Command.Handler != nil {\n\t\t\treturn a, msg.Command.Handler(msg.Command)\n\t\t}\n\t\treturn a, util.ReportInfo(\"Command selected: \" + msg.Command.Title)\n\n\tcase dialog.ShowMultiArgumentsDialogMsg:\n\t\t// Show multi-arguments dialog\n\t\ta.multiArgumentsDialog = dialog.NewMultiArgumentsDialogCmp(msg.CommandID, msg.Content, msg.ArgNames)\n\t\ta.showMultiArgumentsDialog = true\n\t\treturn a, a.multiArgumentsDialog.Init()\n\n\tcase dialog.CloseMultiArgumentsDialogMsg:\n\t\t// Close multi-arguments dialog\n\t\ta.showMultiArgumentsDialog = false\n\n\t\t// If submitted, replace all named arguments and run the command\n\t\tif msg.Submit {\n\t\t\tcontent := msg.Content\n\n\t\t\t// Replace each named argument with its value\n\t\t\tfor name, value := range msg.Args {\n\t\t\t\tplaceholder := \"$\" + name\n\t\t\t\tcontent = strings.ReplaceAll(content, placeholder, value)\n\t\t\t}\n\n\t\t\t// Execute the command with arguments\n\t\t\treturn a, util.CmdHandler(dialog.CommandRunCustomMsg{\n\t\t\t\tContent: content,\n\t\t\t\tArgs: msg.Args,\n\t\t\t})\n\t\t}\n\t\treturn a, nil\n\n\tcase tea.KeyMsg:\n\t\t// If multi-arguments dialog is open, let it handle the key press first\n\t\tif a.showMultiArgumentsDialog {\n\t\t\targs, cmd := a.multiArgumentsDialog.Update(msg)\n\t\t\ta.multiArgumentsDialog = args.(dialog.MultiArgumentsDialogCmp)\n\t\t\treturn a, cmd\n\t\t}\n\n\t\tswitch {\n\n\t\tcase key.Matches(msg, keys.Quit):\n\t\t\ta.showQuit = !a.showQuit\n\t\t\tif a.showHelp {\n\t\t\t\ta.showHelp = false\n\t\t\t}\n\t\t\tif a.showSessionDialog {\n\t\t\t\ta.showSessionDialog = false\n\t\t\t}\n\t\t\tif a.showCommandDialog {\n\t\t\t\ta.showCommandDialog = false\n\t\t\t}\n\t\t\tif a.showFilepicker {\n\t\t\t\ta.showFilepicker = false\n\t\t\t\ta.filepicker.ToggleFilepicker(a.showFilepicker)\n\t\t\t}\n\t\t\tif a.showModelDialog {\n\t\t\t\ta.showModelDialog = false\n\t\t\t}\n\t\t\tif a.showMultiArgumentsDialog {\n\t\t\t\ta.showMultiArgumentsDialog = false\n\t\t\t}\n\t\t\treturn a, nil\n\t\tcase key.Matches(msg, keys.SwitchSession):\n\t\t\tif a.currentPage == page.ChatPage && !a.showQuit && !a.showPermissions && !a.showCommandDialog {\n\t\t\t\t// Load sessions and show the dialog\n\t\t\t\tsessions, err := a.app.Sessions.List(context.Background())\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn a, util.ReportError(err)\n\t\t\t\t}\n\t\t\t\tif len(sessions) == 0 {\n\t\t\t\t\treturn a, util.ReportWarn(\"No sessions available\")\n\t\t\t\t}\n\t\t\t\ta.sessionDialog.SetSessions(sessions)\n\t\t\t\ta.showSessionDialog = true\n\t\t\t\treturn a, nil\n\t\t\t}\n\t\t\treturn a, nil\n\t\tcase key.Matches(msg, keys.Commands):\n\t\t\tif a.currentPage == page.ChatPage && !a.showQuit && !a.showPermissions && !a.showSessionDialog && !a.showThemeDialog && !a.showFilepicker {\n\t\t\t\t// Show commands dialog\n\t\t\t\tif len(a.commands) == 0 {\n\t\t\t\t\treturn a, util.ReportWarn(\"No commands available\")\n\t\t\t\t}\n\t\t\t\ta.commandDialog.SetCommands(a.commands)\n\t\t\t\ta.showCommandDialog = true\n\t\t\t\treturn a, nil\n\t\t\t}\n\t\t\treturn a, nil\n\t\tcase key.Matches(msg, keys.Models):\n\t\t\tif a.showModelDialog {\n\t\t\t\ta.showModelDialog = false\n\t\t\t\treturn a, nil\n\t\t\t}\n\t\t\tif a.currentPage == page.ChatPage && !a.showQuit && !a.showPermissions && !a.showSessionDialog && !a.showCommandDialog {\n\t\t\t\ta.showModelDialog = true\n\t\t\t\treturn a, nil\n\t\t\t}\n\t\t\treturn a, nil\n\t\tcase key.Matches(msg, keys.SwitchTheme):\n\t\t\tif !a.showQuit && !a.showPermissions && !a.showSessionDialog && !a.showCommandDialog {\n\t\t\t\t// Show theme switcher dialog\n\t\t\t\ta.showThemeDialog = true\n\t\t\t\t// Theme list is dynamically loaded by the dialog component\n\t\t\t\treturn a, a.themeDialog.Init()\n\t\t\t}\n\t\t\treturn a, nil\n\t\tcase key.Matches(msg, returnKey) || key.Matches(msg):\n\t\t\tif msg.String() == quitKey {\n\t\t\t\tif a.currentPage == page.LogsPage {\n\t\t\t\t\treturn a, a.moveToPage(page.ChatPage)\n\t\t\t\t}\n\t\t\t} else if !a.filepicker.IsCWDFocused() {\n\t\t\t\tif a.showQuit {\n\t\t\t\t\ta.showQuit = !a.showQuit\n\t\t\t\t\treturn a, nil\n\t\t\t\t}\n\t\t\t\tif a.showHelp {\n\t\t\t\t\ta.showHelp = !a.showHelp\n\t\t\t\t\treturn a, nil\n\t\t\t\t}\n\t\t\t\tif a.showInitDialog {\n\t\t\t\t\ta.showInitDialog = false\n\t\t\t\t\t// Mark the project as initialized without running the command\n\t\t\t\t\tif err := config.MarkProjectInitialized(); err != nil {\n\t\t\t\t\t\treturn a, util.ReportError(err)\n\t\t\t\t\t}\n\t\t\t\t\treturn a, nil\n\t\t\t\t}\n\t\t\t\tif a.showFilepicker {\n\t\t\t\t\ta.showFilepicker = false\n\t\t\t\t\ta.filepicker.ToggleFilepicker(a.showFilepicker)\n\t\t\t\t\treturn a, nil\n\t\t\t\t}\n\t\t\t\tif a.currentPage == page.LogsPage {\n\t\t\t\t\treturn a, a.moveToPage(page.ChatPage)\n\t\t\t\t}\n\t\t\t}\n\t\tcase key.Matches(msg, keys.Logs):\n\t\t\treturn a, a.moveToPage(page.LogsPage)\n\t\tcase key.Matches(msg, keys.Help):\n\t\t\tif a.showQuit {\n\t\t\t\treturn a, nil\n\t\t\t}\n\t\t\ta.showHelp = !a.showHelp\n\t\t\treturn a, nil\n\t\tcase key.Matches(msg, helpEsc):\n\t\t\tif a.app.CoderAgent.IsBusy() {\n\t\t\t\tif a.showQuit {\n\t\t\t\t\treturn a, nil\n\t\t\t\t}\n\t\t\t\ta.showHelp = !a.showHelp\n\t\t\t\treturn a, nil\n\t\t\t}\n\t\tcase key.Matches(msg, keys.Filepicker):\n\t\t\ta.showFilepicker = !a.showFilepicker\n\t\t\ta.filepicker.ToggleFilepicker(a.showFilepicker)\n\t\t\treturn a, nil\n\t\t}\n\tdefault:\n\t\tf, filepickerCmd := a.filepicker.Update(msg)\n\t\ta.filepicker = f.(dialog.FilepickerCmp)\n\t\tcmds = append(cmds, filepickerCmd)\n\n\t}\n\n\tif a.showFilepicker {\n\t\tf, filepickerCmd := a.filepicker.Update(msg)\n\t\ta.filepicker = f.(dialog.FilepickerCmp)\n\t\tcmds = append(cmds, filepickerCmd)\n\t\t// Only block key messages send all other messages down\n\t\tif _, ok := msg.(tea.KeyMsg); ok {\n\t\t\treturn a, tea.Batch(cmds...)\n\t\t}\n\t}\n\n\tif a.showQuit {\n\t\tq, quitCmd := a.quit.Update(msg)\n\t\ta.quit = q.(dialog.QuitDialog)\n\t\tcmds = append(cmds, quitCmd)\n\t\t// Only block key messages send all other messages down\n\t\tif _, ok := msg.(tea.KeyMsg); ok {\n\t\t\treturn a, tea.Batch(cmds...)\n\t\t}\n\t}\n\tif a.showPermissions {\n\t\td, permissionsCmd := a.permissions.Update(msg)\n\t\ta.permissions = d.(dialog.PermissionDialogCmp)\n\t\tcmds = append(cmds, permissionsCmd)\n\t\t// Only block key messages send all other messages down\n\t\tif _, ok := msg.(tea.KeyMsg); ok {\n\t\t\treturn a, tea.Batch(cmds...)\n\t\t}\n\t}\n\n\tif a.showSessionDialog {\n\t\td, sessionCmd := a.sessionDialog.Update(msg)\n\t\ta.sessionDialog = d.(dialog.SessionDialog)\n\t\tcmds = append(cmds, sessionCmd)\n\t\t// Only block key messages send all other messages down\n\t\tif _, ok := msg.(tea.KeyMsg); ok {\n\t\t\treturn a, tea.Batch(cmds...)\n\t\t}\n\t}\n\n\tif a.showCommandDialog {\n\t\td, commandCmd := a.commandDialog.Update(msg)\n\t\ta.commandDialog = d.(dialog.CommandDialog)\n\t\tcmds = append(cmds, commandCmd)\n\t\t// Only block key messages send all other messages down\n\t\tif _, ok := msg.(tea.KeyMsg); ok {\n\t\t\treturn a, tea.Batch(cmds...)\n\t\t}\n\t}\n\n\tif a.showModelDialog {\n\t\td, modelCmd := a.modelDialog.Update(msg)\n\t\ta.modelDialog = d.(dialog.ModelDialog)\n\t\tcmds = append(cmds, modelCmd)\n\t\t// Only block key messages send all other messages down\n\t\tif _, ok := msg.(tea.KeyMsg); ok {\n\t\t\treturn a, tea.Batch(cmds...)\n\t\t}\n\t}\n\n\tif a.showInitDialog {\n\t\td, initCmd := a.initDialog.Update(msg)\n\t\ta.initDialog = d.(dialog.InitDialogCmp)\n\t\tcmds = append(cmds, initCmd)\n\t\t// Only block key messages send all other messages down\n\t\tif _, ok := msg.(tea.KeyMsg); ok {\n\t\t\treturn a, tea.Batch(cmds...)\n\t\t}\n\t}\n\n\tif a.showThemeDialog {\n\t\td, themeCmd := a.themeDialog.Update(msg)\n\t\ta.themeDialog = d.(dialog.ThemeDialog)\n\t\tcmds = append(cmds, themeCmd)\n\t\t// Only block key messages send all other messages down\n\t\tif _, ok := msg.(tea.KeyMsg); ok {\n\t\t\treturn a, tea.Batch(cmds...)\n\t\t}\n\t}\n\n\ts, _ := a.status.Update(msg)\n\ta.status = s.(core.StatusCmp)\n\ta.pages[a.currentPage], cmd = a.pages[a.currentPage].Update(msg)\n\tcmds = append(cmds, cmd)\n\treturn a, tea.Batch(cmds...)\n}\n\n// RegisterCommand adds a command to the command dialog\nfunc (a *appModel) RegisterCommand(cmd dialog.Command) {\n\ta.commands = append(a.commands, cmd)\n}\n\nfunc (a *appModel) findCommand(id string) (dialog.Command, bool) {\n\tfor _, cmd := range a.commands {\n\t\tif cmd.ID == id {\n\t\t\treturn cmd, true\n\t\t}\n\t}\n\treturn dialog.Command{}, false\n}\n\nfunc (a *appModel) moveToPage(pageID page.PageID) tea.Cmd {\n\tif a.app.CoderAgent.IsBusy() {\n\t\t// For now we don't move to any page if the agent is busy\n\t\treturn util.ReportWarn(\"Agent is busy, please wait...\")\n\t}\n\n\tvar cmds []tea.Cmd\n\tif _, ok := a.loadedPages[pageID]; !ok {\n\t\tcmd := a.pages[pageID].Init()\n\t\tcmds = append(cmds, cmd)\n\t\ta.loadedPages[pageID] = true\n\t}\n\ta.previousPage = a.currentPage\n\ta.currentPage = pageID\n\tif sizable, ok := a.pages[a.currentPage].(layout.Sizeable); ok {\n\t\tcmd := sizable.SetSize(a.width, a.height)\n\t\tcmds = append(cmds, cmd)\n\t}\n\n\treturn tea.Batch(cmds...)\n}\n\nfunc (a appModel) View() string {\n\tcomponents := []string{\n\t\ta.pages[a.currentPage].View(),\n\t}\n\n\tcomponents = append(components, a.status.View())\n\n\tappView := lipgloss.JoinVertical(lipgloss.Top, components...)\n\n\tif a.showPermissions {\n\t\toverlay := a.permissions.View()\n\t\trow := lipgloss.Height(appView) / 2\n\t\trow -= lipgloss.Height(overlay) / 2\n\t\tcol := lipgloss.Width(appView) / 2\n\t\tcol -= lipgloss.Width(overlay) / 2\n\t\tappView = layout.PlaceOverlay(\n\t\t\tcol,\n\t\t\trow,\n\t\t\toverlay,\n\t\t\tappView,\n\t\t\ttrue,\n\t\t)\n\t}\n\n\tif a.showFilepicker {\n\t\toverlay := a.filepicker.View()\n\t\trow := lipgloss.Height(appView) / 2\n\t\trow -= lipgloss.Height(overlay) / 2\n\t\tcol := lipgloss.Width(appView) / 2\n\t\tcol -= lipgloss.Width(overlay) / 2\n\t\tappView = layout.PlaceOverlay(\n\t\t\tcol,\n\t\t\trow,\n\t\t\toverlay,\n\t\t\tappView,\n\t\t\ttrue,\n\t\t)\n\n\t}\n\n\t// Show compacting status overlay\n\tif a.isCompacting {\n\t\tt := theme.CurrentTheme()\n\t\tstyle := lipgloss.NewStyle().\n\t\t\tBorder(lipgloss.RoundedBorder()).\n\t\t\tBorderForeground(t.BorderFocused()).\n\t\t\tBorderBackground(t.Background()).\n\t\t\tPadding(1, 2).\n\t\t\tBackground(t.Background()).\n\t\t\tForeground(t.Text())\n\n\t\toverlay := style.Render(\"Summarizing\\n\" + a.compactingMessage)\n\t\trow := lipgloss.Height(appView) / 2\n\t\trow -= lipgloss.Height(overlay) / 2\n\t\tcol := lipgloss.Width(appView) / 2\n\t\tcol -= lipgloss.Width(overlay) / 2\n\t\tappView = layout.PlaceOverlay(\n\t\t\tcol,\n\t\t\trow,\n\t\t\toverlay,\n\t\t\tappView,\n\t\t\ttrue,\n\t\t)\n\t}\n\n\tif a.showHelp {\n\t\tbindings := layout.KeyMapToSlice(keys)\n\t\tif p, ok := a.pages[a.currentPage].(layout.Bindings); ok {\n\t\t\tbindings = append(bindings, p.BindingKeys()...)\n\t\t}\n\t\tif a.showPermissions {\n\t\t\tbindings = append(bindings, a.permissions.BindingKeys()...)\n\t\t}\n\t\tif a.currentPage == page.LogsPage {\n\t\t\tbindings = append(bindings, logsKeyReturnKey)\n\t\t}\n\t\tif !a.app.CoderAgent.IsBusy() {\n\t\t\tbindings = append(bindings, helpEsc)\n\t\t}\n\t\ta.help.SetBindings(bindings)\n\n\t\toverlay := a.help.View()\n\t\trow := lipgloss.Height(appView) / 2\n\t\trow -= lipgloss.Height(overlay) / 2\n\t\tcol := lipgloss.Width(appView) / 2\n\t\tcol -= lipgloss.Width(overlay) / 2\n\t\tappView = layout.PlaceOverlay(\n\t\t\tcol,\n\t\t\trow,\n\t\t\toverlay,\n\t\t\tappView,\n\t\t\ttrue,\n\t\t)\n\t}\n\n\tif a.showQuit {\n\t\toverlay := a.quit.View()\n\t\trow := lipgloss.Height(appView) / 2\n\t\trow -= lipgloss.Height(overlay) / 2\n\t\tcol := lipgloss.Width(appView) / 2\n\t\tcol -= lipgloss.Width(overlay) / 2\n\t\tappView = layout.PlaceOverlay(\n\t\t\tcol,\n\t\t\trow,\n\t\t\toverlay,\n\t\t\tappView,\n\t\t\ttrue,\n\t\t)\n\t}\n\n\tif a.showSessionDialog {\n\t\toverlay := a.sessionDialog.View()\n\t\trow := lipgloss.Height(appView) / 2\n\t\trow -= lipgloss.Height(overlay) / 2\n\t\tcol := lipgloss.Width(appView) / 2\n\t\tcol -= lipgloss.Width(overlay) / 2\n\t\tappView = layout.PlaceOverlay(\n\t\t\tcol,\n\t\t\trow,\n\t\t\toverlay,\n\t\t\tappView,\n\t\t\ttrue,\n\t\t)\n\t}\n\n\tif a.showModelDialog {\n\t\toverlay := a.modelDialog.View()\n\t\trow := lipgloss.Height(appView) / 2\n\t\trow -= lipgloss.Height(overlay) / 2\n\t\tcol := lipgloss.Width(appView) / 2\n\t\tcol -= lipgloss.Width(overlay) / 2\n\t\tappView = layout.PlaceOverlay(\n\t\t\tcol,\n\t\t\trow,\n\t\t\toverlay,\n\t\t\tappView,\n\t\t\ttrue,\n\t\t)\n\t}\n\n\tif a.showCommandDialog {\n\t\toverlay := a.commandDialog.View()\n\t\trow := lipgloss.Height(appView) / 2\n\t\trow -= lipgloss.Height(overlay) / 2\n\t\tcol := lipgloss.Width(appView) / 2\n\t\tcol -= lipgloss.Width(overlay) / 2\n\t\tappView = layout.PlaceOverlay(\n\t\t\tcol,\n\t\t\trow,\n\t\t\toverlay,\n\t\t\tappView,\n\t\t\ttrue,\n\t\t)\n\t}\n\n\tif a.showInitDialog {\n\t\toverlay := a.initDialog.View()\n\t\tappView = layout.PlaceOverlay(\n\t\t\ta.width/2-lipgloss.Width(overlay)/2,\n\t\t\ta.height/2-lipgloss.Height(overlay)/2,\n\t\t\toverlay,\n\t\t\tappView,\n\t\t\ttrue,\n\t\t)\n\t}\n\n\tif a.showThemeDialog {\n\t\toverlay := a.themeDialog.View()\n\t\trow := lipgloss.Height(appView) / 2\n\t\trow -= lipgloss.Height(overlay) / 2\n\t\tcol := lipgloss.Width(appView) / 2\n\t\tcol -= lipgloss.Width(overlay) / 2\n\t\tappView = layout.PlaceOverlay(\n\t\t\tcol,\n\t\t\trow,\n\t\t\toverlay,\n\t\t\tappView,\n\t\t\ttrue,\n\t\t)\n\t}\n\n\tif a.showMultiArgumentsDialog {\n\t\toverlay := a.multiArgumentsDialog.View()\n\t\trow := lipgloss.Height(appView) / 2\n\t\trow -= lipgloss.Height(overlay) / 2\n\t\tcol := lipgloss.Width(appView) / 2\n\t\tcol -= lipgloss.Width(overlay) / 2\n\t\tappView = layout.PlaceOverlay(\n\t\t\tcol,\n\t\t\trow,\n\t\t\toverlay,\n\t\t\tappView,\n\t\t\ttrue,\n\t\t)\n\t}\n\n\treturn appView\n}\n\nfunc New(app *app.App) tea.Model {\n\tstartPage := page.ChatPage\n\tmodel := &appModel{\n\t\tcurrentPage: startPage,\n\t\tloadedPages: make(map[page.PageID]bool),\n\t\tstatus: core.NewStatusCmp(app.LSPClients),\n\t\thelp: dialog.NewHelpCmp(),\n\t\tquit: dialog.NewQuitCmp(),\n\t\tsessionDialog: dialog.NewSessionDialogCmp(),\n\t\tcommandDialog: dialog.NewCommandDialogCmp(),\n\t\tmodelDialog: dialog.NewModelDialogCmp(),\n\t\tpermissions: dialog.NewPermissionDialogCmp(),\n\t\tinitDialog: dialog.NewInitDialogCmp(),\n\t\tthemeDialog: dialog.NewThemeDialogCmp(),\n\t\tapp: app,\n\t\tcommands: []dialog.Command{},\n\t\tpages: map[page.PageID]tea.Model{\n\t\t\tpage.ChatPage: page.NewChatPage(app),\n\t\t\tpage.LogsPage: page.NewLogsPage(),\n\t\t},\n\t\tfilepicker: dialog.NewFilepickerCmp(app),\n\t}\n\n\tmodel.RegisterCommand(dialog.Command{\n\t\tID: \"init\",\n\t\tTitle: \"Initialize Project\",\n\t\tDescription: \"Create/Update the OpenCode.md memory file\",\n\t\tHandler: func(cmd dialog.Command) tea.Cmd {\n\t\t\tprompt := `Please analyze this codebase and create a OpenCode.md file containing:\n1. Build/lint/test commands - especially for running a single test\n2. Code style guidelines including imports, formatting, types, naming conventions, error handling, etc.\n\nThe file you create will be given to agentic coding agents (such as yourself) that operate in this repository. Make it about 20 lines long.\nIf there's already a opencode.md, improve it.\nIf there are Cursor rules (in .cursor/rules/ or .cursorrules) or Copilot rules (in .github/copilot-instructions.md), make sure to include them.`\n\t\t\treturn tea.Batch(\n\t\t\t\tutil.CmdHandler(chat.SendMsg{\n\t\t\t\t\tText: prompt,\n\t\t\t\t}),\n\t\t\t)\n\t\t},\n\t})\n\n\tmodel.RegisterCommand(dialog.Command{\n\t\tID: \"compact\",\n\t\tTitle: \"Compact Session\",\n\t\tDescription: \"Summarize the current session and create a new one with the summary\",\n\t\tHandler: func(cmd dialog.Command) tea.Cmd {\n\t\t\treturn func() tea.Msg {\n\t\t\t\treturn startCompactSessionMsg{}\n\t\t\t}\n\t\t},\n\t})\n\t// Load custom commands\n\tcustomCommands, err := dialog.LoadCustomCommands()\n\tif err != nil {\n\t\tlogging.Warn(\"Failed to load custom commands\", \"error\", err)\n\t} else {\n\t\tfor _, cmd := range customCommands {\n\t\t\tmodel.RegisterCommand(cmd)\n\t\t}\n\t}\n\n\treturn model\n}\n"], ["/opencode/internal/tui/theme/manager.go", "package theme\n\nimport (\n\t\"fmt\"\n\t\"slices\"\n\t\"strings\"\n\t\"sync\"\n\n\t\"github.com/alecthomas/chroma/v2/styles\"\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n)\n\n// Manager handles theme registration, selection, and retrieval.\n// It maintains a registry of available themes and tracks the currently active theme.\ntype Manager struct {\n\tthemes map[string]Theme\n\tcurrentName string\n\tmu sync.RWMutex\n}\n\n// Global instance of the theme manager\nvar globalManager = &Manager{\n\tthemes: make(map[string]Theme),\n\tcurrentName: \"\",\n}\n\n// RegisterTheme adds a new theme to the registry.\n// If this is the first theme registered, it becomes the default.\nfunc RegisterTheme(name string, theme Theme) {\n\tglobalManager.mu.Lock()\n\tdefer globalManager.mu.Unlock()\n\n\tglobalManager.themes[name] = theme\n\n\t// If this is the first theme, make it the default\n\tif globalManager.currentName == \"\" {\n\t\tglobalManager.currentName = name\n\t}\n}\n\n// SetTheme changes the active theme to the one with the specified name.\n// Returns an error if the theme doesn't exist.\nfunc SetTheme(name string) error {\n\tglobalManager.mu.Lock()\n\tdefer globalManager.mu.Unlock()\n\n\tdelete(styles.Registry, \"charm\")\n\tif _, exists := globalManager.themes[name]; !exists {\n\t\treturn fmt.Errorf(\"theme '%s' not found\", name)\n\t}\n\n\tglobalManager.currentName = name\n\n\t// Update the config file using viper\n\tif err := updateConfigTheme(name); err != nil {\n\t\t// Log the error but don't fail the theme change\n\t\tlogging.Warn(\"Warning: Failed to update config file with new theme\", \"err\", err)\n\t}\n\n\treturn nil\n}\n\n// CurrentTheme returns the currently active theme.\n// If no theme is set, it returns nil.\nfunc CurrentTheme() Theme {\n\tglobalManager.mu.RLock()\n\tdefer globalManager.mu.RUnlock()\n\n\tif globalManager.currentName == \"\" {\n\t\treturn nil\n\t}\n\n\treturn globalManager.themes[globalManager.currentName]\n}\n\n// CurrentThemeName returns the name of the currently active theme.\nfunc CurrentThemeName() string {\n\tglobalManager.mu.RLock()\n\tdefer globalManager.mu.RUnlock()\n\n\treturn globalManager.currentName\n}\n\n// AvailableThemes returns a list of all registered theme names.\nfunc AvailableThemes() []string {\n\tglobalManager.mu.RLock()\n\tdefer globalManager.mu.RUnlock()\n\n\tnames := make([]string, 0, len(globalManager.themes))\n\tfor name := range globalManager.themes {\n\t\tnames = append(names, name)\n\t}\n\tslices.SortFunc(names, func(a, b string) int {\n\t\tif a == \"opencode\" {\n\t\t\treturn -1\n\t\t} else if b == \"opencode\" {\n\t\t\treturn 1\n\t\t}\n\t\treturn strings.Compare(a, b)\n\t})\n\treturn names\n}\n\n// GetTheme returns a specific theme by name.\n// Returns nil if the theme doesn't exist.\nfunc GetTheme(name string) Theme {\n\tglobalManager.mu.RLock()\n\tdefer globalManager.mu.RUnlock()\n\n\treturn globalManager.themes[name]\n}\n\n// updateConfigTheme updates the theme setting in the configuration file\nfunc updateConfigTheme(themeName string) error {\n\t// Use the config package to update the theme\n\treturn config.UpdateTheme(themeName)\n}\n"], ["/opencode/internal/diff/diff.go", "package diff\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\"\n\t\"regexp\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"github.com/alecthomas/chroma/v2\"\n\t\"github.com/alecthomas/chroma/v2/formatters\"\n\t\"github.com/alecthomas/chroma/v2/lexers\"\n\t\"github.com/alecthomas/chroma/v2/styles\"\n\t\"github.com/aymanbagabas/go-udiff\"\n\t\"github.com/charmbracelet/lipgloss\"\n\t\"github.com/charmbracelet/x/ansi\"\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n\t\"github.com/sergi/go-diff/diffmatchpatch\"\n)\n\n// -------------------------------------------------------------------------\n// Core Types\n// -------------------------------------------------------------------------\n\n// LineType represents the kind of line in a diff.\ntype LineType int\n\nconst (\n\tLineContext LineType = iota // Line exists in both files\n\tLineAdded // Line added in the new file\n\tLineRemoved // Line removed from the old file\n)\n\n// Segment represents a portion of a line for intra-line highlighting\ntype Segment struct {\n\tStart int\n\tEnd int\n\tType LineType\n\tText string\n}\n\n// DiffLine represents a single line in a diff\ntype DiffLine struct {\n\tOldLineNo int // Line number in old file (0 for added lines)\n\tNewLineNo int // Line number in new file (0 for removed lines)\n\tKind LineType // Type of line (added, removed, context)\n\tContent string // Content of the line\n\tSegments []Segment // Segments for intraline highlighting\n}\n\n// Hunk represents a section of changes in a diff\ntype Hunk struct {\n\tHeader string\n\tLines []DiffLine\n}\n\n// DiffResult contains the parsed result of a diff\ntype DiffResult struct {\n\tOldFile string\n\tNewFile string\n\tHunks []Hunk\n}\n\n// linePair represents a pair of lines for side-by-side display\ntype linePair struct {\n\tleft *DiffLine\n\tright *DiffLine\n}\n\n// -------------------------------------------------------------------------\n// Parse Configuration\n// -------------------------------------------------------------------------\n\n// ParseConfig configures the behavior of diff parsing\ntype ParseConfig struct {\n\tContextSize int // Number of context lines to include\n}\n\n// ParseOption modifies a ParseConfig\ntype ParseOption func(*ParseConfig)\n\n// WithContextSize sets the number of context lines to include\nfunc WithContextSize(size int) ParseOption {\n\treturn func(p *ParseConfig) {\n\t\tif size >= 0 {\n\t\t\tp.ContextSize = size\n\t\t}\n\t}\n}\n\n// -------------------------------------------------------------------------\n// Side-by-Side Configuration\n// -------------------------------------------------------------------------\n\n// SideBySideConfig configures the rendering of side-by-side diffs\ntype SideBySideConfig struct {\n\tTotalWidth int\n}\n\n// SideBySideOption modifies a SideBySideConfig\ntype SideBySideOption func(*SideBySideConfig)\n\n// NewSideBySideConfig creates a SideBySideConfig with default values\nfunc NewSideBySideConfig(opts ...SideBySideOption) SideBySideConfig {\n\tconfig := SideBySideConfig{\n\t\tTotalWidth: 160, // Default width for side-by-side view\n\t}\n\n\tfor _, opt := range opts {\n\t\topt(&config)\n\t}\n\n\treturn config\n}\n\n// WithTotalWidth sets the total width for side-by-side view\nfunc WithTotalWidth(width int) SideBySideOption {\n\treturn func(s *SideBySideConfig) {\n\t\tif width > 0 {\n\t\t\ts.TotalWidth = width\n\t\t}\n\t}\n}\n\n// -------------------------------------------------------------------------\n// Diff Parsing\n// -------------------------------------------------------------------------\n\n// ParseUnifiedDiff parses a unified diff format string into structured data\nfunc ParseUnifiedDiff(diff string) (DiffResult, error) {\n\tvar result DiffResult\n\tvar currentHunk *Hunk\n\n\thunkHeaderRe := regexp.MustCompile(`^@@ -(\\d+),?(\\d*) \\+(\\d+),?(\\d*) @@`)\n\tlines := strings.Split(diff, \"\\n\")\n\n\tvar oldLine, newLine int\n\tinFileHeader := true\n\n\tfor _, line := range lines {\n\t\t// Parse file headers\n\t\tif inFileHeader {\n\t\t\tif strings.HasPrefix(line, \"--- a/\") {\n\t\t\t\tresult.OldFile = strings.TrimPrefix(line, \"--- a/\")\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif strings.HasPrefix(line, \"+++ b/\") {\n\t\t\t\tresult.NewFile = strings.TrimPrefix(line, \"+++ b/\")\n\t\t\t\tinFileHeader = false\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\n\t\t// Parse hunk headers\n\t\tif matches := hunkHeaderRe.FindStringSubmatch(line); matches != nil {\n\t\t\tif currentHunk != nil {\n\t\t\t\tresult.Hunks = append(result.Hunks, *currentHunk)\n\t\t\t}\n\t\t\tcurrentHunk = &Hunk{\n\t\t\t\tHeader: line,\n\t\t\t\tLines: []DiffLine{},\n\t\t\t}\n\n\t\t\toldStart, _ := strconv.Atoi(matches[1])\n\t\t\tnewStart, _ := strconv.Atoi(matches[3])\n\t\t\toldLine = oldStart\n\t\t\tnewLine = newStart\n\t\t\tcontinue\n\t\t}\n\n\t\t// Ignore \"No newline at end of file\" markers\n\t\tif strings.HasPrefix(line, \"\\\\ No newline at end of file\") {\n\t\t\tcontinue\n\t\t}\n\n\t\tif currentHunk == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\t// Process the line based on its prefix\n\t\tif len(line) > 0 {\n\t\t\tswitch line[0] {\n\t\t\tcase '+':\n\t\t\t\tcurrentHunk.Lines = append(currentHunk.Lines, DiffLine{\n\t\t\t\t\tOldLineNo: 0,\n\t\t\t\t\tNewLineNo: newLine,\n\t\t\t\t\tKind: LineAdded,\n\t\t\t\t\tContent: line[1:],\n\t\t\t\t})\n\t\t\t\tnewLine++\n\t\t\tcase '-':\n\t\t\t\tcurrentHunk.Lines = append(currentHunk.Lines, DiffLine{\n\t\t\t\t\tOldLineNo: oldLine,\n\t\t\t\t\tNewLineNo: 0,\n\t\t\t\t\tKind: LineRemoved,\n\t\t\t\t\tContent: line[1:],\n\t\t\t\t})\n\t\t\t\toldLine++\n\t\t\tdefault:\n\t\t\t\tcurrentHunk.Lines = append(currentHunk.Lines, DiffLine{\n\t\t\t\t\tOldLineNo: oldLine,\n\t\t\t\t\tNewLineNo: newLine,\n\t\t\t\t\tKind: LineContext,\n\t\t\t\t\tContent: line,\n\t\t\t\t})\n\t\t\t\toldLine++\n\t\t\t\tnewLine++\n\t\t\t}\n\t\t} else {\n\t\t\t// Handle empty lines\n\t\t\tcurrentHunk.Lines = append(currentHunk.Lines, DiffLine{\n\t\t\t\tOldLineNo: oldLine,\n\t\t\t\tNewLineNo: newLine,\n\t\t\t\tKind: LineContext,\n\t\t\t\tContent: \"\",\n\t\t\t})\n\t\t\toldLine++\n\t\t\tnewLine++\n\t\t}\n\t}\n\n\t// Add the last hunk if there is one\n\tif currentHunk != nil {\n\t\tresult.Hunks = append(result.Hunks, *currentHunk)\n\t}\n\n\treturn result, nil\n}\n\n// HighlightIntralineChanges updates lines in a hunk to show character-level differences\nfunc HighlightIntralineChanges(h *Hunk) {\n\tvar updated []DiffLine\n\tdmp := diffmatchpatch.New()\n\n\tfor i := 0; i < len(h.Lines); i++ {\n\t\t// Look for removed line followed by added line\n\t\tif i+1 < len(h.Lines) &&\n\t\t\th.Lines[i].Kind == LineRemoved &&\n\t\t\th.Lines[i+1].Kind == LineAdded {\n\n\t\t\toldLine := h.Lines[i]\n\t\t\tnewLine := h.Lines[i+1]\n\n\t\t\t// Find character-level differences\n\t\t\tpatches := dmp.DiffMain(oldLine.Content, newLine.Content, false)\n\t\t\tpatches = dmp.DiffCleanupSemantic(patches)\n\t\t\tpatches = dmp.DiffCleanupMerge(patches)\n\t\t\tpatches = dmp.DiffCleanupEfficiency(patches)\n\n\t\t\tsegments := make([]Segment, 0)\n\n\t\t\tremoveStart := 0\n\t\t\taddStart := 0\n\t\t\tfor _, patch := range patches {\n\t\t\t\tswitch patch.Type {\n\t\t\t\tcase diffmatchpatch.DiffDelete:\n\t\t\t\t\tsegments = append(segments, Segment{\n\t\t\t\t\t\tStart: removeStart,\n\t\t\t\t\t\tEnd: removeStart + len(patch.Text),\n\t\t\t\t\t\tType: LineRemoved,\n\t\t\t\t\t\tText: patch.Text,\n\t\t\t\t\t})\n\t\t\t\t\tremoveStart += len(patch.Text)\n\t\t\t\tcase diffmatchpatch.DiffInsert:\n\t\t\t\t\tsegments = append(segments, Segment{\n\t\t\t\t\t\tStart: addStart,\n\t\t\t\t\t\tEnd: addStart + len(patch.Text),\n\t\t\t\t\t\tType: LineAdded,\n\t\t\t\t\t\tText: patch.Text,\n\t\t\t\t\t})\n\t\t\t\t\taddStart += len(patch.Text)\n\t\t\t\tdefault:\n\t\t\t\t\t// Context text, no highlighting needed\n\t\t\t\t\tremoveStart += len(patch.Text)\n\t\t\t\t\taddStart += len(patch.Text)\n\t\t\t\t}\n\t\t\t}\n\t\t\toldLine.Segments = segments\n\t\t\tnewLine.Segments = segments\n\n\t\t\tupdated = append(updated, oldLine, newLine)\n\t\t\ti++ // Skip the next line as we've already processed it\n\t\t} else {\n\t\t\tupdated = append(updated, h.Lines[i])\n\t\t}\n\t}\n\n\th.Lines = updated\n}\n\n// pairLines converts a flat list of diff lines to pairs for side-by-side display\nfunc pairLines(lines []DiffLine) []linePair {\n\tvar pairs []linePair\n\ti := 0\n\n\tfor i < len(lines) {\n\t\tswitch lines[i].Kind {\n\t\tcase LineRemoved:\n\t\t\t// Check if the next line is an addition, if so pair them\n\t\t\tif i+1 < len(lines) && lines[i+1].Kind == LineAdded {\n\t\t\t\tpairs = append(pairs, linePair{left: &lines[i], right: &lines[i+1]})\n\t\t\t\ti += 2\n\t\t\t} else {\n\t\t\t\tpairs = append(pairs, linePair{left: &lines[i], right: nil})\n\t\t\t\ti++\n\t\t\t}\n\t\tcase LineAdded:\n\t\t\tpairs = append(pairs, linePair{left: nil, right: &lines[i]})\n\t\t\ti++\n\t\tcase LineContext:\n\t\t\tpairs = append(pairs, linePair{left: &lines[i], right: &lines[i]})\n\t\t\ti++\n\t\t}\n\t}\n\n\treturn pairs\n}\n\n// -------------------------------------------------------------------------\n// Syntax Highlighting\n// -------------------------------------------------------------------------\n\n// SyntaxHighlight applies syntax highlighting to text based on file extension\nfunc SyntaxHighlight(w io.Writer, source, fileName, formatter string, bg lipgloss.TerminalColor) error {\n\tt := theme.CurrentTheme()\n\n\t// Determine the language lexer to use\n\tl := lexers.Match(fileName)\n\tif l == nil {\n\t\tl = lexers.Analyse(source)\n\t}\n\tif l == nil {\n\t\tl = lexers.Fallback\n\t}\n\tl = chroma.Coalesce(l)\n\n\t// Get the formatter\n\tf := formatters.Get(formatter)\n\tif f == nil {\n\t\tf = formatters.Fallback\n\t}\n\n\t// Dynamic theme based on current theme values\n\tsyntaxThemeXml := fmt.Sprintf(`\n\t\n`,\n\t\tgetColor(t.Background()), // Background\n\t\tgetColor(t.Text()), // Text\n\t\tgetColor(t.Text()), // Other\n\t\tgetColor(t.Error()), // Error\n\n\t\tgetColor(t.SyntaxKeyword()), // Keyword\n\t\tgetColor(t.SyntaxKeyword()), // KeywordConstant\n\t\tgetColor(t.SyntaxKeyword()), // KeywordDeclaration\n\t\tgetColor(t.SyntaxKeyword()), // KeywordNamespace\n\t\tgetColor(t.SyntaxKeyword()), // KeywordPseudo\n\t\tgetColor(t.SyntaxKeyword()), // KeywordReserved\n\t\tgetColor(t.SyntaxType()), // KeywordType\n\n\t\tgetColor(t.Text()), // Name\n\t\tgetColor(t.SyntaxVariable()), // NameAttribute\n\t\tgetColor(t.SyntaxType()), // NameBuiltin\n\t\tgetColor(t.SyntaxVariable()), // NameBuiltinPseudo\n\t\tgetColor(t.SyntaxType()), // NameClass\n\t\tgetColor(t.SyntaxVariable()), // NameConstant\n\t\tgetColor(t.SyntaxFunction()), // NameDecorator\n\t\tgetColor(t.SyntaxVariable()), // NameEntity\n\t\tgetColor(t.SyntaxType()), // NameException\n\t\tgetColor(t.SyntaxFunction()), // NameFunction\n\t\tgetColor(t.Text()), // NameLabel\n\t\tgetColor(t.SyntaxType()), // NameNamespace\n\t\tgetColor(t.SyntaxVariable()), // NameOther\n\t\tgetColor(t.SyntaxKeyword()), // NameTag\n\t\tgetColor(t.SyntaxVariable()), // NameVariable\n\t\tgetColor(t.SyntaxVariable()), // NameVariableClass\n\t\tgetColor(t.SyntaxVariable()), // NameVariableGlobal\n\t\tgetColor(t.SyntaxVariable()), // NameVariableInstance\n\n\t\tgetColor(t.SyntaxString()), // Literal\n\t\tgetColor(t.SyntaxString()), // LiteralDate\n\t\tgetColor(t.SyntaxString()), // LiteralString\n\t\tgetColor(t.SyntaxString()), // LiteralStringBacktick\n\t\tgetColor(t.SyntaxString()), // LiteralStringChar\n\t\tgetColor(t.SyntaxString()), // LiteralStringDoc\n\t\tgetColor(t.SyntaxString()), // LiteralStringDouble\n\t\tgetColor(t.SyntaxString()), // LiteralStringEscape\n\t\tgetColor(t.SyntaxString()), // LiteralStringHeredoc\n\t\tgetColor(t.SyntaxString()), // LiteralStringInterpol\n\t\tgetColor(t.SyntaxString()), // LiteralStringOther\n\t\tgetColor(t.SyntaxString()), // LiteralStringRegex\n\t\tgetColor(t.SyntaxString()), // LiteralStringSingle\n\t\tgetColor(t.SyntaxString()), // LiteralStringSymbol\n\n\t\tgetColor(t.SyntaxNumber()), // LiteralNumber\n\t\tgetColor(t.SyntaxNumber()), // LiteralNumberBin\n\t\tgetColor(t.SyntaxNumber()), // LiteralNumberFloat\n\t\tgetColor(t.SyntaxNumber()), // LiteralNumberHex\n\t\tgetColor(t.SyntaxNumber()), // LiteralNumberInteger\n\t\tgetColor(t.SyntaxNumber()), // LiteralNumberIntegerLong\n\t\tgetColor(t.SyntaxNumber()), // LiteralNumberOct\n\n\t\tgetColor(t.SyntaxOperator()), // Operator\n\t\tgetColor(t.SyntaxKeyword()), // OperatorWord\n\t\tgetColor(t.SyntaxPunctuation()), // Punctuation\n\n\t\tgetColor(t.SyntaxComment()), // Comment\n\t\tgetColor(t.SyntaxComment()), // CommentHashbang\n\t\tgetColor(t.SyntaxComment()), // CommentMultiline\n\t\tgetColor(t.SyntaxComment()), // CommentSingle\n\t\tgetColor(t.SyntaxComment()), // CommentSpecial\n\t\tgetColor(t.SyntaxKeyword()), // CommentPreproc\n\n\t\tgetColor(t.Text()), // Generic\n\t\tgetColor(t.Error()), // GenericDeleted\n\t\tgetColor(t.Text()), // GenericEmph\n\t\tgetColor(t.Error()), // GenericError\n\t\tgetColor(t.Text()), // GenericHeading\n\t\tgetColor(t.Success()), // GenericInserted\n\t\tgetColor(t.TextMuted()), // GenericOutput\n\t\tgetColor(t.Text()), // GenericPrompt\n\t\tgetColor(t.Text()), // GenericStrong\n\t\tgetColor(t.Text()), // GenericSubheading\n\t\tgetColor(t.Error()), // GenericTraceback\n\t\tgetColor(t.Text()), // TextWhitespace\n\t)\n\n\tr := strings.NewReader(syntaxThemeXml)\n\tstyle := chroma.MustNewXMLStyle(r)\n\n\t// Modify the style to use the provided background\n\ts, err := style.Builder().Transform(\n\t\tfunc(t chroma.StyleEntry) chroma.StyleEntry {\n\t\t\tr, g, b, _ := bg.RGBA()\n\t\t\tt.Background = chroma.NewColour(uint8(r>>8), uint8(g>>8), uint8(b>>8))\n\t\t\treturn t\n\t\t},\n\t).Build()\n\tif err != nil {\n\t\ts = styles.Fallback\n\t}\n\n\t// Tokenize and format\n\tit, err := l.Tokenise(nil, source)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn f.Format(w, s, it)\n}\n\n// getColor returns the appropriate hex color string based on terminal background\nfunc getColor(adaptiveColor lipgloss.AdaptiveColor) string {\n\tif lipgloss.HasDarkBackground() {\n\t\treturn adaptiveColor.Dark\n\t}\n\treturn adaptiveColor.Light\n}\n\n// highlightLine applies syntax highlighting to a single line\nfunc highlightLine(fileName string, line string, bg lipgloss.TerminalColor) string {\n\tvar buf bytes.Buffer\n\terr := SyntaxHighlight(&buf, line, fileName, \"terminal16m\", bg)\n\tif err != nil {\n\t\treturn line\n\t}\n\treturn buf.String()\n}\n\n// createStyles generates the lipgloss styles needed for rendering diffs\nfunc createStyles(t theme.Theme) (removedLineStyle, addedLineStyle, contextLineStyle, lineNumberStyle lipgloss.Style) {\n\tremovedLineStyle = lipgloss.NewStyle().Background(t.DiffRemovedBg())\n\taddedLineStyle = lipgloss.NewStyle().Background(t.DiffAddedBg())\n\tcontextLineStyle = lipgloss.NewStyle().Background(t.DiffContextBg())\n\tlineNumberStyle = lipgloss.NewStyle().Foreground(t.DiffLineNumber())\n\n\treturn\n}\n\n// -------------------------------------------------------------------------\n// Rendering Functions\n// -------------------------------------------------------------------------\n\nfunc lipglossToHex(color lipgloss.Color) string {\n\tr, g, b, a := color.RGBA()\n\n\t// Scale uint32 values (0-65535) to uint8 (0-255).\n\tr8 := uint8(r >> 8)\n\tg8 := uint8(g >> 8)\n\tb8 := uint8(b >> 8)\n\ta8 := uint8(a >> 8)\n\n\treturn fmt.Sprintf(\"#%02x%02x%02x%02x\", r8, g8, b8, a8)\n}\n\n// applyHighlighting applies intra-line highlighting to a piece of text\nfunc applyHighlighting(content string, segments []Segment, segmentType LineType, highlightBg lipgloss.AdaptiveColor) string {\n\t// Find all ANSI sequences in the content\n\tansiRegex := regexp.MustCompile(`\\x1b(?:[@-Z\\\\-_]|\\[[0-9?]*(?:;[0-9?]*)*[@-~])`)\n\tansiMatches := ansiRegex.FindAllStringIndex(content, -1)\n\n\t// Build a mapping of visible character positions to their actual indices\n\tvisibleIdx := 0\n\tansiSequences := make(map[int]string)\n\tlastAnsiSeq := \"\\x1b[0m\" // Default reset sequence\n\n\tfor i := 0; i < len(content); {\n\t\tisAnsi := false\n\t\tfor _, match := range ansiMatches {\n\t\t\tif match[0] == i {\n\t\t\t\tansiSequences[visibleIdx] = content[match[0]:match[1]]\n\t\t\t\tlastAnsiSeq = content[match[0]:match[1]]\n\t\t\t\ti = match[1]\n\t\t\t\tisAnsi = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif isAnsi {\n\t\t\tcontinue\n\t\t}\n\n\t\t// For non-ANSI positions, store the last ANSI sequence\n\t\tif _, exists := ansiSequences[visibleIdx]; !exists {\n\t\t\tansiSequences[visibleIdx] = lastAnsiSeq\n\t\t}\n\t\tvisibleIdx++\n\t\ti++\n\t}\n\n\t// Apply highlighting\n\tvar sb strings.Builder\n\tinSelection := false\n\tcurrentPos := 0\n\n\t// Get the appropriate color based on terminal background\n\tbgColor := lipgloss.Color(getColor(highlightBg))\n\tfgColor := lipgloss.Color(getColor(theme.CurrentTheme().Background()))\n\n\tfor i := 0; i < len(content); {\n\t\t// Check if we're at an ANSI sequence\n\t\tisAnsi := false\n\t\tfor _, match := range ansiMatches {\n\t\t\tif match[0] == i {\n\t\t\t\tsb.WriteString(content[match[0]:match[1]]) // Preserve ANSI sequence\n\t\t\t\ti = match[1]\n\t\t\t\tisAnsi = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif isAnsi {\n\t\t\tcontinue\n\t\t}\n\n\t\t// Check for segment boundaries\n\t\tfor _, seg := range segments {\n\t\t\tif seg.Type == segmentType {\n\t\t\t\tif currentPos == seg.Start {\n\t\t\t\t\tinSelection = true\n\t\t\t\t}\n\t\t\t\tif currentPos == seg.End {\n\t\t\t\t\tinSelection = false\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Get current character\n\t\tchar := string(content[i])\n\n\t\tif inSelection {\n\t\t\t// Get the current styling\n\t\t\tcurrentStyle := ansiSequences[currentPos]\n\n\t\t\t// Apply foreground and background highlight\n\t\t\tsb.WriteString(\"\\x1b[38;2;\")\n\t\t\tr, g, b, _ := fgColor.RGBA()\n\t\t\tsb.WriteString(fmt.Sprintf(\"%d;%d;%dm\", r>>8, g>>8, b>>8))\n\t\t\tsb.WriteString(\"\\x1b[48;2;\")\n\t\t\tr, g, b, _ = bgColor.RGBA()\n\t\t\tsb.WriteString(fmt.Sprintf(\"%d;%d;%dm\", r>>8, g>>8, b>>8))\n\t\t\tsb.WriteString(char)\n\t\t\t// Reset foreground and background\n\t\t\tsb.WriteString(\"\\x1b[39m\")\n\n\t\t\t// Reapply the original ANSI sequence\n\t\t\tsb.WriteString(currentStyle)\n\t\t} else {\n\t\t\t// Not in selection, just copy the character\n\t\t\tsb.WriteString(char)\n\t\t}\n\n\t\tcurrentPos++\n\t\ti++\n\t}\n\n\treturn sb.String()\n}\n\n// renderLeftColumn formats the left side of a side-by-side diff\nfunc renderLeftColumn(fileName string, dl *DiffLine, colWidth int) string {\n\tt := theme.CurrentTheme()\n\n\tif dl == nil {\n\t\tcontextLineStyle := lipgloss.NewStyle().Background(t.DiffContextBg())\n\t\treturn contextLineStyle.Width(colWidth).Render(\"\")\n\t}\n\n\tremovedLineStyle, _, contextLineStyle, lineNumberStyle := createStyles(t)\n\n\t// Determine line style based on line type\n\tvar marker string\n\tvar bgStyle lipgloss.Style\n\tswitch dl.Kind {\n\tcase LineRemoved:\n\t\tmarker = removedLineStyle.Foreground(t.DiffRemoved()).Render(\"-\")\n\t\tbgStyle = removedLineStyle\n\t\tlineNumberStyle = lineNumberStyle.Foreground(t.DiffRemoved()).Background(t.DiffRemovedLineNumberBg())\n\tcase LineAdded:\n\t\tmarker = \"?\"\n\t\tbgStyle = contextLineStyle\n\tcase LineContext:\n\t\tmarker = contextLineStyle.Render(\" \")\n\t\tbgStyle = contextLineStyle\n\t}\n\n\t// Format line number\n\tlineNum := \"\"\n\tif dl.OldLineNo > 0 {\n\t\tlineNum = fmt.Sprintf(\"%6d\", dl.OldLineNo)\n\t}\n\n\t// Create the line prefix\n\tprefix := lineNumberStyle.Render(lineNum + \" \" + marker)\n\n\t// Apply syntax highlighting\n\tcontent := highlightLine(fileName, dl.Content, bgStyle.GetBackground())\n\n\t// Apply intra-line highlighting for removed lines\n\tif dl.Kind == LineRemoved && len(dl.Segments) > 0 {\n\t\tcontent = applyHighlighting(content, dl.Segments, LineRemoved, t.DiffHighlightRemoved())\n\t}\n\n\t// Add a padding space for removed lines\n\tif dl.Kind == LineRemoved {\n\t\tcontent = bgStyle.Render(\" \") + content\n\t}\n\n\t// Create the final line and truncate if needed\n\tlineText := prefix + content\n\treturn bgStyle.MaxHeight(1).Width(colWidth).Render(\n\t\tansi.Truncate(\n\t\t\tlineText,\n\t\t\tcolWidth,\n\t\t\tlipgloss.NewStyle().Background(bgStyle.GetBackground()).Foreground(t.TextMuted()).Render(\"...\"),\n\t\t),\n\t)\n}\n\n// renderRightColumn formats the right side of a side-by-side diff\nfunc renderRightColumn(fileName string, dl *DiffLine, colWidth int) string {\n\tt := theme.CurrentTheme()\n\n\tif dl == nil {\n\t\tcontextLineStyle := lipgloss.NewStyle().Background(t.DiffContextBg())\n\t\treturn contextLineStyle.Width(colWidth).Render(\"\")\n\t}\n\n\t_, addedLineStyle, contextLineStyle, lineNumberStyle := createStyles(t)\n\n\t// Determine line style based on line type\n\tvar marker string\n\tvar bgStyle lipgloss.Style\n\tswitch dl.Kind {\n\tcase LineAdded:\n\t\tmarker = addedLineStyle.Foreground(t.DiffAdded()).Render(\"+\")\n\t\tbgStyle = addedLineStyle\n\t\tlineNumberStyle = lineNumberStyle.Foreground(t.DiffAdded()).Background(t.DiffAddedLineNumberBg())\n\tcase LineRemoved:\n\t\tmarker = \"?\"\n\t\tbgStyle = contextLineStyle\n\tcase LineContext:\n\t\tmarker = contextLineStyle.Render(\" \")\n\t\tbgStyle = contextLineStyle\n\t}\n\n\t// Format line number\n\tlineNum := \"\"\n\tif dl.NewLineNo > 0 {\n\t\tlineNum = fmt.Sprintf(\"%6d\", dl.NewLineNo)\n\t}\n\n\t// Create the line prefix\n\tprefix := lineNumberStyle.Render(lineNum + \" \" + marker)\n\n\t// Apply syntax highlighting\n\tcontent := highlightLine(fileName, dl.Content, bgStyle.GetBackground())\n\n\t// Apply intra-line highlighting for added lines\n\tif dl.Kind == LineAdded && len(dl.Segments) > 0 {\n\t\tcontent = applyHighlighting(content, dl.Segments, LineAdded, t.DiffHighlightAdded())\n\t}\n\n\t// Add a padding space for added lines\n\tif dl.Kind == LineAdded {\n\t\tcontent = bgStyle.Render(\" \") + content\n\t}\n\n\t// Create the final line and truncate if needed\n\tlineText := prefix + content\n\treturn bgStyle.MaxHeight(1).Width(colWidth).Render(\n\t\tansi.Truncate(\n\t\t\tlineText,\n\t\t\tcolWidth,\n\t\t\tlipgloss.NewStyle().Background(bgStyle.GetBackground()).Foreground(t.TextMuted()).Render(\"...\"),\n\t\t),\n\t)\n}\n\n// -------------------------------------------------------------------------\n// Public API\n// -------------------------------------------------------------------------\n\n// RenderSideBySideHunk formats a hunk for side-by-side display\nfunc RenderSideBySideHunk(fileName string, h Hunk, opts ...SideBySideOption) string {\n\t// Apply options to create the configuration\n\tconfig := NewSideBySideConfig(opts...)\n\n\t// Make a copy of the hunk so we don't modify the original\n\thunkCopy := Hunk{Lines: make([]DiffLine, len(h.Lines))}\n\tcopy(hunkCopy.Lines, h.Lines)\n\n\t// Highlight changes within lines\n\tHighlightIntralineChanges(&hunkCopy)\n\n\t// Pair lines for side-by-side display\n\tpairs := pairLines(hunkCopy.Lines)\n\n\t// Calculate column width\n\tcolWidth := config.TotalWidth / 2\n\n\tleftWidth := colWidth\n\trightWidth := config.TotalWidth - colWidth\n\tvar sb strings.Builder\n\tfor _, p := range pairs {\n\t\tleftStr := renderLeftColumn(fileName, p.left, leftWidth)\n\t\trightStr := renderRightColumn(fileName, p.right, rightWidth)\n\t\tsb.WriteString(leftStr + rightStr + \"\\n\")\n\t}\n\n\treturn sb.String()\n}\n\n// FormatDiff creates a side-by-side formatted view of a diff\nfunc FormatDiff(diffText string, opts ...SideBySideOption) (string, error) {\n\tdiffResult, err := ParseUnifiedDiff(diffText)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tvar sb strings.Builder\n\tfor _, h := range diffResult.Hunks {\n\t\tsb.WriteString(RenderSideBySideHunk(diffResult.OldFile, h, opts...))\n\t}\n\n\treturn sb.String(), nil\n}\n\n// GenerateDiff creates a unified diff from two file contents\nfunc GenerateDiff(beforeContent, afterContent, fileName string) (string, int, int) {\n\t// remove the cwd prefix and ensure consistent path format\n\t// this prevents issues with absolute paths in different environments\n\tcwd := config.WorkingDirectory()\n\tfileName = strings.TrimPrefix(fileName, cwd)\n\tfileName = strings.TrimPrefix(fileName, \"/\")\n\n\tvar (\n\t\tunified = udiff.Unified(\"a/\"+fileName, \"b/\"+fileName, beforeContent, afterContent)\n\t\tadditions = 0\n\t\tremovals = 0\n\t)\n\n\tlines := strings.SplitSeq(unified, \"\\n\")\n\tfor line := range lines {\n\t\tif strings.HasPrefix(line, \"+\") && !strings.HasPrefix(line, \"+++\") {\n\t\t\tadditions++\n\t\t} else if strings.HasPrefix(line, \"-\") && !strings.HasPrefix(line, \"---\") {\n\t\t\tremovals++\n\t\t}\n\t}\n\n\treturn unified, additions, removals\n}\n"], ["/opencode/internal/app/lsp.go", "package app\n\nimport (\n\t\"context\"\n\t\"time\"\n\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n\t\"github.com/opencode-ai/opencode/internal/lsp\"\n\t\"github.com/opencode-ai/opencode/internal/lsp/watcher\"\n)\n\nfunc (app *App) initLSPClients(ctx context.Context) {\n\tcfg := config.Get()\n\n\t// Initialize LSP clients\n\tfor name, clientConfig := range cfg.LSP {\n\t\t// Start each client initialization in its own goroutine\n\t\tgo app.createAndStartLSPClient(ctx, name, clientConfig.Command, clientConfig.Args...)\n\t}\n\tlogging.Info(\"LSP clients initialization started in background\")\n}\n\n// createAndStartLSPClient creates a new LSP client, initializes it, and starts its workspace watcher\nfunc (app *App) createAndStartLSPClient(ctx context.Context, name string, command string, args ...string) {\n\t// Create a specific context for initialization with a timeout\n\tlogging.Info(\"Creating LSP client\", \"name\", name, \"command\", command, \"args\", args)\n\t\n\t// Create the LSP client\n\tlspClient, err := lsp.NewClient(ctx, command, args...)\n\tif err != nil {\n\t\tlogging.Error(\"Failed to create LSP client for\", name, err)\n\t\treturn\n\t}\n\n\t// Create a longer timeout for initialization (some servers take time to start)\n\tinitCtx, cancel := context.WithTimeout(ctx, 30*time.Second)\n\tdefer cancel()\n\t\n\t// Initialize with the initialization context\n\t_, err = lspClient.InitializeLSPClient(initCtx, config.WorkingDirectory())\n\tif err != nil {\n\t\tlogging.Error(\"Initialize failed\", \"name\", name, \"error\", err)\n\t\t// Clean up the client to prevent resource leaks\n\t\tlspClient.Close()\n\t\treturn\n\t}\n\n\t// Wait for the server to be ready\n\tif err := lspClient.WaitForServerReady(initCtx); err != nil {\n\t\tlogging.Error(\"Server failed to become ready\", \"name\", name, \"error\", err)\n\t\t// We'll continue anyway, as some functionality might still work\n\t\tlspClient.SetServerState(lsp.StateError)\n\t} else {\n\t\tlogging.Info(\"LSP server is ready\", \"name\", name)\n\t\tlspClient.SetServerState(lsp.StateReady)\n\t}\n\n\tlogging.Info(\"LSP client initialized\", \"name\", name)\n\t\n\t// Create a child context that can be canceled when the app is shutting down\n\twatchCtx, cancelFunc := context.WithCancel(ctx)\n\t\n\t// Create a context with the server name for better identification\n\twatchCtx = context.WithValue(watchCtx, \"serverName\", name)\n\t\n\t// Create the workspace watcher\n\tworkspaceWatcher := watcher.NewWorkspaceWatcher(lspClient)\n\n\t// Store the cancel function to be called during cleanup\n\tapp.cancelFuncsMutex.Lock()\n\tapp.watcherCancelFuncs = append(app.watcherCancelFuncs, cancelFunc)\n\tapp.cancelFuncsMutex.Unlock()\n\n\t// Add the watcher to a WaitGroup to track active goroutines\n\tapp.watcherWG.Add(1)\n\n\t// Add to map with mutex protection before starting goroutine\n\tapp.clientsMutex.Lock()\n\tapp.LSPClients[name] = lspClient\n\tapp.clientsMutex.Unlock()\n\n\tgo app.runWorkspaceWatcher(watchCtx, name, workspaceWatcher)\n}\n\n// runWorkspaceWatcher executes the workspace watcher for an LSP client\nfunc (app *App) runWorkspaceWatcher(ctx context.Context, name string, workspaceWatcher *watcher.WorkspaceWatcher) {\n\tdefer app.watcherWG.Done()\n\tdefer logging.RecoverPanic(\"LSP-\"+name, func() {\n\t\t// Try to restart the client\n\t\tapp.restartLSPClient(ctx, name)\n\t})\n\n\tworkspaceWatcher.WatchWorkspace(ctx, config.WorkingDirectory())\n\tlogging.Info(\"Workspace watcher stopped\", \"client\", name)\n}\n\n// restartLSPClient attempts to restart a crashed or failed LSP client\nfunc (app *App) restartLSPClient(ctx context.Context, name string) {\n\t// Get the original configuration\n\tcfg := config.Get()\n\tclientConfig, exists := cfg.LSP[name]\n\tif !exists {\n\t\tlogging.Error(\"Cannot restart client, configuration not found\", \"client\", name)\n\t\treturn\n\t}\n\n\t// Clean up the old client if it exists\n\tapp.clientsMutex.Lock()\n\toldClient, exists := app.LSPClients[name]\n\tif exists {\n\t\tdelete(app.LSPClients, name) // Remove from map before potentially slow shutdown\n\t}\n\tapp.clientsMutex.Unlock()\n\n\tif exists && oldClient != nil {\n\t\t// Try to shut it down gracefully, but don't block on errors\n\t\tshutdownCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)\n\t\t_ = oldClient.Shutdown(shutdownCtx)\n\t\tcancel()\n\t}\n\n\t// Create a new client using the shared function\n\tapp.createAndStartLSPClient(ctx, name, clientConfig.Command, clientConfig.Args...)\n\tlogging.Info(\"Successfully restarted LSP client\", \"client\", name)\n}\n"], ["/opencode/internal/logging/writer.go", "package logging\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"fmt\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com/go-logfmt/logfmt\"\n\t\"github.com/opencode-ai/opencode/internal/pubsub\"\n)\n\nconst (\n\tpersistKeyArg = \"$_persist\"\n\tPersistTimeArg = \"$_persist_time\"\n)\n\ntype LogData struct {\n\tmessages []LogMessage\n\t*pubsub.Broker[LogMessage]\n\tlock sync.Mutex\n}\n\nfunc (l *LogData) Add(msg LogMessage) {\n\tl.lock.Lock()\n\tdefer l.lock.Unlock()\n\tl.messages = append(l.messages, msg)\n\tl.Publish(pubsub.CreatedEvent, msg)\n}\n\nfunc (l *LogData) List() []LogMessage {\n\tl.lock.Lock()\n\tdefer l.lock.Unlock()\n\treturn l.messages\n}\n\nvar defaultLogData = &LogData{\n\tmessages: make([]LogMessage, 0),\n\tBroker: pubsub.NewBroker[LogMessage](),\n}\n\ntype writer struct{}\n\nfunc (w *writer) Write(p []byte) (int, error) {\n\td := logfmt.NewDecoder(bytes.NewReader(p))\n\n\tfor d.ScanRecord() {\n\t\tmsg := LogMessage{\n\t\t\tID: fmt.Sprintf(\"%d\", time.Now().UnixNano()),\n\t\t\tTime: time.Now(),\n\t\t}\n\t\tfor d.ScanKeyval() {\n\t\t\tswitch string(d.Key()) {\n\t\t\tcase \"time\":\n\t\t\t\tparsed, err := time.Parse(time.RFC3339, string(d.Value()))\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn 0, fmt.Errorf(\"parsing time: %w\", err)\n\t\t\t\t}\n\t\t\t\tmsg.Time = parsed\n\t\t\tcase \"level\":\n\t\t\t\tmsg.Level = strings.ToLower(string(d.Value()))\n\t\t\tcase \"msg\":\n\t\t\t\tmsg.Message = string(d.Value())\n\t\t\tdefault:\n\t\t\t\tif string(d.Key()) == persistKeyArg {\n\t\t\t\t\tmsg.Persist = true\n\t\t\t\t} else if string(d.Key()) == PersistTimeArg {\n\t\t\t\t\tparsed, err := time.ParseDuration(string(d.Value()))\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tmsg.PersistTime = parsed\n\t\t\t\t} else {\n\t\t\t\t\tmsg.Attributes = append(msg.Attributes, Attr{\n\t\t\t\t\t\tKey: string(d.Key()),\n\t\t\t\t\t\tValue: string(d.Value()),\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tdefaultLogData.Add(msg)\n\t}\n\tif d.Err() != nil {\n\t\treturn 0, d.Err()\n\t}\n\treturn len(p), nil\n}\n\nfunc NewWriter() *writer {\n\tw := &writer{}\n\treturn w\n}\n\nfunc Subscribe(ctx context.Context) <-chan pubsub.Event[LogMessage] {\n\treturn defaultLogData.Subscribe(ctx)\n}\n\nfunc List() []LogMessage {\n\treturn defaultLogData.List()\n}\n"], ["/opencode/internal/tui/components/dialog/complete.go", "package dialog\n\nimport (\n\t\"github.com/charmbracelet/bubbles/key\"\n\t\"github.com/charmbracelet/bubbles/textarea\"\n\ttea \"github.com/charmbracelet/bubbletea\"\n\t\"github.com/charmbracelet/lipgloss\"\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n\tutilComponents \"github.com/opencode-ai/opencode/internal/tui/components/util\"\n\t\"github.com/opencode-ai/opencode/internal/tui/layout\"\n\t\"github.com/opencode-ai/opencode/internal/tui/styles\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n\t\"github.com/opencode-ai/opencode/internal/tui/util\"\n)\n\ntype CompletionItem struct {\n\ttitle string\n\tTitle string\n\tValue string\n}\n\ntype CompletionItemI interface {\n\tutilComponents.SimpleListItem\n\tGetValue() string\n\tDisplayValue() string\n}\n\nfunc (ci *CompletionItem) Render(selected bool, width int) string {\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\n\titemStyle := baseStyle.\n\t\tWidth(width).\n\t\tPadding(0, 1)\n\n\tif selected {\n\t\titemStyle = itemStyle.\n\t\t\tBackground(t.Background()).\n\t\t\tForeground(t.Primary()).\n\t\t\tBold(true)\n\t}\n\n\ttitle := itemStyle.Render(\n\t\tci.GetValue(),\n\t)\n\n\treturn title\n}\n\nfunc (ci *CompletionItem) DisplayValue() string {\n\treturn ci.Title\n}\n\nfunc (ci *CompletionItem) GetValue() string {\n\treturn ci.Value\n}\n\nfunc NewCompletionItem(completionItem CompletionItem) CompletionItemI {\n\treturn &completionItem\n}\n\ntype CompletionProvider interface {\n\tGetId() string\n\tGetEntry() CompletionItemI\n\tGetChildEntries(query string) ([]CompletionItemI, error)\n}\n\ntype CompletionSelectedMsg struct {\n\tSearchString string\n\tCompletionValue string\n}\n\ntype CompletionDialogCompleteItemMsg struct {\n\tValue string\n}\n\ntype CompletionDialogCloseMsg struct{}\n\ntype CompletionDialog interface {\n\ttea.Model\n\tlayout.Bindings\n\tSetWidth(width int)\n}\n\ntype completionDialogCmp struct {\n\tquery string\n\tcompletionProvider CompletionProvider\n\twidth int\n\theight int\n\tpseudoSearchTextArea textarea.Model\n\tlistView utilComponents.SimpleList[CompletionItemI]\n}\n\ntype completionDialogKeyMap struct {\n\tComplete key.Binding\n\tCancel key.Binding\n}\n\nvar completionDialogKeys = completionDialogKeyMap{\n\tComplete: key.NewBinding(\n\t\tkey.WithKeys(\"tab\", \"enter\"),\n\t),\n\tCancel: key.NewBinding(\n\t\tkey.WithKeys(\" \", \"esc\", \"backspace\"),\n\t),\n}\n\nfunc (c *completionDialogCmp) Init() tea.Cmd {\n\treturn nil\n}\n\nfunc (c *completionDialogCmp) complete(item CompletionItemI) tea.Cmd {\n\tvalue := c.pseudoSearchTextArea.Value()\n\n\tif value == \"\" {\n\t\treturn nil\n\t}\n\n\treturn tea.Batch(\n\t\tutil.CmdHandler(CompletionSelectedMsg{\n\t\t\tSearchString: value,\n\t\t\tCompletionValue: item.GetValue(),\n\t\t}),\n\t\tc.close(),\n\t)\n}\n\nfunc (c *completionDialogCmp) close() tea.Cmd {\n\tc.listView.SetItems([]CompletionItemI{})\n\tc.pseudoSearchTextArea.Reset()\n\tc.pseudoSearchTextArea.Blur()\n\n\treturn util.CmdHandler(CompletionDialogCloseMsg{})\n}\n\nfunc (c *completionDialogCmp) Update(msg tea.Msg) (tea.Model, tea.Cmd) {\n\tvar cmds []tea.Cmd\n\tswitch msg := msg.(type) {\n\tcase tea.KeyMsg:\n\t\tif c.pseudoSearchTextArea.Focused() {\n\n\t\t\tif !key.Matches(msg, completionDialogKeys.Complete) {\n\n\t\t\t\tvar cmd tea.Cmd\n\t\t\t\tc.pseudoSearchTextArea, cmd = c.pseudoSearchTextArea.Update(msg)\n\t\t\t\tcmds = append(cmds, cmd)\n\n\t\t\t\tvar query string\n\t\t\t\tquery = c.pseudoSearchTextArea.Value()\n\t\t\t\tif query != \"\" {\n\t\t\t\t\tquery = query[1:]\n\t\t\t\t}\n\n\t\t\t\tif query != c.query {\n\t\t\t\t\tlogging.Info(\"Query\", query)\n\t\t\t\t\titems, err := c.completionProvider.GetChildEntries(query)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlogging.Error(\"Failed to get child entries\", err)\n\t\t\t\t\t}\n\n\t\t\t\t\tc.listView.SetItems(items)\n\t\t\t\t\tc.query = query\n\t\t\t\t}\n\n\t\t\t\tu, cmd := c.listView.Update(msg)\n\t\t\t\tc.listView = u.(utilComponents.SimpleList[CompletionItemI])\n\n\t\t\t\tcmds = append(cmds, cmd)\n\t\t\t}\n\n\t\t\tswitch {\n\t\t\tcase key.Matches(msg, completionDialogKeys.Complete):\n\t\t\t\titem, i := c.listView.GetSelectedItem()\n\t\t\t\tif i == -1 {\n\t\t\t\t\treturn c, nil\n\t\t\t\t}\n\n\t\t\t\tcmd := c.complete(item)\n\n\t\t\t\treturn c, cmd\n\t\t\tcase key.Matches(msg, completionDialogKeys.Cancel):\n\t\t\t\t// Only close on backspace when there are no characters left\n\t\t\t\tif msg.String() != \"backspace\" || len(c.pseudoSearchTextArea.Value()) <= 0 {\n\t\t\t\t\treturn c, c.close()\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn c, tea.Batch(cmds...)\n\t\t} else {\n\t\t\titems, err := c.completionProvider.GetChildEntries(\"\")\n\t\t\tif err != nil {\n\t\t\t\tlogging.Error(\"Failed to get child entries\", err)\n\t\t\t}\n\n\t\t\tc.listView.SetItems(items)\n\t\t\tc.pseudoSearchTextArea.SetValue(msg.String())\n\t\t\treturn c, c.pseudoSearchTextArea.Focus()\n\t\t}\n\tcase tea.WindowSizeMsg:\n\t\tc.width = msg.Width\n\t\tc.height = msg.Height\n\t}\n\n\treturn c, tea.Batch(cmds...)\n}\n\nfunc (c *completionDialogCmp) View() string {\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\n\tmaxWidth := 40\n\n\tcompletions := c.listView.GetItems()\n\n\tfor _, cmd := range completions {\n\t\ttitle := cmd.DisplayValue()\n\t\tif len(title) > maxWidth-4 {\n\t\t\tmaxWidth = len(title) + 4\n\t\t}\n\t}\n\n\tc.listView.SetMaxWidth(maxWidth)\n\n\treturn baseStyle.Padding(0, 0).\n\t\tBorder(lipgloss.NormalBorder()).\n\t\tBorderBottom(false).\n\t\tBorderRight(false).\n\t\tBorderLeft(false).\n\t\tBorderBackground(t.Background()).\n\t\tBorderForeground(t.TextMuted()).\n\t\tWidth(c.width).\n\t\tRender(c.listView.View())\n}\n\nfunc (c *completionDialogCmp) SetWidth(width int) {\n\tc.width = width\n}\n\nfunc (c *completionDialogCmp) BindingKeys() []key.Binding {\n\treturn layout.KeyMapToSlice(completionDialogKeys)\n}\n\nfunc NewCompletionDialogCmp(completionProvider CompletionProvider) CompletionDialog {\n\tti := textarea.New()\n\n\titems, err := completionProvider.GetChildEntries(\"\")\n\tif err != nil {\n\t\tlogging.Error(\"Failed to get child entries\", err)\n\t}\n\n\tli := utilComponents.NewSimpleList(\n\t\titems,\n\t\t7,\n\t\t\"No file matches found\",\n\t\tfalse,\n\t)\n\n\treturn &completionDialogCmp{\n\t\tquery: \"\",\n\t\tcompletionProvider: completionProvider,\n\t\tpseudoSearchTextArea: ti,\n\t\tlistView: li,\n\t}\n}\n"], ["/opencode/internal/tui/image/images.go", "package image\n\nimport (\n\t\"fmt\"\n\t\"image\"\n\t\"os\"\n\t\"strings\"\n\n\t\"github.com/charmbracelet/lipgloss\"\n\t\"github.com/disintegration/imaging\"\n\t\"github.com/lucasb-eyer/go-colorful\"\n)\n\nfunc ValidateFileSize(filePath string, sizeLimit int64) (bool, error) {\n\tfileInfo, err := os.Stat(filePath)\n\tif err != nil {\n\t\treturn false, fmt.Errorf(\"error getting file info: %w\", err)\n\t}\n\n\tif fileInfo.Size() > sizeLimit {\n\t\treturn true, nil\n\t}\n\n\treturn false, nil\n}\n\nfunc ToString(width int, img image.Image) string {\n\timg = imaging.Resize(img, width, 0, imaging.Lanczos)\n\tb := img.Bounds()\n\timageWidth := b.Max.X\n\th := b.Max.Y\n\tstr := strings.Builder{}\n\n\tfor heightCounter := 0; heightCounter < h; heightCounter += 2 {\n\t\tfor x := range imageWidth {\n\t\t\tc1, _ := colorful.MakeColor(img.At(x, heightCounter))\n\t\t\tcolor1 := lipgloss.Color(c1.Hex())\n\n\t\t\tvar color2 lipgloss.Color\n\t\t\tif heightCounter+1 < h {\n\t\t\t\tc2, _ := colorful.MakeColor(img.At(x, heightCounter+1))\n\t\t\t\tcolor2 = lipgloss.Color(c2.Hex())\n\t\t\t} else {\n\t\t\t\tcolor2 = color1\n\t\t\t}\n\n\t\t\tstr.WriteString(lipgloss.NewStyle().Foreground(color1).\n\t\t\t\tBackground(color2).Render(\"▀\"))\n\t\t}\n\n\t\tstr.WriteString(\"\\n\")\n\t}\n\n\treturn str.String()\n}\n\nfunc ImagePreview(width int, filename string) (string, error) {\n\timageContent, err := os.Open(filename)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer imageContent.Close()\n\n\timg, _, err := image.Decode(imageContent)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\timageString := ToString(width, img)\n\n\treturn imageString, nil\n}\n"], ["/opencode/internal/tui/components/chat/message.go", "package chat\n\nimport (\n\t\"context\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"path/filepath\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/charmbracelet/lipgloss\"\n\t\"github.com/charmbracelet/x/ansi\"\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/diff\"\n\t\"github.com/opencode-ai/opencode/internal/llm/agent\"\n\t\"github.com/opencode-ai/opencode/internal/llm/models\"\n\t\"github.com/opencode-ai/opencode/internal/llm/tools\"\n\t\"github.com/opencode-ai/opencode/internal/message\"\n\t\"github.com/opencode-ai/opencode/internal/tui/styles\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n)\n\ntype uiMessageType int\n\nconst (\n\tuserMessageType uiMessageType = iota\n\tassistantMessageType\n\ttoolMessageType\n\n\tmaxResultHeight = 10\n)\n\ntype uiMessage struct {\n\tID string\n\tmessageType uiMessageType\n\tposition int\n\theight int\n\tcontent string\n}\n\nfunc toMarkdown(content string, focused bool, width int) string {\n\tr := styles.GetMarkdownRenderer(width)\n\trendered, _ := r.Render(content)\n\treturn rendered\n}\n\nfunc renderMessage(msg string, isUser bool, isFocused bool, width int, info ...string) string {\n\tt := theme.CurrentTheme()\n\n\tstyle := styles.BaseStyle().\n\t\tWidth(width - 1).\n\t\tBorderLeft(true).\n\t\tForeground(t.TextMuted()).\n\t\tBorderForeground(t.Primary()).\n\t\tBorderStyle(lipgloss.ThickBorder())\n\n\tif isUser {\n\t\tstyle = style.BorderForeground(t.Secondary())\n\t}\n\n\t// Apply markdown formatting and handle background color\n\tparts := []string{\n\t\tstyles.ForceReplaceBackgroundWithLipgloss(toMarkdown(msg, isFocused, width), t.Background()),\n\t}\n\n\t// Remove newline at the end\n\tparts[0] = strings.TrimSuffix(parts[0], \"\\n\")\n\tif len(info) > 0 {\n\t\tparts = append(parts, info...)\n\t}\n\n\trendered := style.Render(\n\t\tlipgloss.JoinVertical(\n\t\t\tlipgloss.Left,\n\t\t\tparts...,\n\t\t),\n\t)\n\n\treturn rendered\n}\n\nfunc renderUserMessage(msg message.Message, isFocused bool, width int, position int) uiMessage {\n\tvar styledAttachments []string\n\tt := theme.CurrentTheme()\n\tattachmentStyles := styles.BaseStyle().\n\t\tMarginLeft(1).\n\t\tBackground(t.TextMuted()).\n\t\tForeground(t.Text())\n\tfor _, attachment := range msg.BinaryContent() {\n\t\tfile := filepath.Base(attachment.Path)\n\t\tvar filename string\n\t\tif len(file) > 10 {\n\t\t\tfilename = fmt.Sprintf(\" %s %s...\", styles.DocumentIcon, file[0:7])\n\t\t} else {\n\t\t\tfilename = fmt.Sprintf(\" %s %s\", styles.DocumentIcon, file)\n\t\t}\n\t\tstyledAttachments = append(styledAttachments, attachmentStyles.Render(filename))\n\t}\n\tcontent := \"\"\n\tif len(styledAttachments) > 0 {\n\t\tattachmentContent := styles.BaseStyle().Width(width).Render(lipgloss.JoinHorizontal(lipgloss.Left, styledAttachments...))\n\t\tcontent = renderMessage(msg.Content().String(), true, isFocused, width, attachmentContent)\n\t} else {\n\t\tcontent = renderMessage(msg.Content().String(), true, isFocused, width)\n\t}\n\tuserMsg := uiMessage{\n\t\tID: msg.ID,\n\t\tmessageType: userMessageType,\n\t\tposition: position,\n\t\theight: lipgloss.Height(content),\n\t\tcontent: content,\n\t}\n\treturn userMsg\n}\n\n// Returns multiple uiMessages because of the tool calls\nfunc renderAssistantMessage(\n\tmsg message.Message,\n\tmsgIndex int,\n\tallMessages []message.Message, // we need this to get tool results and the user message\n\tmessagesService message.Service, // We need this to get the task tool messages\n\tfocusedUIMessageId string,\n\tisSummary bool,\n\twidth int,\n\tposition int,\n) []uiMessage {\n\tmessages := []uiMessage{}\n\tcontent := msg.Content().String()\n\tthinking := msg.IsThinking()\n\tthinkingContent := msg.ReasoningContent().Thinking\n\tfinished := msg.IsFinished()\n\tfinishData := msg.FinishPart()\n\tinfo := []string{}\n\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\n\t// Add finish info if available\n\tif finished {\n\t\tswitch finishData.Reason {\n\t\tcase message.FinishReasonEndTurn:\n\t\t\ttook := formatTimestampDiff(msg.CreatedAt, finishData.Time)\n\t\t\tinfo = append(info, baseStyle.\n\t\t\t\tWidth(width-1).\n\t\t\t\tForeground(t.TextMuted()).\n\t\t\t\tRender(fmt.Sprintf(\" %s (%s)\", models.SupportedModels[msg.Model].Name, took)),\n\t\t\t)\n\t\tcase message.FinishReasonCanceled:\n\t\t\tinfo = append(info, baseStyle.\n\t\t\t\tWidth(width-1).\n\t\t\t\tForeground(t.TextMuted()).\n\t\t\t\tRender(fmt.Sprintf(\" %s (%s)\", models.SupportedModels[msg.Model].Name, \"canceled\")),\n\t\t\t)\n\t\tcase message.FinishReasonError:\n\t\t\tinfo = append(info, baseStyle.\n\t\t\t\tWidth(width-1).\n\t\t\t\tForeground(t.TextMuted()).\n\t\t\t\tRender(fmt.Sprintf(\" %s (%s)\", models.SupportedModels[msg.Model].Name, \"error\")),\n\t\t\t)\n\t\tcase message.FinishReasonPermissionDenied:\n\t\t\tinfo = append(info, baseStyle.\n\t\t\t\tWidth(width-1).\n\t\t\t\tForeground(t.TextMuted()).\n\t\t\t\tRender(fmt.Sprintf(\" %s (%s)\", models.SupportedModels[msg.Model].Name, \"permission denied\")),\n\t\t\t)\n\t\t}\n\t}\n\tif content != \"\" || (finished && finishData.Reason == message.FinishReasonEndTurn) {\n\t\tif content == \"\" {\n\t\t\tcontent = \"*Finished without output*\"\n\t\t}\n\t\tif isSummary {\n\t\t\tinfo = append(info, baseStyle.Width(width-1).Foreground(t.TextMuted()).Render(\" (summary)\"))\n\t\t}\n\n\t\tcontent = renderMessage(content, false, true, width, info...)\n\t\tmessages = append(messages, uiMessage{\n\t\t\tID: msg.ID,\n\t\t\tmessageType: assistantMessageType,\n\t\t\tposition: position,\n\t\t\theight: lipgloss.Height(content),\n\t\t\tcontent: content,\n\t\t})\n\t\tposition += messages[0].height\n\t\tposition++ // for the space\n\t} else if thinking && thinkingContent != \"\" {\n\t\t// Render the thinking content\n\t\tcontent = renderMessage(thinkingContent, false, msg.ID == focusedUIMessageId, width)\n\t}\n\n\tfor i, toolCall := range msg.ToolCalls() {\n\t\ttoolCallContent := renderToolMessage(\n\t\t\ttoolCall,\n\t\t\tallMessages,\n\t\t\tmessagesService,\n\t\t\tfocusedUIMessageId,\n\t\t\tfalse,\n\t\t\twidth,\n\t\t\ti+1,\n\t\t)\n\t\tmessages = append(messages, toolCallContent)\n\t\tposition += toolCallContent.height\n\t\tposition++ // for the space\n\t}\n\treturn messages\n}\n\nfunc findToolResponse(toolCallID string, futureMessages []message.Message) *message.ToolResult {\n\tfor _, msg := range futureMessages {\n\t\tfor _, result := range msg.ToolResults() {\n\t\t\tif result.ToolCallID == toolCallID {\n\t\t\t\treturn &result\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc toolName(name string) string {\n\tswitch name {\n\tcase agent.AgentToolName:\n\t\treturn \"Task\"\n\tcase tools.BashToolName:\n\t\treturn \"Bash\"\n\tcase tools.EditToolName:\n\t\treturn \"Edit\"\n\tcase tools.FetchToolName:\n\t\treturn \"Fetch\"\n\tcase tools.GlobToolName:\n\t\treturn \"Glob\"\n\tcase tools.GrepToolName:\n\t\treturn \"Grep\"\n\tcase tools.LSToolName:\n\t\treturn \"List\"\n\tcase tools.SourcegraphToolName:\n\t\treturn \"Sourcegraph\"\n\tcase tools.ViewToolName:\n\t\treturn \"View\"\n\tcase tools.WriteToolName:\n\t\treturn \"Write\"\n\tcase tools.PatchToolName:\n\t\treturn \"Patch\"\n\t}\n\treturn name\n}\n\nfunc getToolAction(name string) string {\n\tswitch name {\n\tcase agent.AgentToolName:\n\t\treturn \"Preparing prompt...\"\n\tcase tools.BashToolName:\n\t\treturn \"Building command...\"\n\tcase tools.EditToolName:\n\t\treturn \"Preparing edit...\"\n\tcase tools.FetchToolName:\n\t\treturn \"Writing fetch...\"\n\tcase tools.GlobToolName:\n\t\treturn \"Finding files...\"\n\tcase tools.GrepToolName:\n\t\treturn \"Searching content...\"\n\tcase tools.LSToolName:\n\t\treturn \"Listing directory...\"\n\tcase tools.SourcegraphToolName:\n\t\treturn \"Searching code...\"\n\tcase tools.ViewToolName:\n\t\treturn \"Reading file...\"\n\tcase tools.WriteToolName:\n\t\treturn \"Preparing write...\"\n\tcase tools.PatchToolName:\n\t\treturn \"Preparing patch...\"\n\t}\n\treturn \"Working...\"\n}\n\n// renders params, params[0] (params[1]=params[2] ....)\nfunc renderParams(paramsWidth int, params ...string) string {\n\tif len(params) == 0 {\n\t\treturn \"\"\n\t}\n\tmainParam := params[0]\n\tif len(mainParam) > paramsWidth {\n\t\tmainParam = mainParam[:paramsWidth-3] + \"...\"\n\t}\n\n\tif len(params) == 1 {\n\t\treturn mainParam\n\t}\n\totherParams := params[1:]\n\t// create pairs of key/value\n\t// if odd number of params, the last one is a key without value\n\tif len(otherParams)%2 != 0 {\n\t\totherParams = append(otherParams, \"\")\n\t}\n\tparts := make([]string, 0, len(otherParams)/2)\n\tfor i := 0; i < len(otherParams); i += 2 {\n\t\tkey := otherParams[i]\n\t\tvalue := otherParams[i+1]\n\t\tif value == \"\" {\n\t\t\tcontinue\n\t\t}\n\t\tparts = append(parts, fmt.Sprintf(\"%s=%s\", key, value))\n\t}\n\n\tpartsRendered := strings.Join(parts, \", \")\n\tremainingWidth := paramsWidth - lipgloss.Width(partsRendered) - 5 // for the space\n\tif remainingWidth < 30 {\n\t\t// No space for the params, just show the main\n\t\treturn mainParam\n\t}\n\n\tif len(parts) > 0 {\n\t\tmainParam = fmt.Sprintf(\"%s (%s)\", mainParam, strings.Join(parts, \", \"))\n\t}\n\n\treturn ansi.Truncate(mainParam, paramsWidth, \"...\")\n}\n\nfunc removeWorkingDirPrefix(path string) string {\n\twd := config.WorkingDirectory()\n\tif strings.HasPrefix(path, wd) {\n\t\tpath = strings.TrimPrefix(path, wd)\n\t}\n\tif strings.HasPrefix(path, \"/\") {\n\t\tpath = strings.TrimPrefix(path, \"/\")\n\t}\n\tif strings.HasPrefix(path, \"./\") {\n\t\tpath = strings.TrimPrefix(path, \"./\")\n\t}\n\tif strings.HasPrefix(path, \"../\") {\n\t\tpath = strings.TrimPrefix(path, \"../\")\n\t}\n\treturn path\n}\n\nfunc renderToolParams(paramWidth int, toolCall message.ToolCall) string {\n\tparams := \"\"\n\tswitch toolCall.Name {\n\tcase agent.AgentToolName:\n\t\tvar params agent.AgentParams\n\t\tjson.Unmarshal([]byte(toolCall.Input), ¶ms)\n\t\tprompt := strings.ReplaceAll(params.Prompt, \"\\n\", \" \")\n\t\treturn renderParams(paramWidth, prompt)\n\tcase tools.BashToolName:\n\t\tvar params tools.BashParams\n\t\tjson.Unmarshal([]byte(toolCall.Input), ¶ms)\n\t\tcommand := strings.ReplaceAll(params.Command, \"\\n\", \" \")\n\t\treturn renderParams(paramWidth, command)\n\tcase tools.EditToolName:\n\t\tvar params tools.EditParams\n\t\tjson.Unmarshal([]byte(toolCall.Input), ¶ms)\n\t\tfilePath := removeWorkingDirPrefix(params.FilePath)\n\t\treturn renderParams(paramWidth, filePath)\n\tcase tools.FetchToolName:\n\t\tvar params tools.FetchParams\n\t\tjson.Unmarshal([]byte(toolCall.Input), ¶ms)\n\t\turl := params.URL\n\t\ttoolParams := []string{\n\t\t\turl,\n\t\t}\n\t\tif params.Format != \"\" {\n\t\t\ttoolParams = append(toolParams, \"format\", params.Format)\n\t\t}\n\t\tif params.Timeout != 0 {\n\t\t\ttoolParams = append(toolParams, \"timeout\", (time.Duration(params.Timeout) * time.Second).String())\n\t\t}\n\t\treturn renderParams(paramWidth, toolParams...)\n\tcase tools.GlobToolName:\n\t\tvar params tools.GlobParams\n\t\tjson.Unmarshal([]byte(toolCall.Input), ¶ms)\n\t\tpattern := params.Pattern\n\t\ttoolParams := []string{\n\t\t\tpattern,\n\t\t}\n\t\tif params.Path != \"\" {\n\t\t\ttoolParams = append(toolParams, \"path\", params.Path)\n\t\t}\n\t\treturn renderParams(paramWidth, toolParams...)\n\tcase tools.GrepToolName:\n\t\tvar params tools.GrepParams\n\t\tjson.Unmarshal([]byte(toolCall.Input), ¶ms)\n\t\tpattern := params.Pattern\n\t\ttoolParams := []string{\n\t\t\tpattern,\n\t\t}\n\t\tif params.Path != \"\" {\n\t\t\ttoolParams = append(toolParams, \"path\", params.Path)\n\t\t}\n\t\tif params.Include != \"\" {\n\t\t\ttoolParams = append(toolParams, \"include\", params.Include)\n\t\t}\n\t\tif params.LiteralText {\n\t\t\ttoolParams = append(toolParams, \"literal\", \"true\")\n\t\t}\n\t\treturn renderParams(paramWidth, toolParams...)\n\tcase tools.LSToolName:\n\t\tvar params tools.LSParams\n\t\tjson.Unmarshal([]byte(toolCall.Input), ¶ms)\n\t\tpath := params.Path\n\t\tif path == \"\" {\n\t\t\tpath = \".\"\n\t\t}\n\t\treturn renderParams(paramWidth, path)\n\tcase tools.SourcegraphToolName:\n\t\tvar params tools.SourcegraphParams\n\t\tjson.Unmarshal([]byte(toolCall.Input), ¶ms)\n\t\treturn renderParams(paramWidth, params.Query)\n\tcase tools.ViewToolName:\n\t\tvar params tools.ViewParams\n\t\tjson.Unmarshal([]byte(toolCall.Input), ¶ms)\n\t\tfilePath := removeWorkingDirPrefix(params.FilePath)\n\t\ttoolParams := []string{\n\t\t\tfilePath,\n\t\t}\n\t\tif params.Limit != 0 {\n\t\t\ttoolParams = append(toolParams, \"limit\", fmt.Sprintf(\"%d\", params.Limit))\n\t\t}\n\t\tif params.Offset != 0 {\n\t\t\ttoolParams = append(toolParams, \"offset\", fmt.Sprintf(\"%d\", params.Offset))\n\t\t}\n\t\treturn renderParams(paramWidth, toolParams...)\n\tcase tools.WriteToolName:\n\t\tvar params tools.WriteParams\n\t\tjson.Unmarshal([]byte(toolCall.Input), ¶ms)\n\t\tfilePath := removeWorkingDirPrefix(params.FilePath)\n\t\treturn renderParams(paramWidth, filePath)\n\tdefault:\n\t\tinput := strings.ReplaceAll(toolCall.Input, \"\\n\", \" \")\n\t\tparams = renderParams(paramWidth, input)\n\t}\n\treturn params\n}\n\nfunc truncateHeight(content string, height int) string {\n\tlines := strings.Split(content, \"\\n\")\n\tif len(lines) > height {\n\t\treturn strings.Join(lines[:height], \"\\n\")\n\t}\n\treturn content\n}\n\nfunc renderToolResponse(toolCall message.ToolCall, response message.ToolResult, width int) string {\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\n\tif response.IsError {\n\t\terrContent := fmt.Sprintf(\"Error: %s\", strings.ReplaceAll(response.Content, \"\\n\", \" \"))\n\t\terrContent = ansi.Truncate(errContent, width-1, \"...\")\n\t\treturn baseStyle.\n\t\t\tWidth(width).\n\t\t\tForeground(t.Error()).\n\t\t\tRender(errContent)\n\t}\n\n\tresultContent := truncateHeight(response.Content, maxResultHeight)\n\tswitch toolCall.Name {\n\tcase agent.AgentToolName:\n\t\treturn styles.ForceReplaceBackgroundWithLipgloss(\n\t\t\ttoMarkdown(resultContent, false, width),\n\t\t\tt.Background(),\n\t\t)\n\tcase tools.BashToolName:\n\t\tresultContent = fmt.Sprintf(\"```bash\\n%s\\n```\", resultContent)\n\t\treturn styles.ForceReplaceBackgroundWithLipgloss(\n\t\t\ttoMarkdown(resultContent, true, width),\n\t\t\tt.Background(),\n\t\t)\n\tcase tools.EditToolName:\n\t\tmetadata := tools.EditResponseMetadata{}\n\t\tjson.Unmarshal([]byte(response.Metadata), &metadata)\n\t\ttruncDiff := truncateHeight(metadata.Diff, maxResultHeight)\n\t\tformattedDiff, _ := diff.FormatDiff(truncDiff, diff.WithTotalWidth(width))\n\t\treturn formattedDiff\n\tcase tools.FetchToolName:\n\t\tvar params tools.FetchParams\n\t\tjson.Unmarshal([]byte(toolCall.Input), ¶ms)\n\t\tmdFormat := \"markdown\"\n\t\tswitch params.Format {\n\t\tcase \"text\":\n\t\t\tmdFormat = \"text\"\n\t\tcase \"html\":\n\t\t\tmdFormat = \"html\"\n\t\t}\n\t\tresultContent = fmt.Sprintf(\"```%s\\n%s\\n```\", mdFormat, resultContent)\n\t\treturn styles.ForceReplaceBackgroundWithLipgloss(\n\t\t\ttoMarkdown(resultContent, true, width),\n\t\t\tt.Background(),\n\t\t)\n\tcase tools.GlobToolName:\n\t\treturn baseStyle.Width(width).Foreground(t.TextMuted()).Render(resultContent)\n\tcase tools.GrepToolName:\n\t\treturn baseStyle.Width(width).Foreground(t.TextMuted()).Render(resultContent)\n\tcase tools.LSToolName:\n\t\treturn baseStyle.Width(width).Foreground(t.TextMuted()).Render(resultContent)\n\tcase tools.SourcegraphToolName:\n\t\treturn baseStyle.Width(width).Foreground(t.TextMuted()).Render(resultContent)\n\tcase tools.ViewToolName:\n\t\tmetadata := tools.ViewResponseMetadata{}\n\t\tjson.Unmarshal([]byte(response.Metadata), &metadata)\n\t\text := filepath.Ext(metadata.FilePath)\n\t\tif ext == \"\" {\n\t\t\text = \"\"\n\t\t} else {\n\t\t\text = strings.ToLower(ext[1:])\n\t\t}\n\t\tresultContent = fmt.Sprintf(\"```%s\\n%s\\n```\", ext, truncateHeight(metadata.Content, maxResultHeight))\n\t\treturn styles.ForceReplaceBackgroundWithLipgloss(\n\t\t\ttoMarkdown(resultContent, true, width),\n\t\t\tt.Background(),\n\t\t)\n\tcase tools.WriteToolName:\n\t\tparams := tools.WriteParams{}\n\t\tjson.Unmarshal([]byte(toolCall.Input), ¶ms)\n\t\tmetadata := tools.WriteResponseMetadata{}\n\t\tjson.Unmarshal([]byte(response.Metadata), &metadata)\n\t\text := filepath.Ext(params.FilePath)\n\t\tif ext == \"\" {\n\t\t\text = \"\"\n\t\t} else {\n\t\t\text = strings.ToLower(ext[1:])\n\t\t}\n\t\tresultContent = fmt.Sprintf(\"```%s\\n%s\\n```\", ext, truncateHeight(params.Content, maxResultHeight))\n\t\treturn styles.ForceReplaceBackgroundWithLipgloss(\n\t\t\ttoMarkdown(resultContent, true, width),\n\t\t\tt.Background(),\n\t\t)\n\tdefault:\n\t\tresultContent = fmt.Sprintf(\"```text\\n%s\\n```\", resultContent)\n\t\treturn styles.ForceReplaceBackgroundWithLipgloss(\n\t\t\ttoMarkdown(resultContent, true, width),\n\t\t\tt.Background(),\n\t\t)\n\t}\n}\n\nfunc renderToolMessage(\n\ttoolCall message.ToolCall,\n\tallMessages []message.Message,\n\tmessagesService message.Service,\n\tfocusedUIMessageId string,\n\tnested bool,\n\twidth int,\n\tposition int,\n) uiMessage {\n\tif nested {\n\t\twidth = width - 3\n\t}\n\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\n\tstyle := baseStyle.\n\t\tWidth(width - 1).\n\t\tBorderLeft(true).\n\t\tBorderStyle(lipgloss.ThickBorder()).\n\t\tPaddingLeft(1).\n\t\tBorderForeground(t.TextMuted())\n\n\tresponse := findToolResponse(toolCall.ID, allMessages)\n\ttoolNameText := baseStyle.Foreground(t.TextMuted()).\n\t\tRender(fmt.Sprintf(\"%s: \", toolName(toolCall.Name)))\n\n\tif !toolCall.Finished {\n\t\t// Get a brief description of what the tool is doing\n\t\ttoolAction := getToolAction(toolCall.Name)\n\n\t\tprogressText := baseStyle.\n\t\t\tWidth(width - 2 - lipgloss.Width(toolNameText)).\n\t\t\tForeground(t.TextMuted()).\n\t\t\tRender(fmt.Sprintf(\"%s\", toolAction))\n\n\t\tcontent := style.Render(lipgloss.JoinHorizontal(lipgloss.Left, toolNameText, progressText))\n\t\ttoolMsg := uiMessage{\n\t\t\tmessageType: toolMessageType,\n\t\t\tposition: position,\n\t\t\theight: lipgloss.Height(content),\n\t\t\tcontent: content,\n\t\t}\n\t\treturn toolMsg\n\t}\n\n\tparams := renderToolParams(width-2-lipgloss.Width(toolNameText), toolCall)\n\tresponseContent := \"\"\n\tif response != nil {\n\t\tresponseContent = renderToolResponse(toolCall, *response, width-2)\n\t\tresponseContent = strings.TrimSuffix(responseContent, \"\\n\")\n\t} else {\n\t\tresponseContent = baseStyle.\n\t\t\tItalic(true).\n\t\t\tWidth(width - 2).\n\t\t\tForeground(t.TextMuted()).\n\t\t\tRender(\"Waiting for response...\")\n\t}\n\n\tparts := []string{}\n\tif !nested {\n\t\tformattedParams := baseStyle.\n\t\t\tWidth(width - 2 - lipgloss.Width(toolNameText)).\n\t\t\tForeground(t.TextMuted()).\n\t\t\tRender(params)\n\n\t\tparts = append(parts, lipgloss.JoinHorizontal(lipgloss.Left, toolNameText, formattedParams))\n\t} else {\n\t\tprefix := baseStyle.\n\t\t\tForeground(t.TextMuted()).\n\t\t\tRender(\" └ \")\n\t\tformattedParams := baseStyle.\n\t\t\tWidth(width - 2 - lipgloss.Width(toolNameText)).\n\t\t\tForeground(t.TextMuted()).\n\t\t\tRender(params)\n\t\tparts = append(parts, lipgloss.JoinHorizontal(lipgloss.Left, prefix, toolNameText, formattedParams))\n\t}\n\n\tif toolCall.Name == agent.AgentToolName {\n\t\ttaskMessages, _ := messagesService.List(context.Background(), toolCall.ID)\n\t\ttoolCalls := []message.ToolCall{}\n\t\tfor _, v := range taskMessages {\n\t\t\ttoolCalls = append(toolCalls, v.ToolCalls()...)\n\t\t}\n\t\tfor _, call := range toolCalls {\n\t\t\trendered := renderToolMessage(call, []message.Message{}, messagesService, focusedUIMessageId, true, width, 0)\n\t\t\tparts = append(parts, rendered.content)\n\t\t}\n\t}\n\tif responseContent != \"\" && !nested {\n\t\tparts = append(parts, responseContent)\n\t}\n\n\tcontent := style.Render(\n\t\tlipgloss.JoinVertical(\n\t\t\tlipgloss.Left,\n\t\t\tparts...,\n\t\t),\n\t)\n\tif nested {\n\t\tcontent = lipgloss.JoinVertical(\n\t\t\tlipgloss.Left,\n\t\t\tparts...,\n\t\t)\n\t}\n\ttoolMsg := uiMessage{\n\t\tmessageType: toolMessageType,\n\t\tposition: position,\n\t\theight: lipgloss.Height(content),\n\t\tcontent: content,\n\t}\n\treturn toolMsg\n}\n\n// Helper function to format the time difference between two Unix timestamps\nfunc formatTimestampDiff(start, end int64) string {\n\tdiffSeconds := float64(end-start) / 1000.0 // Convert to seconds\n\tif diffSeconds < 1 {\n\t\treturn fmt.Sprintf(\"%dms\", int(diffSeconds*1000))\n\t}\n\tif diffSeconds < 60 {\n\t\treturn fmt.Sprintf(\"%.1fs\", diffSeconds)\n\t}\n\treturn fmt.Sprintf(\"%.1fm\", diffSeconds/60)\n}\n"], ["/opencode/internal/tui/components/chat/list.go", "package chat\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"math\"\n\n\t\"github.com/charmbracelet/bubbles/key\"\n\t\"github.com/charmbracelet/bubbles/spinner\"\n\t\"github.com/charmbracelet/bubbles/viewport\"\n\ttea \"github.com/charmbracelet/bubbletea\"\n\t\"github.com/charmbracelet/lipgloss\"\n\t\"github.com/opencode-ai/opencode/internal/app\"\n\t\"github.com/opencode-ai/opencode/internal/message\"\n\t\"github.com/opencode-ai/opencode/internal/pubsub\"\n\t\"github.com/opencode-ai/opencode/internal/session\"\n\t\"github.com/opencode-ai/opencode/internal/tui/components/dialog\"\n\t\"github.com/opencode-ai/opencode/internal/tui/styles\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n\t\"github.com/opencode-ai/opencode/internal/tui/util\"\n)\n\ntype cacheItem struct {\n\twidth int\n\tcontent []uiMessage\n}\ntype messagesCmp struct {\n\tapp *app.App\n\twidth, height int\n\tviewport viewport.Model\n\tsession session.Session\n\tmessages []message.Message\n\tuiMessages []uiMessage\n\tcurrentMsgID string\n\tcachedContent map[string]cacheItem\n\tspinner spinner.Model\n\trendering bool\n\tattachments viewport.Model\n}\ntype renderFinishedMsg struct{}\n\ntype MessageKeys struct {\n\tPageDown key.Binding\n\tPageUp key.Binding\n\tHalfPageUp key.Binding\n\tHalfPageDown key.Binding\n}\n\nvar messageKeys = MessageKeys{\n\tPageDown: key.NewBinding(\n\t\tkey.WithKeys(\"pgdown\"),\n\t\tkey.WithHelp(\"f/pgdn\", \"page down\"),\n\t),\n\tPageUp: key.NewBinding(\n\t\tkey.WithKeys(\"pgup\"),\n\t\tkey.WithHelp(\"b/pgup\", \"page up\"),\n\t),\n\tHalfPageUp: key.NewBinding(\n\t\tkey.WithKeys(\"ctrl+u\"),\n\t\tkey.WithHelp(\"ctrl+u\", \"½ page up\"),\n\t),\n\tHalfPageDown: key.NewBinding(\n\t\tkey.WithKeys(\"ctrl+d\", \"ctrl+d\"),\n\t\tkey.WithHelp(\"ctrl+d\", \"½ page down\"),\n\t),\n}\n\nfunc (m *messagesCmp) Init() tea.Cmd {\n\treturn tea.Batch(m.viewport.Init(), m.spinner.Tick)\n}\n\nfunc (m *messagesCmp) Update(msg tea.Msg) (tea.Model, tea.Cmd) {\n\tvar cmds []tea.Cmd\n\tswitch msg := msg.(type) {\n\tcase dialog.ThemeChangedMsg:\n\t\tm.rerender()\n\t\treturn m, nil\n\tcase SessionSelectedMsg:\n\t\tif msg.ID != m.session.ID {\n\t\t\tcmd := m.SetSession(msg)\n\t\t\treturn m, cmd\n\t\t}\n\t\treturn m, nil\n\tcase SessionClearedMsg:\n\t\tm.session = session.Session{}\n\t\tm.messages = make([]message.Message, 0)\n\t\tm.currentMsgID = \"\"\n\t\tm.rendering = false\n\t\treturn m, nil\n\n\tcase tea.KeyMsg:\n\t\tif key.Matches(msg, messageKeys.PageUp) || key.Matches(msg, messageKeys.PageDown) ||\n\t\t\tkey.Matches(msg, messageKeys.HalfPageUp) || key.Matches(msg, messageKeys.HalfPageDown) {\n\t\t\tu, cmd := m.viewport.Update(msg)\n\t\t\tm.viewport = u\n\t\t\tcmds = append(cmds, cmd)\n\t\t}\n\n\tcase renderFinishedMsg:\n\t\tm.rendering = false\n\t\tm.viewport.GotoBottom()\n\tcase pubsub.Event[session.Session]:\n\t\tif msg.Type == pubsub.UpdatedEvent && msg.Payload.ID == m.session.ID {\n\t\t\tm.session = msg.Payload\n\t\t\tif m.session.SummaryMessageID == m.currentMsgID {\n\t\t\t\tdelete(m.cachedContent, m.currentMsgID)\n\t\t\t\tm.renderView()\n\t\t\t}\n\t\t}\n\tcase pubsub.Event[message.Message]:\n\t\tneedsRerender := false\n\t\tif msg.Type == pubsub.CreatedEvent {\n\t\t\tif msg.Payload.SessionID == m.session.ID {\n\n\t\t\t\tmessageExists := false\n\t\t\t\tfor _, v := range m.messages {\n\t\t\t\t\tif v.ID == msg.Payload.ID {\n\t\t\t\t\t\tmessageExists = true\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif !messageExists {\n\t\t\t\t\tif len(m.messages) > 0 {\n\t\t\t\t\t\tlastMsgID := m.messages[len(m.messages)-1].ID\n\t\t\t\t\t\tdelete(m.cachedContent, lastMsgID)\n\t\t\t\t\t}\n\n\t\t\t\t\tm.messages = append(m.messages, msg.Payload)\n\t\t\t\t\tdelete(m.cachedContent, m.currentMsgID)\n\t\t\t\t\tm.currentMsgID = msg.Payload.ID\n\t\t\t\t\tneedsRerender = true\n\t\t\t\t}\n\t\t\t}\n\t\t\t// There are tool calls from the child task\n\t\t\tfor _, v := range m.messages {\n\t\t\t\tfor _, c := range v.ToolCalls() {\n\t\t\t\t\tif c.ID == msg.Payload.SessionID {\n\t\t\t\t\t\tdelete(m.cachedContent, v.ID)\n\t\t\t\t\t\tneedsRerender = true\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t} else if msg.Type == pubsub.UpdatedEvent && msg.Payload.SessionID == m.session.ID {\n\t\t\tfor i, v := range m.messages {\n\t\t\t\tif v.ID == msg.Payload.ID {\n\t\t\t\t\tm.messages[i] = msg.Payload\n\t\t\t\t\tdelete(m.cachedContent, msg.Payload.ID)\n\t\t\t\t\tneedsRerender = true\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif needsRerender {\n\t\t\tm.renderView()\n\t\t\tif len(m.messages) > 0 {\n\t\t\t\tif (msg.Type == pubsub.CreatedEvent) ||\n\t\t\t\t\t(msg.Type == pubsub.UpdatedEvent && msg.Payload.ID == m.messages[len(m.messages)-1].ID) {\n\t\t\t\t\tm.viewport.GotoBottom()\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tspinner, cmd := m.spinner.Update(msg)\n\tm.spinner = spinner\n\tcmds = append(cmds, cmd)\n\treturn m, tea.Batch(cmds...)\n}\n\nfunc (m *messagesCmp) IsAgentWorking() bool {\n\treturn m.app.CoderAgent.IsSessionBusy(m.session.ID)\n}\n\nfunc formatTimeDifference(unixTime1, unixTime2 int64) string {\n\tdiffSeconds := float64(math.Abs(float64(unixTime2 - unixTime1)))\n\n\tif diffSeconds < 60 {\n\t\treturn fmt.Sprintf(\"%.1fs\", diffSeconds)\n\t}\n\n\tminutes := int(diffSeconds / 60)\n\tseconds := int(diffSeconds) % 60\n\treturn fmt.Sprintf(\"%dm%ds\", minutes, seconds)\n}\n\nfunc (m *messagesCmp) renderView() {\n\tm.uiMessages = make([]uiMessage, 0)\n\tpos := 0\n\tbaseStyle := styles.BaseStyle()\n\n\tif m.width == 0 {\n\t\treturn\n\t}\n\tfor inx, msg := range m.messages {\n\t\tswitch msg.Role {\n\t\tcase message.User:\n\t\t\tif cache, ok := m.cachedContent[msg.ID]; ok && cache.width == m.width {\n\t\t\t\tm.uiMessages = append(m.uiMessages, cache.content...)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tuserMsg := renderUserMessage(\n\t\t\t\tmsg,\n\t\t\t\tmsg.ID == m.currentMsgID,\n\t\t\t\tm.width,\n\t\t\t\tpos,\n\t\t\t)\n\t\t\tm.uiMessages = append(m.uiMessages, userMsg)\n\t\t\tm.cachedContent[msg.ID] = cacheItem{\n\t\t\t\twidth: m.width,\n\t\t\t\tcontent: []uiMessage{userMsg},\n\t\t\t}\n\t\t\tpos += userMsg.height + 1 // + 1 for spacing\n\t\tcase message.Assistant:\n\t\t\tif cache, ok := m.cachedContent[msg.ID]; ok && cache.width == m.width {\n\t\t\t\tm.uiMessages = append(m.uiMessages, cache.content...)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tisSummary := m.session.SummaryMessageID == msg.ID\n\n\t\t\tassistantMessages := renderAssistantMessage(\n\t\t\t\tmsg,\n\t\t\t\tinx,\n\t\t\t\tm.messages,\n\t\t\t\tm.app.Messages,\n\t\t\t\tm.currentMsgID,\n\t\t\t\tisSummary,\n\t\t\t\tm.width,\n\t\t\t\tpos,\n\t\t\t)\n\t\t\tfor _, msg := range assistantMessages {\n\t\t\t\tm.uiMessages = append(m.uiMessages, msg)\n\t\t\t\tpos += msg.height + 1 // + 1 for spacing\n\t\t\t}\n\t\t\tm.cachedContent[msg.ID] = cacheItem{\n\t\t\t\twidth: m.width,\n\t\t\t\tcontent: assistantMessages,\n\t\t\t}\n\t\t}\n\t}\n\n\tmessages := make([]string, 0)\n\tfor _, v := range m.uiMessages {\n\t\tmessages = append(messages, lipgloss.JoinVertical(lipgloss.Left, v.content),\n\t\t\tbaseStyle.\n\t\t\t\tWidth(m.width).\n\t\t\t\tRender(\n\t\t\t\t\t\"\",\n\t\t\t\t),\n\t\t)\n\t}\n\n\tm.viewport.SetContent(\n\t\tbaseStyle.\n\t\t\tWidth(m.width).\n\t\t\tRender(\n\t\t\t\tlipgloss.JoinVertical(\n\t\t\t\t\tlipgloss.Top,\n\t\t\t\t\tmessages...,\n\t\t\t\t),\n\t\t\t),\n\t)\n}\n\nfunc (m *messagesCmp) View() string {\n\tbaseStyle := styles.BaseStyle()\n\n\tif m.rendering {\n\t\treturn baseStyle.\n\t\t\tWidth(m.width).\n\t\t\tRender(\n\t\t\t\tlipgloss.JoinVertical(\n\t\t\t\t\tlipgloss.Top,\n\t\t\t\t\t\"Loading...\",\n\t\t\t\t\tm.working(),\n\t\t\t\t\tm.help(),\n\t\t\t\t),\n\t\t\t)\n\t}\n\tif len(m.messages) == 0 {\n\t\tcontent := baseStyle.\n\t\t\tWidth(m.width).\n\t\t\tHeight(m.height - 1).\n\t\t\tRender(\n\t\t\t\tm.initialScreen(),\n\t\t\t)\n\n\t\treturn baseStyle.\n\t\t\tWidth(m.width).\n\t\t\tRender(\n\t\t\t\tlipgloss.JoinVertical(\n\t\t\t\t\tlipgloss.Top,\n\t\t\t\t\tcontent,\n\t\t\t\t\t\"\",\n\t\t\t\t\tm.help(),\n\t\t\t\t),\n\t\t\t)\n\t}\n\n\treturn baseStyle.\n\t\tWidth(m.width).\n\t\tRender(\n\t\t\tlipgloss.JoinVertical(\n\t\t\t\tlipgloss.Top,\n\t\t\t\tm.viewport.View(),\n\t\t\t\tm.working(),\n\t\t\t\tm.help(),\n\t\t\t),\n\t\t)\n}\n\nfunc hasToolsWithoutResponse(messages []message.Message) bool {\n\ttoolCalls := make([]message.ToolCall, 0)\n\ttoolResults := make([]message.ToolResult, 0)\n\tfor _, m := range messages {\n\t\ttoolCalls = append(toolCalls, m.ToolCalls()...)\n\t\ttoolResults = append(toolResults, m.ToolResults()...)\n\t}\n\n\tfor _, v := range toolCalls {\n\t\tfound := false\n\t\tfor _, r := range toolResults {\n\t\t\tif v.ID == r.ToolCallID {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif !found && v.Finished {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc hasUnfinishedToolCalls(messages []message.Message) bool {\n\ttoolCalls := make([]message.ToolCall, 0)\n\tfor _, m := range messages {\n\t\ttoolCalls = append(toolCalls, m.ToolCalls()...)\n\t}\n\tfor _, v := range toolCalls {\n\t\tif !v.Finished {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc (m *messagesCmp) working() string {\n\ttext := \"\"\n\tif m.IsAgentWorking() && len(m.messages) > 0 {\n\t\tt := theme.CurrentTheme()\n\t\tbaseStyle := styles.BaseStyle()\n\n\t\ttask := \"Thinking...\"\n\t\tlastMessage := m.messages[len(m.messages)-1]\n\t\tif hasToolsWithoutResponse(m.messages) {\n\t\t\ttask = \"Waiting for tool response...\"\n\t\t} else if hasUnfinishedToolCalls(m.messages) {\n\t\t\ttask = \"Building tool call...\"\n\t\t} else if !lastMessage.IsFinished() {\n\t\t\ttask = \"Generating...\"\n\t\t}\n\t\tif task != \"\" {\n\t\t\ttext += baseStyle.\n\t\t\t\tWidth(m.width).\n\t\t\t\tForeground(t.Primary()).\n\t\t\t\tBold(true).\n\t\t\t\tRender(fmt.Sprintf(\"%s %s \", m.spinner.View(), task))\n\t\t}\n\t}\n\treturn text\n}\n\nfunc (m *messagesCmp) help() string {\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\n\ttext := \"\"\n\n\tif m.app.CoderAgent.IsBusy() {\n\t\ttext += lipgloss.JoinHorizontal(\n\t\t\tlipgloss.Left,\n\t\t\tbaseStyle.Foreground(t.TextMuted()).Bold(true).Render(\"press \"),\n\t\t\tbaseStyle.Foreground(t.Text()).Bold(true).Render(\"esc\"),\n\t\t\tbaseStyle.Foreground(t.TextMuted()).Bold(true).Render(\" to exit cancel\"),\n\t\t)\n\t} else {\n\t\ttext += lipgloss.JoinHorizontal(\n\t\t\tlipgloss.Left,\n\t\t\tbaseStyle.Foreground(t.TextMuted()).Bold(true).Render(\"press \"),\n\t\t\tbaseStyle.Foreground(t.Text()).Bold(true).Render(\"enter\"),\n\t\t\tbaseStyle.Foreground(t.TextMuted()).Bold(true).Render(\" to send the message,\"),\n\t\t\tbaseStyle.Foreground(t.TextMuted()).Bold(true).Render(\" write\"),\n\t\t\tbaseStyle.Foreground(t.Text()).Bold(true).Render(\" \\\\\"),\n\t\t\tbaseStyle.Foreground(t.TextMuted()).Bold(true).Render(\" and enter to add a new line\"),\n\t\t)\n\t}\n\treturn baseStyle.\n\t\tWidth(m.width).\n\t\tRender(text)\n}\n\nfunc (m *messagesCmp) initialScreen() string {\n\tbaseStyle := styles.BaseStyle()\n\n\treturn baseStyle.Width(m.width).Render(\n\t\tlipgloss.JoinVertical(\n\t\t\tlipgloss.Top,\n\t\t\theader(m.width),\n\t\t\t\"\",\n\t\t\tlspsConfigured(m.width),\n\t\t),\n\t)\n}\n\nfunc (m *messagesCmp) rerender() {\n\tfor _, msg := range m.messages {\n\t\tdelete(m.cachedContent, msg.ID)\n\t}\n\tm.renderView()\n}\n\nfunc (m *messagesCmp) SetSize(width, height int) tea.Cmd {\n\tif m.width == width && m.height == height {\n\t\treturn nil\n\t}\n\tm.width = width\n\tm.height = height\n\tm.viewport.Width = width\n\tm.viewport.Height = height - 2\n\tm.attachments.Width = width + 40\n\tm.attachments.Height = 3\n\tm.rerender()\n\treturn nil\n}\n\nfunc (m *messagesCmp) GetSize() (int, int) {\n\treturn m.width, m.height\n}\n\nfunc (m *messagesCmp) SetSession(session session.Session) tea.Cmd {\n\tif m.session.ID == session.ID {\n\t\treturn nil\n\t}\n\tm.session = session\n\tmessages, err := m.app.Messages.List(context.Background(), session.ID)\n\tif err != nil {\n\t\treturn util.ReportError(err)\n\t}\n\tm.messages = messages\n\tif len(m.messages) > 0 {\n\t\tm.currentMsgID = m.messages[len(m.messages)-1].ID\n\t}\n\tdelete(m.cachedContent, m.currentMsgID)\n\tm.rendering = true\n\treturn func() tea.Msg {\n\t\tm.renderView()\n\t\treturn renderFinishedMsg{}\n\t}\n}\n\nfunc (m *messagesCmp) BindingKeys() []key.Binding {\n\treturn []key.Binding{\n\t\tm.viewport.KeyMap.PageDown,\n\t\tm.viewport.KeyMap.PageUp,\n\t\tm.viewport.KeyMap.HalfPageUp,\n\t\tm.viewport.KeyMap.HalfPageDown,\n\t}\n}\n\nfunc NewMessagesCmp(app *app.App) tea.Model {\n\ts := spinner.New()\n\ts.Spinner = spinner.Pulse\n\tvp := viewport.New(0, 0)\n\tattachmets := viewport.New(0, 0)\n\tvp.KeyMap.PageUp = messageKeys.PageUp\n\tvp.KeyMap.PageDown = messageKeys.PageDown\n\tvp.KeyMap.HalfPageUp = messageKeys.HalfPageUp\n\tvp.KeyMap.HalfPageDown = messageKeys.HalfPageDown\n\treturn &messagesCmp{\n\t\tapp: app,\n\t\tcachedContent: make(map[string]cacheItem),\n\t\tviewport: vp,\n\t\tspinner: s,\n\t\tattachments: attachmets,\n\t}\n}\n"], ["/opencode/internal/lsp/protocol/tsjson.go", "// Copyright 2023 The Go Authors. All rights reserved.\n// Use of this source code is governed by a BSD-style\n// license that can be found in the LICENSE file.\n\n// Code generated for LSP. DO NOT EDIT.\n\npackage protocol\n\n// Code generated from protocol/metaModel.json at ref release/protocol/3.17.6-next.9 (hash c94395b5da53729e6dff931293b051009ccaaaa4).\n// https://github.com/microsoft/vscode-languageserver-node/blob/release/protocol/3.17.6-next.9/protocol/metaModel.json\n// LSP metaData.version = 3.17.0.\n\nimport \"bytes\"\nimport \"encoding/json\"\n\nimport \"fmt\"\n\n// UnmarshalError indicates that a JSON value did not conform to\n// one of the expected cases of an LSP union type.\ntype UnmarshalError struct {\n\tmsg string\n}\n\nfunc (e UnmarshalError) Error() string {\n\treturn e.msg\n}\nfunc (t Or_CancelParams_id) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase int32:\n\t\treturn json.Marshal(x)\n\tcase string:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [int32 string]\", t)\n}\n\nfunc (t *Or_CancelParams_id) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder41 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder41.DisallowUnknownFields()\n\tvar int32Val int32\n\tif err := decoder41.Decode(&int32Val); err == nil {\n\t\tt.Value = int32Val\n\t\treturn nil\n\t}\n\tdecoder42 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder42.DisallowUnknownFields()\n\tvar stringVal string\n\tif err := decoder42.Decode(&stringVal); err == nil {\n\t\tt.Value = stringVal\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [int32 string]\"}\n}\n\nfunc (t Or_ClientSemanticTokensRequestOptions_full) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase ClientSemanticTokensRequestFullDelta:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [ClientSemanticTokensRequestFullDelta bool]\", t)\n}\n\nfunc (t *Or_ClientSemanticTokensRequestOptions_full) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder220 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder220.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder220.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder221 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder221.DisallowUnknownFields()\n\tvar h221 ClientSemanticTokensRequestFullDelta\n\tif err := decoder221.Decode(&h221); err == nil {\n\t\tt.Value = h221\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [ClientSemanticTokensRequestFullDelta bool]\"}\n}\n\nfunc (t Or_ClientSemanticTokensRequestOptions_range) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase Lit_ClientSemanticTokensRequestOptions_range_Item1:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [Lit_ClientSemanticTokensRequestOptions_range_Item1 bool]\", t)\n}\n\nfunc (t *Or_ClientSemanticTokensRequestOptions_range) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder217 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder217.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder217.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder218 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder218.DisallowUnknownFields()\n\tvar h218 Lit_ClientSemanticTokensRequestOptions_range_Item1\n\tif err := decoder218.Decode(&h218); err == nil {\n\t\tt.Value = h218\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [Lit_ClientSemanticTokensRequestOptions_range_Item1 bool]\"}\n}\n\nfunc (t Or_CompletionItemDefaults_editRange) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase EditRangeWithInsertReplace:\n\t\treturn json.Marshal(x)\n\tcase Range:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [EditRangeWithInsertReplace Range]\", t)\n}\n\nfunc (t *Or_CompletionItemDefaults_editRange) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder183 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder183.DisallowUnknownFields()\n\tvar h183 EditRangeWithInsertReplace\n\tif err := decoder183.Decode(&h183); err == nil {\n\t\tt.Value = h183\n\t\treturn nil\n\t}\n\tdecoder184 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder184.DisallowUnknownFields()\n\tvar h184 Range\n\tif err := decoder184.Decode(&h184); err == nil {\n\t\tt.Value = h184\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [EditRangeWithInsertReplace Range]\"}\n}\n\nfunc (t Or_CompletionItem_documentation) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase MarkupContent:\n\t\treturn json.Marshal(x)\n\tcase string:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [MarkupContent string]\", t)\n}\n\nfunc (t *Or_CompletionItem_documentation) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder25 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder25.DisallowUnknownFields()\n\tvar stringVal string\n\tif err := decoder25.Decode(&stringVal); err == nil {\n\t\tt.Value = stringVal\n\t\treturn nil\n\t}\n\tdecoder26 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder26.DisallowUnknownFields()\n\tvar h26 MarkupContent\n\tif err := decoder26.Decode(&h26); err == nil {\n\t\tt.Value = h26\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [MarkupContent string]\"}\n}\n\nfunc (t Or_CompletionItem_textEdit) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase InsertReplaceEdit:\n\t\treturn json.Marshal(x)\n\tcase TextEdit:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [InsertReplaceEdit TextEdit]\", t)\n}\n\nfunc (t *Or_CompletionItem_textEdit) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder29 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder29.DisallowUnknownFields()\n\tvar h29 InsertReplaceEdit\n\tif err := decoder29.Decode(&h29); err == nil {\n\t\tt.Value = h29\n\t\treturn nil\n\t}\n\tdecoder30 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder30.DisallowUnknownFields()\n\tvar h30 TextEdit\n\tif err := decoder30.Decode(&h30); err == nil {\n\t\tt.Value = h30\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [InsertReplaceEdit TextEdit]\"}\n}\n\nfunc (t Or_Declaration) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase Location:\n\t\treturn json.Marshal(x)\n\tcase []Location:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [Location []Location]\", t)\n}\n\nfunc (t *Or_Declaration) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder237 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder237.DisallowUnknownFields()\n\tvar h237 Location\n\tif err := decoder237.Decode(&h237); err == nil {\n\t\tt.Value = h237\n\t\treturn nil\n\t}\n\tdecoder238 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder238.DisallowUnknownFields()\n\tvar h238 []Location\n\tif err := decoder238.Decode(&h238); err == nil {\n\t\tt.Value = h238\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [Location []Location]\"}\n}\n\nfunc (t Or_Definition) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase Location:\n\t\treturn json.Marshal(x)\n\tcase []Location:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [Location []Location]\", t)\n}\n\nfunc (t *Or_Definition) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder224 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder224.DisallowUnknownFields()\n\tvar h224 Location\n\tif err := decoder224.Decode(&h224); err == nil {\n\t\tt.Value = h224\n\t\treturn nil\n\t}\n\tdecoder225 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder225.DisallowUnknownFields()\n\tvar h225 []Location\n\tif err := decoder225.Decode(&h225); err == nil {\n\t\tt.Value = h225\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [Location []Location]\"}\n}\n\nfunc (t Or_Diagnostic_code) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase int32:\n\t\treturn json.Marshal(x)\n\tcase string:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [int32 string]\", t)\n}\n\nfunc (t *Or_Diagnostic_code) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder179 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder179.DisallowUnknownFields()\n\tvar int32Val int32\n\tif err := decoder179.Decode(&int32Val); err == nil {\n\t\tt.Value = int32Val\n\t\treturn nil\n\t}\n\tdecoder180 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder180.DisallowUnknownFields()\n\tvar stringVal string\n\tif err := decoder180.Decode(&stringVal); err == nil {\n\t\tt.Value = stringVal\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [int32 string]\"}\n}\n\nfunc (t Or_DidChangeConfigurationRegistrationOptions_section) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase []string:\n\t\treturn json.Marshal(x)\n\tcase string:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [[]string string]\", t)\n}\n\nfunc (t *Or_DidChangeConfigurationRegistrationOptions_section) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder22 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder22.DisallowUnknownFields()\n\tvar stringVal string\n\tif err := decoder22.Decode(&stringVal); err == nil {\n\t\tt.Value = stringVal\n\t\treturn nil\n\t}\n\tdecoder23 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder23.DisallowUnknownFields()\n\tvar h23 []string\n\tif err := decoder23.Decode(&h23); err == nil {\n\t\tt.Value = h23\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [[]string string]\"}\n}\n\nfunc (t Or_DocumentDiagnosticReport) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase RelatedFullDocumentDiagnosticReport:\n\t\treturn json.Marshal(x)\n\tcase RelatedUnchangedDocumentDiagnosticReport:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [RelatedFullDocumentDiagnosticReport RelatedUnchangedDocumentDiagnosticReport]\", t)\n}\n\nfunc (t *Or_DocumentDiagnosticReport) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder247 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder247.DisallowUnknownFields()\n\tvar h247 RelatedFullDocumentDiagnosticReport\n\tif err := decoder247.Decode(&h247); err == nil {\n\t\tt.Value = h247\n\t\treturn nil\n\t}\n\tdecoder248 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder248.DisallowUnknownFields()\n\tvar h248 RelatedUnchangedDocumentDiagnosticReport\n\tif err := decoder248.Decode(&h248); err == nil {\n\t\tt.Value = h248\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [RelatedFullDocumentDiagnosticReport RelatedUnchangedDocumentDiagnosticReport]\"}\n}\n\nfunc (t Or_DocumentDiagnosticReportPartialResult_relatedDocuments_Value) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase FullDocumentDiagnosticReport:\n\t\treturn json.Marshal(x)\n\tcase UnchangedDocumentDiagnosticReport:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [FullDocumentDiagnosticReport UnchangedDocumentDiagnosticReport]\", t)\n}\n\nfunc (t *Or_DocumentDiagnosticReportPartialResult_relatedDocuments_Value) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder16 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder16.DisallowUnknownFields()\n\tvar h16 FullDocumentDiagnosticReport\n\tif err := decoder16.Decode(&h16); err == nil {\n\t\tt.Value = h16\n\t\treturn nil\n\t}\n\tdecoder17 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder17.DisallowUnknownFields()\n\tvar h17 UnchangedDocumentDiagnosticReport\n\tif err := decoder17.Decode(&h17); err == nil {\n\t\tt.Value = h17\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [FullDocumentDiagnosticReport UnchangedDocumentDiagnosticReport]\"}\n}\n\nfunc (t Or_DocumentFilter) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase NotebookCellTextDocumentFilter:\n\t\treturn json.Marshal(x)\n\tcase TextDocumentFilter:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [NotebookCellTextDocumentFilter TextDocumentFilter]\", t)\n}\n\nfunc (t *Or_DocumentFilter) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder270 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder270.DisallowUnknownFields()\n\tvar h270 NotebookCellTextDocumentFilter\n\tif err := decoder270.Decode(&h270); err == nil {\n\t\tt.Value = h270\n\t\treturn nil\n\t}\n\tdecoder271 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder271.DisallowUnknownFields()\n\tvar h271 TextDocumentFilter\n\tif err := decoder271.Decode(&h271); err == nil {\n\t\tt.Value = h271\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [NotebookCellTextDocumentFilter TextDocumentFilter]\"}\n}\n\nfunc (t Or_GlobPattern) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase Pattern:\n\t\treturn json.Marshal(x)\n\tcase RelativePattern:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [Pattern RelativePattern]\", t)\n}\n\nfunc (t *Or_GlobPattern) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder274 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder274.DisallowUnknownFields()\n\tvar h274 Pattern\n\tif err := decoder274.Decode(&h274); err == nil {\n\t\tt.Value = h274\n\t\treturn nil\n\t}\n\tdecoder275 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder275.DisallowUnknownFields()\n\tvar h275 RelativePattern\n\tif err := decoder275.Decode(&h275); err == nil {\n\t\tt.Value = h275\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [Pattern RelativePattern]\"}\n}\n\nfunc (t Or_Hover_contents) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase MarkedString:\n\t\treturn json.Marshal(x)\n\tcase MarkupContent:\n\t\treturn json.Marshal(x)\n\tcase []MarkedString:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [MarkedString MarkupContent []MarkedString]\", t)\n}\n\nfunc (t *Or_Hover_contents) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder34 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder34.DisallowUnknownFields()\n\tvar h34 MarkedString\n\tif err := decoder34.Decode(&h34); err == nil {\n\t\tt.Value = h34\n\t\treturn nil\n\t}\n\tdecoder35 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder35.DisallowUnknownFields()\n\tvar h35 MarkupContent\n\tif err := decoder35.Decode(&h35); err == nil {\n\t\tt.Value = h35\n\t\treturn nil\n\t}\n\tdecoder36 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder36.DisallowUnknownFields()\n\tvar h36 []MarkedString\n\tif err := decoder36.Decode(&h36); err == nil {\n\t\tt.Value = h36\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [MarkedString MarkupContent []MarkedString]\"}\n}\n\nfunc (t Or_InlayHintLabelPart_tooltip) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase MarkupContent:\n\t\treturn json.Marshal(x)\n\tcase string:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [MarkupContent string]\", t)\n}\n\nfunc (t *Or_InlayHintLabelPart_tooltip) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder56 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder56.DisallowUnknownFields()\n\tvar stringVal string\n\tif err := decoder56.Decode(&stringVal); err == nil {\n\t\tt.Value = stringVal\n\t\treturn nil\n\t}\n\tdecoder57 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder57.DisallowUnknownFields()\n\tvar h57 MarkupContent\n\tif err := decoder57.Decode(&h57); err == nil {\n\t\tt.Value = h57\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [MarkupContent string]\"}\n}\n\nfunc (t Or_InlayHint_label) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase []InlayHintLabelPart:\n\t\treturn json.Marshal(x)\n\tcase string:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [[]InlayHintLabelPart string]\", t)\n}\n\nfunc (t *Or_InlayHint_label) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder9 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder9.DisallowUnknownFields()\n\tvar stringVal string\n\tif err := decoder9.Decode(&stringVal); err == nil {\n\t\tt.Value = stringVal\n\t\treturn nil\n\t}\n\tdecoder10 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder10.DisallowUnknownFields()\n\tvar h10 []InlayHintLabelPart\n\tif err := decoder10.Decode(&h10); err == nil {\n\t\tt.Value = h10\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [[]InlayHintLabelPart string]\"}\n}\n\nfunc (t Or_InlayHint_tooltip) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase MarkupContent:\n\t\treturn json.Marshal(x)\n\tcase string:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [MarkupContent string]\", t)\n}\n\nfunc (t *Or_InlayHint_tooltip) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder12 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder12.DisallowUnknownFields()\n\tvar stringVal string\n\tif err := decoder12.Decode(&stringVal); err == nil {\n\t\tt.Value = stringVal\n\t\treturn nil\n\t}\n\tdecoder13 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder13.DisallowUnknownFields()\n\tvar h13 MarkupContent\n\tif err := decoder13.Decode(&h13); err == nil {\n\t\tt.Value = h13\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [MarkupContent string]\"}\n}\n\nfunc (t Or_InlineCompletionItem_insertText) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase StringValue:\n\t\treturn json.Marshal(x)\n\tcase string:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [StringValue string]\", t)\n}\n\nfunc (t *Or_InlineCompletionItem_insertText) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder19 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder19.DisallowUnknownFields()\n\tvar stringVal string\n\tif err := decoder19.Decode(&stringVal); err == nil {\n\t\tt.Value = stringVal\n\t\treturn nil\n\t}\n\tdecoder20 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder20.DisallowUnknownFields()\n\tvar h20 StringValue\n\tif err := decoder20.Decode(&h20); err == nil {\n\t\tt.Value = h20\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [StringValue string]\"}\n}\n\nfunc (t Or_InlineValue) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase InlineValueEvaluatableExpression:\n\t\treturn json.Marshal(x)\n\tcase InlineValueText:\n\t\treturn json.Marshal(x)\n\tcase InlineValueVariableLookup:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [InlineValueEvaluatableExpression InlineValueText InlineValueVariableLookup]\", t)\n}\n\nfunc (t *Or_InlineValue) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder242 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder242.DisallowUnknownFields()\n\tvar h242 InlineValueEvaluatableExpression\n\tif err := decoder242.Decode(&h242); err == nil {\n\t\tt.Value = h242\n\t\treturn nil\n\t}\n\tdecoder243 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder243.DisallowUnknownFields()\n\tvar h243 InlineValueText\n\tif err := decoder243.Decode(&h243); err == nil {\n\t\tt.Value = h243\n\t\treturn nil\n\t}\n\tdecoder244 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder244.DisallowUnknownFields()\n\tvar h244 InlineValueVariableLookup\n\tif err := decoder244.Decode(&h244); err == nil {\n\t\tt.Value = h244\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [InlineValueEvaluatableExpression InlineValueText InlineValueVariableLookup]\"}\n}\n\nfunc (t Or_LSPAny) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase LSPArray:\n\t\treturn json.Marshal(x)\n\tcase LSPObject:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase float64:\n\t\treturn json.Marshal(x)\n\tcase int32:\n\t\treturn json.Marshal(x)\n\tcase string:\n\t\treturn json.Marshal(x)\n\tcase uint32:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [LSPArray LSPObject bool float64 int32 string uint32]\", t)\n}\n\nfunc (t *Or_LSPAny) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder228 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder228.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder228.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder229 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder229.DisallowUnknownFields()\n\tvar float64Val float64\n\tif err := decoder229.Decode(&float64Val); err == nil {\n\t\tt.Value = float64Val\n\t\treturn nil\n\t}\n\tdecoder230 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder230.DisallowUnknownFields()\n\tvar int32Val int32\n\tif err := decoder230.Decode(&int32Val); err == nil {\n\t\tt.Value = int32Val\n\t\treturn nil\n\t}\n\tdecoder231 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder231.DisallowUnknownFields()\n\tvar stringVal string\n\tif err := decoder231.Decode(&stringVal); err == nil {\n\t\tt.Value = stringVal\n\t\treturn nil\n\t}\n\tdecoder232 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder232.DisallowUnknownFields()\n\tvar uint32Val uint32\n\tif err := decoder232.Decode(&uint32Val); err == nil {\n\t\tt.Value = uint32Val\n\t\treturn nil\n\t}\n\tdecoder233 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder233.DisallowUnknownFields()\n\tvar h233 LSPArray\n\tif err := decoder233.Decode(&h233); err == nil {\n\t\tt.Value = h233\n\t\treturn nil\n\t}\n\tdecoder234 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder234.DisallowUnknownFields()\n\tvar h234 LSPObject\n\tif err := decoder234.Decode(&h234); err == nil {\n\t\tt.Value = h234\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [LSPArray LSPObject bool float64 int32 string uint32]\"}\n}\n\nfunc (t Or_MarkedString) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase MarkedStringWithLanguage:\n\t\treturn json.Marshal(x)\n\tcase string:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [MarkedStringWithLanguage string]\", t)\n}\n\nfunc (t *Or_MarkedString) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder266 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder266.DisallowUnknownFields()\n\tvar stringVal string\n\tif err := decoder266.Decode(&stringVal); err == nil {\n\t\tt.Value = stringVal\n\t\treturn nil\n\t}\n\tdecoder267 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder267.DisallowUnknownFields()\n\tvar h267 MarkedStringWithLanguage\n\tif err := decoder267.Decode(&h267); err == nil {\n\t\tt.Value = h267\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [MarkedStringWithLanguage string]\"}\n}\n\nfunc (t Or_NotebookCellTextDocumentFilter_notebook) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase NotebookDocumentFilter:\n\t\treturn json.Marshal(x)\n\tcase string:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [NotebookDocumentFilter string]\", t)\n}\n\nfunc (t *Or_NotebookCellTextDocumentFilter_notebook) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder208 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder208.DisallowUnknownFields()\n\tvar stringVal string\n\tif err := decoder208.Decode(&stringVal); err == nil {\n\t\tt.Value = stringVal\n\t\treturn nil\n\t}\n\tdecoder209 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder209.DisallowUnknownFields()\n\tvar h209 NotebookDocumentFilter\n\tif err := decoder209.Decode(&h209); err == nil {\n\t\tt.Value = h209\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [NotebookDocumentFilter string]\"}\n}\n\nfunc (t Or_NotebookDocumentFilter) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase NotebookDocumentFilterNotebookType:\n\t\treturn json.Marshal(x)\n\tcase NotebookDocumentFilterPattern:\n\t\treturn json.Marshal(x)\n\tcase NotebookDocumentFilterScheme:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [NotebookDocumentFilterNotebookType NotebookDocumentFilterPattern NotebookDocumentFilterScheme]\", t)\n}\n\nfunc (t *Or_NotebookDocumentFilter) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder285 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder285.DisallowUnknownFields()\n\tvar h285 NotebookDocumentFilterNotebookType\n\tif err := decoder285.Decode(&h285); err == nil {\n\t\tt.Value = h285\n\t\treturn nil\n\t}\n\tdecoder286 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder286.DisallowUnknownFields()\n\tvar h286 NotebookDocumentFilterPattern\n\tif err := decoder286.Decode(&h286); err == nil {\n\t\tt.Value = h286\n\t\treturn nil\n\t}\n\tdecoder287 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder287.DisallowUnknownFields()\n\tvar h287 NotebookDocumentFilterScheme\n\tif err := decoder287.Decode(&h287); err == nil {\n\t\tt.Value = h287\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [NotebookDocumentFilterNotebookType NotebookDocumentFilterPattern NotebookDocumentFilterScheme]\"}\n}\n\nfunc (t Or_NotebookDocumentFilterWithCells_notebook) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase NotebookDocumentFilter:\n\t\treturn json.Marshal(x)\n\tcase string:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [NotebookDocumentFilter string]\", t)\n}\n\nfunc (t *Or_NotebookDocumentFilterWithCells_notebook) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder192 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder192.DisallowUnknownFields()\n\tvar stringVal string\n\tif err := decoder192.Decode(&stringVal); err == nil {\n\t\tt.Value = stringVal\n\t\treturn nil\n\t}\n\tdecoder193 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder193.DisallowUnknownFields()\n\tvar h193 NotebookDocumentFilter\n\tif err := decoder193.Decode(&h193); err == nil {\n\t\tt.Value = h193\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [NotebookDocumentFilter string]\"}\n}\n\nfunc (t Or_NotebookDocumentFilterWithNotebook_notebook) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase NotebookDocumentFilter:\n\t\treturn json.Marshal(x)\n\tcase string:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [NotebookDocumentFilter string]\", t)\n}\n\nfunc (t *Or_NotebookDocumentFilterWithNotebook_notebook) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder189 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder189.DisallowUnknownFields()\n\tvar stringVal string\n\tif err := decoder189.Decode(&stringVal); err == nil {\n\t\tt.Value = stringVal\n\t\treturn nil\n\t}\n\tdecoder190 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder190.DisallowUnknownFields()\n\tvar h190 NotebookDocumentFilter\n\tif err := decoder190.Decode(&h190); err == nil {\n\t\tt.Value = h190\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [NotebookDocumentFilter string]\"}\n}\n\nfunc (t Or_NotebookDocumentSyncOptions_notebookSelector_Elem) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase NotebookDocumentFilterWithCells:\n\t\treturn json.Marshal(x)\n\tcase NotebookDocumentFilterWithNotebook:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [NotebookDocumentFilterWithCells NotebookDocumentFilterWithNotebook]\", t)\n}\n\nfunc (t *Or_NotebookDocumentSyncOptions_notebookSelector_Elem) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder68 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder68.DisallowUnknownFields()\n\tvar h68 NotebookDocumentFilterWithCells\n\tif err := decoder68.Decode(&h68); err == nil {\n\t\tt.Value = h68\n\t\treturn nil\n\t}\n\tdecoder69 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder69.DisallowUnknownFields()\n\tvar h69 NotebookDocumentFilterWithNotebook\n\tif err := decoder69.Decode(&h69); err == nil {\n\t\tt.Value = h69\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [NotebookDocumentFilterWithCells NotebookDocumentFilterWithNotebook]\"}\n}\n\nfunc (t Or_ParameterInformation_documentation) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase MarkupContent:\n\t\treturn json.Marshal(x)\n\tcase string:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [MarkupContent string]\", t)\n}\n\nfunc (t *Or_ParameterInformation_documentation) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder205 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder205.DisallowUnknownFields()\n\tvar stringVal string\n\tif err := decoder205.Decode(&stringVal); err == nil {\n\t\tt.Value = stringVal\n\t\treturn nil\n\t}\n\tdecoder206 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder206.DisallowUnknownFields()\n\tvar h206 MarkupContent\n\tif err := decoder206.Decode(&h206); err == nil {\n\t\tt.Value = h206\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [MarkupContent string]\"}\n}\n\nfunc (t Or_ParameterInformation_label) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase Tuple_ParameterInformation_label_Item1:\n\t\treturn json.Marshal(x)\n\tcase string:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [Tuple_ParameterInformation_label_Item1 string]\", t)\n}\n\nfunc (t *Or_ParameterInformation_label) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder202 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder202.DisallowUnknownFields()\n\tvar stringVal string\n\tif err := decoder202.Decode(&stringVal); err == nil {\n\t\tt.Value = stringVal\n\t\treturn nil\n\t}\n\tdecoder203 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder203.DisallowUnknownFields()\n\tvar h203 Tuple_ParameterInformation_label_Item1\n\tif err := decoder203.Decode(&h203); err == nil {\n\t\tt.Value = h203\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [Tuple_ParameterInformation_label_Item1 string]\"}\n}\n\nfunc (t Or_PrepareRenameResult) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase PrepareRenameDefaultBehavior:\n\t\treturn json.Marshal(x)\n\tcase PrepareRenamePlaceholder:\n\t\treturn json.Marshal(x)\n\tcase Range:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [PrepareRenameDefaultBehavior PrepareRenamePlaceholder Range]\", t)\n}\n\nfunc (t *Or_PrepareRenameResult) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder252 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder252.DisallowUnknownFields()\n\tvar h252 PrepareRenameDefaultBehavior\n\tif err := decoder252.Decode(&h252); err == nil {\n\t\tt.Value = h252\n\t\treturn nil\n\t}\n\tdecoder253 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder253.DisallowUnknownFields()\n\tvar h253 PrepareRenamePlaceholder\n\tif err := decoder253.Decode(&h253); err == nil {\n\t\tt.Value = h253\n\t\treturn nil\n\t}\n\tdecoder254 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder254.DisallowUnknownFields()\n\tvar h254 Range\n\tif err := decoder254.Decode(&h254); err == nil {\n\t\tt.Value = h254\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [PrepareRenameDefaultBehavior PrepareRenamePlaceholder Range]\"}\n}\n\nfunc (t Or_ProgressToken) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase int32:\n\t\treturn json.Marshal(x)\n\tcase string:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [int32 string]\", t)\n}\n\nfunc (t *Or_ProgressToken) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder255 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder255.DisallowUnknownFields()\n\tvar int32Val int32\n\tif err := decoder255.Decode(&int32Val); err == nil {\n\t\tt.Value = int32Val\n\t\treturn nil\n\t}\n\tdecoder256 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder256.DisallowUnknownFields()\n\tvar stringVal string\n\tif err := decoder256.Decode(&stringVal); err == nil {\n\t\tt.Value = stringVal\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [int32 string]\"}\n}\n\nfunc (t Or_RelatedFullDocumentDiagnosticReport_relatedDocuments_Value) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase FullDocumentDiagnosticReport:\n\t\treturn json.Marshal(x)\n\tcase UnchangedDocumentDiagnosticReport:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [FullDocumentDiagnosticReport UnchangedDocumentDiagnosticReport]\", t)\n}\n\nfunc (t *Or_RelatedFullDocumentDiagnosticReport_relatedDocuments_Value) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder60 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder60.DisallowUnknownFields()\n\tvar h60 FullDocumentDiagnosticReport\n\tif err := decoder60.Decode(&h60); err == nil {\n\t\tt.Value = h60\n\t\treturn nil\n\t}\n\tdecoder61 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder61.DisallowUnknownFields()\n\tvar h61 UnchangedDocumentDiagnosticReport\n\tif err := decoder61.Decode(&h61); err == nil {\n\t\tt.Value = h61\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [FullDocumentDiagnosticReport UnchangedDocumentDiagnosticReport]\"}\n}\n\nfunc (t Or_RelatedUnchangedDocumentDiagnosticReport_relatedDocuments_Value) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase FullDocumentDiagnosticReport:\n\t\treturn json.Marshal(x)\n\tcase UnchangedDocumentDiagnosticReport:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [FullDocumentDiagnosticReport UnchangedDocumentDiagnosticReport]\", t)\n}\n\nfunc (t *Or_RelatedUnchangedDocumentDiagnosticReport_relatedDocuments_Value) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder64 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder64.DisallowUnknownFields()\n\tvar h64 FullDocumentDiagnosticReport\n\tif err := decoder64.Decode(&h64); err == nil {\n\t\tt.Value = h64\n\t\treturn nil\n\t}\n\tdecoder65 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder65.DisallowUnknownFields()\n\tvar h65 UnchangedDocumentDiagnosticReport\n\tif err := decoder65.Decode(&h65); err == nil {\n\t\tt.Value = h65\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [FullDocumentDiagnosticReport UnchangedDocumentDiagnosticReport]\"}\n}\n\nfunc (t Or_RelativePattern_baseUri) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase URI:\n\t\treturn json.Marshal(x)\n\tcase WorkspaceFolder:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [URI WorkspaceFolder]\", t)\n}\n\nfunc (t *Or_RelativePattern_baseUri) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder214 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder214.DisallowUnknownFields()\n\tvar h214 URI\n\tif err := decoder214.Decode(&h214); err == nil {\n\t\tt.Value = h214\n\t\treturn nil\n\t}\n\tdecoder215 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder215.DisallowUnknownFields()\n\tvar h215 WorkspaceFolder\n\tif err := decoder215.Decode(&h215); err == nil {\n\t\tt.Value = h215\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [URI WorkspaceFolder]\"}\n}\n\nfunc (t Or_Result_textDocument_codeAction_Item0_Elem) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase CodeAction:\n\t\treturn json.Marshal(x)\n\tcase Command:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [CodeAction Command]\", t)\n}\n\nfunc (t *Or_Result_textDocument_codeAction_Item0_Elem) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder322 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder322.DisallowUnknownFields()\n\tvar h322 CodeAction\n\tif err := decoder322.Decode(&h322); err == nil {\n\t\tt.Value = h322\n\t\treturn nil\n\t}\n\tdecoder323 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder323.DisallowUnknownFields()\n\tvar h323 Command\n\tif err := decoder323.Decode(&h323); err == nil {\n\t\tt.Value = h323\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [CodeAction Command]\"}\n}\n\nfunc (t Or_Result_textDocument_completion) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase CompletionList:\n\t\treturn json.Marshal(x)\n\tcase []CompletionItem:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [CompletionList []CompletionItem]\", t)\n}\n\nfunc (t *Or_Result_textDocument_completion) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder310 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder310.DisallowUnknownFields()\n\tvar h310 CompletionList\n\tif err := decoder310.Decode(&h310); err == nil {\n\t\tt.Value = h310\n\t\treturn nil\n\t}\n\tdecoder311 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder311.DisallowUnknownFields()\n\tvar h311 []CompletionItem\n\tif err := decoder311.Decode(&h311); err == nil {\n\t\tt.Value = h311\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [CompletionList []CompletionItem]\"}\n}\n\nfunc (t Or_Result_textDocument_declaration) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase Declaration:\n\t\treturn json.Marshal(x)\n\tcase []DeclarationLink:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [Declaration []DeclarationLink]\", t)\n}\n\nfunc (t *Or_Result_textDocument_declaration) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder298 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder298.DisallowUnknownFields()\n\tvar h298 Declaration\n\tif err := decoder298.Decode(&h298); err == nil {\n\t\tt.Value = h298\n\t\treturn nil\n\t}\n\tdecoder299 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder299.DisallowUnknownFields()\n\tvar h299 []DeclarationLink\n\tif err := decoder299.Decode(&h299); err == nil {\n\t\tt.Value = h299\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [Declaration []DeclarationLink]\"}\n}\n\nfunc (t Or_Result_textDocument_definition) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase Definition:\n\t\treturn json.Marshal(x)\n\tcase []DefinitionLink:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [Definition []DefinitionLink]\", t)\n}\n\nfunc (t *Or_Result_textDocument_definition) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder314 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder314.DisallowUnknownFields()\n\tvar h314 Definition\n\tif err := decoder314.Decode(&h314); err == nil {\n\t\tt.Value = h314\n\t\treturn nil\n\t}\n\tdecoder315 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder315.DisallowUnknownFields()\n\tvar h315 []DefinitionLink\n\tif err := decoder315.Decode(&h315); err == nil {\n\t\tt.Value = h315\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [Definition []DefinitionLink]\"}\n}\n\nfunc (t Or_Result_textDocument_documentSymbol) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase []DocumentSymbol:\n\t\treturn json.Marshal(x)\n\tcase []SymbolInformation:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [[]DocumentSymbol []SymbolInformation]\", t)\n}\n\nfunc (t *Or_Result_textDocument_documentSymbol) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder318 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder318.DisallowUnknownFields()\n\tvar h318 []DocumentSymbol\n\tif err := decoder318.Decode(&h318); err == nil {\n\t\tt.Value = h318\n\t\treturn nil\n\t}\n\tdecoder319 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder319.DisallowUnknownFields()\n\tvar h319 []SymbolInformation\n\tif err := decoder319.Decode(&h319); err == nil {\n\t\tt.Value = h319\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [[]DocumentSymbol []SymbolInformation]\"}\n}\n\nfunc (t Or_Result_textDocument_implementation) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase Definition:\n\t\treturn json.Marshal(x)\n\tcase []DefinitionLink:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [Definition []DefinitionLink]\", t)\n}\n\nfunc (t *Or_Result_textDocument_implementation) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder290 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder290.DisallowUnknownFields()\n\tvar h290 Definition\n\tif err := decoder290.Decode(&h290); err == nil {\n\t\tt.Value = h290\n\t\treturn nil\n\t}\n\tdecoder291 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder291.DisallowUnknownFields()\n\tvar h291 []DefinitionLink\n\tif err := decoder291.Decode(&h291); err == nil {\n\t\tt.Value = h291\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [Definition []DefinitionLink]\"}\n}\n\nfunc (t Or_Result_textDocument_inlineCompletion) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase InlineCompletionList:\n\t\treturn json.Marshal(x)\n\tcase []InlineCompletionItem:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [InlineCompletionList []InlineCompletionItem]\", t)\n}\n\nfunc (t *Or_Result_textDocument_inlineCompletion) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder306 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder306.DisallowUnknownFields()\n\tvar h306 InlineCompletionList\n\tif err := decoder306.Decode(&h306); err == nil {\n\t\tt.Value = h306\n\t\treturn nil\n\t}\n\tdecoder307 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder307.DisallowUnknownFields()\n\tvar h307 []InlineCompletionItem\n\tif err := decoder307.Decode(&h307); err == nil {\n\t\tt.Value = h307\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [InlineCompletionList []InlineCompletionItem]\"}\n}\n\nfunc (t Or_Result_textDocument_semanticTokens_full_delta) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase SemanticTokens:\n\t\treturn json.Marshal(x)\n\tcase SemanticTokensDelta:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [SemanticTokens SemanticTokensDelta]\", t)\n}\n\nfunc (t *Or_Result_textDocument_semanticTokens_full_delta) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder302 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder302.DisallowUnknownFields()\n\tvar h302 SemanticTokens\n\tif err := decoder302.Decode(&h302); err == nil {\n\t\tt.Value = h302\n\t\treturn nil\n\t}\n\tdecoder303 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder303.DisallowUnknownFields()\n\tvar h303 SemanticTokensDelta\n\tif err := decoder303.Decode(&h303); err == nil {\n\t\tt.Value = h303\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [SemanticTokens SemanticTokensDelta]\"}\n}\n\nfunc (t Or_Result_textDocument_typeDefinition) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase Definition:\n\t\treturn json.Marshal(x)\n\tcase []DefinitionLink:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [Definition []DefinitionLink]\", t)\n}\n\nfunc (t *Or_Result_textDocument_typeDefinition) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder294 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder294.DisallowUnknownFields()\n\tvar h294 Definition\n\tif err := decoder294.Decode(&h294); err == nil {\n\t\tt.Value = h294\n\t\treturn nil\n\t}\n\tdecoder295 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder295.DisallowUnknownFields()\n\tvar h295 []DefinitionLink\n\tif err := decoder295.Decode(&h295); err == nil {\n\t\tt.Value = h295\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [Definition []DefinitionLink]\"}\n}\n\nfunc (t Or_Result_workspace_symbol) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase []SymbolInformation:\n\t\treturn json.Marshal(x)\n\tcase []WorkspaceSymbol:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [[]SymbolInformation []WorkspaceSymbol]\", t)\n}\n\nfunc (t *Or_Result_workspace_symbol) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder326 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder326.DisallowUnknownFields()\n\tvar h326 []SymbolInformation\n\tif err := decoder326.Decode(&h326); err == nil {\n\t\tt.Value = h326\n\t\treturn nil\n\t}\n\tdecoder327 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder327.DisallowUnknownFields()\n\tvar h327 []WorkspaceSymbol\n\tif err := decoder327.Decode(&h327); err == nil {\n\t\tt.Value = h327\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [[]SymbolInformation []WorkspaceSymbol]\"}\n}\n\nfunc (t Or_SemanticTokensOptions_full) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase SemanticTokensFullDelta:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [SemanticTokensFullDelta bool]\", t)\n}\n\nfunc (t *Or_SemanticTokensOptions_full) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder47 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder47.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder47.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder48 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder48.DisallowUnknownFields()\n\tvar h48 SemanticTokensFullDelta\n\tif err := decoder48.Decode(&h48); err == nil {\n\t\tt.Value = h48\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [SemanticTokensFullDelta bool]\"}\n}\n\nfunc (t Or_SemanticTokensOptions_range) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase Lit_SemanticTokensOptions_range_Item1:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [Lit_SemanticTokensOptions_range_Item1 bool]\", t)\n}\n\nfunc (t *Or_SemanticTokensOptions_range) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder44 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder44.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder44.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder45 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder45.DisallowUnknownFields()\n\tvar h45 Lit_SemanticTokensOptions_range_Item1\n\tif err := decoder45.Decode(&h45); err == nil {\n\t\tt.Value = h45\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [Lit_SemanticTokensOptions_range_Item1 bool]\"}\n}\n\nfunc (t Or_ServerCapabilities_callHierarchyProvider) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase CallHierarchyOptions:\n\t\treturn json.Marshal(x)\n\tcase CallHierarchyRegistrationOptions:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [CallHierarchyOptions CallHierarchyRegistrationOptions bool]\", t)\n}\n\nfunc (t *Or_ServerCapabilities_callHierarchyProvider) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder140 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder140.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder140.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder141 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder141.DisallowUnknownFields()\n\tvar h141 CallHierarchyOptions\n\tif err := decoder141.Decode(&h141); err == nil {\n\t\tt.Value = h141\n\t\treturn nil\n\t}\n\tdecoder142 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder142.DisallowUnknownFields()\n\tvar h142 CallHierarchyRegistrationOptions\n\tif err := decoder142.Decode(&h142); err == nil {\n\t\tt.Value = h142\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [CallHierarchyOptions CallHierarchyRegistrationOptions bool]\"}\n}\n\nfunc (t Or_ServerCapabilities_codeActionProvider) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase CodeActionOptions:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [CodeActionOptions bool]\", t)\n}\n\nfunc (t *Or_ServerCapabilities_codeActionProvider) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder109 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder109.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder109.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder110 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder110.DisallowUnknownFields()\n\tvar h110 CodeActionOptions\n\tif err := decoder110.Decode(&h110); err == nil {\n\t\tt.Value = h110\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [CodeActionOptions bool]\"}\n}\n\nfunc (t Or_ServerCapabilities_colorProvider) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase DocumentColorOptions:\n\t\treturn json.Marshal(x)\n\tcase DocumentColorRegistrationOptions:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [DocumentColorOptions DocumentColorRegistrationOptions bool]\", t)\n}\n\nfunc (t *Or_ServerCapabilities_colorProvider) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder113 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder113.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder113.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder114 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder114.DisallowUnknownFields()\n\tvar h114 DocumentColorOptions\n\tif err := decoder114.Decode(&h114); err == nil {\n\t\tt.Value = h114\n\t\treturn nil\n\t}\n\tdecoder115 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder115.DisallowUnknownFields()\n\tvar h115 DocumentColorRegistrationOptions\n\tif err := decoder115.Decode(&h115); err == nil {\n\t\tt.Value = h115\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [DocumentColorOptions DocumentColorRegistrationOptions bool]\"}\n}\n\nfunc (t Or_ServerCapabilities_declarationProvider) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase DeclarationOptions:\n\t\treturn json.Marshal(x)\n\tcase DeclarationRegistrationOptions:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [DeclarationOptions DeclarationRegistrationOptions bool]\", t)\n}\n\nfunc (t *Or_ServerCapabilities_declarationProvider) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder83 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder83.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder83.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder84 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder84.DisallowUnknownFields()\n\tvar h84 DeclarationOptions\n\tif err := decoder84.Decode(&h84); err == nil {\n\t\tt.Value = h84\n\t\treturn nil\n\t}\n\tdecoder85 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder85.DisallowUnknownFields()\n\tvar h85 DeclarationRegistrationOptions\n\tif err := decoder85.Decode(&h85); err == nil {\n\t\tt.Value = h85\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [DeclarationOptions DeclarationRegistrationOptions bool]\"}\n}\n\nfunc (t Or_ServerCapabilities_definitionProvider) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase DefinitionOptions:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [DefinitionOptions bool]\", t)\n}\n\nfunc (t *Or_ServerCapabilities_definitionProvider) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder87 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder87.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder87.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder88 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder88.DisallowUnknownFields()\n\tvar h88 DefinitionOptions\n\tif err := decoder88.Decode(&h88); err == nil {\n\t\tt.Value = h88\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [DefinitionOptions bool]\"}\n}\n\nfunc (t Or_ServerCapabilities_diagnosticProvider) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase DiagnosticOptions:\n\t\treturn json.Marshal(x)\n\tcase DiagnosticRegistrationOptions:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [DiagnosticOptions DiagnosticRegistrationOptions]\", t)\n}\n\nfunc (t *Or_ServerCapabilities_diagnosticProvider) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder174 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder174.DisallowUnknownFields()\n\tvar h174 DiagnosticOptions\n\tif err := decoder174.Decode(&h174); err == nil {\n\t\tt.Value = h174\n\t\treturn nil\n\t}\n\tdecoder175 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder175.DisallowUnknownFields()\n\tvar h175 DiagnosticRegistrationOptions\n\tif err := decoder175.Decode(&h175); err == nil {\n\t\tt.Value = h175\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [DiagnosticOptions DiagnosticRegistrationOptions]\"}\n}\n\nfunc (t Or_ServerCapabilities_documentFormattingProvider) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase DocumentFormattingOptions:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [DocumentFormattingOptions bool]\", t)\n}\n\nfunc (t *Or_ServerCapabilities_documentFormattingProvider) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder120 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder120.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder120.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder121 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder121.DisallowUnknownFields()\n\tvar h121 DocumentFormattingOptions\n\tif err := decoder121.Decode(&h121); err == nil {\n\t\tt.Value = h121\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [DocumentFormattingOptions bool]\"}\n}\n\nfunc (t Or_ServerCapabilities_documentHighlightProvider) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase DocumentHighlightOptions:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [DocumentHighlightOptions bool]\", t)\n}\n\nfunc (t *Or_ServerCapabilities_documentHighlightProvider) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder103 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder103.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder103.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder104 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder104.DisallowUnknownFields()\n\tvar h104 DocumentHighlightOptions\n\tif err := decoder104.Decode(&h104); err == nil {\n\t\tt.Value = h104\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [DocumentHighlightOptions bool]\"}\n}\n\nfunc (t Or_ServerCapabilities_documentRangeFormattingProvider) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase DocumentRangeFormattingOptions:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [DocumentRangeFormattingOptions bool]\", t)\n}\n\nfunc (t *Or_ServerCapabilities_documentRangeFormattingProvider) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder123 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder123.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder123.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder124 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder124.DisallowUnknownFields()\n\tvar h124 DocumentRangeFormattingOptions\n\tif err := decoder124.Decode(&h124); err == nil {\n\t\tt.Value = h124\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [DocumentRangeFormattingOptions bool]\"}\n}\n\nfunc (t Or_ServerCapabilities_documentSymbolProvider) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase DocumentSymbolOptions:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [DocumentSymbolOptions bool]\", t)\n}\n\nfunc (t *Or_ServerCapabilities_documentSymbolProvider) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder106 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder106.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder106.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder107 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder107.DisallowUnknownFields()\n\tvar h107 DocumentSymbolOptions\n\tif err := decoder107.Decode(&h107); err == nil {\n\t\tt.Value = h107\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [DocumentSymbolOptions bool]\"}\n}\n\nfunc (t Or_ServerCapabilities_foldingRangeProvider) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase FoldingRangeOptions:\n\t\treturn json.Marshal(x)\n\tcase FoldingRangeRegistrationOptions:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [FoldingRangeOptions FoldingRangeRegistrationOptions bool]\", t)\n}\n\nfunc (t *Or_ServerCapabilities_foldingRangeProvider) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder130 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder130.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder130.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder131 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder131.DisallowUnknownFields()\n\tvar h131 FoldingRangeOptions\n\tif err := decoder131.Decode(&h131); err == nil {\n\t\tt.Value = h131\n\t\treturn nil\n\t}\n\tdecoder132 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder132.DisallowUnknownFields()\n\tvar h132 FoldingRangeRegistrationOptions\n\tif err := decoder132.Decode(&h132); err == nil {\n\t\tt.Value = h132\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [FoldingRangeOptions FoldingRangeRegistrationOptions bool]\"}\n}\n\nfunc (t Or_ServerCapabilities_hoverProvider) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase HoverOptions:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [HoverOptions bool]\", t)\n}\n\nfunc (t *Or_ServerCapabilities_hoverProvider) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder79 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder79.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder79.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder80 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder80.DisallowUnknownFields()\n\tvar h80 HoverOptions\n\tif err := decoder80.Decode(&h80); err == nil {\n\t\tt.Value = h80\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [HoverOptions bool]\"}\n}\n\nfunc (t Or_ServerCapabilities_implementationProvider) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase ImplementationOptions:\n\t\treturn json.Marshal(x)\n\tcase ImplementationRegistrationOptions:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [ImplementationOptions ImplementationRegistrationOptions bool]\", t)\n}\n\nfunc (t *Or_ServerCapabilities_implementationProvider) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder96 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder96.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder96.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder97 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder97.DisallowUnknownFields()\n\tvar h97 ImplementationOptions\n\tif err := decoder97.Decode(&h97); err == nil {\n\t\tt.Value = h97\n\t\treturn nil\n\t}\n\tdecoder98 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder98.DisallowUnknownFields()\n\tvar h98 ImplementationRegistrationOptions\n\tif err := decoder98.Decode(&h98); err == nil {\n\t\tt.Value = h98\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [ImplementationOptions ImplementationRegistrationOptions bool]\"}\n}\n\nfunc (t Or_ServerCapabilities_inlayHintProvider) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase InlayHintOptions:\n\t\treturn json.Marshal(x)\n\tcase InlayHintRegistrationOptions:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [InlayHintOptions InlayHintRegistrationOptions bool]\", t)\n}\n\nfunc (t *Or_ServerCapabilities_inlayHintProvider) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder169 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder169.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder169.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder170 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder170.DisallowUnknownFields()\n\tvar h170 InlayHintOptions\n\tif err := decoder170.Decode(&h170); err == nil {\n\t\tt.Value = h170\n\t\treturn nil\n\t}\n\tdecoder171 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder171.DisallowUnknownFields()\n\tvar h171 InlayHintRegistrationOptions\n\tif err := decoder171.Decode(&h171); err == nil {\n\t\tt.Value = h171\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [InlayHintOptions InlayHintRegistrationOptions bool]\"}\n}\n\nfunc (t Or_ServerCapabilities_inlineCompletionProvider) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase InlineCompletionOptions:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [InlineCompletionOptions bool]\", t)\n}\n\nfunc (t *Or_ServerCapabilities_inlineCompletionProvider) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder177 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder177.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder177.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder178 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder178.DisallowUnknownFields()\n\tvar h178 InlineCompletionOptions\n\tif err := decoder178.Decode(&h178); err == nil {\n\t\tt.Value = h178\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [InlineCompletionOptions bool]\"}\n}\n\nfunc (t Or_ServerCapabilities_inlineValueProvider) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase InlineValueOptions:\n\t\treturn json.Marshal(x)\n\tcase InlineValueRegistrationOptions:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [InlineValueOptions InlineValueRegistrationOptions bool]\", t)\n}\n\nfunc (t *Or_ServerCapabilities_inlineValueProvider) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder164 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder164.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder164.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder165 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder165.DisallowUnknownFields()\n\tvar h165 InlineValueOptions\n\tif err := decoder165.Decode(&h165); err == nil {\n\t\tt.Value = h165\n\t\treturn nil\n\t}\n\tdecoder166 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder166.DisallowUnknownFields()\n\tvar h166 InlineValueRegistrationOptions\n\tif err := decoder166.Decode(&h166); err == nil {\n\t\tt.Value = h166\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [InlineValueOptions InlineValueRegistrationOptions bool]\"}\n}\n\nfunc (t Or_ServerCapabilities_linkedEditingRangeProvider) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase LinkedEditingRangeOptions:\n\t\treturn json.Marshal(x)\n\tcase LinkedEditingRangeRegistrationOptions:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [LinkedEditingRangeOptions LinkedEditingRangeRegistrationOptions bool]\", t)\n}\n\nfunc (t *Or_ServerCapabilities_linkedEditingRangeProvider) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder145 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder145.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder145.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder146 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder146.DisallowUnknownFields()\n\tvar h146 LinkedEditingRangeOptions\n\tif err := decoder146.Decode(&h146); err == nil {\n\t\tt.Value = h146\n\t\treturn nil\n\t}\n\tdecoder147 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder147.DisallowUnknownFields()\n\tvar h147 LinkedEditingRangeRegistrationOptions\n\tif err := decoder147.Decode(&h147); err == nil {\n\t\tt.Value = h147\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [LinkedEditingRangeOptions LinkedEditingRangeRegistrationOptions bool]\"}\n}\n\nfunc (t Or_ServerCapabilities_monikerProvider) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase MonikerOptions:\n\t\treturn json.Marshal(x)\n\tcase MonikerRegistrationOptions:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [MonikerOptions MonikerRegistrationOptions bool]\", t)\n}\n\nfunc (t *Or_ServerCapabilities_monikerProvider) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder154 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder154.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder154.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder155 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder155.DisallowUnknownFields()\n\tvar h155 MonikerOptions\n\tif err := decoder155.Decode(&h155); err == nil {\n\t\tt.Value = h155\n\t\treturn nil\n\t}\n\tdecoder156 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder156.DisallowUnknownFields()\n\tvar h156 MonikerRegistrationOptions\n\tif err := decoder156.Decode(&h156); err == nil {\n\t\tt.Value = h156\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [MonikerOptions MonikerRegistrationOptions bool]\"}\n}\n\nfunc (t Or_ServerCapabilities_notebookDocumentSync) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase NotebookDocumentSyncOptions:\n\t\treturn json.Marshal(x)\n\tcase NotebookDocumentSyncRegistrationOptions:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [NotebookDocumentSyncOptions NotebookDocumentSyncRegistrationOptions]\", t)\n}\n\nfunc (t *Or_ServerCapabilities_notebookDocumentSync) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder76 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder76.DisallowUnknownFields()\n\tvar h76 NotebookDocumentSyncOptions\n\tif err := decoder76.Decode(&h76); err == nil {\n\t\tt.Value = h76\n\t\treturn nil\n\t}\n\tdecoder77 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder77.DisallowUnknownFields()\n\tvar h77 NotebookDocumentSyncRegistrationOptions\n\tif err := decoder77.Decode(&h77); err == nil {\n\t\tt.Value = h77\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [NotebookDocumentSyncOptions NotebookDocumentSyncRegistrationOptions]\"}\n}\n\nfunc (t Or_ServerCapabilities_referencesProvider) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase ReferenceOptions:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [ReferenceOptions bool]\", t)\n}\n\nfunc (t *Or_ServerCapabilities_referencesProvider) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder100 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder100.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder100.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder101 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder101.DisallowUnknownFields()\n\tvar h101 ReferenceOptions\n\tif err := decoder101.Decode(&h101); err == nil {\n\t\tt.Value = h101\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [ReferenceOptions bool]\"}\n}\n\nfunc (t Or_ServerCapabilities_renameProvider) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase RenameOptions:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [RenameOptions bool]\", t)\n}\n\nfunc (t *Or_ServerCapabilities_renameProvider) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder126 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder126.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder126.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder127 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder127.DisallowUnknownFields()\n\tvar h127 RenameOptions\n\tif err := decoder127.Decode(&h127); err == nil {\n\t\tt.Value = h127\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [RenameOptions bool]\"}\n}\n\nfunc (t Or_ServerCapabilities_selectionRangeProvider) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase SelectionRangeOptions:\n\t\treturn json.Marshal(x)\n\tcase SelectionRangeRegistrationOptions:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [SelectionRangeOptions SelectionRangeRegistrationOptions bool]\", t)\n}\n\nfunc (t *Or_ServerCapabilities_selectionRangeProvider) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder135 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder135.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder135.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder136 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder136.DisallowUnknownFields()\n\tvar h136 SelectionRangeOptions\n\tif err := decoder136.Decode(&h136); err == nil {\n\t\tt.Value = h136\n\t\treturn nil\n\t}\n\tdecoder137 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder137.DisallowUnknownFields()\n\tvar h137 SelectionRangeRegistrationOptions\n\tif err := decoder137.Decode(&h137); err == nil {\n\t\tt.Value = h137\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [SelectionRangeOptions SelectionRangeRegistrationOptions bool]\"}\n}\n\nfunc (t Or_ServerCapabilities_semanticTokensProvider) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase SemanticTokensOptions:\n\t\treturn json.Marshal(x)\n\tcase SemanticTokensRegistrationOptions:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [SemanticTokensOptions SemanticTokensRegistrationOptions]\", t)\n}\n\nfunc (t *Or_ServerCapabilities_semanticTokensProvider) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder150 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder150.DisallowUnknownFields()\n\tvar h150 SemanticTokensOptions\n\tif err := decoder150.Decode(&h150); err == nil {\n\t\tt.Value = h150\n\t\treturn nil\n\t}\n\tdecoder151 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder151.DisallowUnknownFields()\n\tvar h151 SemanticTokensRegistrationOptions\n\tif err := decoder151.Decode(&h151); err == nil {\n\t\tt.Value = h151\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [SemanticTokensOptions SemanticTokensRegistrationOptions]\"}\n}\n\nfunc (t Or_ServerCapabilities_textDocumentSync) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase TextDocumentSyncKind:\n\t\treturn json.Marshal(x)\n\tcase TextDocumentSyncOptions:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [TextDocumentSyncKind TextDocumentSyncOptions]\", t)\n}\n\nfunc (t *Or_ServerCapabilities_textDocumentSync) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder72 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder72.DisallowUnknownFields()\n\tvar h72 TextDocumentSyncKind\n\tif err := decoder72.Decode(&h72); err == nil {\n\t\tt.Value = h72\n\t\treturn nil\n\t}\n\tdecoder73 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder73.DisallowUnknownFields()\n\tvar h73 TextDocumentSyncOptions\n\tif err := decoder73.Decode(&h73); err == nil {\n\t\tt.Value = h73\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [TextDocumentSyncKind TextDocumentSyncOptions]\"}\n}\n\nfunc (t Or_ServerCapabilities_typeDefinitionProvider) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase TypeDefinitionOptions:\n\t\treturn json.Marshal(x)\n\tcase TypeDefinitionRegistrationOptions:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [TypeDefinitionOptions TypeDefinitionRegistrationOptions bool]\", t)\n}\n\nfunc (t *Or_ServerCapabilities_typeDefinitionProvider) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder91 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder91.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder91.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder92 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder92.DisallowUnknownFields()\n\tvar h92 TypeDefinitionOptions\n\tif err := decoder92.Decode(&h92); err == nil {\n\t\tt.Value = h92\n\t\treturn nil\n\t}\n\tdecoder93 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder93.DisallowUnknownFields()\n\tvar h93 TypeDefinitionRegistrationOptions\n\tif err := decoder93.Decode(&h93); err == nil {\n\t\tt.Value = h93\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [TypeDefinitionOptions TypeDefinitionRegistrationOptions bool]\"}\n}\n\nfunc (t Or_ServerCapabilities_typeHierarchyProvider) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase TypeHierarchyOptions:\n\t\treturn json.Marshal(x)\n\tcase TypeHierarchyRegistrationOptions:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [TypeHierarchyOptions TypeHierarchyRegistrationOptions bool]\", t)\n}\n\nfunc (t *Or_ServerCapabilities_typeHierarchyProvider) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder159 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder159.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder159.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder160 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder160.DisallowUnknownFields()\n\tvar h160 TypeHierarchyOptions\n\tif err := decoder160.Decode(&h160); err == nil {\n\t\tt.Value = h160\n\t\treturn nil\n\t}\n\tdecoder161 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder161.DisallowUnknownFields()\n\tvar h161 TypeHierarchyRegistrationOptions\n\tif err := decoder161.Decode(&h161); err == nil {\n\t\tt.Value = h161\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [TypeHierarchyOptions TypeHierarchyRegistrationOptions bool]\"}\n}\n\nfunc (t Or_ServerCapabilities_workspaceSymbolProvider) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase WorkspaceSymbolOptions:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [WorkspaceSymbolOptions bool]\", t)\n}\n\nfunc (t *Or_ServerCapabilities_workspaceSymbolProvider) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder117 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder117.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder117.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder118 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder118.DisallowUnknownFields()\n\tvar h118 WorkspaceSymbolOptions\n\tif err := decoder118.Decode(&h118); err == nil {\n\t\tt.Value = h118\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [WorkspaceSymbolOptions bool]\"}\n}\n\nfunc (t Or_SignatureInformation_documentation) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase MarkupContent:\n\t\treturn json.Marshal(x)\n\tcase string:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [MarkupContent string]\", t)\n}\n\nfunc (t *Or_SignatureInformation_documentation) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder186 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder186.DisallowUnknownFields()\n\tvar stringVal string\n\tif err := decoder186.Decode(&stringVal); err == nil {\n\t\tt.Value = stringVal\n\t\treturn nil\n\t}\n\tdecoder187 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder187.DisallowUnknownFields()\n\tvar h187 MarkupContent\n\tif err := decoder187.Decode(&h187); err == nil {\n\t\tt.Value = h187\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [MarkupContent string]\"}\n}\n\nfunc (t Or_TextDocumentContentChangeEvent) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase TextDocumentContentChangePartial:\n\t\treturn json.Marshal(x)\n\tcase TextDocumentContentChangeWholeDocument:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [TextDocumentContentChangePartial TextDocumentContentChangeWholeDocument]\", t)\n}\n\nfunc (t *Or_TextDocumentContentChangeEvent) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder263 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder263.DisallowUnknownFields()\n\tvar h263 TextDocumentContentChangePartial\n\tif err := decoder263.Decode(&h263); err == nil {\n\t\tt.Value = h263\n\t\treturn nil\n\t}\n\tdecoder264 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder264.DisallowUnknownFields()\n\tvar h264 TextDocumentContentChangeWholeDocument\n\tif err := decoder264.Decode(&h264); err == nil {\n\t\tt.Value = h264\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [TextDocumentContentChangePartial TextDocumentContentChangeWholeDocument]\"}\n}\n\nfunc (t Or_TextDocumentEdit_edits_Elem) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase AnnotatedTextEdit:\n\t\treturn json.Marshal(x)\n\tcase SnippetTextEdit:\n\t\treturn json.Marshal(x)\n\tcase TextEdit:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [AnnotatedTextEdit SnippetTextEdit TextEdit]\", t)\n}\n\nfunc (t *Or_TextDocumentEdit_edits_Elem) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder52 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder52.DisallowUnknownFields()\n\tvar h52 AnnotatedTextEdit\n\tif err := decoder52.Decode(&h52); err == nil {\n\t\tt.Value = h52\n\t\treturn nil\n\t}\n\tdecoder53 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder53.DisallowUnknownFields()\n\tvar h53 SnippetTextEdit\n\tif err := decoder53.Decode(&h53); err == nil {\n\t\tt.Value = h53\n\t\treturn nil\n\t}\n\tdecoder54 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder54.DisallowUnknownFields()\n\tvar h54 TextEdit\n\tif err := decoder54.Decode(&h54); err == nil {\n\t\tt.Value = h54\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [AnnotatedTextEdit SnippetTextEdit TextEdit]\"}\n}\n\nfunc (t Or_TextDocumentFilter) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase TextDocumentFilterLanguage:\n\t\treturn json.Marshal(x)\n\tcase TextDocumentFilterPattern:\n\t\treturn json.Marshal(x)\n\tcase TextDocumentFilterScheme:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [TextDocumentFilterLanguage TextDocumentFilterPattern TextDocumentFilterScheme]\", t)\n}\n\nfunc (t *Or_TextDocumentFilter) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder279 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder279.DisallowUnknownFields()\n\tvar h279 TextDocumentFilterLanguage\n\tif err := decoder279.Decode(&h279); err == nil {\n\t\tt.Value = h279\n\t\treturn nil\n\t}\n\tdecoder280 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder280.DisallowUnknownFields()\n\tvar h280 TextDocumentFilterPattern\n\tif err := decoder280.Decode(&h280); err == nil {\n\t\tt.Value = h280\n\t\treturn nil\n\t}\n\tdecoder281 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder281.DisallowUnknownFields()\n\tvar h281 TextDocumentFilterScheme\n\tif err := decoder281.Decode(&h281); err == nil {\n\t\tt.Value = h281\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [TextDocumentFilterLanguage TextDocumentFilterPattern TextDocumentFilterScheme]\"}\n}\n\nfunc (t Or_TextDocumentSyncOptions_save) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase SaveOptions:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [SaveOptions bool]\", t)\n}\n\nfunc (t *Or_TextDocumentSyncOptions_save) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder195 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder195.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder195.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder196 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder196.DisallowUnknownFields()\n\tvar h196 SaveOptions\n\tif err := decoder196.Decode(&h196); err == nil {\n\t\tt.Value = h196\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [SaveOptions bool]\"}\n}\n\nfunc (t Or_WorkspaceDocumentDiagnosticReport) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase WorkspaceFullDocumentDiagnosticReport:\n\t\treturn json.Marshal(x)\n\tcase WorkspaceUnchangedDocumentDiagnosticReport:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [WorkspaceFullDocumentDiagnosticReport WorkspaceUnchangedDocumentDiagnosticReport]\", t)\n}\n\nfunc (t *Or_WorkspaceDocumentDiagnosticReport) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder259 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder259.DisallowUnknownFields()\n\tvar h259 WorkspaceFullDocumentDiagnosticReport\n\tif err := decoder259.Decode(&h259); err == nil {\n\t\tt.Value = h259\n\t\treturn nil\n\t}\n\tdecoder260 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder260.DisallowUnknownFields()\n\tvar h260 WorkspaceUnchangedDocumentDiagnosticReport\n\tif err := decoder260.Decode(&h260); err == nil {\n\t\tt.Value = h260\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [WorkspaceFullDocumentDiagnosticReport WorkspaceUnchangedDocumentDiagnosticReport]\"}\n}\n\nfunc (t Or_WorkspaceEdit_documentChanges_Elem) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase CreateFile:\n\t\treturn json.Marshal(x)\n\tcase DeleteFile:\n\t\treturn json.Marshal(x)\n\tcase RenameFile:\n\t\treturn json.Marshal(x)\n\tcase TextDocumentEdit:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [CreateFile DeleteFile RenameFile TextDocumentEdit]\", t)\n}\n\nfunc (t *Or_WorkspaceEdit_documentChanges_Elem) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder4 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder4.DisallowUnknownFields()\n\tvar h4 CreateFile\n\tif err := decoder4.Decode(&h4); err == nil {\n\t\tt.Value = h4\n\t\treturn nil\n\t}\n\tdecoder5 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder5.DisallowUnknownFields()\n\tvar h5 DeleteFile\n\tif err := decoder5.Decode(&h5); err == nil {\n\t\tt.Value = h5\n\t\treturn nil\n\t}\n\tdecoder6 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder6.DisallowUnknownFields()\n\tvar h6 RenameFile\n\tif err := decoder6.Decode(&h6); err == nil {\n\t\tt.Value = h6\n\t\treturn nil\n\t}\n\tdecoder7 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder7.DisallowUnknownFields()\n\tvar h7 TextDocumentEdit\n\tif err := decoder7.Decode(&h7); err == nil {\n\t\tt.Value = h7\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [CreateFile DeleteFile RenameFile TextDocumentEdit]\"}\n}\n\nfunc (t Or_WorkspaceFoldersServerCapabilities_changeNotifications) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase string:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [bool string]\", t)\n}\n\nfunc (t *Or_WorkspaceFoldersServerCapabilities_changeNotifications) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder210 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder210.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder210.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder211 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder211.DisallowUnknownFields()\n\tvar stringVal string\n\tif err := decoder211.Decode(&stringVal); err == nil {\n\t\tt.Value = stringVal\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [bool string]\"}\n}\n\nfunc (t Or_WorkspaceOptions_textDocumentContent) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase TextDocumentContentOptions:\n\t\treturn json.Marshal(x)\n\tcase TextDocumentContentRegistrationOptions:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [TextDocumentContentOptions TextDocumentContentRegistrationOptions]\", t)\n}\n\nfunc (t *Or_WorkspaceOptions_textDocumentContent) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder199 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder199.DisallowUnknownFields()\n\tvar h199 TextDocumentContentOptions\n\tif err := decoder199.Decode(&h199); err == nil {\n\t\tt.Value = h199\n\t\treturn nil\n\t}\n\tdecoder200 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder200.DisallowUnknownFields()\n\tvar h200 TextDocumentContentRegistrationOptions\n\tif err := decoder200.Decode(&h200); err == nil {\n\t\tt.Value = h200\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [TextDocumentContentOptions TextDocumentContentRegistrationOptions]\"}\n}\n\nfunc (t Or_WorkspaceSymbol_location) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase Location:\n\t\treturn json.Marshal(x)\n\tcase LocationUriOnly:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [Location LocationUriOnly]\", t)\n}\n\nfunc (t *Or_WorkspaceSymbol_location) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder39 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder39.DisallowUnknownFields()\n\tvar h39 Location\n\tif err := decoder39.Decode(&h39); err == nil {\n\t\tt.Value = h39\n\t\treturn nil\n\t}\n\tdecoder40 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder40.DisallowUnknownFields()\n\tvar h40 LocationUriOnly\n\tif err := decoder40.Decode(&h40); err == nil {\n\t\tt.Value = h40\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [Location LocationUriOnly]\"}\n}\n"], ["/opencode/internal/lsp/handlers.go", "package lsp\n\nimport (\n\t\"encoding/json\"\n\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n\t\"github.com/opencode-ai/opencode/internal/lsp/protocol\"\n\t\"github.com/opencode-ai/opencode/internal/lsp/util\"\n)\n\n// Requests\n\nfunc HandleWorkspaceConfiguration(params json.RawMessage) (any, error) {\n\treturn []map[string]any{{}}, nil\n}\n\nfunc HandleRegisterCapability(params json.RawMessage) (any, error) {\n\tvar registerParams protocol.RegistrationParams\n\tif err := json.Unmarshal(params, ®isterParams); err != nil {\n\t\tlogging.Error(\"Error unmarshaling registration params\", \"error\", err)\n\t\treturn nil, err\n\t}\n\n\tfor _, reg := range registerParams.Registrations {\n\t\tswitch reg.Method {\n\t\tcase \"workspace/didChangeWatchedFiles\":\n\t\t\t// Parse the registration options\n\t\t\toptionsJSON, err := json.Marshal(reg.RegisterOptions)\n\t\t\tif err != nil {\n\t\t\t\tlogging.Error(\"Error marshaling registration options\", \"error\", err)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tvar options protocol.DidChangeWatchedFilesRegistrationOptions\n\t\t\tif err := json.Unmarshal(optionsJSON, &options); err != nil {\n\t\t\t\tlogging.Error(\"Error unmarshaling registration options\", \"error\", err)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// Store the file watchers registrations\n\t\t\tnotifyFileWatchRegistration(reg.ID, options.Watchers)\n\t\t}\n\t}\n\n\treturn nil, nil\n}\n\nfunc HandleApplyEdit(params json.RawMessage) (any, error) {\n\tvar edit protocol.ApplyWorkspaceEditParams\n\tif err := json.Unmarshal(params, &edit); err != nil {\n\t\treturn nil, err\n\t}\n\n\terr := util.ApplyWorkspaceEdit(edit.Edit)\n\tif err != nil {\n\t\tlogging.Error(\"Error applying workspace edit\", \"error\", err)\n\t\treturn protocol.ApplyWorkspaceEditResult{Applied: false, FailureReason: err.Error()}, nil\n\t}\n\n\treturn protocol.ApplyWorkspaceEditResult{Applied: true}, nil\n}\n\n// FileWatchRegistrationHandler is a function that will be called when file watch registrations are received\ntype FileWatchRegistrationHandler func(id string, watchers []protocol.FileSystemWatcher)\n\n// fileWatchHandler holds the current handler for file watch registrations\nvar fileWatchHandler FileWatchRegistrationHandler\n\n// RegisterFileWatchHandler sets the handler for file watch registrations\nfunc RegisterFileWatchHandler(handler FileWatchRegistrationHandler) {\n\tfileWatchHandler = handler\n}\n\n// notifyFileWatchRegistration notifies the handler about new file watch registrations\nfunc notifyFileWatchRegistration(id string, watchers []protocol.FileSystemWatcher) {\n\tif fileWatchHandler != nil {\n\t\tfileWatchHandler(id, watchers)\n\t}\n}\n\n// Notifications\n\nfunc HandleServerMessage(params json.RawMessage) {\n\tcnf := config.Get()\n\tvar msg struct {\n\t\tType int `json:\"type\"`\n\t\tMessage string `json:\"message\"`\n\t}\n\tif err := json.Unmarshal(params, &msg); err == nil {\n\t\tif cnf.DebugLSP {\n\t\t\tlogging.Debug(\"Server message\", \"type\", msg.Type, \"message\", msg.Message)\n\t\t}\n\t}\n}\n\nfunc HandleDiagnostics(client *Client, params json.RawMessage) {\n\tvar diagParams protocol.PublishDiagnosticsParams\n\tif err := json.Unmarshal(params, &diagParams); err != nil {\n\t\tlogging.Error(\"Error unmarshaling diagnostics params\", \"error\", err)\n\t\treturn\n\t}\n\n\tclient.diagnosticsMu.Lock()\n\tdefer client.diagnosticsMu.Unlock()\n\n\tclient.diagnostics[diagParams.URI] = diagParams.Diagnostics\n}\n"], ["/opencode/internal/session/session.go", "package session\n\nimport (\n\t\"context\"\n\t\"database/sql\"\n\n\t\"github.com/google/uuid\"\n\t\"github.com/opencode-ai/opencode/internal/db\"\n\t\"github.com/opencode-ai/opencode/internal/pubsub\"\n)\n\ntype Session struct {\n\tID string\n\tParentSessionID string\n\tTitle string\n\tMessageCount int64\n\tPromptTokens int64\n\tCompletionTokens int64\n\tSummaryMessageID string\n\tCost float64\n\tCreatedAt int64\n\tUpdatedAt int64\n}\n\ntype Service interface {\n\tpubsub.Suscriber[Session]\n\tCreate(ctx context.Context, title string) (Session, error)\n\tCreateTitleSession(ctx context.Context, parentSessionID string) (Session, error)\n\tCreateTaskSession(ctx context.Context, toolCallID, parentSessionID, title string) (Session, error)\n\tGet(ctx context.Context, id string) (Session, error)\n\tList(ctx context.Context) ([]Session, error)\n\tSave(ctx context.Context, session Session) (Session, error)\n\tDelete(ctx context.Context, id string) error\n}\n\ntype service struct {\n\t*pubsub.Broker[Session]\n\tq db.Querier\n}\n\nfunc (s *service) Create(ctx context.Context, title string) (Session, error) {\n\tdbSession, err := s.q.CreateSession(ctx, db.CreateSessionParams{\n\t\tID: uuid.New().String(),\n\t\tTitle: title,\n\t})\n\tif err != nil {\n\t\treturn Session{}, err\n\t}\n\tsession := s.fromDBItem(dbSession)\n\ts.Publish(pubsub.CreatedEvent, session)\n\treturn session, nil\n}\n\nfunc (s *service) CreateTaskSession(ctx context.Context, toolCallID, parentSessionID, title string) (Session, error) {\n\tdbSession, err := s.q.CreateSession(ctx, db.CreateSessionParams{\n\t\tID: toolCallID,\n\t\tParentSessionID: sql.NullString{String: parentSessionID, Valid: true},\n\t\tTitle: title,\n\t})\n\tif err != nil {\n\t\treturn Session{}, err\n\t}\n\tsession := s.fromDBItem(dbSession)\n\ts.Publish(pubsub.CreatedEvent, session)\n\treturn session, nil\n}\n\nfunc (s *service) CreateTitleSession(ctx context.Context, parentSessionID string) (Session, error) {\n\tdbSession, err := s.q.CreateSession(ctx, db.CreateSessionParams{\n\t\tID: \"title-\" + parentSessionID,\n\t\tParentSessionID: sql.NullString{String: parentSessionID, Valid: true},\n\t\tTitle: \"Generate a title\",\n\t})\n\tif err != nil {\n\t\treturn Session{}, err\n\t}\n\tsession := s.fromDBItem(dbSession)\n\ts.Publish(pubsub.CreatedEvent, session)\n\treturn session, nil\n}\n\nfunc (s *service) Delete(ctx context.Context, id string) error {\n\tsession, err := s.Get(ctx, id)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = s.q.DeleteSession(ctx, session.ID)\n\tif err != nil {\n\t\treturn err\n\t}\n\ts.Publish(pubsub.DeletedEvent, session)\n\treturn nil\n}\n\nfunc (s *service) Get(ctx context.Context, id string) (Session, error) {\n\tdbSession, err := s.q.GetSessionByID(ctx, id)\n\tif err != nil {\n\t\treturn Session{}, err\n\t}\n\treturn s.fromDBItem(dbSession), nil\n}\n\nfunc (s *service) Save(ctx context.Context, session Session) (Session, error) {\n\tdbSession, err := s.q.UpdateSession(ctx, db.UpdateSessionParams{\n\t\tID: session.ID,\n\t\tTitle: session.Title,\n\t\tPromptTokens: session.PromptTokens,\n\t\tCompletionTokens: session.CompletionTokens,\n\t\tSummaryMessageID: sql.NullString{\n\t\t\tString: session.SummaryMessageID,\n\t\t\tValid: session.SummaryMessageID != \"\",\n\t\t},\n\t\tCost: session.Cost,\n\t})\n\tif err != nil {\n\t\treturn Session{}, err\n\t}\n\tsession = s.fromDBItem(dbSession)\n\ts.Publish(pubsub.UpdatedEvent, session)\n\treturn session, nil\n}\n\nfunc (s *service) List(ctx context.Context) ([]Session, error) {\n\tdbSessions, err := s.q.ListSessions(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsessions := make([]Session, len(dbSessions))\n\tfor i, dbSession := range dbSessions {\n\t\tsessions[i] = s.fromDBItem(dbSession)\n\t}\n\treturn sessions, nil\n}\n\nfunc (s service) fromDBItem(item db.Session) Session {\n\treturn Session{\n\t\tID: item.ID,\n\t\tParentSessionID: item.ParentSessionID.String,\n\t\tTitle: item.Title,\n\t\tMessageCount: item.MessageCount,\n\t\tPromptTokens: item.PromptTokens,\n\t\tCompletionTokens: item.CompletionTokens,\n\t\tSummaryMessageID: item.SummaryMessageID.String,\n\t\tCost: item.Cost,\n\t\tCreatedAt: item.CreatedAt,\n\t\tUpdatedAt: item.UpdatedAt,\n\t}\n}\n\nfunc NewService(q db.Querier) Service {\n\tbroker := pubsub.NewBroker[Session]()\n\treturn &service{\n\t\tbroker,\n\t\tq,\n\t}\n}\n"], ["/opencode/internal/tui/page/chat.go", "package page\n\nimport (\n\t\"context\"\n\t\"strings\"\n\n\t\"github.com/charmbracelet/bubbles/key\"\n\ttea \"github.com/charmbracelet/bubbletea\"\n\t\"github.com/charmbracelet/lipgloss\"\n\t\"github.com/opencode-ai/opencode/internal/app\"\n\t\"github.com/opencode-ai/opencode/internal/completions\"\n\t\"github.com/opencode-ai/opencode/internal/message\"\n\t\"github.com/opencode-ai/opencode/internal/session\"\n\t\"github.com/opencode-ai/opencode/internal/tui/components/chat\"\n\t\"github.com/opencode-ai/opencode/internal/tui/components/dialog\"\n\t\"github.com/opencode-ai/opencode/internal/tui/layout\"\n\t\"github.com/opencode-ai/opencode/internal/tui/util\"\n)\n\nvar ChatPage PageID = \"chat\"\n\ntype chatPage struct {\n\tapp *app.App\n\teditor layout.Container\n\tmessages layout.Container\n\tlayout layout.SplitPaneLayout\n\tsession session.Session\n\tcompletionDialog dialog.CompletionDialog\n\tshowCompletionDialog bool\n}\n\ntype ChatKeyMap struct {\n\tShowCompletionDialog key.Binding\n\tNewSession key.Binding\n\tCancel key.Binding\n}\n\nvar keyMap = ChatKeyMap{\n\tShowCompletionDialog: key.NewBinding(\n\t\tkey.WithKeys(\"@\"),\n\t\tkey.WithHelp(\"@\", \"Complete\"),\n\t),\n\tNewSession: key.NewBinding(\n\t\tkey.WithKeys(\"ctrl+n\"),\n\t\tkey.WithHelp(\"ctrl+n\", \"new session\"),\n\t),\n\tCancel: key.NewBinding(\n\t\tkey.WithKeys(\"esc\"),\n\t\tkey.WithHelp(\"esc\", \"cancel\"),\n\t),\n}\n\nfunc (p *chatPage) Init() tea.Cmd {\n\tcmds := []tea.Cmd{\n\t\tp.layout.Init(),\n\t\tp.completionDialog.Init(),\n\t}\n\treturn tea.Batch(cmds...)\n}\n\nfunc (p *chatPage) Update(msg tea.Msg) (tea.Model, tea.Cmd) {\n\tvar cmds []tea.Cmd\n\tswitch msg := msg.(type) {\n\tcase tea.WindowSizeMsg:\n\t\tcmd := p.layout.SetSize(msg.Width, msg.Height)\n\t\tcmds = append(cmds, cmd)\n\tcase dialog.CompletionDialogCloseMsg:\n\t\tp.showCompletionDialog = false\n\tcase chat.SendMsg:\n\t\tcmd := p.sendMessage(msg.Text, msg.Attachments)\n\t\tif cmd != nil {\n\t\t\treturn p, cmd\n\t\t}\n\tcase dialog.CommandRunCustomMsg:\n\t\t// Check if the agent is busy before executing custom commands\n\t\tif p.app.CoderAgent.IsBusy() {\n\t\t\treturn p, util.ReportWarn(\"Agent is busy, please wait before executing a command...\")\n\t\t}\n\t\t\n\t\t// Process the command content with arguments if any\n\t\tcontent := msg.Content\n\t\tif msg.Args != nil {\n\t\t\t// Replace all named arguments with their values\n\t\t\tfor name, value := range msg.Args {\n\t\t\t\tplaceholder := \"$\" + name\n\t\t\t\tcontent = strings.ReplaceAll(content, placeholder, value)\n\t\t\t}\n\t\t}\n\t\t\n\t\t// Handle custom command execution\n\t\tcmd := p.sendMessage(content, nil)\n\t\tif cmd != nil {\n\t\t\treturn p, cmd\n\t\t}\n\tcase chat.SessionSelectedMsg:\n\t\tif p.session.ID == \"\" {\n\t\t\tcmd := p.setSidebar()\n\t\t\tif cmd != nil {\n\t\t\t\tcmds = append(cmds, cmd)\n\t\t\t}\n\t\t}\n\t\tp.session = msg\n\tcase tea.KeyMsg:\n\t\tswitch {\n\t\tcase key.Matches(msg, keyMap.ShowCompletionDialog):\n\t\t\tp.showCompletionDialog = true\n\t\t\t// Continue sending keys to layout->chat\n\t\tcase key.Matches(msg, keyMap.NewSession):\n\t\t\tp.session = session.Session{}\n\t\t\treturn p, tea.Batch(\n\t\t\t\tp.clearSidebar(),\n\t\t\t\tutil.CmdHandler(chat.SessionClearedMsg{}),\n\t\t\t)\n\t\tcase key.Matches(msg, keyMap.Cancel):\n\t\t\tif p.session.ID != \"\" {\n\t\t\t\t// Cancel the current session's generation process\n\t\t\t\t// This allows users to interrupt long-running operations\n\t\t\t\tp.app.CoderAgent.Cancel(p.session.ID)\n\t\t\t\treturn p, nil\n\t\t\t}\n\t\t}\n\t}\n\tif p.showCompletionDialog {\n\t\tcontext, contextCmd := p.completionDialog.Update(msg)\n\t\tp.completionDialog = context.(dialog.CompletionDialog)\n\t\tcmds = append(cmds, contextCmd)\n\n\t\t// Doesn't forward event if enter key is pressed\n\t\tif keyMsg, ok := msg.(tea.KeyMsg); ok {\n\t\t\tif keyMsg.String() == \"enter\" {\n\t\t\t\treturn p, tea.Batch(cmds...)\n\t\t\t}\n\t\t}\n\t}\n\n\tu, cmd := p.layout.Update(msg)\n\tcmds = append(cmds, cmd)\n\tp.layout = u.(layout.SplitPaneLayout)\n\n\treturn p, tea.Batch(cmds...)\n}\n\nfunc (p *chatPage) setSidebar() tea.Cmd {\n\tsidebarContainer := layout.NewContainer(\n\t\tchat.NewSidebarCmp(p.session, p.app.History),\n\t\tlayout.WithPadding(1, 1, 1, 1),\n\t)\n\treturn tea.Batch(p.layout.SetRightPanel(sidebarContainer), sidebarContainer.Init())\n}\n\nfunc (p *chatPage) clearSidebar() tea.Cmd {\n\treturn p.layout.ClearRightPanel()\n}\n\nfunc (p *chatPage) sendMessage(text string, attachments []message.Attachment) tea.Cmd {\n\tvar cmds []tea.Cmd\n\tif p.session.ID == \"\" {\n\t\tsession, err := p.app.Sessions.Create(context.Background(), \"New Session\")\n\t\tif err != nil {\n\t\t\treturn util.ReportError(err)\n\t\t}\n\n\t\tp.session = session\n\t\tcmd := p.setSidebar()\n\t\tif cmd != nil {\n\t\t\tcmds = append(cmds, cmd)\n\t\t}\n\t\tcmds = append(cmds, util.CmdHandler(chat.SessionSelectedMsg(session)))\n\t}\n\n\t_, err := p.app.CoderAgent.Run(context.Background(), p.session.ID, text, attachments...)\n\tif err != nil {\n\t\treturn util.ReportError(err)\n\t}\n\treturn tea.Batch(cmds...)\n}\n\nfunc (p *chatPage) SetSize(width, height int) tea.Cmd {\n\treturn p.layout.SetSize(width, height)\n}\n\nfunc (p *chatPage) GetSize() (int, int) {\n\treturn p.layout.GetSize()\n}\n\nfunc (p *chatPage) View() string {\n\tlayoutView := p.layout.View()\n\n\tif p.showCompletionDialog {\n\t\t_, layoutHeight := p.layout.GetSize()\n\t\teditorWidth, editorHeight := p.editor.GetSize()\n\n\t\tp.completionDialog.SetWidth(editorWidth)\n\t\toverlay := p.completionDialog.View()\n\n\t\tlayoutView = layout.PlaceOverlay(\n\t\t\t0,\n\t\t\tlayoutHeight-editorHeight-lipgloss.Height(overlay),\n\t\t\toverlay,\n\t\t\tlayoutView,\n\t\t\tfalse,\n\t\t)\n\t}\n\n\treturn layoutView\n}\n\nfunc (p *chatPage) BindingKeys() []key.Binding {\n\tbindings := layout.KeyMapToSlice(keyMap)\n\tbindings = append(bindings, p.messages.BindingKeys()...)\n\tbindings = append(bindings, p.editor.BindingKeys()...)\n\treturn bindings\n}\n\nfunc NewChatPage(app *app.App) tea.Model {\n\tcg := completions.NewFileAndFolderContextGroup()\n\tcompletionDialog := dialog.NewCompletionDialogCmp(cg)\n\n\tmessagesContainer := layout.NewContainer(\n\t\tchat.NewMessagesCmp(app),\n\t\tlayout.WithPadding(1, 1, 0, 1),\n\t)\n\teditorContainer := layout.NewContainer(\n\t\tchat.NewEditorCmp(app),\n\t\tlayout.WithBorder(true, false, false, false),\n\t)\n\treturn &chatPage{\n\t\tapp: app,\n\t\teditor: editorContainer,\n\t\tmessages: messagesContainer,\n\t\tcompletionDialog: completionDialog,\n\t\tlayout: layout.NewSplitPane(\n\t\t\tlayout.WithLeftPanel(messagesContainer),\n\t\t\tlayout.WithBottomPanel(editorContainer),\n\t\t),\n\t}\n}\n"], ["/opencode/internal/tui/components/core/status.go", "package core\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\t\"time\"\n\n\ttea \"github.com/charmbracelet/bubbletea\"\n\t\"github.com/charmbracelet/lipgloss\"\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/llm/models\"\n\t\"github.com/opencode-ai/opencode/internal/lsp\"\n\t\"github.com/opencode-ai/opencode/internal/lsp/protocol\"\n\t\"github.com/opencode-ai/opencode/internal/pubsub\"\n\t\"github.com/opencode-ai/opencode/internal/session\"\n\t\"github.com/opencode-ai/opencode/internal/tui/components/chat\"\n\t\"github.com/opencode-ai/opencode/internal/tui/styles\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n\t\"github.com/opencode-ai/opencode/internal/tui/util\"\n)\n\ntype StatusCmp interface {\n\ttea.Model\n}\n\ntype statusCmp struct {\n\tinfo util.InfoMsg\n\twidth int\n\tmessageTTL time.Duration\n\tlspClients map[string]*lsp.Client\n\tsession session.Session\n}\n\n// clearMessageCmd is a command that clears status messages after a timeout\nfunc (m statusCmp) clearMessageCmd(ttl time.Duration) tea.Cmd {\n\treturn tea.Tick(ttl, func(time.Time) tea.Msg {\n\t\treturn util.ClearStatusMsg{}\n\t})\n}\n\nfunc (m statusCmp) Init() tea.Cmd {\n\treturn nil\n}\n\nfunc (m statusCmp) Update(msg tea.Msg) (tea.Model, tea.Cmd) {\n\tswitch msg := msg.(type) {\n\tcase tea.WindowSizeMsg:\n\t\tm.width = msg.Width\n\t\treturn m, nil\n\tcase chat.SessionSelectedMsg:\n\t\tm.session = msg\n\tcase chat.SessionClearedMsg:\n\t\tm.session = session.Session{}\n\tcase pubsub.Event[session.Session]:\n\t\tif msg.Type == pubsub.UpdatedEvent {\n\t\t\tif m.session.ID == msg.Payload.ID {\n\t\t\t\tm.session = msg.Payload\n\t\t\t}\n\t\t}\n\tcase util.InfoMsg:\n\t\tm.info = msg\n\t\tttl := msg.TTL\n\t\tif ttl == 0 {\n\t\t\tttl = m.messageTTL\n\t\t}\n\t\treturn m, m.clearMessageCmd(ttl)\n\tcase util.ClearStatusMsg:\n\t\tm.info = util.InfoMsg{}\n\t}\n\treturn m, nil\n}\n\nvar helpWidget = \"\"\n\n// getHelpWidget returns the help widget with current theme colors\nfunc getHelpWidget() string {\n\tt := theme.CurrentTheme()\n\thelpText := \"ctrl+? help\"\n\n\treturn styles.Padded().\n\t\tBackground(t.TextMuted()).\n\t\tForeground(t.BackgroundDarker()).\n\t\tBold(true).\n\t\tRender(helpText)\n}\n\nfunc formatTokensAndCost(tokens, contextWindow int64, cost float64) string {\n\t// Format tokens in human-readable format (e.g., 110K, 1.2M)\n\tvar formattedTokens string\n\tswitch {\n\tcase tokens >= 1_000_000:\n\t\tformattedTokens = fmt.Sprintf(\"%.1fM\", float64(tokens)/1_000_000)\n\tcase tokens >= 1_000:\n\t\tformattedTokens = fmt.Sprintf(\"%.1fK\", float64(tokens)/1_000)\n\tdefault:\n\t\tformattedTokens = fmt.Sprintf(\"%d\", tokens)\n\t}\n\n\t// Remove .0 suffix if present\n\tif strings.HasSuffix(formattedTokens, \".0K\") {\n\t\tformattedTokens = strings.Replace(formattedTokens, \".0K\", \"K\", 1)\n\t}\n\tif strings.HasSuffix(formattedTokens, \".0M\") {\n\t\tformattedTokens = strings.Replace(formattedTokens, \".0M\", \"M\", 1)\n\t}\n\n\t// Format cost with $ symbol and 2 decimal places\n\tformattedCost := fmt.Sprintf(\"$%.2f\", cost)\n\n\tpercentage := (float64(tokens) / float64(contextWindow)) * 100\n\tif percentage > 80 {\n\t\t// add the warning icon and percentage\n\t\tformattedTokens = fmt.Sprintf(\"%s(%d%%)\", styles.WarningIcon, int(percentage))\n\t}\n\n\treturn fmt.Sprintf(\"Context: %s, Cost: %s\", formattedTokens, formattedCost)\n}\n\nfunc (m statusCmp) View() string {\n\tt := theme.CurrentTheme()\n\tmodelID := config.Get().Agents[config.AgentCoder].Model\n\tmodel := models.SupportedModels[modelID]\n\n\t// Initialize the help widget\n\tstatus := getHelpWidget()\n\n\ttokenInfoWidth := 0\n\tif m.session.ID != \"\" {\n\t\ttotalTokens := m.session.PromptTokens + m.session.CompletionTokens\n\t\ttokens := formatTokensAndCost(totalTokens, model.ContextWindow, m.session.Cost)\n\t\ttokensStyle := styles.Padded().\n\t\t\tBackground(t.Text()).\n\t\t\tForeground(t.BackgroundSecondary())\n\t\tpercentage := (float64(totalTokens) / float64(model.ContextWindow)) * 100\n\t\tif percentage > 80 {\n\t\t\ttokensStyle = tokensStyle.Background(t.Warning())\n\t\t}\n\t\ttokenInfoWidth = lipgloss.Width(tokens) + 2\n\t\tstatus += tokensStyle.Render(tokens)\n\t}\n\n\tdiagnostics := styles.Padded().\n\t\tBackground(t.BackgroundDarker()).\n\t\tRender(m.projectDiagnostics())\n\n\tavailableWidht := max(0, m.width-lipgloss.Width(helpWidget)-lipgloss.Width(m.model())-lipgloss.Width(diagnostics)-tokenInfoWidth)\n\n\tif m.info.Msg != \"\" {\n\t\tinfoStyle := styles.Padded().\n\t\t\tForeground(t.Background()).\n\t\t\tWidth(availableWidht)\n\n\t\tswitch m.info.Type {\n\t\tcase util.InfoTypeInfo:\n\t\t\tinfoStyle = infoStyle.Background(t.Info())\n\t\tcase util.InfoTypeWarn:\n\t\t\tinfoStyle = infoStyle.Background(t.Warning())\n\t\tcase util.InfoTypeError:\n\t\t\tinfoStyle = infoStyle.Background(t.Error())\n\t\t}\n\n\t\tinfoWidth := availableWidht - 10\n\t\t// Truncate message if it's longer than available width\n\t\tmsg := m.info.Msg\n\t\tif len(msg) > infoWidth && infoWidth > 0 {\n\t\t\tmsg = msg[:infoWidth] + \"...\"\n\t\t}\n\t\tstatus += infoStyle.Render(msg)\n\t} else {\n\t\tstatus += styles.Padded().\n\t\t\tForeground(t.Text()).\n\t\t\tBackground(t.BackgroundSecondary()).\n\t\t\tWidth(availableWidht).\n\t\t\tRender(\"\")\n\t}\n\n\tstatus += diagnostics\n\tstatus += m.model()\n\treturn status\n}\n\nfunc (m *statusCmp) projectDiagnostics() string {\n\tt := theme.CurrentTheme()\n\n\t// Check if any LSP server is still initializing\n\tinitializing := false\n\tfor _, client := range m.lspClients {\n\t\tif client.GetServerState() == lsp.StateStarting {\n\t\t\tinitializing = true\n\t\t\tbreak\n\t\t}\n\t}\n\n\t// If any server is initializing, show that status\n\tif initializing {\n\t\treturn lipgloss.NewStyle().\n\t\t\tBackground(t.BackgroundDarker()).\n\t\t\tForeground(t.Warning()).\n\t\t\tRender(fmt.Sprintf(\"%s Initializing LSP...\", styles.SpinnerIcon))\n\t}\n\n\terrorDiagnostics := []protocol.Diagnostic{}\n\twarnDiagnostics := []protocol.Diagnostic{}\n\thintDiagnostics := []protocol.Diagnostic{}\n\tinfoDiagnostics := []protocol.Diagnostic{}\n\tfor _, client := range m.lspClients {\n\t\tfor _, d := range client.GetDiagnostics() {\n\t\t\tfor _, diag := range d {\n\t\t\t\tswitch diag.Severity {\n\t\t\t\tcase protocol.SeverityError:\n\t\t\t\t\terrorDiagnostics = append(errorDiagnostics, diag)\n\t\t\t\tcase protocol.SeverityWarning:\n\t\t\t\t\twarnDiagnostics = append(warnDiagnostics, diag)\n\t\t\t\tcase protocol.SeverityHint:\n\t\t\t\t\thintDiagnostics = append(hintDiagnostics, diag)\n\t\t\t\tcase protocol.SeverityInformation:\n\t\t\t\t\tinfoDiagnostics = append(infoDiagnostics, diag)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif len(errorDiagnostics) == 0 && len(warnDiagnostics) == 0 && len(hintDiagnostics) == 0 && len(infoDiagnostics) == 0 {\n\t\treturn \"No diagnostics\"\n\t}\n\n\tdiagnostics := []string{}\n\n\tif len(errorDiagnostics) > 0 {\n\t\terrStr := lipgloss.NewStyle().\n\t\t\tBackground(t.BackgroundDarker()).\n\t\t\tForeground(t.Error()).\n\t\t\tRender(fmt.Sprintf(\"%s %d\", styles.ErrorIcon, len(errorDiagnostics)))\n\t\tdiagnostics = append(diagnostics, errStr)\n\t}\n\tif len(warnDiagnostics) > 0 {\n\t\twarnStr := lipgloss.NewStyle().\n\t\t\tBackground(t.BackgroundDarker()).\n\t\t\tForeground(t.Warning()).\n\t\t\tRender(fmt.Sprintf(\"%s %d\", styles.WarningIcon, len(warnDiagnostics)))\n\t\tdiagnostics = append(diagnostics, warnStr)\n\t}\n\tif len(hintDiagnostics) > 0 {\n\t\thintStr := lipgloss.NewStyle().\n\t\t\tBackground(t.BackgroundDarker()).\n\t\t\tForeground(t.Text()).\n\t\t\tRender(fmt.Sprintf(\"%s %d\", styles.HintIcon, len(hintDiagnostics)))\n\t\tdiagnostics = append(diagnostics, hintStr)\n\t}\n\tif len(infoDiagnostics) > 0 {\n\t\tinfoStr := lipgloss.NewStyle().\n\t\t\tBackground(t.BackgroundDarker()).\n\t\t\tForeground(t.Info()).\n\t\t\tRender(fmt.Sprintf(\"%s %d\", styles.InfoIcon, len(infoDiagnostics)))\n\t\tdiagnostics = append(diagnostics, infoStr)\n\t}\n\n\treturn strings.Join(diagnostics, \" \")\n}\n\nfunc (m statusCmp) availableFooterMsgWidth(diagnostics, tokenInfo string) int {\n\ttokensWidth := 0\n\tif m.session.ID != \"\" {\n\t\ttokensWidth = lipgloss.Width(tokenInfo) + 2\n\t}\n\treturn max(0, m.width-lipgloss.Width(helpWidget)-lipgloss.Width(m.model())-lipgloss.Width(diagnostics)-tokensWidth)\n}\n\nfunc (m statusCmp) model() string {\n\tt := theme.CurrentTheme()\n\n\tcfg := config.Get()\n\n\tcoder, ok := cfg.Agents[config.AgentCoder]\n\tif !ok {\n\t\treturn \"Unknown\"\n\t}\n\tmodel := models.SupportedModels[coder.Model]\n\n\treturn styles.Padded().\n\t\tBackground(t.Secondary()).\n\t\tForeground(t.Background()).\n\t\tRender(model.Name)\n}\n\nfunc NewStatusCmp(lspClients map[string]*lsp.Client) StatusCmp {\n\thelpWidget = getHelpWidget()\n\n\treturn &statusCmp{\n\t\tmessageTTL: 10 * time.Second,\n\t\tlspClients: lspClients,\n\t}\n}\n"], ["/opencode/internal/llm/provider/vertexai.go", "package provider\n\nimport (\n\t\"context\"\n\t\"os\"\n\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n\t\"google.golang.org/genai\"\n)\n\ntype VertexAIClient ProviderClient\n\nfunc newVertexAIClient(opts providerClientOptions) VertexAIClient {\n\tgeminiOpts := geminiOptions{}\n\tfor _, o := range opts.geminiOptions {\n\t\to(&geminiOpts)\n\t}\n\n\tclient, err := genai.NewClient(context.Background(), &genai.ClientConfig{\n\t\tProject: os.Getenv(\"VERTEXAI_PROJECT\"),\n\t\tLocation: os.Getenv(\"VERTEXAI_LOCATION\"),\n\t\tBackend: genai.BackendVertexAI,\n\t})\n\tif err != nil {\n\t\tlogging.Error(\"Failed to create VertexAI client\", \"error\", err)\n\t\treturn nil\n\t}\n\n\treturn &geminiClient{\n\t\tproviderOptions: opts,\n\t\toptions: geminiOpts,\n\t\tclient: client,\n\t}\n}\n"], ["/opencode/internal/lsp/protocol/tsdocument-changes.go", "// Copyright 2022 The Go Authors. All rights reserved.\n// Use of this source code is governed by a BSD-style\n// license that can be found in the LICENSE file.\n\npackage protocol\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n)\n\n// DocumentChange is a union of various file edit operations.\n//\n// Exactly one field of this struct is non-nil; see [DocumentChange.Valid].\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#resourceChanges\ntype DocumentChange struct {\n\tTextDocumentEdit *TextDocumentEdit\n\tCreateFile *CreateFile\n\tRenameFile *RenameFile\n\tDeleteFile *DeleteFile\n}\n\n// Valid reports whether the DocumentChange sum-type value is valid,\n// that is, exactly one of create, delete, edit, or rename.\nfunc (ch DocumentChange) Valid() bool {\n\tn := 0\n\tif ch.TextDocumentEdit != nil {\n\t\tn++\n\t}\n\tif ch.CreateFile != nil {\n\t\tn++\n\t}\n\tif ch.RenameFile != nil {\n\t\tn++\n\t}\n\tif ch.DeleteFile != nil {\n\t\tn++\n\t}\n\treturn n == 1\n}\n\nfunc (d *DocumentChange) UnmarshalJSON(data []byte) error {\n\tvar m map[string]any\n\tif err := json.Unmarshal(data, &m); err != nil {\n\t\treturn err\n\t}\n\n\tif _, ok := m[\"textDocument\"]; ok {\n\t\td.TextDocumentEdit = new(TextDocumentEdit)\n\t\treturn json.Unmarshal(data, d.TextDocumentEdit)\n\t}\n\n\t// The {Create,Rename,Delete}File types all share a 'kind' field.\n\tkind := m[\"kind\"]\n\tswitch kind {\n\tcase \"create\":\n\t\td.CreateFile = new(CreateFile)\n\t\treturn json.Unmarshal(data, d.CreateFile)\n\tcase \"rename\":\n\t\td.RenameFile = new(RenameFile)\n\t\treturn json.Unmarshal(data, d.RenameFile)\n\tcase \"delete\":\n\t\td.DeleteFile = new(DeleteFile)\n\t\treturn json.Unmarshal(data, d.DeleteFile)\n\t}\n\treturn fmt.Errorf(\"DocumentChanges: unexpected kind: %q\", kind)\n}\n\nfunc (d *DocumentChange) MarshalJSON() ([]byte, error) {\n\tif d.TextDocumentEdit != nil {\n\t\treturn json.Marshal(d.TextDocumentEdit)\n\t} else if d.CreateFile != nil {\n\t\treturn json.Marshal(d.CreateFile)\n\t} else if d.RenameFile != nil {\n\t\treturn json.Marshal(d.RenameFile)\n\t} else if d.DeleteFile != nil {\n\t\treturn json.Marshal(d.DeleteFile)\n\t}\n\treturn nil, fmt.Errorf(\"empty DocumentChanges union value\")\n}\n"], ["/opencode/internal/tui/components/dialog/theme.go", "package dialog\n\nimport (\n\t\"github.com/charmbracelet/bubbles/key\"\n\ttea \"github.com/charmbracelet/bubbletea\"\n\t\"github.com/charmbracelet/lipgloss\"\n\t\"github.com/opencode-ai/opencode/internal/tui/layout\"\n\t\"github.com/opencode-ai/opencode/internal/tui/styles\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n\t\"github.com/opencode-ai/opencode/internal/tui/util\"\n)\n\n// ThemeChangedMsg is sent when the theme is changed\ntype ThemeChangedMsg struct {\n\tThemeName string\n}\n\n// CloseThemeDialogMsg is sent when the theme dialog is closed\ntype CloseThemeDialogMsg struct{}\n\n// ThemeDialog interface for the theme switching dialog\ntype ThemeDialog interface {\n\ttea.Model\n\tlayout.Bindings\n}\n\ntype themeDialogCmp struct {\n\tthemes []string\n\tselectedIdx int\n\twidth int\n\theight int\n\tcurrentTheme string\n}\n\ntype themeKeyMap struct {\n\tUp key.Binding\n\tDown key.Binding\n\tEnter key.Binding\n\tEscape key.Binding\n\tJ key.Binding\n\tK key.Binding\n}\n\nvar themeKeys = themeKeyMap{\n\tUp: key.NewBinding(\n\t\tkey.WithKeys(\"up\"),\n\t\tkey.WithHelp(\"↑\", \"previous theme\"),\n\t),\n\tDown: key.NewBinding(\n\t\tkey.WithKeys(\"down\"),\n\t\tkey.WithHelp(\"↓\", \"next theme\"),\n\t),\n\tEnter: key.NewBinding(\n\t\tkey.WithKeys(\"enter\"),\n\t\tkey.WithHelp(\"enter\", \"select theme\"),\n\t),\n\tEscape: key.NewBinding(\n\t\tkey.WithKeys(\"esc\"),\n\t\tkey.WithHelp(\"esc\", \"close\"),\n\t),\n\tJ: key.NewBinding(\n\t\tkey.WithKeys(\"j\"),\n\t\tkey.WithHelp(\"j\", \"next theme\"),\n\t),\n\tK: key.NewBinding(\n\t\tkey.WithKeys(\"k\"),\n\t\tkey.WithHelp(\"k\", \"previous theme\"),\n\t),\n}\n\nfunc (t *themeDialogCmp) Init() tea.Cmd {\n\t// Load available themes and update selectedIdx based on current theme\n\tt.themes = theme.AvailableThemes()\n\tt.currentTheme = theme.CurrentThemeName()\n\n\t// Find the current theme in the list\n\tfor i, name := range t.themes {\n\t\tif name == t.currentTheme {\n\t\t\tt.selectedIdx = i\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc (t *themeDialogCmp) Update(msg tea.Msg) (tea.Model, tea.Cmd) {\n\tswitch msg := msg.(type) {\n\tcase tea.KeyMsg:\n\t\tswitch {\n\t\tcase key.Matches(msg, themeKeys.Up) || key.Matches(msg, themeKeys.K):\n\t\t\tif t.selectedIdx > 0 {\n\t\t\t\tt.selectedIdx--\n\t\t\t}\n\t\t\treturn t, nil\n\t\tcase key.Matches(msg, themeKeys.Down) || key.Matches(msg, themeKeys.J):\n\t\t\tif t.selectedIdx < len(t.themes)-1 {\n\t\t\t\tt.selectedIdx++\n\t\t\t}\n\t\t\treturn t, nil\n\t\tcase key.Matches(msg, themeKeys.Enter):\n\t\t\tif len(t.themes) > 0 {\n\t\t\t\tpreviousTheme := theme.CurrentThemeName()\n\t\t\t\tselectedTheme := t.themes[t.selectedIdx]\n\t\t\t\tif previousTheme == selectedTheme {\n\t\t\t\t\treturn t, util.CmdHandler(CloseThemeDialogMsg{})\n\t\t\t\t}\n\t\t\t\tif err := theme.SetTheme(selectedTheme); err != nil {\n\t\t\t\t\treturn t, util.ReportError(err)\n\t\t\t\t}\n\t\t\t\treturn t, util.CmdHandler(ThemeChangedMsg{\n\t\t\t\t\tThemeName: selectedTheme,\n\t\t\t\t})\n\t\t\t}\n\t\tcase key.Matches(msg, themeKeys.Escape):\n\t\t\treturn t, util.CmdHandler(CloseThemeDialogMsg{})\n\t\t}\n\tcase tea.WindowSizeMsg:\n\t\tt.width = msg.Width\n\t\tt.height = msg.Height\n\t}\n\treturn t, nil\n}\n\nfunc (t *themeDialogCmp) View() string {\n\tcurrentTheme := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\n\tif len(t.themes) == 0 {\n\t\treturn baseStyle.Padding(1, 2).\n\t\t\tBorder(lipgloss.RoundedBorder()).\n\t\t\tBorderBackground(currentTheme.Background()).\n\t\t\tBorderForeground(currentTheme.TextMuted()).\n\t\t\tWidth(40).\n\t\t\tRender(\"No themes available\")\n\t}\n\n\t// Calculate max width needed for theme names\n\tmaxWidth := 40 // Minimum width\n\tfor _, themeName := range t.themes {\n\t\tif len(themeName) > maxWidth-4 { // Account for padding\n\t\t\tmaxWidth = len(themeName) + 4\n\t\t}\n\t}\n\n\tmaxWidth = max(30, min(maxWidth, t.width-15)) // Limit width to avoid overflow\n\n\t// Build the theme list\n\tthemeItems := make([]string, 0, len(t.themes))\n\tfor i, themeName := range t.themes {\n\t\titemStyle := baseStyle.Width(maxWidth)\n\n\t\tif i == t.selectedIdx {\n\t\t\titemStyle = itemStyle.\n\t\t\t\tBackground(currentTheme.Primary()).\n\t\t\t\tForeground(currentTheme.Background()).\n\t\t\t\tBold(true)\n\t\t}\n\n\t\tthemeItems = append(themeItems, itemStyle.Padding(0, 1).Render(themeName))\n\t}\n\n\ttitle := baseStyle.\n\t\tForeground(currentTheme.Primary()).\n\t\tBold(true).\n\t\tWidth(maxWidth).\n\t\tPadding(0, 1).\n\t\tRender(\"Select Theme\")\n\n\tcontent := lipgloss.JoinVertical(\n\t\tlipgloss.Left,\n\t\ttitle,\n\t\tbaseStyle.Width(maxWidth).Render(\"\"),\n\t\tbaseStyle.Width(maxWidth).Render(lipgloss.JoinVertical(lipgloss.Left, themeItems...)),\n\t\tbaseStyle.Width(maxWidth).Render(\"\"),\n\t)\n\n\treturn baseStyle.Padding(1, 2).\n\t\tBorder(lipgloss.RoundedBorder()).\n\t\tBorderBackground(currentTheme.Background()).\n\t\tBorderForeground(currentTheme.TextMuted()).\n\t\tWidth(lipgloss.Width(content) + 4).\n\t\tRender(content)\n}\n\nfunc (t *themeDialogCmp) BindingKeys() []key.Binding {\n\treturn layout.KeyMapToSlice(themeKeys)\n}\n\n// NewThemeDialogCmp creates a new theme switching dialog\nfunc NewThemeDialogCmp() ThemeDialog {\n\treturn &themeDialogCmp{\n\t\tthemes: []string{},\n\t\tselectedIdx: 0,\n\t\tcurrentTheme: \"\",\n\t}\n}\n\n"], ["/opencode/internal/llm/prompt/coder.go", "package prompt\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"runtime\"\n\t\"time\"\n\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/llm/models\"\n\t\"github.com/opencode-ai/opencode/internal/llm/tools\"\n)\n\nfunc CoderPrompt(provider models.ModelProvider) string {\n\tbasePrompt := baseAnthropicCoderPrompt\n\tswitch provider {\n\tcase models.ProviderOpenAI:\n\t\tbasePrompt = baseOpenAICoderPrompt\n\t}\n\tenvInfo := getEnvironmentInfo()\n\n\treturn fmt.Sprintf(\"%s\\n\\n%s\\n%s\", basePrompt, envInfo, lspInformation())\n}\n\nconst baseOpenAICoderPrompt = `\nYou are operating as and within the OpenCode CLI, a terminal-based agentic coding assistant built by OpenAI. It wraps OpenAI models to enable natural language interaction with a local codebase. You are expected to be precise, safe, and helpful.\n\nYou can:\n- Receive user prompts, project context, and files.\n- Stream responses and emit function calls (e.g., shell commands, code edits).\n- Apply patches, run commands, and manage user approvals based on policy.\n- Work inside a sandboxed, git-backed workspace with rollback support.\n- Log telemetry so sessions can be replayed or inspected later.\n- More details on your functionality are available at \"opencode --help\"\n\n\nYou are an agent - please keep going until the user's query is completely resolved, before ending your turn and yielding back to the user. Only terminate your turn when you are sure that the problem is solved. If you are not sure about file content or codebase structure pertaining to the user's request, use your tools to read files and gather the relevant information: do NOT guess or make up an answer.\n\nPlease resolve the user's task by editing and testing the code files in your current code execution session. You are a deployed coding agent. Your session allows for you to modify and run code. The repo(s) are already cloned in your working directory, and you must fully solve the problem for your answer to be considered correct.\n\nYou MUST adhere to the following criteria when executing the task:\n- Working on the repo(s) in the current environment is allowed, even if they are proprietary.\n- Analyzing code for vulnerabilities is allowed.\n- Showing user code and tool call details is allowed.\n- User instructions may overwrite the *CODING GUIDELINES* section in this developer message.\n- If completing the user's task requires writing or modifying files:\n - Your code and final answer should follow these *CODING GUIDELINES*:\n - Fix the problem at the root cause rather than applying surface-level patches, when possible.\n - Avoid unneeded complexity in your solution.\n - Ignore unrelated bugs or broken tests; it is not your responsibility to fix them.\n - Update documentation as necessary.\n - Keep changes consistent with the style of the existing codebase. Changes should be minimal and focused on the task.\n - Use \"git log\" and \"git blame\" to search the history of the codebase if additional context is required; internet access is disabled.\n - NEVER add copyright or license headers unless specifically requested.\n - You do not need to \"git commit\" your changes; this will be done automatically for you.\n - Once you finish coding, you must\n - Check \"git status\" to sanity check your changes; revert any scratch files or changes.\n - Remove all inline comments you added as much as possible, even if they look normal. Check using \"git diff\". Inline comments must be generally avoided, unless active maintainers of the repo, after long careful study of the code and the issue, will still misinterpret the code without the comments.\n - Check if you accidentally add copyright or license headers. If so, remove them.\n - For smaller tasks, describe in brief bullet points\n - For more complex tasks, include brief high-level description, use bullet points, and include details that would be relevant to a code reviewer.\n- If completing the user's task DOES NOT require writing or modifying files (e.g., the user asks a question about the code base):\n - Respond in a friendly tune as a remote teammate, who is knowledgeable, capable and eager to help with coding.\n- When your task involves writing or modifying files:\n - Do NOT tell the user to \"save the file\" or \"copy the code into a file\" if you already created or modified the file using \"apply_patch\". Instead, reference the file as already saved.\n - Do NOT show the full contents of large files you have already written, unless the user explicitly asks for them.\n- When doing things with paths, always use use the full path, if the working directory is /abc/xyz and you want to edit the file abc.go in the working dir refer to it as /abc/xyz/abc.go.\n- If you send a path not including the working dir, the working dir will be prepended to it.\n- Remember the user does not see the full output of tools\n`\n\nconst baseAnthropicCoderPrompt = `You are OpenCode, an interactive CLI tool that helps users with software engineering tasks. Use the instructions below and the tools available to you to assist the user.\n\nIMPORTANT: Before you begin work, think about what the code you're editing is supposed to do based on the filenames directory structure.\n\n# Memory\nIf the current working directory contains a file called OpenCode.md, it will be automatically added to your context. This file serves multiple purposes:\n1. Storing frequently used bash commands (build, test, lint, etc.) so you can use them without searching each time\n2. Recording the user's code style preferences (naming conventions, preferred libraries, etc.)\n3. Maintaining useful information about the codebase structure and organization\n\nWhen you spend time searching for commands to typecheck, lint, build, or test, you should ask the user if it's okay to add those commands to OpenCode.md. Similarly, when learning about code style preferences or important codebase information, ask if it's okay to add that to OpenCode.md so you can remember it for next time.\n\n# Tone and style\nYou should be concise, direct, and to the point. When you run a non-trivial bash command, you should explain what the command does and why you are running it, to make sure the user understands what you are doing (this is especially important when you are running a command that will make changes to the user's system).\nRemember that your output will be displayed on a command line interface. Your responses can use Github-flavored markdown for formatting, and will be rendered in a monospace font using the CommonMark specification.\nOutput text to communicate with the user; all text you output outside of tool use is displayed to the user. Only use tools to complete tasks. Never use tools like Bash or code comments as means to communicate with the user during the session.\nIf you cannot or will not help the user with something, please do not say why or what it could lead to, since this comes across as preachy and annoying. Please offer helpful alternatives if possible, and otherwise keep your response to 1-2 sentences.\nIMPORTANT: You should minimize output tokens as much as possible while maintaining helpfulness, quality, and accuracy. Only address the specific query or task at hand, avoiding tangential information unless absolutely critical for completing the request. If you can answer in 1-3 sentences or a short paragraph, please do.\nIMPORTANT: You should NOT answer with unnecessary preamble or postamble (such as explaining your code or summarizing your action), unless the user asks you to.\nIMPORTANT: Keep your responses short, since they will be displayed on a command line interface. You MUST answer concisely with fewer than 4 lines (not including tool use or code generation), unless user asks for detail. Answer the user's question directly, without elaboration, explanation, or details. One word answers are best. Avoid introductions, conclusions, and explanations. You MUST avoid text before/after your response, such as \"The answer is .\", \"Here is the content of the file...\" or \"Based on the information provided, the answer is...\" or \"Here is what I will do next...\". Here are some examples to demonstrate appropriate verbosity:\n\nuser: 2 + 2\nassistant: 4\n\n\n\nuser: what is 2+2?\nassistant: 4\n\n\n\nuser: is 11 a prime number?\nassistant: true\n\n\n\nuser: what command should I run to list files in the current directory?\nassistant: ls\n\n\n\nuser: what command should I run to watch files in the current directory?\nassistant: [use the ls tool to list the files in the current directory, then read docs/commands in the relevant file to find out how to watch files]\nnpm run dev\n\n\n\nuser: How many golf balls fit inside a jetta?\nassistant: 150000\n\n\n\nuser: what files are in the directory src/?\nassistant: [runs ls and sees foo.c, bar.c, baz.c]\nuser: which file contains the implementation of foo?\nassistant: src/foo.c\n\n\n\nuser: write tests for new feature\nassistant: [uses grep and glob search tools to find where similar tests are defined, uses concurrent read file tool use blocks in one tool call to read relevant files at the same time, uses edit/patch file tool to write new tests]\n\n\n# Proactiveness\nYou are allowed to be proactive, but only when the user asks you to do something. You should strive to strike a balance between:\n1. Doing the right thing when asked, including taking actions and follow-up actions\n2. Not surprising the user with actions you take without asking\nFor example, if the user asks you how to approach something, you should do your best to answer their question first, and not immediately jump into taking actions.\n3. Do not add additional code explanation summary unless requested by the user. After working on a file, just stop, rather than providing an explanation of what you did.\n\n# Following conventions\nWhen making changes to files, first understand the file's code conventions. Mimic code style, use existing libraries and utilities, and follow existing patterns.\n- NEVER assume that a given library is available, even if it is well known. Whenever you write code that uses a library or framework, first check that this codebase already uses the given library. For example, you might look at neighboring files, or check the package.json (or cargo.toml, and so on depending on the language).\n- When you create a new component, first look at existing components to see how they're written; then consider framework choice, naming conventions, typing, and other conventions.\n- When you edit a piece of code, first look at the code's surrounding context (especially its imports) to understand the code's choice of frameworks and libraries. Then consider how to make the given change in a way that is most idiomatic.\n- Always follow security best practices. Never introduce code that exposes or logs secrets and keys. Never commit secrets or keys to the repository.\n\n# Code style\n- Do not add comments to the code you write, unless the user asks you to, or the code is complex and requires additional context.\n\n# Doing tasks\nThe user will primarily request you perform software engineering tasks. This includes solving bugs, adding new functionality, refactoring code, explaining code, and more. For these tasks the following steps are recommended:\n1. Use the available search tools to understand the codebase and the user's query. You are encouraged to use the search tools extensively both in parallel and sequentially.\n2. Implement the solution using all tools available to you\n3. Verify the solution if possible with tests. NEVER assume specific test framework or test script. Check the README or search codebase to determine the testing approach.\n4. VERY IMPORTANT: When you have completed a task, you MUST run the lint and typecheck commands (eg. npm run lint, npm run typecheck, ruff, etc.) if they were provided to you to ensure your code is correct. If you are unable to find the correct command, ask the user for the command to run and if they supply it, proactively suggest writing it to opencode.md so that you will know to run it next time.\n\nNEVER commit changes unless the user explicitly asks you to. It is VERY IMPORTANT to only commit when explicitly asked, otherwise the user will feel that you are being too proactive.\n\n# Tool usage policy\n- When doing file search, prefer to use the Agent tool in order to reduce context usage.\n- If you intend to call multiple tools and there are no dependencies between the calls, make all of the independent calls in the same function_calls block.\n- IMPORTANT: The user does not see the full output of the tool responses, so if you need the output of the tool for the response make sure to summarize it for the user.\n\nYou MUST answer concisely with fewer than 4 lines of text (not including tool use or code generation), unless user asks for detail.`\n\nfunc getEnvironmentInfo() string {\n\tcwd := config.WorkingDirectory()\n\tisGit := isGitRepo(cwd)\n\tplatform := runtime.GOOS\n\tdate := time.Now().Format(\"1/2/2006\")\n\tls := tools.NewLsTool()\n\tr, _ := ls.Run(context.Background(), tools.ToolCall{\n\t\tInput: `{\"path\":\".\"}`,\n\t})\n\treturn fmt.Sprintf(`Here is useful information about the environment you are running in:\n\nWorking directory: %s\nIs directory a git repo: %s\nPlatform: %s\nToday's date: %s\n\n\n%s\n\n\t\t`, cwd, boolToYesNo(isGit), platform, date, r.Content)\n}\n\nfunc isGitRepo(dir string) bool {\n\t_, err := os.Stat(filepath.Join(dir, \".git\"))\n\treturn err == nil\n}\n\nfunc lspInformation() string {\n\tcfg := config.Get()\n\thasLSP := false\n\tfor _, v := range cfg.LSP {\n\t\tif !v.Disabled {\n\t\t\thasLSP = true\n\t\t\tbreak\n\t\t}\n\t}\n\tif !hasLSP {\n\t\treturn \"\"\n\t}\n\treturn `# LSP Information\nTools that support it will also include useful diagnostics such as linting and typechecking.\n- These diagnostics will be automatically enabled when you run the tool, and will be displayed in the output at the bottom within the and tags.\n- Take necessary actions to fix the issues.\n- You should ignore diagnostics of files that you did not change or are not related or caused by your changes unless the user explicitly asks you to fix them.\n`\n}\n\nfunc boolToYesNo(b bool) string {\n\tif b {\n\t\treturn \"Yes\"\n\t}\n\treturn \"No\"\n}\n"], ["/opencode/internal/tui/components/logs/details.go", "package logs\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/charmbracelet/bubbles/key\"\n\t\"github.com/charmbracelet/bubbles/viewport\"\n\ttea \"github.com/charmbracelet/bubbletea\"\n\t\"github.com/charmbracelet/lipgloss\"\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n\t\"github.com/opencode-ai/opencode/internal/tui/layout\"\n\t\"github.com/opencode-ai/opencode/internal/tui/styles\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n)\n\ntype DetailComponent interface {\n\ttea.Model\n\tlayout.Sizeable\n\tlayout.Bindings\n}\n\ntype detailCmp struct {\n\twidth, height int\n\tcurrentLog logging.LogMessage\n\tviewport viewport.Model\n}\n\nfunc (i *detailCmp) Init() tea.Cmd {\n\tmessages := logging.List()\n\tif len(messages) == 0 {\n\t\treturn nil\n\t}\n\ti.currentLog = messages[0]\n\treturn nil\n}\n\nfunc (i *detailCmp) Update(msg tea.Msg) (tea.Model, tea.Cmd) {\n\tswitch msg := msg.(type) {\n\tcase selectedLogMsg:\n\t\tif msg.ID != i.currentLog.ID {\n\t\t\ti.currentLog = logging.LogMessage(msg)\n\t\t\ti.updateContent()\n\t\t}\n\t}\n\n\treturn i, nil\n}\n\nfunc (i *detailCmp) updateContent() {\n\tvar content strings.Builder\n\tt := theme.CurrentTheme()\n\n\t// Format the header with timestamp and level\n\ttimeStyle := lipgloss.NewStyle().Foreground(t.TextMuted())\n\tlevelStyle := getLevelStyle(i.currentLog.Level)\n\n\theader := lipgloss.JoinHorizontal(\n\t\tlipgloss.Center,\n\t\ttimeStyle.Render(i.currentLog.Time.Format(time.RFC3339)),\n\t\t\" \",\n\t\tlevelStyle.Render(i.currentLog.Level),\n\t)\n\n\tcontent.WriteString(lipgloss.NewStyle().Bold(true).Render(header))\n\tcontent.WriteString(\"\\n\\n\")\n\n\t// Message with styling\n\tmessageStyle := lipgloss.NewStyle().Bold(true).Foreground(t.Text())\n\tcontent.WriteString(messageStyle.Render(\"Message:\"))\n\tcontent.WriteString(\"\\n\")\n\tcontent.WriteString(lipgloss.NewStyle().Padding(0, 2).Render(i.currentLog.Message))\n\tcontent.WriteString(\"\\n\\n\")\n\n\t// Attributes section\n\tif len(i.currentLog.Attributes) > 0 {\n\t\tattrHeaderStyle := lipgloss.NewStyle().Bold(true).Foreground(t.Text())\n\t\tcontent.WriteString(attrHeaderStyle.Render(\"Attributes:\"))\n\t\tcontent.WriteString(\"\\n\")\n\n\t\t// Create a table-like display for attributes\n\t\tkeyStyle := lipgloss.NewStyle().Foreground(t.Primary()).Bold(true)\n\t\tvalueStyle := lipgloss.NewStyle().Foreground(t.Text())\n\n\t\tfor _, attr := range i.currentLog.Attributes {\n\t\t\tattrLine := fmt.Sprintf(\"%s: %s\",\n\t\t\t\tkeyStyle.Render(attr.Key),\n\t\t\t\tvalueStyle.Render(attr.Value),\n\t\t\t)\n\t\t\tcontent.WriteString(lipgloss.NewStyle().Padding(0, 2).Render(attrLine))\n\t\t\tcontent.WriteString(\"\\n\")\n\t\t}\n\t}\n\n\ti.viewport.SetContent(content.String())\n}\n\nfunc getLevelStyle(level string) lipgloss.Style {\n\tstyle := lipgloss.NewStyle().Bold(true)\n\tt := theme.CurrentTheme()\n\t\n\tswitch strings.ToLower(level) {\n\tcase \"info\":\n\t\treturn style.Foreground(t.Info())\n\tcase \"warn\", \"warning\":\n\t\treturn style.Foreground(t.Warning())\n\tcase \"error\", \"err\":\n\t\treturn style.Foreground(t.Error())\n\tcase \"debug\":\n\t\treturn style.Foreground(t.Success())\n\tdefault:\n\t\treturn style.Foreground(t.Text())\n\t}\n}\n\nfunc (i *detailCmp) View() string {\n\tt := theme.CurrentTheme()\n\treturn styles.ForceReplaceBackgroundWithLipgloss(i.viewport.View(), t.Background())\n}\n\nfunc (i *detailCmp) GetSize() (int, int) {\n\treturn i.width, i.height\n}\n\nfunc (i *detailCmp) SetSize(width int, height int) tea.Cmd {\n\ti.width = width\n\ti.height = height\n\ti.viewport.Width = i.width\n\ti.viewport.Height = i.height\n\ti.updateContent()\n\treturn nil\n}\n\nfunc (i *detailCmp) BindingKeys() []key.Binding {\n\treturn layout.KeyMapToSlice(i.viewport.KeyMap)\n}\n\nfunc NewLogsDetails() DetailComponent {\n\treturn &detailCmp{\n\t\tviewport: viewport.New(0, 0),\n\t}\n}\n"], ["/opencode/internal/format/format.go", "package format\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"strings\"\n)\n\n// OutputFormat represents the output format type for non-interactive mode\ntype OutputFormat string\n\nconst (\n\t// Text format outputs the AI response as plain text.\n\tText OutputFormat = \"text\"\n\n\t// JSON format outputs the AI response wrapped in a JSON object.\n\tJSON OutputFormat = \"json\"\n)\n\n// String returns the string representation of the OutputFormat\nfunc (f OutputFormat) String() string {\n\treturn string(f)\n}\n\n// SupportedFormats is a list of all supported output formats as strings\nvar SupportedFormats = []string{\n\tstring(Text),\n\tstring(JSON),\n}\n\n// Parse converts a string to an OutputFormat\nfunc Parse(s string) (OutputFormat, error) {\n\ts = strings.ToLower(strings.TrimSpace(s))\n\n\tswitch s {\n\tcase string(Text):\n\t\treturn Text, nil\n\tcase string(JSON):\n\t\treturn JSON, nil\n\tdefault:\n\t\treturn \"\", fmt.Errorf(\"invalid format: %s\", s)\n\t}\n}\n\n// IsValid checks if the provided format string is supported\nfunc IsValid(s string) bool {\n\t_, err := Parse(s)\n\treturn err == nil\n}\n\n// GetHelpText returns a formatted string describing all supported formats\nfunc GetHelpText() string {\n\treturn fmt.Sprintf(`Supported output formats:\n- %s: Plain text output (default)\n- %s: Output wrapped in a JSON object`,\n\t\tText, JSON)\n}\n\n// FormatOutput formats the AI response according to the specified format\nfunc FormatOutput(content string, formatStr string) string {\n\tformat, err := Parse(formatStr)\n\tif err != nil {\n\t\t// Default to text format on error\n\t\treturn content\n\t}\n\n\tswitch format {\n\tcase JSON:\n\t\treturn formatAsJSON(content)\n\tcase Text:\n\t\tfallthrough\n\tdefault:\n\t\treturn content\n\t}\n}\n\n// formatAsJSON wraps the content in a simple JSON object\nfunc formatAsJSON(content string) string {\n\t// Use the JSON package to properly escape the content\n\tresponse := struct {\n\t\tResponse string `json:\"response\"`\n\t}{\n\t\tResponse: content,\n\t}\n\n\tjsonBytes, err := json.MarshalIndent(response, \"\", \" \")\n\tif err != nil {\n\t\t// In case of an error, return a manually formatted JSON\n\t\tjsonEscaped := strings.Replace(content, \"\\\\\", \"\\\\\\\\\", -1)\n\t\tjsonEscaped = strings.Replace(jsonEscaped, \"\\\"\", \"\\\\\\\"\", -1)\n\t\tjsonEscaped = strings.Replace(jsonEscaped, \"\\n\", \"\\\\n\", -1)\n\t\tjsonEscaped = strings.Replace(jsonEscaped, \"\\r\", \"\\\\r\", -1)\n\t\tjsonEscaped = strings.Replace(jsonEscaped, \"\\t\", \"\\\\t\", -1)\n\n\t\treturn fmt.Sprintf(\"{\\n \\\"response\\\": \\\"%s\\\"\\n}\", jsonEscaped)\n\t}\n\n\treturn string(jsonBytes)\n}\n"], ["/opencode/internal/llm/provider/provider.go", "package provider\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"os\"\n\n\t\"github.com/opencode-ai/opencode/internal/llm/models\"\n\t\"github.com/opencode-ai/opencode/internal/llm/tools\"\n\t\"github.com/opencode-ai/opencode/internal/message\"\n)\n\ntype EventType string\n\nconst maxRetries = 8\n\nconst (\n\tEventContentStart EventType = \"content_start\"\n\tEventToolUseStart EventType = \"tool_use_start\"\n\tEventToolUseDelta EventType = \"tool_use_delta\"\n\tEventToolUseStop EventType = \"tool_use_stop\"\n\tEventContentDelta EventType = \"content_delta\"\n\tEventThinkingDelta EventType = \"thinking_delta\"\n\tEventContentStop EventType = \"content_stop\"\n\tEventComplete EventType = \"complete\"\n\tEventError EventType = \"error\"\n\tEventWarning EventType = \"warning\"\n)\n\ntype TokenUsage struct {\n\tInputTokens int64\n\tOutputTokens int64\n\tCacheCreationTokens int64\n\tCacheReadTokens int64\n}\n\ntype ProviderResponse struct {\n\tContent string\n\tToolCalls []message.ToolCall\n\tUsage TokenUsage\n\tFinishReason message.FinishReason\n}\n\ntype ProviderEvent struct {\n\tType EventType\n\n\tContent string\n\tThinking string\n\tResponse *ProviderResponse\n\tToolCall *message.ToolCall\n\tError error\n}\ntype Provider interface {\n\tSendMessages(ctx context.Context, messages []message.Message, tools []tools.BaseTool) (*ProviderResponse, error)\n\n\tStreamResponse(ctx context.Context, messages []message.Message, tools []tools.BaseTool) <-chan ProviderEvent\n\n\tModel() models.Model\n}\n\ntype providerClientOptions struct {\n\tapiKey string\n\tmodel models.Model\n\tmaxTokens int64\n\tsystemMessage string\n\n\tanthropicOptions []AnthropicOption\n\topenaiOptions []OpenAIOption\n\tgeminiOptions []GeminiOption\n\tbedrockOptions []BedrockOption\n\tcopilotOptions []CopilotOption\n}\n\ntype ProviderClientOption func(*providerClientOptions)\n\ntype ProviderClient interface {\n\tsend(ctx context.Context, messages []message.Message, tools []tools.BaseTool) (*ProviderResponse, error)\n\tstream(ctx context.Context, messages []message.Message, tools []tools.BaseTool) <-chan ProviderEvent\n}\n\ntype baseProvider[C ProviderClient] struct {\n\toptions providerClientOptions\n\tclient C\n}\n\nfunc NewProvider(providerName models.ModelProvider, opts ...ProviderClientOption) (Provider, error) {\n\tclientOptions := providerClientOptions{}\n\tfor _, o := range opts {\n\t\to(&clientOptions)\n\t}\n\tswitch providerName {\n\tcase models.ProviderCopilot:\n\t\treturn &baseProvider[CopilotClient]{\n\t\t\toptions: clientOptions,\n\t\t\tclient: newCopilotClient(clientOptions),\n\t\t}, nil\n\tcase models.ProviderAnthropic:\n\t\treturn &baseProvider[AnthropicClient]{\n\t\t\toptions: clientOptions,\n\t\t\tclient: newAnthropicClient(clientOptions),\n\t\t}, nil\n\tcase models.ProviderOpenAI:\n\t\treturn &baseProvider[OpenAIClient]{\n\t\t\toptions: clientOptions,\n\t\t\tclient: newOpenAIClient(clientOptions),\n\t\t}, nil\n\tcase models.ProviderGemini:\n\t\treturn &baseProvider[GeminiClient]{\n\t\t\toptions: clientOptions,\n\t\t\tclient: newGeminiClient(clientOptions),\n\t\t}, nil\n\tcase models.ProviderBedrock:\n\t\treturn &baseProvider[BedrockClient]{\n\t\t\toptions: clientOptions,\n\t\t\tclient: newBedrockClient(clientOptions),\n\t\t}, nil\n\tcase models.ProviderGROQ:\n\t\tclientOptions.openaiOptions = append(clientOptions.openaiOptions,\n\t\t\tWithOpenAIBaseURL(\"https://api.groq.com/openai/v1\"),\n\t\t)\n\t\treturn &baseProvider[OpenAIClient]{\n\t\t\toptions: clientOptions,\n\t\t\tclient: newOpenAIClient(clientOptions),\n\t\t}, nil\n\tcase models.ProviderAzure:\n\t\treturn &baseProvider[AzureClient]{\n\t\t\toptions: clientOptions,\n\t\t\tclient: newAzureClient(clientOptions),\n\t\t}, nil\n\tcase models.ProviderVertexAI:\n\t\treturn &baseProvider[VertexAIClient]{\n\t\t\toptions: clientOptions,\n\t\t\tclient: newVertexAIClient(clientOptions),\n\t\t}, nil\n\tcase models.ProviderOpenRouter:\n\t\tclientOptions.openaiOptions = append(clientOptions.openaiOptions,\n\t\t\tWithOpenAIBaseURL(\"https://openrouter.ai/api/v1\"),\n\t\t\tWithOpenAIExtraHeaders(map[string]string{\n\t\t\t\t\"HTTP-Referer\": \"opencode.ai\",\n\t\t\t\t\"X-Title\": \"OpenCode\",\n\t\t\t}),\n\t\t)\n\t\treturn &baseProvider[OpenAIClient]{\n\t\t\toptions: clientOptions,\n\t\t\tclient: newOpenAIClient(clientOptions),\n\t\t}, nil\n\tcase models.ProviderXAI:\n\t\tclientOptions.openaiOptions = append(clientOptions.openaiOptions,\n\t\t\tWithOpenAIBaseURL(\"https://api.x.ai/v1\"),\n\t\t)\n\t\treturn &baseProvider[OpenAIClient]{\n\t\t\toptions: clientOptions,\n\t\t\tclient: newOpenAIClient(clientOptions),\n\t\t}, nil\n\tcase models.ProviderLocal:\n\t\tclientOptions.openaiOptions = append(clientOptions.openaiOptions,\n\t\t\tWithOpenAIBaseURL(os.Getenv(\"LOCAL_ENDPOINT\")),\n\t\t)\n\t\treturn &baseProvider[OpenAIClient]{\n\t\t\toptions: clientOptions,\n\t\t\tclient: newOpenAIClient(clientOptions),\n\t\t}, nil\n\tcase models.ProviderMock:\n\t\t// TODO: implement mock client for test\n\t\tpanic(\"not implemented\")\n\t}\n\treturn nil, fmt.Errorf(\"provider not supported: %s\", providerName)\n}\n\nfunc (p *baseProvider[C]) cleanMessages(messages []message.Message) (cleaned []message.Message) {\n\tfor _, msg := range messages {\n\t\t// The message has no content\n\t\tif len(msg.Parts) == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tcleaned = append(cleaned, msg)\n\t}\n\treturn\n}\n\nfunc (p *baseProvider[C]) SendMessages(ctx context.Context, messages []message.Message, tools []tools.BaseTool) (*ProviderResponse, error) {\n\tmessages = p.cleanMessages(messages)\n\treturn p.client.send(ctx, messages, tools)\n}\n\nfunc (p *baseProvider[C]) Model() models.Model {\n\treturn p.options.model\n}\n\nfunc (p *baseProvider[C]) StreamResponse(ctx context.Context, messages []message.Message, tools []tools.BaseTool) <-chan ProviderEvent {\n\tmessages = p.cleanMessages(messages)\n\treturn p.client.stream(ctx, messages, tools)\n}\n\nfunc WithAPIKey(apiKey string) ProviderClientOption {\n\treturn func(options *providerClientOptions) {\n\t\toptions.apiKey = apiKey\n\t}\n}\n\nfunc WithModel(model models.Model) ProviderClientOption {\n\treturn func(options *providerClientOptions) {\n\t\toptions.model = model\n\t}\n}\n\nfunc WithMaxTokens(maxTokens int64) ProviderClientOption {\n\treturn func(options *providerClientOptions) {\n\t\toptions.maxTokens = maxTokens\n\t}\n}\n\nfunc WithSystemMessage(systemMessage string) ProviderClientOption {\n\treturn func(options *providerClientOptions) {\n\t\toptions.systemMessage = systemMessage\n\t}\n}\n\nfunc WithAnthropicOptions(anthropicOptions ...AnthropicOption) ProviderClientOption {\n\treturn func(options *providerClientOptions) {\n\t\toptions.anthropicOptions = anthropicOptions\n\t}\n}\n\nfunc WithOpenAIOptions(openaiOptions ...OpenAIOption) ProviderClientOption {\n\treturn func(options *providerClientOptions) {\n\t\toptions.openaiOptions = openaiOptions\n\t}\n}\n\nfunc WithGeminiOptions(geminiOptions ...GeminiOption) ProviderClientOption {\n\treturn func(options *providerClientOptions) {\n\t\toptions.geminiOptions = geminiOptions\n\t}\n}\n\nfunc WithBedrockOptions(bedrockOptions ...BedrockOption) ProviderClientOption {\n\treturn func(options *providerClientOptions) {\n\t\toptions.bedrockOptions = bedrockOptions\n\t}\n}\n\nfunc WithCopilotOptions(copilotOptions ...CopilotOption) ProviderClientOption {\n\treturn func(options *providerClientOptions) {\n\t\toptions.copilotOptions = copilotOptions\n\t}\n}\n"], ["/opencode/cmd/schema/main.go", "package main\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"os\"\n\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/llm/models\"\n)\n\n// JSONSchemaType represents a JSON Schema type\ntype JSONSchemaType struct {\n\tType string `json:\"type,omitempty\"`\n\tDescription string `json:\"description,omitempty\"`\n\tProperties map[string]any `json:\"properties,omitempty\"`\n\tRequired []string `json:\"required,omitempty\"`\n\tAdditionalProperties any `json:\"additionalProperties,omitempty\"`\n\tEnum []any `json:\"enum,omitempty\"`\n\tItems map[string]any `json:\"items,omitempty\"`\n\tOneOf []map[string]any `json:\"oneOf,omitempty\"`\n\tAnyOf []map[string]any `json:\"anyOf,omitempty\"`\n\tDefault any `json:\"default,omitempty\"`\n}\n\nfunc main() {\n\tschema := generateSchema()\n\n\t// Pretty print the schema\n\tencoder := json.NewEncoder(os.Stdout)\n\tencoder.SetIndent(\"\", \" \")\n\tif err := encoder.Encode(schema); err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"Error encoding schema: %v\\n\", err)\n\t\tos.Exit(1)\n\t}\n}\n\nfunc generateSchema() map[string]any {\n\tschema := map[string]any{\n\t\t\"$schema\": \"http://json-schema.org/draft-07/schema#\",\n\t\t\"title\": \"OpenCode Configuration\",\n\t\t\"description\": \"Configuration schema for the OpenCode application\",\n\t\t\"type\": \"object\",\n\t\t\"properties\": map[string]any{},\n\t}\n\n\t// Add Data configuration\n\tschema[\"properties\"].(map[string]any)[\"data\"] = map[string]any{\n\t\t\"type\": \"object\",\n\t\t\"description\": \"Storage configuration\",\n\t\t\"properties\": map[string]any{\n\t\t\t\"directory\": map[string]any{\n\t\t\t\t\"type\": \"string\",\n\t\t\t\t\"description\": \"Directory where application data is stored\",\n\t\t\t\t\"default\": \".opencode\",\n\t\t\t},\n\t\t},\n\t\t\"required\": []string{\"directory\"},\n\t}\n\n\t// Add working directory\n\tschema[\"properties\"].(map[string]any)[\"wd\"] = map[string]any{\n\t\t\"type\": \"string\",\n\t\t\"description\": \"Working directory for the application\",\n\t}\n\n\t// Add debug flags\n\tschema[\"properties\"].(map[string]any)[\"debug\"] = map[string]any{\n\t\t\"type\": \"boolean\",\n\t\t\"description\": \"Enable debug mode\",\n\t\t\"default\": false,\n\t}\n\n\tschema[\"properties\"].(map[string]any)[\"debugLSP\"] = map[string]any{\n\t\t\"type\": \"boolean\",\n\t\t\"description\": \"Enable LSP debug mode\",\n\t\t\"default\": false,\n\t}\n\n\tschema[\"properties\"].(map[string]any)[\"contextPaths\"] = map[string]any{\n\t\t\"type\": \"array\",\n\t\t\"description\": \"Context paths for the application\",\n\t\t\"items\": map[string]any{\n\t\t\t\"type\": \"string\",\n\t\t},\n\t\t\"default\": []string{\n\t\t\t\".github/copilot-instructions.md\",\n\t\t\t\".cursorrules\",\n\t\t\t\".cursor/rules/\",\n\t\t\t\"CLAUDE.md\",\n\t\t\t\"CLAUDE.local.md\",\n\t\t\t\"opencode.md\",\n\t\t\t\"opencode.local.md\",\n\t\t\t\"OpenCode.md\",\n\t\t\t\"OpenCode.local.md\",\n\t\t\t\"OPENCODE.md\",\n\t\t\t\"OPENCODE.local.md\",\n\t\t},\n\t}\n\n\tschema[\"properties\"].(map[string]any)[\"tui\"] = map[string]any{\n\t\t\"type\": \"object\",\n\t\t\"description\": \"Terminal User Interface configuration\",\n\t\t\"properties\": map[string]any{\n\t\t\t\"theme\": map[string]any{\n\t\t\t\t\"type\": \"string\",\n\t\t\t\t\"description\": \"TUI theme name\",\n\t\t\t\t\"default\": \"opencode\",\n\t\t\t\t\"enum\": []string{\n\t\t\t\t\t\"opencode\",\n\t\t\t\t\t\"catppuccin\",\n\t\t\t\t\t\"dracula\",\n\t\t\t\t\t\"flexoki\",\n\t\t\t\t\t\"gruvbox\",\n\t\t\t\t\t\"monokai\",\n\t\t\t\t\t\"onedark\",\n\t\t\t\t\t\"tokyonight\",\n\t\t\t\t\t\"tron\",\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\t// Add MCP servers\n\tschema[\"properties\"].(map[string]any)[\"mcpServers\"] = map[string]any{\n\t\t\"type\": \"object\",\n\t\t\"description\": \"Model Control Protocol server configurations\",\n\t\t\"additionalProperties\": map[string]any{\n\t\t\t\"type\": \"object\",\n\t\t\t\"description\": \"MCP server configuration\",\n\t\t\t\"properties\": map[string]any{\n\t\t\t\t\"command\": map[string]any{\n\t\t\t\t\t\"type\": \"string\",\n\t\t\t\t\t\"description\": \"Command to execute for the MCP server\",\n\t\t\t\t},\n\t\t\t\t\"env\": map[string]any{\n\t\t\t\t\t\"type\": \"array\",\n\t\t\t\t\t\"description\": \"Environment variables for the MCP server\",\n\t\t\t\t\t\"items\": map[string]any{\n\t\t\t\t\t\t\"type\": \"string\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t\"args\": map[string]any{\n\t\t\t\t\t\"type\": \"array\",\n\t\t\t\t\t\"description\": \"Command arguments for the MCP server\",\n\t\t\t\t\t\"items\": map[string]any{\n\t\t\t\t\t\t\"type\": \"string\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t\"type\": map[string]any{\n\t\t\t\t\t\"type\": \"string\",\n\t\t\t\t\t\"description\": \"Type of MCP server\",\n\t\t\t\t\t\"enum\": []string{\"stdio\", \"sse\"},\n\t\t\t\t\t\"default\": \"stdio\",\n\t\t\t\t},\n\t\t\t\t\"url\": map[string]any{\n\t\t\t\t\t\"type\": \"string\",\n\t\t\t\t\t\"description\": \"URL for SSE type MCP servers\",\n\t\t\t\t},\n\t\t\t\t\"headers\": map[string]any{\n\t\t\t\t\t\"type\": \"object\",\n\t\t\t\t\t\"description\": \"HTTP headers for SSE type MCP servers\",\n\t\t\t\t\t\"additionalProperties\": map[string]any{\n\t\t\t\t\t\t\"type\": \"string\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\t\"required\": []string{\"command\"},\n\t\t},\n\t}\n\n\t// Add providers\n\tproviderSchema := map[string]any{\n\t\t\"type\": \"object\",\n\t\t\"description\": \"LLM provider configurations\",\n\t\t\"additionalProperties\": map[string]any{\n\t\t\t\"type\": \"object\",\n\t\t\t\"description\": \"Provider configuration\",\n\t\t\t\"properties\": map[string]any{\n\t\t\t\t\"apiKey\": map[string]any{\n\t\t\t\t\t\"type\": \"string\",\n\t\t\t\t\t\"description\": \"API key for the provider\",\n\t\t\t\t},\n\t\t\t\t\"disabled\": map[string]any{\n\t\t\t\t\t\"type\": \"boolean\",\n\t\t\t\t\t\"description\": \"Whether the provider is disabled\",\n\t\t\t\t\t\"default\": false,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\t// Add known providers\n\tknownProviders := []string{\n\t\tstring(models.ProviderAnthropic),\n\t\tstring(models.ProviderOpenAI),\n\t\tstring(models.ProviderGemini),\n\t\tstring(models.ProviderGROQ),\n\t\tstring(models.ProviderOpenRouter),\n\t\tstring(models.ProviderBedrock),\n\t\tstring(models.ProviderAzure),\n\t\tstring(models.ProviderVertexAI),\n\t}\n\n\tproviderSchema[\"additionalProperties\"].(map[string]any)[\"properties\"].(map[string]any)[\"provider\"] = map[string]any{\n\t\t\"type\": \"string\",\n\t\t\"description\": \"Provider type\",\n\t\t\"enum\": knownProviders,\n\t}\n\n\tschema[\"properties\"].(map[string]any)[\"providers\"] = providerSchema\n\n\t// Add agents\n\tagentSchema := map[string]any{\n\t\t\"type\": \"object\",\n\t\t\"description\": \"Agent configurations\",\n\t\t\"additionalProperties\": map[string]any{\n\t\t\t\"type\": \"object\",\n\t\t\t\"description\": \"Agent configuration\",\n\t\t\t\"properties\": map[string]any{\n\t\t\t\t\"model\": map[string]any{\n\t\t\t\t\t\"type\": \"string\",\n\t\t\t\t\t\"description\": \"Model ID for the agent\",\n\t\t\t\t},\n\t\t\t\t\"maxTokens\": map[string]any{\n\t\t\t\t\t\"type\": \"integer\",\n\t\t\t\t\t\"description\": \"Maximum tokens for the agent\",\n\t\t\t\t\t\"minimum\": 1,\n\t\t\t\t},\n\t\t\t\t\"reasoningEffort\": map[string]any{\n\t\t\t\t\t\"type\": \"string\",\n\t\t\t\t\t\"description\": \"Reasoning effort for models that support it (OpenAI, Anthropic)\",\n\t\t\t\t\t\"enum\": []string{\"low\", \"medium\", \"high\"},\n\t\t\t\t},\n\t\t\t},\n\t\t\t\"required\": []string{\"model\"},\n\t\t},\n\t}\n\n\t// Add model enum\n\tmodelEnum := []string{}\n\tfor modelID := range models.SupportedModels {\n\t\tmodelEnum = append(modelEnum, string(modelID))\n\t}\n\tagentSchema[\"additionalProperties\"].(map[string]any)[\"properties\"].(map[string]any)[\"model\"].(map[string]any)[\"enum\"] = modelEnum\n\n\t// Add specific agent properties\n\tagentProperties := map[string]any{}\n\tknownAgents := []string{\n\t\tstring(config.AgentCoder),\n\t\tstring(config.AgentTask),\n\t\tstring(config.AgentTitle),\n\t}\n\n\tfor _, agentName := range knownAgents {\n\t\tagentProperties[agentName] = map[string]any{\n\t\t\t\"$ref\": \"#/definitions/agent\",\n\t\t}\n\t}\n\n\t// Create a combined schema that allows both specific agents and additional ones\n\tcombinedAgentSchema := map[string]any{\n\t\t\"type\": \"object\",\n\t\t\"description\": \"Agent configurations\",\n\t\t\"properties\": agentProperties,\n\t\t\"additionalProperties\": agentSchema[\"additionalProperties\"],\n\t}\n\n\tschema[\"properties\"].(map[string]any)[\"agents\"] = combinedAgentSchema\n\tschema[\"definitions\"] = map[string]any{\n\t\t\"agent\": agentSchema[\"additionalProperties\"],\n\t}\n\n\t// Add LSP configuration\n\tschema[\"properties\"].(map[string]any)[\"lsp\"] = map[string]any{\n\t\t\"type\": \"object\",\n\t\t\"description\": \"Language Server Protocol configurations\",\n\t\t\"additionalProperties\": map[string]any{\n\t\t\t\"type\": \"object\",\n\t\t\t\"description\": \"LSP configuration for a language\",\n\t\t\t\"properties\": map[string]any{\n\t\t\t\t\"disabled\": map[string]any{\n\t\t\t\t\t\"type\": \"boolean\",\n\t\t\t\t\t\"description\": \"Whether the LSP is disabled\",\n\t\t\t\t\t\"default\": false,\n\t\t\t\t},\n\t\t\t\t\"command\": map[string]any{\n\t\t\t\t\t\"type\": \"string\",\n\t\t\t\t\t\"description\": \"Command to execute for the LSP server\",\n\t\t\t\t},\n\t\t\t\t\"args\": map[string]any{\n\t\t\t\t\t\"type\": \"array\",\n\t\t\t\t\t\"description\": \"Command arguments for the LSP server\",\n\t\t\t\t\t\"items\": map[string]any{\n\t\t\t\t\t\t\"type\": \"string\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t\"options\": map[string]any{\n\t\t\t\t\t\"type\": \"object\",\n\t\t\t\t\t\"description\": \"Additional options for the LSP server\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t\"required\": []string{\"command\"},\n\t\t},\n\t}\n\n\treturn schema\n}\n"], ["/opencode/internal/tui/components/dialog/models.go", "package dialog\n\nimport (\n\t\"fmt\"\n\t\"slices\"\n\t\"strings\"\n\n\t\"github.com/charmbracelet/bubbles/key\"\n\ttea \"github.com/charmbracelet/bubbletea\"\n\t\"github.com/charmbracelet/lipgloss\"\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/llm/models\"\n\t\"github.com/opencode-ai/opencode/internal/tui/layout\"\n\t\"github.com/opencode-ai/opencode/internal/tui/styles\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n\t\"github.com/opencode-ai/opencode/internal/tui/util\"\n)\n\nconst (\n\tnumVisibleModels = 10\n\tmaxDialogWidth = 40\n)\n\n// ModelSelectedMsg is sent when a model is selected\ntype ModelSelectedMsg struct {\n\tModel models.Model\n}\n\n// CloseModelDialogMsg is sent when a model is selected\ntype CloseModelDialogMsg struct{}\n\n// ModelDialog interface for the model selection dialog\ntype ModelDialog interface {\n\ttea.Model\n\tlayout.Bindings\n}\n\ntype modelDialogCmp struct {\n\tmodels []models.Model\n\tprovider models.ModelProvider\n\tavailableProviders []models.ModelProvider\n\n\tselectedIdx int\n\twidth int\n\theight int\n\tscrollOffset int\n\thScrollOffset int\n\thScrollPossible bool\n}\n\ntype modelKeyMap struct {\n\tUp key.Binding\n\tDown key.Binding\n\tLeft key.Binding\n\tRight key.Binding\n\tEnter key.Binding\n\tEscape key.Binding\n\tJ key.Binding\n\tK key.Binding\n\tH key.Binding\n\tL key.Binding\n}\n\nvar modelKeys = modelKeyMap{\n\tUp: key.NewBinding(\n\t\tkey.WithKeys(\"up\"),\n\t\tkey.WithHelp(\"↑\", \"previous model\"),\n\t),\n\tDown: key.NewBinding(\n\t\tkey.WithKeys(\"down\"),\n\t\tkey.WithHelp(\"↓\", \"next model\"),\n\t),\n\tLeft: key.NewBinding(\n\t\tkey.WithKeys(\"left\"),\n\t\tkey.WithHelp(\"←\", \"scroll left\"),\n\t),\n\tRight: key.NewBinding(\n\t\tkey.WithKeys(\"right\"),\n\t\tkey.WithHelp(\"→\", \"scroll right\"),\n\t),\n\tEnter: key.NewBinding(\n\t\tkey.WithKeys(\"enter\"),\n\t\tkey.WithHelp(\"enter\", \"select model\"),\n\t),\n\tEscape: key.NewBinding(\n\t\tkey.WithKeys(\"esc\"),\n\t\tkey.WithHelp(\"esc\", \"close\"),\n\t),\n\tJ: key.NewBinding(\n\t\tkey.WithKeys(\"j\"),\n\t\tkey.WithHelp(\"j\", \"next model\"),\n\t),\n\tK: key.NewBinding(\n\t\tkey.WithKeys(\"k\"),\n\t\tkey.WithHelp(\"k\", \"previous model\"),\n\t),\n\tH: key.NewBinding(\n\t\tkey.WithKeys(\"h\"),\n\t\tkey.WithHelp(\"h\", \"scroll left\"),\n\t),\n\tL: key.NewBinding(\n\t\tkey.WithKeys(\"l\"),\n\t\tkey.WithHelp(\"l\", \"scroll right\"),\n\t),\n}\n\nfunc (m *modelDialogCmp) Init() tea.Cmd {\n\tm.setupModels()\n\treturn nil\n}\n\nfunc (m *modelDialogCmp) Update(msg tea.Msg) (tea.Model, tea.Cmd) {\n\tswitch msg := msg.(type) {\n\tcase tea.KeyMsg:\n\t\tswitch {\n\t\tcase key.Matches(msg, modelKeys.Up) || key.Matches(msg, modelKeys.K):\n\t\t\tm.moveSelectionUp()\n\t\tcase key.Matches(msg, modelKeys.Down) || key.Matches(msg, modelKeys.J):\n\t\t\tm.moveSelectionDown()\n\t\tcase key.Matches(msg, modelKeys.Left) || key.Matches(msg, modelKeys.H):\n\t\t\tif m.hScrollPossible {\n\t\t\t\tm.switchProvider(-1)\n\t\t\t}\n\t\tcase key.Matches(msg, modelKeys.Right) || key.Matches(msg, modelKeys.L):\n\t\t\tif m.hScrollPossible {\n\t\t\t\tm.switchProvider(1)\n\t\t\t}\n\t\tcase key.Matches(msg, modelKeys.Enter):\n\t\t\tutil.ReportInfo(fmt.Sprintf(\"selected model: %s\", m.models[m.selectedIdx].Name))\n\t\t\treturn m, util.CmdHandler(ModelSelectedMsg{Model: m.models[m.selectedIdx]})\n\t\tcase key.Matches(msg, modelKeys.Escape):\n\t\t\treturn m, util.CmdHandler(CloseModelDialogMsg{})\n\t\t}\n\tcase tea.WindowSizeMsg:\n\t\tm.width = msg.Width\n\t\tm.height = msg.Height\n\t}\n\n\treturn m, nil\n}\n\n// moveSelectionUp moves the selection up or wraps to bottom\nfunc (m *modelDialogCmp) moveSelectionUp() {\n\tif m.selectedIdx > 0 {\n\t\tm.selectedIdx--\n\t} else {\n\t\tm.selectedIdx = len(m.models) - 1\n\t\tm.scrollOffset = max(0, len(m.models)-numVisibleModels)\n\t}\n\n\t// Keep selection visible\n\tif m.selectedIdx < m.scrollOffset {\n\t\tm.scrollOffset = m.selectedIdx\n\t}\n}\n\n// moveSelectionDown moves the selection down or wraps to top\nfunc (m *modelDialogCmp) moveSelectionDown() {\n\tif m.selectedIdx < len(m.models)-1 {\n\t\tm.selectedIdx++\n\t} else {\n\t\tm.selectedIdx = 0\n\t\tm.scrollOffset = 0\n\t}\n\n\t// Keep selection visible\n\tif m.selectedIdx >= m.scrollOffset+numVisibleModels {\n\t\tm.scrollOffset = m.selectedIdx - (numVisibleModels - 1)\n\t}\n}\n\nfunc (m *modelDialogCmp) switchProvider(offset int) {\n\tnewOffset := m.hScrollOffset + offset\n\n\t// Ensure we stay within bounds\n\tif newOffset < 0 {\n\t\tnewOffset = len(m.availableProviders) - 1\n\t}\n\tif newOffset >= len(m.availableProviders) {\n\t\tnewOffset = 0\n\t}\n\n\tm.hScrollOffset = newOffset\n\tm.provider = m.availableProviders[m.hScrollOffset]\n\tm.setupModelsForProvider(m.provider)\n}\n\nfunc (m *modelDialogCmp) View() string {\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\n\t// Capitalize first letter of provider name\n\tproviderName := strings.ToUpper(string(m.provider)[:1]) + string(m.provider[1:])\n\ttitle := baseStyle.\n\t\tForeground(t.Primary()).\n\t\tBold(true).\n\t\tWidth(maxDialogWidth).\n\t\tPadding(0, 0, 1).\n\t\tRender(fmt.Sprintf(\"Select %s Model\", providerName))\n\n\t// Render visible models\n\tendIdx := min(m.scrollOffset+numVisibleModels, len(m.models))\n\tmodelItems := make([]string, 0, endIdx-m.scrollOffset)\n\n\tfor i := m.scrollOffset; i < endIdx; i++ {\n\t\titemStyle := baseStyle.Width(maxDialogWidth)\n\t\tif i == m.selectedIdx {\n\t\t\titemStyle = itemStyle.Background(t.Primary()).\n\t\t\t\tForeground(t.Background()).Bold(true)\n\t\t}\n\t\tmodelItems = append(modelItems, itemStyle.Render(m.models[i].Name))\n\t}\n\n\tscrollIndicator := m.getScrollIndicators(maxDialogWidth)\n\n\tcontent := lipgloss.JoinVertical(\n\t\tlipgloss.Left,\n\t\ttitle,\n\t\tbaseStyle.Width(maxDialogWidth).Render(lipgloss.JoinVertical(lipgloss.Left, modelItems...)),\n\t\tscrollIndicator,\n\t)\n\n\treturn baseStyle.Padding(1, 2).\n\t\tBorder(lipgloss.RoundedBorder()).\n\t\tBorderBackground(t.Background()).\n\t\tBorderForeground(t.TextMuted()).\n\t\tWidth(lipgloss.Width(content) + 4).\n\t\tRender(content)\n}\n\nfunc (m *modelDialogCmp) getScrollIndicators(maxWidth int) string {\n\tvar indicator string\n\n\tif len(m.models) > numVisibleModels {\n\t\tif m.scrollOffset > 0 {\n\t\t\tindicator += \"↑ \"\n\t\t}\n\t\tif m.scrollOffset+numVisibleModels < len(m.models) {\n\t\t\tindicator += \"↓ \"\n\t\t}\n\t}\n\n\tif m.hScrollPossible {\n\t\tif m.hScrollOffset > 0 {\n\t\t\tindicator = \"← \" + indicator\n\t\t}\n\t\tif m.hScrollOffset < len(m.availableProviders)-1 {\n\t\t\tindicator += \"→\"\n\t\t}\n\t}\n\n\tif indicator == \"\" {\n\t\treturn \"\"\n\t}\n\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\n\treturn baseStyle.\n\t\tForeground(t.Primary()).\n\t\tWidth(maxWidth).\n\t\tAlign(lipgloss.Right).\n\t\tBold(true).\n\t\tRender(indicator)\n}\n\nfunc (m *modelDialogCmp) BindingKeys() []key.Binding {\n\treturn layout.KeyMapToSlice(modelKeys)\n}\n\nfunc (m *modelDialogCmp) setupModels() {\n\tcfg := config.Get()\n\tmodelInfo := GetSelectedModel(cfg)\n\tm.availableProviders = getEnabledProviders(cfg)\n\tm.hScrollPossible = len(m.availableProviders) > 1\n\n\tm.provider = modelInfo.Provider\n\tm.hScrollOffset = findProviderIndex(m.availableProviders, m.provider)\n\n\tm.setupModelsForProvider(m.provider)\n}\n\nfunc GetSelectedModel(cfg *config.Config) models.Model {\n\n\tagentCfg := cfg.Agents[config.AgentCoder]\n\tselectedModelId := agentCfg.Model\n\treturn models.SupportedModels[selectedModelId]\n}\n\nfunc getEnabledProviders(cfg *config.Config) []models.ModelProvider {\n\tvar providers []models.ModelProvider\n\tfor providerId, provider := range cfg.Providers {\n\t\tif !provider.Disabled {\n\t\t\tproviders = append(providers, providerId)\n\t\t}\n\t}\n\n\t// Sort by provider popularity\n\tslices.SortFunc(providers, func(a, b models.ModelProvider) int {\n\t\trA := models.ProviderPopularity[a]\n\t\trB := models.ProviderPopularity[b]\n\n\t\t// models not included in popularity ranking default to last\n\t\tif rA == 0 {\n\t\t\trA = 999\n\t\t}\n\t\tif rB == 0 {\n\t\t\trB = 999\n\t\t}\n\t\treturn rA - rB\n\t})\n\treturn providers\n}\n\n// findProviderIndex returns the index of the provider in the list, or -1 if not found\nfunc findProviderIndex(providers []models.ModelProvider, provider models.ModelProvider) int {\n\tfor i, p := range providers {\n\t\tif p == provider {\n\t\t\treturn i\n\t\t}\n\t}\n\treturn -1\n}\n\nfunc (m *modelDialogCmp) setupModelsForProvider(provider models.ModelProvider) {\n\tcfg := config.Get()\n\tagentCfg := cfg.Agents[config.AgentCoder]\n\tselectedModelId := agentCfg.Model\n\n\tm.provider = provider\n\tm.models = getModelsForProvider(provider)\n\tm.selectedIdx = 0\n\tm.scrollOffset = 0\n\n\t// Try to select the current model if it belongs to this provider\n\tif provider == models.SupportedModels[selectedModelId].Provider {\n\t\tfor i, model := range m.models {\n\t\t\tif model.ID == selectedModelId {\n\t\t\t\tm.selectedIdx = i\n\t\t\t\t// Adjust scroll position to keep selected model visible\n\t\t\t\tif m.selectedIdx >= numVisibleModels {\n\t\t\t\t\tm.scrollOffset = m.selectedIdx - (numVisibleModels - 1)\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc getModelsForProvider(provider models.ModelProvider) []models.Model {\n\tvar providerModels []models.Model\n\tfor _, model := range models.SupportedModels {\n\t\tif model.Provider == provider {\n\t\t\tproviderModels = append(providerModels, model)\n\t\t}\n\t}\n\n\t// reverse alphabetical order (if llm naming was consistent latest would appear first)\n\tslices.SortFunc(providerModels, func(a, b models.Model) int {\n\t\tif a.Name > b.Name {\n\t\t\treturn -1\n\t\t} else if a.Name < b.Name {\n\t\t\treturn 1\n\t\t}\n\t\treturn 0\n\t})\n\n\treturn providerModels\n}\n\nfunc NewModelDialogCmp() ModelDialog {\n\treturn &modelDialogCmp{}\n}\n"], ["/opencode/internal/tui/components/dialog/session.go", "package dialog\n\nimport (\n\t\"github.com/charmbracelet/bubbles/key\"\n\ttea \"github.com/charmbracelet/bubbletea\"\n\t\"github.com/charmbracelet/lipgloss\"\n\t\"github.com/opencode-ai/opencode/internal/session\"\n\t\"github.com/opencode-ai/opencode/internal/tui/layout\"\n\t\"github.com/opencode-ai/opencode/internal/tui/styles\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n\t\"github.com/opencode-ai/opencode/internal/tui/util\"\n)\n\n// SessionSelectedMsg is sent when a session is selected\ntype SessionSelectedMsg struct {\n\tSession session.Session\n}\n\n// CloseSessionDialogMsg is sent when the session dialog is closed\ntype CloseSessionDialogMsg struct{}\n\n// SessionDialog interface for the session switching dialog\ntype SessionDialog interface {\n\ttea.Model\n\tlayout.Bindings\n\tSetSessions(sessions []session.Session)\n\tSetSelectedSession(sessionID string)\n}\n\ntype sessionDialogCmp struct {\n\tsessions []session.Session\n\tselectedIdx int\n\twidth int\n\theight int\n\tselectedSessionID string\n}\n\ntype sessionKeyMap struct {\n\tUp key.Binding\n\tDown key.Binding\n\tEnter key.Binding\n\tEscape key.Binding\n\tJ key.Binding\n\tK key.Binding\n}\n\nvar sessionKeys = sessionKeyMap{\n\tUp: key.NewBinding(\n\t\tkey.WithKeys(\"up\"),\n\t\tkey.WithHelp(\"↑\", \"previous session\"),\n\t),\n\tDown: key.NewBinding(\n\t\tkey.WithKeys(\"down\"),\n\t\tkey.WithHelp(\"↓\", \"next session\"),\n\t),\n\tEnter: key.NewBinding(\n\t\tkey.WithKeys(\"enter\"),\n\t\tkey.WithHelp(\"enter\", \"select session\"),\n\t),\n\tEscape: key.NewBinding(\n\t\tkey.WithKeys(\"esc\"),\n\t\tkey.WithHelp(\"esc\", \"close\"),\n\t),\n\tJ: key.NewBinding(\n\t\tkey.WithKeys(\"j\"),\n\t\tkey.WithHelp(\"j\", \"next session\"),\n\t),\n\tK: key.NewBinding(\n\t\tkey.WithKeys(\"k\"),\n\t\tkey.WithHelp(\"k\", \"previous session\"),\n\t),\n}\n\nfunc (s *sessionDialogCmp) Init() tea.Cmd {\n\treturn nil\n}\n\nfunc (s *sessionDialogCmp) Update(msg tea.Msg) (tea.Model, tea.Cmd) {\n\tswitch msg := msg.(type) {\n\tcase tea.KeyMsg:\n\t\tswitch {\n\t\tcase key.Matches(msg, sessionKeys.Up) || key.Matches(msg, sessionKeys.K):\n\t\t\tif s.selectedIdx > 0 {\n\t\t\t\ts.selectedIdx--\n\t\t\t}\n\t\t\treturn s, nil\n\t\tcase key.Matches(msg, sessionKeys.Down) || key.Matches(msg, sessionKeys.J):\n\t\t\tif s.selectedIdx < len(s.sessions)-1 {\n\t\t\t\ts.selectedIdx++\n\t\t\t}\n\t\t\treturn s, nil\n\t\tcase key.Matches(msg, sessionKeys.Enter):\n\t\t\tif len(s.sessions) > 0 {\n\t\t\t\treturn s, util.CmdHandler(SessionSelectedMsg{\n\t\t\t\t\tSession: s.sessions[s.selectedIdx],\n\t\t\t\t})\n\t\t\t}\n\t\tcase key.Matches(msg, sessionKeys.Escape):\n\t\t\treturn s, util.CmdHandler(CloseSessionDialogMsg{})\n\t\t}\n\tcase tea.WindowSizeMsg:\n\t\ts.width = msg.Width\n\t\ts.height = msg.Height\n\t}\n\treturn s, nil\n}\n\nfunc (s *sessionDialogCmp) View() string {\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\t\n\tif len(s.sessions) == 0 {\n\t\treturn baseStyle.Padding(1, 2).\n\t\t\tBorder(lipgloss.RoundedBorder()).\n\t\t\tBorderBackground(t.Background()).\n\t\t\tBorderForeground(t.TextMuted()).\n\t\t\tWidth(40).\n\t\t\tRender(\"No sessions available\")\n\t}\n\n\t// Calculate max width needed for session titles\n\tmaxWidth := 40 // Minimum width\n\tfor _, sess := range s.sessions {\n\t\tif len(sess.Title) > maxWidth-4 { // Account for padding\n\t\t\tmaxWidth = len(sess.Title) + 4\n\t\t}\n\t}\n\n\tmaxWidth = max(30, min(maxWidth, s.width-15)) // Limit width to avoid overflow\n\n\t// Limit height to avoid taking up too much screen space\n\tmaxVisibleSessions := min(10, len(s.sessions))\n\n\t// Build the session list\n\tsessionItems := make([]string, 0, maxVisibleSessions)\n\tstartIdx := 0\n\n\t// If we have more sessions than can be displayed, adjust the start index\n\tif len(s.sessions) > maxVisibleSessions {\n\t\t// Center the selected item when possible\n\t\thalfVisible := maxVisibleSessions / 2\n\t\tif s.selectedIdx >= halfVisible && s.selectedIdx < len(s.sessions)-halfVisible {\n\t\t\tstartIdx = s.selectedIdx - halfVisible\n\t\t} else if s.selectedIdx >= len(s.sessions)-halfVisible {\n\t\t\tstartIdx = len(s.sessions) - maxVisibleSessions\n\t\t}\n\t}\n\n\tendIdx := min(startIdx+maxVisibleSessions, len(s.sessions))\n\n\tfor i := startIdx; i < endIdx; i++ {\n\t\tsess := s.sessions[i]\n\t\titemStyle := baseStyle.Width(maxWidth)\n\n\t\tif i == s.selectedIdx {\n\t\t\titemStyle = itemStyle.\n\t\t\t\tBackground(t.Primary()).\n\t\t\t\tForeground(t.Background()).\n\t\t\t\tBold(true)\n\t\t}\n\n\t\tsessionItems = append(sessionItems, itemStyle.Padding(0, 1).Render(sess.Title))\n\t}\n\n\ttitle := baseStyle.\n\t\tForeground(t.Primary()).\n\t\tBold(true).\n\t\tWidth(maxWidth).\n\t\tPadding(0, 1).\n\t\tRender(\"Switch Session\")\n\n\tcontent := lipgloss.JoinVertical(\n\t\tlipgloss.Left,\n\t\ttitle,\n\t\tbaseStyle.Width(maxWidth).Render(\"\"),\n\t\tbaseStyle.Width(maxWidth).Render(lipgloss.JoinVertical(lipgloss.Left, sessionItems...)),\n\t\tbaseStyle.Width(maxWidth).Render(\"\"),\n\t)\n\n\treturn baseStyle.Padding(1, 2).\n\t\tBorder(lipgloss.RoundedBorder()).\n\t\tBorderBackground(t.Background()).\n\t\tBorderForeground(t.TextMuted()).\n\t\tWidth(lipgloss.Width(content) + 4).\n\t\tRender(content)\n}\n\nfunc (s *sessionDialogCmp) BindingKeys() []key.Binding {\n\treturn layout.KeyMapToSlice(sessionKeys)\n}\n\nfunc (s *sessionDialogCmp) SetSessions(sessions []session.Session) {\n\ts.sessions = sessions\n\n\t// If we have a selected session ID, find its index\n\tif s.selectedSessionID != \"\" {\n\t\tfor i, sess := range sessions {\n\t\t\tif sess.ID == s.selectedSessionID {\n\t\t\t\ts.selectedIdx = i\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\n\t// Default to first session if selected not found\n\ts.selectedIdx = 0\n}\n\nfunc (s *sessionDialogCmp) SetSelectedSession(sessionID string) {\n\ts.selectedSessionID = sessionID\n\n\t// Update the selected index if sessions are already loaded\n\tif len(s.sessions) > 0 {\n\t\tfor i, sess := range s.sessions {\n\t\t\tif sess.ID == sessionID {\n\t\t\t\ts.selectedIdx = i\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}\n\n// NewSessionDialogCmp creates a new session switching dialog\nfunc NewSessionDialogCmp() SessionDialog {\n\treturn &sessionDialogCmp{\n\t\tsessions: []session.Session{},\n\t\tselectedIdx: 0,\n\t\tselectedSessionID: \"\",\n\t}\n}\n"], ["/opencode/internal/tui/components/chat/chat.go", "package chat\n\nimport (\n\t\"fmt\"\n\t\"sort\"\n\n\t\"github.com/charmbracelet/lipgloss\"\n\t\"github.com/charmbracelet/x/ansi\"\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/message\"\n\t\"github.com/opencode-ai/opencode/internal/session\"\n\t\"github.com/opencode-ai/opencode/internal/tui/styles\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n\t\"github.com/opencode-ai/opencode/internal/version\"\n)\n\ntype SendMsg struct {\n\tText string\n\tAttachments []message.Attachment\n}\n\ntype SessionSelectedMsg = session.Session\n\ntype SessionClearedMsg struct{}\n\ntype EditorFocusMsg bool\n\nfunc header(width int) string {\n\treturn lipgloss.JoinVertical(\n\t\tlipgloss.Top,\n\t\tlogo(width),\n\t\trepo(width),\n\t\t\"\",\n\t\tcwd(width),\n\t)\n}\n\nfunc lspsConfigured(width int) string {\n\tcfg := config.Get()\n\ttitle := \"LSP Configuration\"\n\ttitle = ansi.Truncate(title, width, \"…\")\n\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\n\tlsps := baseStyle.\n\t\tWidth(width).\n\t\tForeground(t.Primary()).\n\t\tBold(true).\n\t\tRender(title)\n\n\t// Get LSP names and sort them for consistent ordering\n\tvar lspNames []string\n\tfor name := range cfg.LSP {\n\t\tlspNames = append(lspNames, name)\n\t}\n\tsort.Strings(lspNames)\n\n\tvar lspViews []string\n\tfor _, name := range lspNames {\n\t\tlsp := cfg.LSP[name]\n\t\tlspName := baseStyle.\n\t\t\tForeground(t.Text()).\n\t\t\tRender(fmt.Sprintf(\"• %s\", name))\n\n\t\tcmd := lsp.Command\n\t\tcmd = ansi.Truncate(cmd, width-lipgloss.Width(lspName)-3, \"…\")\n\n\t\tlspPath := baseStyle.\n\t\t\tForeground(t.TextMuted()).\n\t\t\tRender(fmt.Sprintf(\" (%s)\", cmd))\n\n\t\tlspViews = append(lspViews,\n\t\t\tbaseStyle.\n\t\t\t\tWidth(width).\n\t\t\t\tRender(\n\t\t\t\t\tlipgloss.JoinHorizontal(\n\t\t\t\t\t\tlipgloss.Left,\n\t\t\t\t\t\tlspName,\n\t\t\t\t\t\tlspPath,\n\t\t\t\t\t),\n\t\t\t\t),\n\t\t)\n\t}\n\n\treturn baseStyle.\n\t\tWidth(width).\n\t\tRender(\n\t\t\tlipgloss.JoinVertical(\n\t\t\t\tlipgloss.Left,\n\t\t\t\tlsps,\n\t\t\t\tlipgloss.JoinVertical(\n\t\t\t\t\tlipgloss.Left,\n\t\t\t\t\tlspViews...,\n\t\t\t\t),\n\t\t\t),\n\t\t)\n}\n\nfunc logo(width int) string {\n\tlogo := fmt.Sprintf(\"%s %s\", styles.OpenCodeIcon, \"OpenCode\")\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\n\tversionText := baseStyle.\n\t\tForeground(t.TextMuted()).\n\t\tRender(version.Version)\n\n\treturn baseStyle.\n\t\tBold(true).\n\t\tWidth(width).\n\t\tRender(\n\t\t\tlipgloss.JoinHorizontal(\n\t\t\t\tlipgloss.Left,\n\t\t\t\tlogo,\n\t\t\t\t\" \",\n\t\t\t\tversionText,\n\t\t\t),\n\t\t)\n}\n\nfunc repo(width int) string {\n\trepo := \"https://github.com/opencode-ai/opencode\"\n\tt := theme.CurrentTheme()\n\n\treturn styles.BaseStyle().\n\t\tForeground(t.TextMuted()).\n\t\tWidth(width).\n\t\tRender(repo)\n}\n\nfunc cwd(width int) string {\n\tcwd := fmt.Sprintf(\"cwd: %s\", config.WorkingDirectory())\n\tt := theme.CurrentTheme()\n\n\treturn styles.BaseStyle().\n\t\tForeground(t.TextMuted()).\n\t\tWidth(width).\n\t\tRender(cwd)\n}\n\n"], ["/opencode/internal/db/messages.sql.go", "// Code generated by sqlc. DO NOT EDIT.\n// versions:\n// sqlc v1.29.0\n// source: messages.sql\n\npackage db\n\nimport (\n\t\"context\"\n\t\"database/sql\"\n)\n\nconst createMessage = `-- name: CreateMessage :one\nINSERT INTO messages (\n id,\n session_id,\n role,\n parts,\n model,\n created_at,\n updated_at\n) VALUES (\n ?, ?, ?, ?, ?, strftime('%s', 'now'), strftime('%s', 'now')\n)\nRETURNING id, session_id, role, parts, model, created_at, updated_at, finished_at\n`\n\ntype CreateMessageParams struct {\n\tID string `json:\"id\"`\n\tSessionID string `json:\"session_id\"`\n\tRole string `json:\"role\"`\n\tParts string `json:\"parts\"`\n\tModel sql.NullString `json:\"model\"`\n}\n\nfunc (q *Queries) CreateMessage(ctx context.Context, arg CreateMessageParams) (Message, error) {\n\trow := q.queryRow(ctx, q.createMessageStmt, createMessage,\n\t\targ.ID,\n\t\targ.SessionID,\n\t\targ.Role,\n\t\targ.Parts,\n\t\targ.Model,\n\t)\n\tvar i Message\n\terr := row.Scan(\n\t\t&i.ID,\n\t\t&i.SessionID,\n\t\t&i.Role,\n\t\t&i.Parts,\n\t\t&i.Model,\n\t\t&i.CreatedAt,\n\t\t&i.UpdatedAt,\n\t\t&i.FinishedAt,\n\t)\n\treturn i, err\n}\n\nconst deleteMessage = `-- name: DeleteMessage :exec\nDELETE FROM messages\nWHERE id = ?\n`\n\nfunc (q *Queries) DeleteMessage(ctx context.Context, id string) error {\n\t_, err := q.exec(ctx, q.deleteMessageStmt, deleteMessage, id)\n\treturn err\n}\n\nconst deleteSessionMessages = `-- name: DeleteSessionMessages :exec\nDELETE FROM messages\nWHERE session_id = ?\n`\n\nfunc (q *Queries) DeleteSessionMessages(ctx context.Context, sessionID string) error {\n\t_, err := q.exec(ctx, q.deleteSessionMessagesStmt, deleteSessionMessages, sessionID)\n\treturn err\n}\n\nconst getMessage = `-- name: GetMessage :one\nSELECT id, session_id, role, parts, model, created_at, updated_at, finished_at\nFROM messages\nWHERE id = ? LIMIT 1\n`\n\nfunc (q *Queries) GetMessage(ctx context.Context, id string) (Message, error) {\n\trow := q.queryRow(ctx, q.getMessageStmt, getMessage, id)\n\tvar i Message\n\terr := row.Scan(\n\t\t&i.ID,\n\t\t&i.SessionID,\n\t\t&i.Role,\n\t\t&i.Parts,\n\t\t&i.Model,\n\t\t&i.CreatedAt,\n\t\t&i.UpdatedAt,\n\t\t&i.FinishedAt,\n\t)\n\treturn i, err\n}\n\nconst listMessagesBySession = `-- name: ListMessagesBySession :many\nSELECT id, session_id, role, parts, model, created_at, updated_at, finished_at\nFROM messages\nWHERE session_id = ?\nORDER BY created_at ASC\n`\n\nfunc (q *Queries) ListMessagesBySession(ctx context.Context, sessionID string) ([]Message, error) {\n\trows, err := q.query(ctx, q.listMessagesBySessionStmt, listMessagesBySession, sessionID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer rows.Close()\n\titems := []Message{}\n\tfor rows.Next() {\n\t\tvar i Message\n\t\tif err := rows.Scan(\n\t\t\t&i.ID,\n\t\t\t&i.SessionID,\n\t\t\t&i.Role,\n\t\t\t&i.Parts,\n\t\t\t&i.Model,\n\t\t\t&i.CreatedAt,\n\t\t\t&i.UpdatedAt,\n\t\t\t&i.FinishedAt,\n\t\t); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\titems = append(items, i)\n\t}\n\tif err := rows.Close(); err != nil {\n\t\treturn nil, err\n\t}\n\tif err := rows.Err(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn items, nil\n}\n\nconst updateMessage = `-- name: UpdateMessage :exec\nUPDATE messages\nSET\n parts = ?,\n finished_at = ?,\n updated_at = strftime('%s', 'now')\nWHERE id = ?\n`\n\ntype UpdateMessageParams struct {\n\tParts string `json:\"parts\"`\n\tFinishedAt sql.NullInt64 `json:\"finished_at\"`\n\tID string `json:\"id\"`\n}\n\nfunc (q *Queries) UpdateMessage(ctx context.Context, arg UpdateMessageParams) error {\n\t_, err := q.exec(ctx, q.updateMessageStmt, updateMessage, arg.Parts, arg.FinishedAt, arg.ID)\n\treturn err\n}\n"], ["/opencode/internal/tui/components/logs/table.go", "package logs\n\nimport (\n\t\"encoding/json\"\n\t\"slices\"\n\n\t\"github.com/charmbracelet/bubbles/key\"\n\t\"github.com/charmbracelet/bubbles/table\"\n\ttea \"github.com/charmbracelet/bubbletea\"\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n\t\"github.com/opencode-ai/opencode/internal/pubsub\"\n\t\"github.com/opencode-ai/opencode/internal/tui/layout\"\n\t\"github.com/opencode-ai/opencode/internal/tui/styles\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n\t\"github.com/opencode-ai/opencode/internal/tui/util\"\n)\n\ntype TableComponent interface {\n\ttea.Model\n\tlayout.Sizeable\n\tlayout.Bindings\n}\n\ntype tableCmp struct {\n\ttable table.Model\n}\n\ntype selectedLogMsg logging.LogMessage\n\nfunc (i *tableCmp) Init() tea.Cmd {\n\ti.setRows()\n\treturn nil\n}\n\nfunc (i *tableCmp) Update(msg tea.Msg) (tea.Model, tea.Cmd) {\n\tvar cmds []tea.Cmd\n\tswitch msg.(type) {\n\tcase pubsub.Event[logging.LogMessage]:\n\t\ti.setRows()\n\t\treturn i, nil\n\t}\n\tprevSelectedRow := i.table.SelectedRow()\n\tt, cmd := i.table.Update(msg)\n\tcmds = append(cmds, cmd)\n\ti.table = t\n\tselectedRow := i.table.SelectedRow()\n\tif selectedRow != nil {\n\t\tif prevSelectedRow == nil || selectedRow[0] == prevSelectedRow[0] {\n\t\t\tvar log logging.LogMessage\n\t\t\tfor _, row := range logging.List() {\n\t\t\t\tif row.ID == selectedRow[0] {\n\t\t\t\t\tlog = row\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\tif log.ID != \"\" {\n\t\t\t\tcmds = append(cmds, util.CmdHandler(selectedLogMsg(log)))\n\t\t\t}\n\t\t}\n\t}\n\treturn i, tea.Batch(cmds...)\n}\n\nfunc (i *tableCmp) View() string {\n\tt := theme.CurrentTheme()\n\tdefaultStyles := table.DefaultStyles()\n\tdefaultStyles.Selected = defaultStyles.Selected.Foreground(t.Primary())\n\ti.table.SetStyles(defaultStyles)\n\treturn styles.ForceReplaceBackgroundWithLipgloss(i.table.View(), t.Background())\n}\n\nfunc (i *tableCmp) GetSize() (int, int) {\n\treturn i.table.Width(), i.table.Height()\n}\n\nfunc (i *tableCmp) SetSize(width int, height int) tea.Cmd {\n\ti.table.SetWidth(width)\n\ti.table.SetHeight(height)\n\tcloumns := i.table.Columns()\n\tfor i, col := range cloumns {\n\t\tcol.Width = (width / len(cloumns)) - 2\n\t\tcloumns[i] = col\n\t}\n\ti.table.SetColumns(cloumns)\n\treturn nil\n}\n\nfunc (i *tableCmp) BindingKeys() []key.Binding {\n\treturn layout.KeyMapToSlice(i.table.KeyMap)\n}\n\nfunc (i *tableCmp) setRows() {\n\trows := []table.Row{}\n\n\tlogs := logging.List()\n\tslices.SortFunc(logs, func(a, b logging.LogMessage) int {\n\t\tif a.Time.Before(b.Time) {\n\t\t\treturn 1\n\t\t}\n\t\tif a.Time.After(b.Time) {\n\t\t\treturn -1\n\t\t}\n\t\treturn 0\n\t})\n\n\tfor _, log := range logs {\n\t\tbm, _ := json.Marshal(log.Attributes)\n\n\t\trow := table.Row{\n\t\t\tlog.ID,\n\t\t\tlog.Time.Format(\"15:04:05\"),\n\t\t\tlog.Level,\n\t\t\tlog.Message,\n\t\t\tstring(bm),\n\t\t}\n\t\trows = append(rows, row)\n\t}\n\ti.table.SetRows(rows)\n}\n\nfunc NewLogsTable() TableComponent {\n\tcolumns := []table.Column{\n\t\t{Title: \"ID\", Width: 4},\n\t\t{Title: \"Time\", Width: 4},\n\t\t{Title: \"Level\", Width: 10},\n\t\t{Title: \"Message\", Width: 10},\n\t\t{Title: \"Attributes\", Width: 10},\n\t}\n\n\ttableModel := table.New(\n\t\ttable.WithColumns(columns),\n\t)\n\ttableModel.Focus()\n\treturn &tableCmp{\n\t\ttable: tableModel,\n\t}\n}\n"], ["/opencode/internal/db/sessions.sql.go", "// Code generated by sqlc. DO NOT EDIT.\n// versions:\n// sqlc v1.29.0\n// source: sessions.sql\n\npackage db\n\nimport (\n\t\"context\"\n\t\"database/sql\"\n)\n\nconst createSession = `-- name: CreateSession :one\nINSERT INTO sessions (\n id,\n parent_session_id,\n title,\n message_count,\n prompt_tokens,\n completion_tokens,\n cost,\n summary_message_id,\n updated_at,\n created_at\n) VALUES (\n ?,\n ?,\n ?,\n ?,\n ?,\n ?,\n ?,\n null,\n strftime('%s', 'now'),\n strftime('%s', 'now')\n) RETURNING id, parent_session_id, title, message_count, prompt_tokens, completion_tokens, cost, updated_at, created_at, summary_message_id\n`\n\ntype CreateSessionParams struct {\n\tID string `json:\"id\"`\n\tParentSessionID sql.NullString `json:\"parent_session_id\"`\n\tTitle string `json:\"title\"`\n\tMessageCount int64 `json:\"message_count\"`\n\tPromptTokens int64 `json:\"prompt_tokens\"`\n\tCompletionTokens int64 `json:\"completion_tokens\"`\n\tCost float64 `json:\"cost\"`\n}\n\nfunc (q *Queries) CreateSession(ctx context.Context, arg CreateSessionParams) (Session, error) {\n\trow := q.queryRow(ctx, q.createSessionStmt, createSession,\n\t\targ.ID,\n\t\targ.ParentSessionID,\n\t\targ.Title,\n\t\targ.MessageCount,\n\t\targ.PromptTokens,\n\t\targ.CompletionTokens,\n\t\targ.Cost,\n\t)\n\tvar i Session\n\terr := row.Scan(\n\t\t&i.ID,\n\t\t&i.ParentSessionID,\n\t\t&i.Title,\n\t\t&i.MessageCount,\n\t\t&i.PromptTokens,\n\t\t&i.CompletionTokens,\n\t\t&i.Cost,\n\t\t&i.UpdatedAt,\n\t\t&i.CreatedAt,\n\t\t&i.SummaryMessageID,\n\t)\n\treturn i, err\n}\n\nconst deleteSession = `-- name: DeleteSession :exec\nDELETE FROM sessions\nWHERE id = ?\n`\n\nfunc (q *Queries) DeleteSession(ctx context.Context, id string) error {\n\t_, err := q.exec(ctx, q.deleteSessionStmt, deleteSession, id)\n\treturn err\n}\n\nconst getSessionByID = `-- name: GetSessionByID :one\nSELECT id, parent_session_id, title, message_count, prompt_tokens, completion_tokens, cost, updated_at, created_at, summary_message_id\nFROM sessions\nWHERE id = ? LIMIT 1\n`\n\nfunc (q *Queries) GetSessionByID(ctx context.Context, id string) (Session, error) {\n\trow := q.queryRow(ctx, q.getSessionByIDStmt, getSessionByID, id)\n\tvar i Session\n\terr := row.Scan(\n\t\t&i.ID,\n\t\t&i.ParentSessionID,\n\t\t&i.Title,\n\t\t&i.MessageCount,\n\t\t&i.PromptTokens,\n\t\t&i.CompletionTokens,\n\t\t&i.Cost,\n\t\t&i.UpdatedAt,\n\t\t&i.CreatedAt,\n\t\t&i.SummaryMessageID,\n\t)\n\treturn i, err\n}\n\nconst listSessions = `-- name: ListSessions :many\nSELECT id, parent_session_id, title, message_count, prompt_tokens, completion_tokens, cost, updated_at, created_at, summary_message_id\nFROM sessions\nWHERE parent_session_id is NULL\nORDER BY created_at DESC\n`\n\nfunc (q *Queries) ListSessions(ctx context.Context) ([]Session, error) {\n\trows, err := q.query(ctx, q.listSessionsStmt, listSessions)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer rows.Close()\n\titems := []Session{}\n\tfor rows.Next() {\n\t\tvar i Session\n\t\tif err := rows.Scan(\n\t\t\t&i.ID,\n\t\t\t&i.ParentSessionID,\n\t\t\t&i.Title,\n\t\t\t&i.MessageCount,\n\t\t\t&i.PromptTokens,\n\t\t\t&i.CompletionTokens,\n\t\t\t&i.Cost,\n\t\t\t&i.UpdatedAt,\n\t\t\t&i.CreatedAt,\n\t\t\t&i.SummaryMessageID,\n\t\t); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\titems = append(items, i)\n\t}\n\tif err := rows.Close(); err != nil {\n\t\treturn nil, err\n\t}\n\tif err := rows.Err(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn items, nil\n}\n\nconst updateSession = `-- name: UpdateSession :one\nUPDATE sessions\nSET\n title = ?,\n prompt_tokens = ?,\n completion_tokens = ?,\n summary_message_id = ?,\n cost = ?\nWHERE id = ?\nRETURNING id, parent_session_id, title, message_count, prompt_tokens, completion_tokens, cost, updated_at, created_at, summary_message_id\n`\n\ntype UpdateSessionParams struct {\n\tTitle string `json:\"title\"`\n\tPromptTokens int64 `json:\"prompt_tokens\"`\n\tCompletionTokens int64 `json:\"completion_tokens\"`\n\tSummaryMessageID sql.NullString `json:\"summary_message_id\"`\n\tCost float64 `json:\"cost\"`\n\tID string `json:\"id\"`\n}\n\nfunc (q *Queries) UpdateSession(ctx context.Context, arg UpdateSessionParams) (Session, error) {\n\trow := q.queryRow(ctx, q.updateSessionStmt, updateSession,\n\t\targ.Title,\n\t\targ.PromptTokens,\n\t\targ.CompletionTokens,\n\t\targ.SummaryMessageID,\n\t\targ.Cost,\n\t\targ.ID,\n\t)\n\tvar i Session\n\terr := row.Scan(\n\t\t&i.ID,\n\t\t&i.ParentSessionID,\n\t\t&i.Title,\n\t\t&i.MessageCount,\n\t\t&i.PromptTokens,\n\t\t&i.CompletionTokens,\n\t\t&i.Cost,\n\t\t&i.UpdatedAt,\n\t\t&i.CreatedAt,\n\t\t&i.SummaryMessageID,\n\t)\n\treturn i, err\n}\n"], ["/opencode/internal/lsp/methods.go", "// Generated code. Do not edit\npackage lsp\n\nimport (\n\t\"context\"\n\n\t\"github.com/opencode-ai/opencode/internal/lsp/protocol\"\n)\n\n// Implementation sends a textDocument/implementation request to the LSP server.\n// A request to resolve the implementation locations of a symbol at a given text document position. The request's parameter is of type TextDocumentPositionParams the response is of type Definition or a Thenable that resolves to such.\nfunc (c *Client) Implementation(ctx context.Context, params protocol.ImplementationParams) (protocol.Or_Result_textDocument_implementation, error) {\n\tvar result protocol.Or_Result_textDocument_implementation\n\terr := c.Call(ctx, \"textDocument/implementation\", params, &result)\n\treturn result, err\n}\n\n// TypeDefinition sends a textDocument/typeDefinition request to the LSP server.\n// A request to resolve the type definition locations of a symbol at a given text document position. The request's parameter is of type TextDocumentPositionParams the response is of type Definition or a Thenable that resolves to such.\nfunc (c *Client) TypeDefinition(ctx context.Context, params protocol.TypeDefinitionParams) (protocol.Or_Result_textDocument_typeDefinition, error) {\n\tvar result protocol.Or_Result_textDocument_typeDefinition\n\terr := c.Call(ctx, \"textDocument/typeDefinition\", params, &result)\n\treturn result, err\n}\n\n// DocumentColor sends a textDocument/documentColor request to the LSP server.\n// A request to list all color symbols found in a given text document. The request's parameter is of type DocumentColorParams the response is of type ColorInformation ColorInformation[] or a Thenable that resolves to such.\nfunc (c *Client) DocumentColor(ctx context.Context, params protocol.DocumentColorParams) ([]protocol.ColorInformation, error) {\n\tvar result []protocol.ColorInformation\n\terr := c.Call(ctx, \"textDocument/documentColor\", params, &result)\n\treturn result, err\n}\n\n// ColorPresentation sends a textDocument/colorPresentation request to the LSP server.\n// A request to list all presentation for a color. The request's parameter is of type ColorPresentationParams the response is of type ColorInformation ColorInformation[] or a Thenable that resolves to such.\nfunc (c *Client) ColorPresentation(ctx context.Context, params protocol.ColorPresentationParams) ([]protocol.ColorPresentation, error) {\n\tvar result []protocol.ColorPresentation\n\terr := c.Call(ctx, \"textDocument/colorPresentation\", params, &result)\n\treturn result, err\n}\n\n// FoldingRange sends a textDocument/foldingRange request to the LSP server.\n// A request to provide folding ranges in a document. The request's parameter is of type FoldingRangeParams, the response is of type FoldingRangeList or a Thenable that resolves to such.\nfunc (c *Client) FoldingRange(ctx context.Context, params protocol.FoldingRangeParams) ([]protocol.FoldingRange, error) {\n\tvar result []protocol.FoldingRange\n\terr := c.Call(ctx, \"textDocument/foldingRange\", params, &result)\n\treturn result, err\n}\n\n// Declaration sends a textDocument/declaration request to the LSP server.\n// A request to resolve the type definition locations of a symbol at a given text document position. The request's parameter is of type TextDocumentPositionParams the response is of type Declaration or a typed array of DeclarationLink or a Thenable that resolves to such.\nfunc (c *Client) Declaration(ctx context.Context, params protocol.DeclarationParams) (protocol.Or_Result_textDocument_declaration, error) {\n\tvar result protocol.Or_Result_textDocument_declaration\n\terr := c.Call(ctx, \"textDocument/declaration\", params, &result)\n\treturn result, err\n}\n\n// SelectionRange sends a textDocument/selectionRange request to the LSP server.\n// A request to provide selection ranges in a document. The request's parameter is of type SelectionRangeParams, the response is of type SelectionRange SelectionRange[] or a Thenable that resolves to such.\nfunc (c *Client) SelectionRange(ctx context.Context, params protocol.SelectionRangeParams) ([]protocol.SelectionRange, error) {\n\tvar result []protocol.SelectionRange\n\terr := c.Call(ctx, \"textDocument/selectionRange\", params, &result)\n\treturn result, err\n}\n\n// PrepareCallHierarchy sends a textDocument/prepareCallHierarchy request to the LSP server.\n// A request to result a CallHierarchyItem in a document at a given position. Can be used as an input to an incoming or outgoing call hierarchy. Since 3.16.0\nfunc (c *Client) PrepareCallHierarchy(ctx context.Context, params protocol.CallHierarchyPrepareParams) ([]protocol.CallHierarchyItem, error) {\n\tvar result []protocol.CallHierarchyItem\n\terr := c.Call(ctx, \"textDocument/prepareCallHierarchy\", params, &result)\n\treturn result, err\n}\n\n// IncomingCalls sends a callHierarchy/incomingCalls request to the LSP server.\n// A request to resolve the incoming calls for a given CallHierarchyItem. Since 3.16.0\nfunc (c *Client) IncomingCalls(ctx context.Context, params protocol.CallHierarchyIncomingCallsParams) ([]protocol.CallHierarchyIncomingCall, error) {\n\tvar result []protocol.CallHierarchyIncomingCall\n\terr := c.Call(ctx, \"callHierarchy/incomingCalls\", params, &result)\n\treturn result, err\n}\n\n// OutgoingCalls sends a callHierarchy/outgoingCalls request to the LSP server.\n// A request to resolve the outgoing calls for a given CallHierarchyItem. Since 3.16.0\nfunc (c *Client) OutgoingCalls(ctx context.Context, params protocol.CallHierarchyOutgoingCallsParams) ([]protocol.CallHierarchyOutgoingCall, error) {\n\tvar result []protocol.CallHierarchyOutgoingCall\n\terr := c.Call(ctx, \"callHierarchy/outgoingCalls\", params, &result)\n\treturn result, err\n}\n\n// SemanticTokensFull sends a textDocument/semanticTokens/full request to the LSP server.\n// Since 3.16.0\nfunc (c *Client) SemanticTokensFull(ctx context.Context, params protocol.SemanticTokensParams) (protocol.SemanticTokens, error) {\n\tvar result protocol.SemanticTokens\n\terr := c.Call(ctx, \"textDocument/semanticTokens/full\", params, &result)\n\treturn result, err\n}\n\n// SemanticTokensFullDelta sends a textDocument/semanticTokens/full/delta request to the LSP server.\n// Since 3.16.0\nfunc (c *Client) SemanticTokensFullDelta(ctx context.Context, params protocol.SemanticTokensDeltaParams) (protocol.Or_Result_textDocument_semanticTokens_full_delta, error) {\n\tvar result protocol.Or_Result_textDocument_semanticTokens_full_delta\n\terr := c.Call(ctx, \"textDocument/semanticTokens/full/delta\", params, &result)\n\treturn result, err\n}\n\n// SemanticTokensRange sends a textDocument/semanticTokens/range request to the LSP server.\n// Since 3.16.0\nfunc (c *Client) SemanticTokensRange(ctx context.Context, params protocol.SemanticTokensRangeParams) (protocol.SemanticTokens, error) {\n\tvar result protocol.SemanticTokens\n\terr := c.Call(ctx, \"textDocument/semanticTokens/range\", params, &result)\n\treturn result, err\n}\n\n// LinkedEditingRange sends a textDocument/linkedEditingRange request to the LSP server.\n// A request to provide ranges that can be edited together. Since 3.16.0\nfunc (c *Client) LinkedEditingRange(ctx context.Context, params protocol.LinkedEditingRangeParams) (protocol.LinkedEditingRanges, error) {\n\tvar result protocol.LinkedEditingRanges\n\terr := c.Call(ctx, \"textDocument/linkedEditingRange\", params, &result)\n\treturn result, err\n}\n\n// WillCreateFiles sends a workspace/willCreateFiles request to the LSP server.\n// The will create files request is sent from the client to the server before files are actually created as long as the creation is triggered from within the client. The request can return a WorkspaceEdit which will be applied to workspace before the files are created. Hence the WorkspaceEdit can not manipulate the content of the file to be created. Since 3.16.0\nfunc (c *Client) WillCreateFiles(ctx context.Context, params protocol.CreateFilesParams) (protocol.WorkspaceEdit, error) {\n\tvar result protocol.WorkspaceEdit\n\terr := c.Call(ctx, \"workspace/willCreateFiles\", params, &result)\n\treturn result, err\n}\n\n// WillRenameFiles sends a workspace/willRenameFiles request to the LSP server.\n// The will rename files request is sent from the client to the server before files are actually renamed as long as the rename is triggered from within the client. Since 3.16.0\nfunc (c *Client) WillRenameFiles(ctx context.Context, params protocol.RenameFilesParams) (protocol.WorkspaceEdit, error) {\n\tvar result protocol.WorkspaceEdit\n\terr := c.Call(ctx, \"workspace/willRenameFiles\", params, &result)\n\treturn result, err\n}\n\n// WillDeleteFiles sends a workspace/willDeleteFiles request to the LSP server.\n// The did delete files notification is sent from the client to the server when files were deleted from within the client. Since 3.16.0\nfunc (c *Client) WillDeleteFiles(ctx context.Context, params protocol.DeleteFilesParams) (protocol.WorkspaceEdit, error) {\n\tvar result protocol.WorkspaceEdit\n\terr := c.Call(ctx, \"workspace/willDeleteFiles\", params, &result)\n\treturn result, err\n}\n\n// Moniker sends a textDocument/moniker request to the LSP server.\n// A request to get the moniker of a symbol at a given text document position. The request parameter is of type TextDocumentPositionParams. The response is of type Moniker Moniker[] or null.\nfunc (c *Client) Moniker(ctx context.Context, params protocol.MonikerParams) ([]protocol.Moniker, error) {\n\tvar result []protocol.Moniker\n\terr := c.Call(ctx, \"textDocument/moniker\", params, &result)\n\treturn result, err\n}\n\n// PrepareTypeHierarchy sends a textDocument/prepareTypeHierarchy request to the LSP server.\n// A request to result a TypeHierarchyItem in a document at a given position. Can be used as an input to a subtypes or supertypes type hierarchy. Since 3.17.0\nfunc (c *Client) PrepareTypeHierarchy(ctx context.Context, params protocol.TypeHierarchyPrepareParams) ([]protocol.TypeHierarchyItem, error) {\n\tvar result []protocol.TypeHierarchyItem\n\terr := c.Call(ctx, \"textDocument/prepareTypeHierarchy\", params, &result)\n\treturn result, err\n}\n\n// Supertypes sends a typeHierarchy/supertypes request to the LSP server.\n// A request to resolve the supertypes for a given TypeHierarchyItem. Since 3.17.0\nfunc (c *Client) Supertypes(ctx context.Context, params protocol.TypeHierarchySupertypesParams) ([]protocol.TypeHierarchyItem, error) {\n\tvar result []protocol.TypeHierarchyItem\n\terr := c.Call(ctx, \"typeHierarchy/supertypes\", params, &result)\n\treturn result, err\n}\n\n// Subtypes sends a typeHierarchy/subtypes request to the LSP server.\n// A request to resolve the subtypes for a given TypeHierarchyItem. Since 3.17.0\nfunc (c *Client) Subtypes(ctx context.Context, params protocol.TypeHierarchySubtypesParams) ([]protocol.TypeHierarchyItem, error) {\n\tvar result []protocol.TypeHierarchyItem\n\terr := c.Call(ctx, \"typeHierarchy/subtypes\", params, &result)\n\treturn result, err\n}\n\n// InlineValue sends a textDocument/inlineValue request to the LSP server.\n// A request to provide inline values in a document. The request's parameter is of type InlineValueParams, the response is of type InlineValue InlineValue[] or a Thenable that resolves to such. Since 3.17.0\nfunc (c *Client) InlineValue(ctx context.Context, params protocol.InlineValueParams) ([]protocol.InlineValue, error) {\n\tvar result []protocol.InlineValue\n\terr := c.Call(ctx, \"textDocument/inlineValue\", params, &result)\n\treturn result, err\n}\n\n// InlayHint sends a textDocument/inlayHint request to the LSP server.\n// A request to provide inlay hints in a document. The request's parameter is of type InlayHintsParams, the response is of type InlayHint InlayHint[] or a Thenable that resolves to such. Since 3.17.0\nfunc (c *Client) InlayHint(ctx context.Context, params protocol.InlayHintParams) ([]protocol.InlayHint, error) {\n\tvar result []protocol.InlayHint\n\terr := c.Call(ctx, \"textDocument/inlayHint\", params, &result)\n\treturn result, err\n}\n\n// Resolve sends a inlayHint/resolve request to the LSP server.\n// A request to resolve additional properties for an inlay hint. The request's parameter is of type InlayHint, the response is of type InlayHint or a Thenable that resolves to such. Since 3.17.0\nfunc (c *Client) Resolve(ctx context.Context, params protocol.InlayHint) (protocol.InlayHint, error) {\n\tvar result protocol.InlayHint\n\terr := c.Call(ctx, \"inlayHint/resolve\", params, &result)\n\treturn result, err\n}\n\n// Diagnostic sends a textDocument/diagnostic request to the LSP server.\n// The document diagnostic request definition. Since 3.17.0\nfunc (c *Client) Diagnostic(ctx context.Context, params protocol.DocumentDiagnosticParams) (protocol.DocumentDiagnosticReport, error) {\n\tvar result protocol.DocumentDiagnosticReport\n\terr := c.Call(ctx, \"textDocument/diagnostic\", params, &result)\n\treturn result, err\n}\n\n// DiagnosticWorkspace sends a workspace/diagnostic request to the LSP server.\n// The workspace diagnostic request definition. Since 3.17.0\nfunc (c *Client) DiagnosticWorkspace(ctx context.Context, params protocol.WorkspaceDiagnosticParams) (protocol.WorkspaceDiagnosticReport, error) {\n\tvar result protocol.WorkspaceDiagnosticReport\n\terr := c.Call(ctx, \"workspace/diagnostic\", params, &result)\n\treturn result, err\n}\n\n// InlineCompletion sends a textDocument/inlineCompletion request to the LSP server.\n// A request to provide inline completions in a document. The request's parameter is of type InlineCompletionParams, the response is of type InlineCompletion InlineCompletion[] or a Thenable that resolves to such. Since 3.18.0 PROPOSED\nfunc (c *Client) InlineCompletion(ctx context.Context, params protocol.InlineCompletionParams) (protocol.Or_Result_textDocument_inlineCompletion, error) {\n\tvar result protocol.Or_Result_textDocument_inlineCompletion\n\terr := c.Call(ctx, \"textDocument/inlineCompletion\", params, &result)\n\treturn result, err\n}\n\n// TextDocumentContent sends a workspace/textDocumentContent request to the LSP server.\n// The workspace/textDocumentContent request is sent from the client to the server to request the content of a text document. Since 3.18.0 PROPOSED\nfunc (c *Client) TextDocumentContent(ctx context.Context, params protocol.TextDocumentContentParams) (string, error) {\n\tvar result string\n\terr := c.Call(ctx, \"workspace/textDocumentContent\", params, &result)\n\treturn result, err\n}\n\n// Initialize sends a initialize request to the LSP server.\n// The initialize request is sent from the client to the server. It is sent once as the request after starting up the server. The requests parameter is of type InitializeParams the response if of type InitializeResult of a Thenable that resolves to such.\nfunc (c *Client) Initialize(ctx context.Context, params protocol.ParamInitialize) (protocol.InitializeResult, error) {\n\tvar result protocol.InitializeResult\n\terr := c.Call(ctx, \"initialize\", params, &result)\n\treturn result, err\n}\n\n// Shutdown sends a shutdown request to the LSP server.\n// A shutdown request is sent from the client to the server. It is sent once when the client decides to shutdown the server. The only notification that is sent after a shutdown request is the exit event.\nfunc (c *Client) Shutdown(ctx context.Context) error {\n\treturn c.Call(ctx, \"shutdown\", nil, nil)\n}\n\n// WillSaveWaitUntil sends a textDocument/willSaveWaitUntil request to the LSP server.\n// A document will save request is sent from the client to the server before the document is actually saved. The request can return an array of TextEdits which will be applied to the text document before it is saved. Please note that clients might drop results if computing the text edits took too long or if a server constantly fails on this request. This is done to keep the save fast and reliable.\nfunc (c *Client) WillSaveWaitUntil(ctx context.Context, params protocol.WillSaveTextDocumentParams) ([]protocol.TextEdit, error) {\n\tvar result []protocol.TextEdit\n\terr := c.Call(ctx, \"textDocument/willSaveWaitUntil\", params, &result)\n\treturn result, err\n}\n\n// Completion sends a textDocument/completion request to the LSP server.\n// Request to request completion at a given text document position. The request's parameter is of type TextDocumentPosition the response is of type CompletionItem CompletionItem[] or CompletionList or a Thenable that resolves to such. The request can delay the computation of the CompletionItem.detail detail and CompletionItem.documentation documentation properties to the completionItem/resolve request. However, properties that are needed for the initial sorting and filtering, like sortText, filterText, insertText, and textEdit, must not be changed during resolve.\nfunc (c *Client) Completion(ctx context.Context, params protocol.CompletionParams) (protocol.Or_Result_textDocument_completion, error) {\n\tvar result protocol.Or_Result_textDocument_completion\n\terr := c.Call(ctx, \"textDocument/completion\", params, &result)\n\treturn result, err\n}\n\n// ResolveCompletionItem sends a completionItem/resolve request to the LSP server.\n// Request to resolve additional information for a given completion item.The request's parameter is of type CompletionItem the response is of type CompletionItem or a Thenable that resolves to such.\nfunc (c *Client) ResolveCompletionItem(ctx context.Context, params protocol.CompletionItem) (protocol.CompletionItem, error) {\n\tvar result protocol.CompletionItem\n\terr := c.Call(ctx, \"completionItem/resolve\", params, &result)\n\treturn result, err\n}\n\n// Hover sends a textDocument/hover request to the LSP server.\n// Request to request hover information at a given text document position. The request's parameter is of type TextDocumentPosition the response is of type Hover or a Thenable that resolves to such.\nfunc (c *Client) Hover(ctx context.Context, params protocol.HoverParams) (protocol.Hover, error) {\n\tvar result protocol.Hover\n\terr := c.Call(ctx, \"textDocument/hover\", params, &result)\n\treturn result, err\n}\n\n// SignatureHelp sends a textDocument/signatureHelp request to the LSP server.\nfunc (c *Client) SignatureHelp(ctx context.Context, params protocol.SignatureHelpParams) (protocol.SignatureHelp, error) {\n\tvar result protocol.SignatureHelp\n\terr := c.Call(ctx, \"textDocument/signatureHelp\", params, &result)\n\treturn result, err\n}\n\n// Definition sends a textDocument/definition request to the LSP server.\n// A request to resolve the definition location of a symbol at a given text document position. The request's parameter is of type TextDocumentPosition the response is of either type Definition or a typed array of DefinitionLink or a Thenable that resolves to such.\nfunc (c *Client) Definition(ctx context.Context, params protocol.DefinitionParams) (protocol.Or_Result_textDocument_definition, error) {\n\tvar result protocol.Or_Result_textDocument_definition\n\terr := c.Call(ctx, \"textDocument/definition\", params, &result)\n\treturn result, err\n}\n\n// References sends a textDocument/references request to the LSP server.\n// A request to resolve project-wide references for the symbol denoted by the given text document position. The request's parameter is of type ReferenceParams the response is of type Location Location[] or a Thenable that resolves to such.\nfunc (c *Client) References(ctx context.Context, params protocol.ReferenceParams) ([]protocol.Location, error) {\n\tvar result []protocol.Location\n\terr := c.Call(ctx, \"textDocument/references\", params, &result)\n\treturn result, err\n}\n\n// DocumentHighlight sends a textDocument/documentHighlight request to the LSP server.\n// Request to resolve a DocumentHighlight for a given text document position. The request's parameter is of type TextDocumentPosition the request response is an array of type DocumentHighlight or a Thenable that resolves to such.\nfunc (c *Client) DocumentHighlight(ctx context.Context, params protocol.DocumentHighlightParams) ([]protocol.DocumentHighlight, error) {\n\tvar result []protocol.DocumentHighlight\n\terr := c.Call(ctx, \"textDocument/documentHighlight\", params, &result)\n\treturn result, err\n}\n\n// DocumentSymbol sends a textDocument/documentSymbol request to the LSP server.\n// A request to list all symbols found in a given text document. The request's parameter is of type TextDocumentIdentifier the response is of type SymbolInformation SymbolInformation[] or a Thenable that resolves to such.\nfunc (c *Client) DocumentSymbol(ctx context.Context, params protocol.DocumentSymbolParams) (protocol.Or_Result_textDocument_documentSymbol, error) {\n\tvar result protocol.Or_Result_textDocument_documentSymbol\n\terr := c.Call(ctx, \"textDocument/documentSymbol\", params, &result)\n\treturn result, err\n}\n\n// CodeAction sends a textDocument/codeAction request to the LSP server.\n// A request to provide commands for the given text document and range.\nfunc (c *Client) CodeAction(ctx context.Context, params protocol.CodeActionParams) ([]protocol.Or_Result_textDocument_codeAction_Item0_Elem, error) {\n\tvar result []protocol.Or_Result_textDocument_codeAction_Item0_Elem\n\terr := c.Call(ctx, \"textDocument/codeAction\", params, &result)\n\treturn result, err\n}\n\n// ResolveCodeAction sends a codeAction/resolve request to the LSP server.\n// Request to resolve additional information for a given code action.The request's parameter is of type CodeAction the response is of type CodeAction or a Thenable that resolves to such.\nfunc (c *Client) ResolveCodeAction(ctx context.Context, params protocol.CodeAction) (protocol.CodeAction, error) {\n\tvar result protocol.CodeAction\n\terr := c.Call(ctx, \"codeAction/resolve\", params, &result)\n\treturn result, err\n}\n\n// Symbol sends a workspace/symbol request to the LSP server.\n// A request to list project-wide symbols matching the query string given by the WorkspaceSymbolParams. The response is of type SymbolInformation SymbolInformation[] or a Thenable that resolves to such. Since 3.17.0 - support for WorkspaceSymbol in the returned data. Clients need to advertise support for WorkspaceSymbols via the client capability workspace.symbol.resolveSupport.\nfunc (c *Client) Symbol(ctx context.Context, params protocol.WorkspaceSymbolParams) (protocol.Or_Result_workspace_symbol, error) {\n\tvar result protocol.Or_Result_workspace_symbol\n\terr := c.Call(ctx, \"workspace/symbol\", params, &result)\n\treturn result, err\n}\n\n// ResolveWorkspaceSymbol sends a workspaceSymbol/resolve request to the LSP server.\n// A request to resolve the range inside the workspace symbol's location. Since 3.17.0\nfunc (c *Client) ResolveWorkspaceSymbol(ctx context.Context, params protocol.WorkspaceSymbol) (protocol.WorkspaceSymbol, error) {\n\tvar result protocol.WorkspaceSymbol\n\terr := c.Call(ctx, \"workspaceSymbol/resolve\", params, &result)\n\treturn result, err\n}\n\n// CodeLens sends a textDocument/codeLens request to the LSP server.\n// A request to provide code lens for the given text document.\nfunc (c *Client) CodeLens(ctx context.Context, params protocol.CodeLensParams) ([]protocol.CodeLens, error) {\n\tvar result []protocol.CodeLens\n\terr := c.Call(ctx, \"textDocument/codeLens\", params, &result)\n\treturn result, err\n}\n\n// ResolveCodeLens sends a codeLens/resolve request to the LSP server.\n// A request to resolve a command for a given code lens.\nfunc (c *Client) ResolveCodeLens(ctx context.Context, params protocol.CodeLens) (protocol.CodeLens, error) {\n\tvar result protocol.CodeLens\n\terr := c.Call(ctx, \"codeLens/resolve\", params, &result)\n\treturn result, err\n}\n\n// DocumentLink sends a textDocument/documentLink request to the LSP server.\n// A request to provide document links\nfunc (c *Client) DocumentLink(ctx context.Context, params protocol.DocumentLinkParams) ([]protocol.DocumentLink, error) {\n\tvar result []protocol.DocumentLink\n\terr := c.Call(ctx, \"textDocument/documentLink\", params, &result)\n\treturn result, err\n}\n\n// ResolveDocumentLink sends a documentLink/resolve request to the LSP server.\n// Request to resolve additional information for a given document link. The request's parameter is of type DocumentLink the response is of type DocumentLink or a Thenable that resolves to such.\nfunc (c *Client) ResolveDocumentLink(ctx context.Context, params protocol.DocumentLink) (protocol.DocumentLink, error) {\n\tvar result protocol.DocumentLink\n\terr := c.Call(ctx, \"documentLink/resolve\", params, &result)\n\treturn result, err\n}\n\n// Formatting sends a textDocument/formatting request to the LSP server.\n// A request to format a whole document.\nfunc (c *Client) Formatting(ctx context.Context, params protocol.DocumentFormattingParams) ([]protocol.TextEdit, error) {\n\tvar result []protocol.TextEdit\n\terr := c.Call(ctx, \"textDocument/formatting\", params, &result)\n\treturn result, err\n}\n\n// RangeFormatting sends a textDocument/rangeFormatting request to the LSP server.\n// A request to format a range in a document.\nfunc (c *Client) RangeFormatting(ctx context.Context, params protocol.DocumentRangeFormattingParams) ([]protocol.TextEdit, error) {\n\tvar result []protocol.TextEdit\n\terr := c.Call(ctx, \"textDocument/rangeFormatting\", params, &result)\n\treturn result, err\n}\n\n// RangesFormatting sends a textDocument/rangesFormatting request to the LSP server.\n// A request to format ranges in a document. Since 3.18.0 PROPOSED\nfunc (c *Client) RangesFormatting(ctx context.Context, params protocol.DocumentRangesFormattingParams) ([]protocol.TextEdit, error) {\n\tvar result []protocol.TextEdit\n\terr := c.Call(ctx, \"textDocument/rangesFormatting\", params, &result)\n\treturn result, err\n}\n\n// OnTypeFormatting sends a textDocument/onTypeFormatting request to the LSP server.\n// A request to format a document on type.\nfunc (c *Client) OnTypeFormatting(ctx context.Context, params protocol.DocumentOnTypeFormattingParams) ([]protocol.TextEdit, error) {\n\tvar result []protocol.TextEdit\n\terr := c.Call(ctx, \"textDocument/onTypeFormatting\", params, &result)\n\treturn result, err\n}\n\n// Rename sends a textDocument/rename request to the LSP server.\n// A request to rename a symbol.\nfunc (c *Client) Rename(ctx context.Context, params protocol.RenameParams) (protocol.WorkspaceEdit, error) {\n\tvar result protocol.WorkspaceEdit\n\terr := c.Call(ctx, \"textDocument/rename\", params, &result)\n\treturn result, err\n}\n\n// PrepareRename sends a textDocument/prepareRename request to the LSP server.\n// A request to test and perform the setup necessary for a rename. Since 3.16 - support for default behavior\nfunc (c *Client) PrepareRename(ctx context.Context, params protocol.PrepareRenameParams) (protocol.PrepareRenameResult, error) {\n\tvar result protocol.PrepareRenameResult\n\terr := c.Call(ctx, \"textDocument/prepareRename\", params, &result)\n\treturn result, err\n}\n\n// ExecuteCommand sends a workspace/executeCommand request to the LSP server.\n// A request send from the client to the server to execute a command. The request might return a workspace edit which the client will apply to the workspace.\nfunc (c *Client) ExecuteCommand(ctx context.Context, params protocol.ExecuteCommandParams) (any, error) {\n\tvar result any\n\terr := c.Call(ctx, \"workspace/executeCommand\", params, &result)\n\treturn result, err\n}\n\n// DidChangeWorkspaceFolders sends a workspace/didChangeWorkspaceFolders notification to the LSP server.\n// The workspace/didChangeWorkspaceFolders notification is sent from the client to the server when the workspace folder configuration changes.\nfunc (c *Client) DidChangeWorkspaceFolders(ctx context.Context, params protocol.DidChangeWorkspaceFoldersParams) error {\n\treturn c.Notify(ctx, \"workspace/didChangeWorkspaceFolders\", params)\n}\n\n// WorkDoneProgressCancel sends a window/workDoneProgress/cancel notification to the LSP server.\n// The window/workDoneProgress/cancel notification is sent from the client to the server to cancel a progress initiated on the server side.\nfunc (c *Client) WorkDoneProgressCancel(ctx context.Context, params protocol.WorkDoneProgressCancelParams) error {\n\treturn c.Notify(ctx, \"window/workDoneProgress/cancel\", params)\n}\n\n// DidCreateFiles sends a workspace/didCreateFiles notification to the LSP server.\n// The did create files notification is sent from the client to the server when files were created from within the client. Since 3.16.0\nfunc (c *Client) DidCreateFiles(ctx context.Context, params protocol.CreateFilesParams) error {\n\treturn c.Notify(ctx, \"workspace/didCreateFiles\", params)\n}\n\n// DidRenameFiles sends a workspace/didRenameFiles notification to the LSP server.\n// The did rename files notification is sent from the client to the server when files were renamed from within the client. Since 3.16.0\nfunc (c *Client) DidRenameFiles(ctx context.Context, params protocol.RenameFilesParams) error {\n\treturn c.Notify(ctx, \"workspace/didRenameFiles\", params)\n}\n\n// DidDeleteFiles sends a workspace/didDeleteFiles notification to the LSP server.\n// The will delete files request is sent from the client to the server before files are actually deleted as long as the deletion is triggered from within the client. Since 3.16.0\nfunc (c *Client) DidDeleteFiles(ctx context.Context, params protocol.DeleteFilesParams) error {\n\treturn c.Notify(ctx, \"workspace/didDeleteFiles\", params)\n}\n\n// DidOpenNotebookDocument sends a notebookDocument/didOpen notification to the LSP server.\n// A notification sent when a notebook opens. Since 3.17.0\nfunc (c *Client) DidOpenNotebookDocument(ctx context.Context, params protocol.DidOpenNotebookDocumentParams) error {\n\treturn c.Notify(ctx, \"notebookDocument/didOpen\", params)\n}\n\n// DidChangeNotebookDocument sends a notebookDocument/didChange notification to the LSP server.\nfunc (c *Client) DidChangeNotebookDocument(ctx context.Context, params protocol.DidChangeNotebookDocumentParams) error {\n\treturn c.Notify(ctx, \"notebookDocument/didChange\", params)\n}\n\n// DidSaveNotebookDocument sends a notebookDocument/didSave notification to the LSP server.\n// A notification sent when a notebook document is saved. Since 3.17.0\nfunc (c *Client) DidSaveNotebookDocument(ctx context.Context, params protocol.DidSaveNotebookDocumentParams) error {\n\treturn c.Notify(ctx, \"notebookDocument/didSave\", params)\n}\n\n// DidCloseNotebookDocument sends a notebookDocument/didClose notification to the LSP server.\n// A notification sent when a notebook closes. Since 3.17.0\nfunc (c *Client) DidCloseNotebookDocument(ctx context.Context, params protocol.DidCloseNotebookDocumentParams) error {\n\treturn c.Notify(ctx, \"notebookDocument/didClose\", params)\n}\n\n// Initialized sends a initialized notification to the LSP server.\n// The initialized notification is sent from the client to the server after the client is fully initialized and the server is allowed to send requests from the server to the client.\nfunc (c *Client) Initialized(ctx context.Context, params protocol.InitializedParams) error {\n\treturn c.Notify(ctx, \"initialized\", params)\n}\n\n// Exit sends a exit notification to the LSP server.\n// The exit event is sent from the client to the server to ask the server to exit its process.\nfunc (c *Client) Exit(ctx context.Context) error {\n\treturn c.Notify(ctx, \"exit\", nil)\n}\n\n// DidChangeConfiguration sends a workspace/didChangeConfiguration notification to the LSP server.\n// The configuration change notification is sent from the client to the server when the client's configuration has changed. The notification contains the changed configuration as defined by the language client.\nfunc (c *Client) DidChangeConfiguration(ctx context.Context, params protocol.DidChangeConfigurationParams) error {\n\treturn c.Notify(ctx, \"workspace/didChangeConfiguration\", params)\n}\n\n// DidOpen sends a textDocument/didOpen notification to the LSP server.\n// The document open notification is sent from the client to the server to signal newly opened text documents. The document's truth is now managed by the client and the server must not try to read the document's truth using the document's uri. Open in this sense means it is managed by the client. It doesn't necessarily mean that its content is presented in an editor. An open notification must not be sent more than once without a corresponding close notification send before. This means open and close notification must be balanced and the max open count is one.\nfunc (c *Client) DidOpen(ctx context.Context, params protocol.DidOpenTextDocumentParams) error {\n\treturn c.Notify(ctx, \"textDocument/didOpen\", params)\n}\n\n// DidChange sends a textDocument/didChange notification to the LSP server.\n// The document change notification is sent from the client to the server to signal changes to a text document.\nfunc (c *Client) DidChange(ctx context.Context, params protocol.DidChangeTextDocumentParams) error {\n\treturn c.Notify(ctx, \"textDocument/didChange\", params)\n}\n\n// DidClose sends a textDocument/didClose notification to the LSP server.\n// The document close notification is sent from the client to the server when the document got closed in the client. The document's truth now exists where the document's uri points to (e.g. if the document's uri is a file uri the truth now exists on disk). As with the open notification the close notification is about managing the document's content. Receiving a close notification doesn't mean that the document was open in an editor before. A close notification requires a previous open notification to be sent.\nfunc (c *Client) DidClose(ctx context.Context, params protocol.DidCloseTextDocumentParams) error {\n\treturn c.Notify(ctx, \"textDocument/didClose\", params)\n}\n\n// DidSave sends a textDocument/didSave notification to the LSP server.\n// The document save notification is sent from the client to the server when the document got saved in the client.\nfunc (c *Client) DidSave(ctx context.Context, params protocol.DidSaveTextDocumentParams) error {\n\treturn c.Notify(ctx, \"textDocument/didSave\", params)\n}\n\n// WillSave sends a textDocument/willSave notification to the LSP server.\n// A document will save notification is sent from the client to the server before the document is actually saved.\nfunc (c *Client) WillSave(ctx context.Context, params protocol.WillSaveTextDocumentParams) error {\n\treturn c.Notify(ctx, \"textDocument/willSave\", params)\n}\n\n// DidChangeWatchedFiles sends a workspace/didChangeWatchedFiles notification to the LSP server.\n// The watched files notification is sent from the client to the server when the client detects changes to file watched by the language client.\nfunc (c *Client) DidChangeWatchedFiles(ctx context.Context, params protocol.DidChangeWatchedFilesParams) error {\n\treturn c.Notify(ctx, \"workspace/didChangeWatchedFiles\", params)\n}\n\n// SetTrace sends a $/setTrace notification to the LSP server.\nfunc (c *Client) SetTrace(ctx context.Context, params protocol.SetTraceParams) error {\n\treturn c.Notify(ctx, \"$/setTrace\", params)\n}\n\n// Progress sends a $/progress notification to the LSP server.\nfunc (c *Client) Progress(ctx context.Context, params protocol.ProgressParams) error {\n\treturn c.Notify(ctx, \"$/progress\", params)\n}\n"], ["/opencode/internal/tui/components/dialog/init.go", "package dialog\n\nimport (\n\t\"github.com/charmbracelet/bubbles/key\"\n\ttea \"github.com/charmbracelet/bubbletea\"\n\t\"github.com/charmbracelet/lipgloss\"\n\n\t\"github.com/opencode-ai/opencode/internal/tui/styles\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n\t\"github.com/opencode-ai/opencode/internal/tui/util\"\n)\n\n// InitDialogCmp is a component that asks the user if they want to initialize the project.\ntype InitDialogCmp struct {\n\twidth, height int\n\tselected int\n\tkeys initDialogKeyMap\n}\n\n// NewInitDialogCmp creates a new InitDialogCmp.\nfunc NewInitDialogCmp() InitDialogCmp {\n\treturn InitDialogCmp{\n\t\tselected: 0,\n\t\tkeys: initDialogKeyMap{},\n\t}\n}\n\ntype initDialogKeyMap struct {\n\tTab key.Binding\n\tLeft key.Binding\n\tRight key.Binding\n\tEnter key.Binding\n\tEscape key.Binding\n\tY key.Binding\n\tN key.Binding\n}\n\n// ShortHelp implements key.Map.\nfunc (k initDialogKeyMap) ShortHelp() []key.Binding {\n\treturn []key.Binding{\n\t\tkey.NewBinding(\n\t\t\tkey.WithKeys(\"tab\", \"left\", \"right\"),\n\t\t\tkey.WithHelp(\"tab/←/→\", \"toggle selection\"),\n\t\t),\n\t\tkey.NewBinding(\n\t\t\tkey.WithKeys(\"enter\"),\n\t\t\tkey.WithHelp(\"enter\", \"confirm\"),\n\t\t),\n\t\tkey.NewBinding(\n\t\t\tkey.WithKeys(\"esc\", \"q\"),\n\t\t\tkey.WithHelp(\"esc/q\", \"cancel\"),\n\t\t),\n\t\tkey.NewBinding(\n\t\t\tkey.WithKeys(\"y\", \"n\"),\n\t\t\tkey.WithHelp(\"y/n\", \"yes/no\"),\n\t\t),\n\t}\n}\n\n// FullHelp implements key.Map.\nfunc (k initDialogKeyMap) FullHelp() [][]key.Binding {\n\treturn [][]key.Binding{k.ShortHelp()}\n}\n\n// Init implements tea.Model.\nfunc (m InitDialogCmp) Init() tea.Cmd {\n\treturn nil\n}\n\n// Update implements tea.Model.\nfunc (m InitDialogCmp) Update(msg tea.Msg) (tea.Model, tea.Cmd) {\n\tswitch msg := msg.(type) {\n\tcase tea.KeyMsg:\n\t\tswitch {\n\t\tcase key.Matches(msg, key.NewBinding(key.WithKeys(\"esc\"))):\n\t\t\treturn m, util.CmdHandler(CloseInitDialogMsg{Initialize: false})\n\t\tcase key.Matches(msg, key.NewBinding(key.WithKeys(\"tab\", \"left\", \"right\", \"h\", \"l\"))):\n\t\t\tm.selected = (m.selected + 1) % 2\n\t\t\treturn m, nil\n\t\tcase key.Matches(msg, key.NewBinding(key.WithKeys(\"enter\"))):\n\t\t\treturn m, util.CmdHandler(CloseInitDialogMsg{Initialize: m.selected == 0})\n\t\tcase key.Matches(msg, key.NewBinding(key.WithKeys(\"y\"))):\n\t\t\treturn m, util.CmdHandler(CloseInitDialogMsg{Initialize: true})\n\t\tcase key.Matches(msg, key.NewBinding(key.WithKeys(\"n\"))):\n\t\t\treturn m, util.CmdHandler(CloseInitDialogMsg{Initialize: false})\n\t\t}\n\tcase tea.WindowSizeMsg:\n\t\tm.width = msg.Width\n\t\tm.height = msg.Height\n\t}\n\treturn m, nil\n}\n\n// View implements tea.Model.\nfunc (m InitDialogCmp) View() string {\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\t\n\t// Calculate width needed for content\n\tmaxWidth := 60 // Width for explanation text\n\n\ttitle := baseStyle.\n\t\tForeground(t.Primary()).\n\t\tBold(true).\n\t\tWidth(maxWidth).\n\t\tPadding(0, 1).\n\t\tRender(\"Initialize Project\")\n\n\texplanation := baseStyle.\n\t\tForeground(t.Text()).\n\t\tWidth(maxWidth).\n\t\tPadding(0, 1).\n\t\tRender(\"Initialization generates a new OpenCode.md file that contains information about your codebase, this file serves as memory for each project, you can freely add to it to help the agents be better at their job.\")\n\n\tquestion := baseStyle.\n\t\tForeground(t.Text()).\n\t\tWidth(maxWidth).\n\t\tPadding(1, 1).\n\t\tRender(\"Would you like to initialize this project?\")\n\n\tmaxWidth = min(maxWidth, m.width-10)\n\tyesStyle := baseStyle\n\tnoStyle := baseStyle\n\n\tif m.selected == 0 {\n\t\tyesStyle = yesStyle.\n\t\t\tBackground(t.Primary()).\n\t\t\tForeground(t.Background()).\n\t\t\tBold(true)\n\t\tnoStyle = noStyle.\n\t\t\tBackground(t.Background()).\n\t\t\tForeground(t.Primary())\n\t} else {\n\t\tnoStyle = noStyle.\n\t\t\tBackground(t.Primary()).\n\t\t\tForeground(t.Background()).\n\t\t\tBold(true)\n\t\tyesStyle = yesStyle.\n\t\t\tBackground(t.Background()).\n\t\t\tForeground(t.Primary())\n\t}\n\n\tyes := yesStyle.Padding(0, 3).Render(\"Yes\")\n\tno := noStyle.Padding(0, 3).Render(\"No\")\n\n\tbuttons := lipgloss.JoinHorizontal(lipgloss.Center, yes, baseStyle.Render(\" \"), no)\n\tbuttons = baseStyle.\n\t\tWidth(maxWidth).\n\t\tPadding(1, 0).\n\t\tRender(buttons)\n\n\tcontent := lipgloss.JoinVertical(\n\t\tlipgloss.Left,\n\t\ttitle,\n\t\tbaseStyle.Width(maxWidth).Render(\"\"),\n\t\texplanation,\n\t\tquestion,\n\t\tbuttons,\n\t\tbaseStyle.Width(maxWidth).Render(\"\"),\n\t)\n\n\treturn baseStyle.Padding(1, 2).\n\t\tBorder(lipgloss.RoundedBorder()).\n\t\tBorderBackground(t.Background()).\n\t\tBorderForeground(t.TextMuted()).\n\t\tWidth(lipgloss.Width(content) + 4).\n\t\tRender(content)\n}\n\n// SetSize sets the size of the component.\nfunc (m *InitDialogCmp) SetSize(width, height int) {\n\tm.width = width\n\tm.height = height\n}\n\n// Bindings implements layout.Bindings.\nfunc (m InitDialogCmp) Bindings() []key.Binding {\n\treturn m.keys.ShortHelp()\n}\n\n// CloseInitDialogMsg is a message that is sent when the init dialog is closed.\ntype CloseInitDialogMsg struct {\n\tInitialize bool\n}\n\n// ShowInitDialogMsg is a message that is sent to show the init dialog.\ntype ShowInitDialogMsg struct {\n\tShow bool\n}\n"], ["/opencode/internal/tui/components/dialog/arguments.go", "package dialog\n\nimport (\n\t\"fmt\"\n\t\"github.com/charmbracelet/bubbles/key\"\n\t\"github.com/charmbracelet/bubbles/textinput\"\n\ttea \"github.com/charmbracelet/bubbletea\"\n\t\"github.com/charmbracelet/lipgloss\"\n\n\t\"github.com/opencode-ai/opencode/internal/tui/styles\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n\t\"github.com/opencode-ai/opencode/internal/tui/util\"\n)\n\ntype argumentsDialogKeyMap struct {\n\tEnter key.Binding\n\tEscape key.Binding\n}\n\n// ShortHelp implements key.Map.\nfunc (k argumentsDialogKeyMap) ShortHelp() []key.Binding {\n\treturn []key.Binding{\n\t\tkey.NewBinding(\n\t\t\tkey.WithKeys(\"enter\"),\n\t\t\tkey.WithHelp(\"enter\", \"confirm\"),\n\t\t),\n\t\tkey.NewBinding(\n\t\t\tkey.WithKeys(\"esc\"),\n\t\t\tkey.WithHelp(\"esc\", \"cancel\"),\n\t\t),\n\t}\n}\n\n// FullHelp implements key.Map.\nfunc (k argumentsDialogKeyMap) FullHelp() [][]key.Binding {\n\treturn [][]key.Binding{k.ShortHelp()}\n}\n\n// ShowMultiArgumentsDialogMsg is a message that is sent to show the multi-arguments dialog.\ntype ShowMultiArgumentsDialogMsg struct {\n\tCommandID string\n\tContent string\n\tArgNames []string\n}\n\n// CloseMultiArgumentsDialogMsg is a message that is sent when the multi-arguments dialog is closed.\ntype CloseMultiArgumentsDialogMsg struct {\n\tSubmit bool\n\tCommandID string\n\tContent string\n\tArgs map[string]string\n}\n\n// MultiArgumentsDialogCmp is a component that asks the user for multiple command arguments.\ntype MultiArgumentsDialogCmp struct {\n\twidth, height int\n\tinputs []textinput.Model\n\tfocusIndex int\n\tkeys argumentsDialogKeyMap\n\tcommandID string\n\tcontent string\n\targNames []string\n}\n\n// NewMultiArgumentsDialogCmp creates a new MultiArgumentsDialogCmp.\nfunc NewMultiArgumentsDialogCmp(commandID, content string, argNames []string) MultiArgumentsDialogCmp {\n\tt := theme.CurrentTheme()\n\tinputs := make([]textinput.Model, len(argNames))\n\n\tfor i, name := range argNames {\n\t\tti := textinput.New()\n\t\tti.Placeholder = fmt.Sprintf(\"Enter value for %s...\", name)\n\t\tti.Width = 40\n\t\tti.Prompt = \"\"\n\t\tti.PlaceholderStyle = ti.PlaceholderStyle.Background(t.Background())\n\t\tti.PromptStyle = ti.PromptStyle.Background(t.Background())\n\t\tti.TextStyle = ti.TextStyle.Background(t.Background())\n\t\t\n\t\t// Only focus the first input initially\n\t\tif i == 0 {\n\t\t\tti.Focus()\n\t\t\tti.PromptStyle = ti.PromptStyle.Foreground(t.Primary())\n\t\t\tti.TextStyle = ti.TextStyle.Foreground(t.Primary())\n\t\t} else {\n\t\t\tti.Blur()\n\t\t}\n\n\t\tinputs[i] = ti\n\t}\n\n\treturn MultiArgumentsDialogCmp{\n\t\tinputs: inputs,\n\t\tkeys: argumentsDialogKeyMap{},\n\t\tcommandID: commandID,\n\t\tcontent: content,\n\t\targNames: argNames,\n\t\tfocusIndex: 0,\n\t}\n}\n\n// Init implements tea.Model.\nfunc (m MultiArgumentsDialogCmp) Init() tea.Cmd {\n\t// Make sure only the first input is focused\n\tfor i := range m.inputs {\n\t\tif i == 0 {\n\t\t\tm.inputs[i].Focus()\n\t\t} else {\n\t\t\tm.inputs[i].Blur()\n\t\t}\n\t}\n\t\n\treturn textinput.Blink\n}\n\n// Update implements tea.Model.\nfunc (m MultiArgumentsDialogCmp) Update(msg tea.Msg) (tea.Model, tea.Cmd) {\n\tvar cmds []tea.Cmd\n\tt := theme.CurrentTheme()\n\n\tswitch msg := msg.(type) {\n\tcase tea.KeyMsg:\n\t\tswitch {\n\t\tcase key.Matches(msg, key.NewBinding(key.WithKeys(\"esc\"))):\n\t\t\treturn m, util.CmdHandler(CloseMultiArgumentsDialogMsg{\n\t\t\t\tSubmit: false,\n\t\t\t\tCommandID: m.commandID,\n\t\t\t\tContent: m.content,\n\t\t\t\tArgs: nil,\n\t\t\t})\n\t\tcase key.Matches(msg, key.NewBinding(key.WithKeys(\"enter\"))):\n\t\t\t// If we're on the last input, submit the form\n\t\t\tif m.focusIndex == len(m.inputs)-1 {\n\t\t\t\targs := make(map[string]string)\n\t\t\t\tfor i, name := range m.argNames {\n\t\t\t\t\targs[name] = m.inputs[i].Value()\n\t\t\t\t}\n\t\t\t\treturn m, util.CmdHandler(CloseMultiArgumentsDialogMsg{\n\t\t\t\t\tSubmit: true,\n\t\t\t\t\tCommandID: m.commandID,\n\t\t\t\t\tContent: m.content,\n\t\t\t\t\tArgs: args,\n\t\t\t\t})\n\t\t\t}\n\t\t\t// Otherwise, move to the next input\n\t\t\tm.inputs[m.focusIndex].Blur()\n\t\t\tm.focusIndex++\n\t\t\tm.inputs[m.focusIndex].Focus()\n\t\t\tm.inputs[m.focusIndex].PromptStyle = m.inputs[m.focusIndex].PromptStyle.Foreground(t.Primary())\n\t\t\tm.inputs[m.focusIndex].TextStyle = m.inputs[m.focusIndex].TextStyle.Foreground(t.Primary())\n\t\tcase key.Matches(msg, key.NewBinding(key.WithKeys(\"tab\"))):\n\t\t\t// Move to the next input\n\t\t\tm.inputs[m.focusIndex].Blur()\n\t\t\tm.focusIndex = (m.focusIndex + 1) % len(m.inputs)\n\t\t\tm.inputs[m.focusIndex].Focus()\n\t\t\tm.inputs[m.focusIndex].PromptStyle = m.inputs[m.focusIndex].PromptStyle.Foreground(t.Primary())\n\t\t\tm.inputs[m.focusIndex].TextStyle = m.inputs[m.focusIndex].TextStyle.Foreground(t.Primary())\n\t\tcase key.Matches(msg, key.NewBinding(key.WithKeys(\"shift+tab\"))):\n\t\t\t// Move to the previous input\n\t\t\tm.inputs[m.focusIndex].Blur()\n\t\t\tm.focusIndex = (m.focusIndex - 1 + len(m.inputs)) % len(m.inputs)\n\t\t\tm.inputs[m.focusIndex].Focus()\n\t\t\tm.inputs[m.focusIndex].PromptStyle = m.inputs[m.focusIndex].PromptStyle.Foreground(t.Primary())\n\t\t\tm.inputs[m.focusIndex].TextStyle = m.inputs[m.focusIndex].TextStyle.Foreground(t.Primary())\n\t\t}\n\tcase tea.WindowSizeMsg:\n\t\tm.width = msg.Width\n\t\tm.height = msg.Height\n\t}\n\n\t// Update the focused input\n\tvar cmd tea.Cmd\n\tm.inputs[m.focusIndex], cmd = m.inputs[m.focusIndex].Update(msg)\n\tcmds = append(cmds, cmd)\n\n\treturn m, tea.Batch(cmds...)\n}\n\n// View implements tea.Model.\nfunc (m MultiArgumentsDialogCmp) View() string {\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\n\t// Calculate width needed for content\n\tmaxWidth := 60 // Width for explanation text\n\n\ttitle := lipgloss.NewStyle().\n\t\tForeground(t.Primary()).\n\t\tBold(true).\n\t\tWidth(maxWidth).\n\t\tPadding(0, 1).\n\t\tBackground(t.Background()).\n\t\tRender(\"Command Arguments\")\n\n\texplanation := lipgloss.NewStyle().\n\t\tForeground(t.Text()).\n\t\tWidth(maxWidth).\n\t\tPadding(0, 1).\n\t\tBackground(t.Background()).\n\t\tRender(\"This command requires multiple arguments. Please enter values for each:\")\n\n\t// Create input fields for each argument\n\tinputFields := make([]string, len(m.inputs))\n\tfor i, input := range m.inputs {\n\t\t// Highlight the label of the focused input\n\t\tlabelStyle := lipgloss.NewStyle().\n\t\t\tWidth(maxWidth).\n\t\t\tPadding(1, 1, 0, 1).\n\t\t\tBackground(t.Background())\n\t\t\t\n\t\tif i == m.focusIndex {\n\t\t\tlabelStyle = labelStyle.Foreground(t.Primary()).Bold(true)\n\t\t} else {\n\t\t\tlabelStyle = labelStyle.Foreground(t.TextMuted())\n\t\t}\n\t\t\n\t\tlabel := labelStyle.Render(m.argNames[i] + \":\")\n\n\t\tfield := lipgloss.NewStyle().\n\t\t\tForeground(t.Text()).\n\t\t\tWidth(maxWidth).\n\t\t\tPadding(0, 1).\n\t\t\tBackground(t.Background()).\n\t\t\tRender(input.View())\n\n\t\tinputFields[i] = lipgloss.JoinVertical(lipgloss.Left, label, field)\n\t}\n\n\tmaxWidth = min(maxWidth, m.width-10)\n\n\t// Join all elements vertically\n\telements := []string{title, explanation}\n\telements = append(elements, inputFields...)\n\n\tcontent := lipgloss.JoinVertical(\n\t\tlipgloss.Left,\n\t\telements...,\n\t)\n\n\treturn baseStyle.Padding(1, 2).\n\t\tBorder(lipgloss.RoundedBorder()).\n\t\tBorderBackground(t.Background()).\n\t\tBorderForeground(t.TextMuted()).\n\t\tBackground(t.Background()).\n\t\tWidth(lipgloss.Width(content) + 4).\n\t\tRender(content)\n}\n\n// SetSize sets the size of the component.\nfunc (m *MultiArgumentsDialogCmp) SetSize(width, height int) {\n\tm.width = width\n\tm.height = height\n}\n\n// Bindings implements layout.Bindings.\nfunc (m MultiArgumentsDialogCmp) Bindings() []key.Binding {\n\treturn m.keys.ShortHelp()\n}"], ["/opencode/internal/db/files.sql.go", "// Code generated by sqlc. DO NOT EDIT.\n// versions:\n// sqlc v1.29.0\n// source: files.sql\n\npackage db\n\nimport (\n\t\"context\"\n)\n\nconst createFile = `-- name: CreateFile :one\nINSERT INTO files (\n id,\n session_id,\n path,\n content,\n version,\n created_at,\n updated_at\n) VALUES (\n ?, ?, ?, ?, ?, strftime('%s', 'now'), strftime('%s', 'now')\n)\nRETURNING id, session_id, path, content, version, created_at, updated_at\n`\n\ntype CreateFileParams struct {\n\tID string `json:\"id\"`\n\tSessionID string `json:\"session_id\"`\n\tPath string `json:\"path\"`\n\tContent string `json:\"content\"`\n\tVersion string `json:\"version\"`\n}\n\nfunc (q *Queries) CreateFile(ctx context.Context, arg CreateFileParams) (File, error) {\n\trow := q.queryRow(ctx, q.createFileStmt, createFile,\n\t\targ.ID,\n\t\targ.SessionID,\n\t\targ.Path,\n\t\targ.Content,\n\t\targ.Version,\n\t)\n\tvar i File\n\terr := row.Scan(\n\t\t&i.ID,\n\t\t&i.SessionID,\n\t\t&i.Path,\n\t\t&i.Content,\n\t\t&i.Version,\n\t\t&i.CreatedAt,\n\t\t&i.UpdatedAt,\n\t)\n\treturn i, err\n}\n\nconst deleteFile = `-- name: DeleteFile :exec\nDELETE FROM files\nWHERE id = ?\n`\n\nfunc (q *Queries) DeleteFile(ctx context.Context, id string) error {\n\t_, err := q.exec(ctx, q.deleteFileStmt, deleteFile, id)\n\treturn err\n}\n\nconst deleteSessionFiles = `-- name: DeleteSessionFiles :exec\nDELETE FROM files\nWHERE session_id = ?\n`\n\nfunc (q *Queries) DeleteSessionFiles(ctx context.Context, sessionID string) error {\n\t_, err := q.exec(ctx, q.deleteSessionFilesStmt, deleteSessionFiles, sessionID)\n\treturn err\n}\n\nconst getFile = `-- name: GetFile :one\nSELECT id, session_id, path, content, version, created_at, updated_at\nFROM files\nWHERE id = ? LIMIT 1\n`\n\nfunc (q *Queries) GetFile(ctx context.Context, id string) (File, error) {\n\trow := q.queryRow(ctx, q.getFileStmt, getFile, id)\n\tvar i File\n\terr := row.Scan(\n\t\t&i.ID,\n\t\t&i.SessionID,\n\t\t&i.Path,\n\t\t&i.Content,\n\t\t&i.Version,\n\t\t&i.CreatedAt,\n\t\t&i.UpdatedAt,\n\t)\n\treturn i, err\n}\n\nconst getFileByPathAndSession = `-- name: GetFileByPathAndSession :one\nSELECT id, session_id, path, content, version, created_at, updated_at\nFROM files\nWHERE path = ? AND session_id = ?\nORDER BY created_at DESC\nLIMIT 1\n`\n\ntype GetFileByPathAndSessionParams struct {\n\tPath string `json:\"path\"`\n\tSessionID string `json:\"session_id\"`\n}\n\nfunc (q *Queries) GetFileByPathAndSession(ctx context.Context, arg GetFileByPathAndSessionParams) (File, error) {\n\trow := q.queryRow(ctx, q.getFileByPathAndSessionStmt, getFileByPathAndSession, arg.Path, arg.SessionID)\n\tvar i File\n\terr := row.Scan(\n\t\t&i.ID,\n\t\t&i.SessionID,\n\t\t&i.Path,\n\t\t&i.Content,\n\t\t&i.Version,\n\t\t&i.CreatedAt,\n\t\t&i.UpdatedAt,\n\t)\n\treturn i, err\n}\n\nconst listFilesByPath = `-- name: ListFilesByPath :many\nSELECT id, session_id, path, content, version, created_at, updated_at\nFROM files\nWHERE path = ?\nORDER BY created_at DESC\n`\n\nfunc (q *Queries) ListFilesByPath(ctx context.Context, path string) ([]File, error) {\n\trows, err := q.query(ctx, q.listFilesByPathStmt, listFilesByPath, path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer rows.Close()\n\titems := []File{}\n\tfor rows.Next() {\n\t\tvar i File\n\t\tif err := rows.Scan(\n\t\t\t&i.ID,\n\t\t\t&i.SessionID,\n\t\t\t&i.Path,\n\t\t\t&i.Content,\n\t\t\t&i.Version,\n\t\t\t&i.CreatedAt,\n\t\t\t&i.UpdatedAt,\n\t\t); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\titems = append(items, i)\n\t}\n\tif err := rows.Close(); err != nil {\n\t\treturn nil, err\n\t}\n\tif err := rows.Err(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn items, nil\n}\n\nconst listFilesBySession = `-- name: ListFilesBySession :many\nSELECT id, session_id, path, content, version, created_at, updated_at\nFROM files\nWHERE session_id = ?\nORDER BY created_at ASC\n`\n\nfunc (q *Queries) ListFilesBySession(ctx context.Context, sessionID string) ([]File, error) {\n\trows, err := q.query(ctx, q.listFilesBySessionStmt, listFilesBySession, sessionID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer rows.Close()\n\titems := []File{}\n\tfor rows.Next() {\n\t\tvar i File\n\t\tif err := rows.Scan(\n\t\t\t&i.ID,\n\t\t\t&i.SessionID,\n\t\t\t&i.Path,\n\t\t\t&i.Content,\n\t\t\t&i.Version,\n\t\t\t&i.CreatedAt,\n\t\t\t&i.UpdatedAt,\n\t\t); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\titems = append(items, i)\n\t}\n\tif err := rows.Close(); err != nil {\n\t\treturn nil, err\n\t}\n\tif err := rows.Err(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn items, nil\n}\n\nconst listLatestSessionFiles = `-- name: ListLatestSessionFiles :many\nSELECT f.id, f.session_id, f.path, f.content, f.version, f.created_at, f.updated_at\nFROM files f\nINNER JOIN (\n SELECT path, MAX(created_at) as max_created_at\n FROM files\n GROUP BY path\n) latest ON f.path = latest.path AND f.created_at = latest.max_created_at\nWHERE f.session_id = ?\nORDER BY f.path\n`\n\nfunc (q *Queries) ListLatestSessionFiles(ctx context.Context, sessionID string) ([]File, error) {\n\trows, err := q.query(ctx, q.listLatestSessionFilesStmt, listLatestSessionFiles, sessionID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer rows.Close()\n\titems := []File{}\n\tfor rows.Next() {\n\t\tvar i File\n\t\tif err := rows.Scan(\n\t\t\t&i.ID,\n\t\t\t&i.SessionID,\n\t\t\t&i.Path,\n\t\t\t&i.Content,\n\t\t\t&i.Version,\n\t\t\t&i.CreatedAt,\n\t\t\t&i.UpdatedAt,\n\t\t); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\titems = append(items, i)\n\t}\n\tif err := rows.Close(); err != nil {\n\t\treturn nil, err\n\t}\n\tif err := rows.Err(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn items, nil\n}\n\nconst listNewFiles = `-- name: ListNewFiles :many\nSELECT id, session_id, path, content, version, created_at, updated_at\nFROM files\nWHERE is_new = 1\nORDER BY created_at DESC\n`\n\nfunc (q *Queries) ListNewFiles(ctx context.Context) ([]File, error) {\n\trows, err := q.query(ctx, q.listNewFilesStmt, listNewFiles)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer rows.Close()\n\titems := []File{}\n\tfor rows.Next() {\n\t\tvar i File\n\t\tif err := rows.Scan(\n\t\t\t&i.ID,\n\t\t\t&i.SessionID,\n\t\t\t&i.Path,\n\t\t\t&i.Content,\n\t\t\t&i.Version,\n\t\t\t&i.CreatedAt,\n\t\t\t&i.UpdatedAt,\n\t\t); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\titems = append(items, i)\n\t}\n\tif err := rows.Close(); err != nil {\n\t\treturn nil, err\n\t}\n\tif err := rows.Err(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn items, nil\n}\n\nconst updateFile = `-- name: UpdateFile :one\nUPDATE files\nSET\n content = ?,\n version = ?,\n updated_at = strftime('%s', 'now')\nWHERE id = ?\nRETURNING id, session_id, path, content, version, created_at, updated_at\n`\n\ntype UpdateFileParams struct {\n\tContent string `json:\"content\"`\n\tVersion string `json:\"version\"`\n\tID string `json:\"id\"`\n}\n\nfunc (q *Queries) UpdateFile(ctx context.Context, arg UpdateFileParams) (File, error) {\n\trow := q.queryRow(ctx, q.updateFileStmt, updateFile, arg.Content, arg.Version, arg.ID)\n\tvar i File\n\terr := row.Scan(\n\t\t&i.ID,\n\t\t&i.SessionID,\n\t\t&i.Path,\n\t\t&i.Content,\n\t\t&i.Version,\n\t\t&i.CreatedAt,\n\t\t&i.UpdatedAt,\n\t)\n\treturn i, err\n}\n"], ["/opencode/internal/format/spinner.go", "package format\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"os\"\n\n\t\"github.com/charmbracelet/bubbles/spinner\"\n\ttea \"github.com/charmbracelet/bubbletea\"\n)\n\n// Spinner wraps the bubbles spinner for non-interactive mode\ntype Spinner struct {\n\tmodel spinner.Model\n\tdone chan struct{}\n\tprog *tea.Program\n\tctx context.Context\n\tcancel context.CancelFunc\n}\n\n// spinnerModel is the tea.Model for the spinner\ntype spinnerModel struct {\n\tspinner spinner.Model\n\tmessage string\n\tquitting bool\n}\n\nfunc (m spinnerModel) Init() tea.Cmd {\n\treturn m.spinner.Tick\n}\n\nfunc (m spinnerModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {\n\tswitch msg := msg.(type) {\n\tcase tea.KeyMsg:\n\t\tm.quitting = true\n\t\treturn m, tea.Quit\n\tcase spinner.TickMsg:\n\t\tvar cmd tea.Cmd\n\t\tm.spinner, cmd = m.spinner.Update(msg)\n\t\treturn m, cmd\n\tcase quitMsg:\n\t\tm.quitting = true\n\t\treturn m, tea.Quit\n\tdefault:\n\t\treturn m, nil\n\t}\n}\n\nfunc (m spinnerModel) View() string {\n\tif m.quitting {\n\t\treturn \"\"\n\t}\n\treturn fmt.Sprintf(\"%s %s\", m.spinner.View(), m.message)\n}\n\n// quitMsg is sent when we want to quit the spinner\ntype quitMsg struct{}\n\n// NewSpinner creates a new spinner with the given message\nfunc NewSpinner(message string) *Spinner {\n\ts := spinner.New()\n\ts.Spinner = spinner.Dot\n\ts.Style = s.Style.Foreground(s.Style.GetForeground())\n\n\tctx, cancel := context.WithCancel(context.Background())\n\n\tmodel := spinnerModel{\n\t\tspinner: s,\n\t\tmessage: message,\n\t}\n\n\tprog := tea.NewProgram(model, tea.WithOutput(os.Stderr), tea.WithoutCatchPanics())\n\n\treturn &Spinner{\n\t\tmodel: s,\n\t\tdone: make(chan struct{}),\n\t\tprog: prog,\n\t\tctx: ctx,\n\t\tcancel: cancel,\n\t}\n}\n\n// Start begins the spinner animation\nfunc (s *Spinner) Start() {\n\tgo func() {\n\t\tdefer close(s.done)\n\t\tgo func() {\n\t\t\t<-s.ctx.Done()\n\t\t\ts.prog.Send(quitMsg{})\n\t\t}()\n\t\t_, err := s.prog.Run()\n\t\tif err != nil {\n\t\t\tfmt.Fprintf(os.Stderr, \"Error running spinner: %v\\n\", err)\n\t\t}\n\t}()\n}\n\n// Stop ends the spinner animation\nfunc (s *Spinner) Stop() {\n\ts.cancel()\n\t<-s.done\n}\n"], ["/opencode/internal/llm/provider/bedrock.go", "package provider\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"os\"\n\t\"strings\"\n\n\t\"github.com/opencode-ai/opencode/internal/llm/tools\"\n\t\"github.com/opencode-ai/opencode/internal/message\"\n)\n\ntype bedrockOptions struct {\n\t// Bedrock specific options can be added here\n}\n\ntype BedrockOption func(*bedrockOptions)\n\ntype bedrockClient struct {\n\tproviderOptions providerClientOptions\n\toptions bedrockOptions\n\tchildProvider ProviderClient\n}\n\ntype BedrockClient ProviderClient\n\nfunc newBedrockClient(opts providerClientOptions) BedrockClient {\n\tbedrockOpts := bedrockOptions{}\n\t// Apply bedrock specific options if they are added in the future\n\n\t// Get AWS region from environment\n\tregion := os.Getenv(\"AWS_REGION\")\n\tif region == \"\" {\n\t\tregion = os.Getenv(\"AWS_DEFAULT_REGION\")\n\t}\n\n\tif region == \"\" {\n\t\tregion = \"us-east-1\" // default region\n\t}\n\tif len(region) < 2 {\n\t\treturn &bedrockClient{\n\t\t\tproviderOptions: opts,\n\t\t\toptions: bedrockOpts,\n\t\t\tchildProvider: nil, // Will cause an error when used\n\t\t}\n\t}\n\n\t// Prefix the model name with region\n\tregionPrefix := region[:2]\n\tmodelName := opts.model.APIModel\n\topts.model.APIModel = fmt.Sprintf(\"%s.%s\", regionPrefix, modelName)\n\n\t// Determine which provider to use based on the model\n\tif strings.Contains(string(opts.model.APIModel), \"anthropic\") {\n\t\t// Create Anthropic client with Bedrock configuration\n\t\tanthropicOpts := opts\n\t\tanthropicOpts.anthropicOptions = append(anthropicOpts.anthropicOptions,\n\t\t\tWithAnthropicBedrock(true),\n\t\t\tWithAnthropicDisableCache(),\n\t\t)\n\t\treturn &bedrockClient{\n\t\t\tproviderOptions: opts,\n\t\t\toptions: bedrockOpts,\n\t\t\tchildProvider: newAnthropicClient(anthropicOpts),\n\t\t}\n\t}\n\n\t// Return client with nil childProvider if model is not supported\n\t// This will cause an error when used\n\treturn &bedrockClient{\n\t\tproviderOptions: opts,\n\t\toptions: bedrockOpts,\n\t\tchildProvider: nil,\n\t}\n}\n\nfunc (b *bedrockClient) send(ctx context.Context, messages []message.Message, tools []tools.BaseTool) (*ProviderResponse, error) {\n\tif b.childProvider == nil {\n\t\treturn nil, errors.New(\"unsupported model for bedrock provider\")\n\t}\n\treturn b.childProvider.send(ctx, messages, tools)\n}\n\nfunc (b *bedrockClient) stream(ctx context.Context, messages []message.Message, tools []tools.BaseTool) <-chan ProviderEvent {\n\teventChan := make(chan ProviderEvent)\n\n\tif b.childProvider == nil {\n\t\tgo func() {\n\t\t\teventChan <- ProviderEvent{\n\t\t\t\tType: EventError,\n\t\t\t\tError: errors.New(\"unsupported model for bedrock provider\"),\n\t\t\t}\n\t\t\tclose(eventChan)\n\t\t}()\n\t\treturn eventChan\n\t}\n\n\treturn b.childProvider.stream(ctx, messages, tools)\n}\n\n"], ["/opencode/internal/lsp/protocol/pattern_interfaces.go", "package protocol\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n)\n\n// PatternInfo is an interface for types that represent glob patterns\ntype PatternInfo interface {\n\tGetPattern() string\n\tGetBasePath() string\n\tisPattern() // marker method\n}\n\n// StringPattern implements PatternInfo for string patterns\ntype StringPattern struct {\n\tPattern string\n}\n\nfunc (p StringPattern) GetPattern() string { return p.Pattern }\nfunc (p StringPattern) GetBasePath() string { return \"\" }\nfunc (p StringPattern) isPattern() {}\n\n// RelativePatternInfo implements PatternInfo for RelativePattern\ntype RelativePatternInfo struct {\n\tRP RelativePattern\n\tBasePath string\n}\n\nfunc (p RelativePatternInfo) GetPattern() string { return string(p.RP.Pattern) }\nfunc (p RelativePatternInfo) GetBasePath() string { return p.BasePath }\nfunc (p RelativePatternInfo) isPattern() {}\n\n// AsPattern converts GlobPattern to a PatternInfo object\nfunc (g *GlobPattern) AsPattern() (PatternInfo, error) {\n\tif g.Value == nil {\n\t\treturn nil, fmt.Errorf(\"nil pattern\")\n\t}\n\n\tswitch v := g.Value.(type) {\n\tcase string:\n\t\treturn StringPattern{Pattern: v}, nil\n\tcase RelativePattern:\n\t\t// Handle BaseURI which could be string or DocumentUri\n\t\tbasePath := \"\"\n\t\tswitch baseURI := v.BaseURI.Value.(type) {\n\t\tcase string:\n\t\t\tbasePath = strings.TrimPrefix(baseURI, \"file://\")\n\t\tcase DocumentUri:\n\t\t\tbasePath = strings.TrimPrefix(string(baseURI), \"file://\")\n\t\tdefault:\n\t\t\treturn nil, fmt.Errorf(\"unknown BaseURI type: %T\", v.BaseURI.Value)\n\t\t}\n\t\treturn RelativePatternInfo{RP: v, BasePath: basePath}, nil\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"unknown pattern type: %T\", g.Value)\n\t}\n}\n"], ["/opencode/internal/lsp/protocol/interface.go", "package protocol\n\nimport \"fmt\"\n\n// TextEditResult is an interface for types that represent workspace symbols\ntype WorkspaceSymbolResult interface {\n\tGetName() string\n\tGetLocation() Location\n\tisWorkspaceSymbol() // marker method\n}\n\nfunc (ws *WorkspaceSymbol) GetName() string { return ws.Name }\nfunc (ws *WorkspaceSymbol) GetLocation() Location {\n\tswitch v := ws.Location.Value.(type) {\n\tcase Location:\n\t\treturn v\n\tcase LocationUriOnly:\n\t\treturn Location{URI: v.URI}\n\t}\n\treturn Location{}\n}\nfunc (ws *WorkspaceSymbol) isWorkspaceSymbol() {}\n\nfunc (si *SymbolInformation) GetName() string { return si.Name }\nfunc (si *SymbolInformation) GetLocation() Location { return si.Location }\nfunc (si *SymbolInformation) isWorkspaceSymbol() {}\n\n// Results converts the Value to a slice of WorkspaceSymbolResult\nfunc (r Or_Result_workspace_symbol) Results() ([]WorkspaceSymbolResult, error) {\n\tif r.Value == nil {\n\t\treturn make([]WorkspaceSymbolResult, 0), nil\n\t}\n\tswitch v := r.Value.(type) {\n\tcase []WorkspaceSymbol:\n\t\tresults := make([]WorkspaceSymbolResult, len(v))\n\t\tfor i := range v {\n\t\t\tresults[i] = &v[i]\n\t\t}\n\t\treturn results, nil\n\tcase []SymbolInformation:\n\t\tresults := make([]WorkspaceSymbolResult, len(v))\n\t\tfor i := range v {\n\t\t\tresults[i] = &v[i]\n\t\t}\n\t\treturn results, nil\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"unknown symbol type: %T\", r.Value)\n\t}\n}\n\n// TextEditResult is an interface for types that represent document symbols\ntype DocumentSymbolResult interface {\n\tGetRange() Range\n\tGetName() string\n\tisDocumentSymbol() // marker method\n}\n\nfunc (ds *DocumentSymbol) GetRange() Range { return ds.Range }\nfunc (ds *DocumentSymbol) GetName() string { return ds.Name }\nfunc (ds *DocumentSymbol) isDocumentSymbol() {}\n\nfunc (si *SymbolInformation) GetRange() Range { return si.Location.Range }\n\n// Note: SymbolInformation already has GetName() implemented above\nfunc (si *SymbolInformation) isDocumentSymbol() {}\n\n// Results converts the Value to a slice of DocumentSymbolResult\nfunc (r Or_Result_textDocument_documentSymbol) Results() ([]DocumentSymbolResult, error) {\n\tif r.Value == nil {\n\t\treturn make([]DocumentSymbolResult, 0), nil\n\t}\n\tswitch v := r.Value.(type) {\n\tcase []DocumentSymbol:\n\t\tresults := make([]DocumentSymbolResult, len(v))\n\t\tfor i := range v {\n\t\t\tresults[i] = &v[i]\n\t\t}\n\t\treturn results, nil\n\tcase []SymbolInformation:\n\t\tresults := make([]DocumentSymbolResult, len(v))\n\t\tfor i := range v {\n\t\t\tresults[i] = &v[i]\n\t\t}\n\t\treturn results, nil\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"unknown document symbol type: %T\", v)\n\t}\n}\n\n// TextEditResult is an interface for types that can be used as text edits\ntype TextEditResult interface {\n\tGetRange() Range\n\tGetNewText() string\n\tisTextEdit() // marker method\n}\n\nfunc (te *TextEdit) GetRange() Range { return te.Range }\nfunc (te *TextEdit) GetNewText() string { return te.NewText }\nfunc (te *TextEdit) isTextEdit() {}\n\n// Convert Or_TextDocumentEdit_edits_Elem to TextEdit\nfunc (e Or_TextDocumentEdit_edits_Elem) AsTextEdit() (TextEdit, error) {\n\tif e.Value == nil {\n\t\treturn TextEdit{}, fmt.Errorf(\"nil text edit\")\n\t}\n\tswitch v := e.Value.(type) {\n\tcase TextEdit:\n\t\treturn v, nil\n\tcase AnnotatedTextEdit:\n\t\treturn TextEdit{\n\t\t\tRange: v.Range,\n\t\t\tNewText: v.NewText,\n\t\t}, nil\n\tdefault:\n\t\treturn TextEdit{}, fmt.Errorf(\"unknown text edit type: %T\", e.Value)\n\t}\n}\n"], ["/opencode/internal/tui/styles/background.go", "package styles\n\nimport (\n\t\"fmt\"\n\t\"regexp\"\n\t\"strings\"\n\n\t\"github.com/charmbracelet/lipgloss\"\n)\n\nvar ansiEscape = regexp.MustCompile(\"\\x1b\\\\[[0-9;]*m\")\n\nfunc getColorRGB(c lipgloss.TerminalColor) (uint8, uint8, uint8) {\n\tr, g, b, a := c.RGBA()\n\n\t// Un-premultiply alpha if needed\n\tif a > 0 && a < 0xffff {\n\t\tr = (r * 0xffff) / a\n\t\tg = (g * 0xffff) / a\n\t\tb = (b * 0xffff) / a\n\t}\n\n\t// Convert from 16-bit to 8-bit color\n\treturn uint8(r >> 8), uint8(g >> 8), uint8(b >> 8)\n}\n\n// ForceReplaceBackgroundWithLipgloss replaces any ANSI background color codes\n// in `input` with a single 24‑bit background (48;2;R;G;B).\nfunc ForceReplaceBackgroundWithLipgloss(input string, newBgColor lipgloss.TerminalColor) string {\n\t// Precompute our new-bg sequence once\n\tr, g, b := getColorRGB(newBgColor)\n\tnewBg := fmt.Sprintf(\"48;2;%d;%d;%d\", r, g, b)\n\n\treturn ansiEscape.ReplaceAllStringFunc(input, func(seq string) string {\n\t\tconst (\n\t\t\tescPrefixLen = 2 // \"\\x1b[\"\n\t\t\tescSuffixLen = 1 // \"m\"\n\t\t)\n\n\t\traw := seq\n\t\tstart := escPrefixLen\n\t\tend := len(raw) - escSuffixLen\n\n\t\tvar sb strings.Builder\n\t\t// reserve enough space: original content minus bg codes + our newBg\n\t\tsb.Grow((end - start) + len(newBg) + 2)\n\n\t\t// scan from start..end, token by token\n\t\tfor i := start; i < end; {\n\t\t\t// find the next ';' or end\n\t\t\tj := i\n\t\t\tfor j < end && raw[j] != ';' {\n\t\t\t\tj++\n\t\t\t}\n\t\t\ttoken := raw[i:j]\n\n\t\t\t// fast‑path: skip \"48;5;N\" or \"48;2;R;G;B\"\n\t\t\tif len(token) == 2 && token[0] == '4' && token[1] == '8' {\n\t\t\t\tk := j + 1\n\t\t\t\tif k < end {\n\t\t\t\t\t// find next token\n\t\t\t\t\tl := k\n\t\t\t\t\tfor l < end && raw[l] != ';' {\n\t\t\t\t\t\tl++\n\t\t\t\t\t}\n\t\t\t\t\tnext := raw[k:l]\n\t\t\t\t\tif next == \"5\" {\n\t\t\t\t\t\t// skip \"48;5;N\"\n\t\t\t\t\t\tm := l + 1\n\t\t\t\t\t\tfor m < end && raw[m] != ';' {\n\t\t\t\t\t\t\tm++\n\t\t\t\t\t\t}\n\t\t\t\t\t\ti = m + 1\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t} else if next == \"2\" {\n\t\t\t\t\t\t// skip \"48;2;R;G;B\"\n\t\t\t\t\t\tm := l + 1\n\t\t\t\t\t\tfor count := 0; count < 3 && m < end; count++ {\n\t\t\t\t\t\t\tfor m < end && raw[m] != ';' {\n\t\t\t\t\t\t\t\tm++\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tm++\n\t\t\t\t\t\t}\n\t\t\t\t\t\ti = m\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// decide whether to keep this token\n\t\t\t// manually parse ASCII digits to int\n\t\t\tisNum := true\n\t\t\tval := 0\n\t\t\tfor p := i; p < j; p++ {\n\t\t\t\tc := raw[p]\n\t\t\t\tif c < '0' || c > '9' {\n\t\t\t\t\tisNum = false\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tval = val*10 + int(c-'0')\n\t\t\t}\n\t\t\tkeep := !isNum ||\n\t\t\t\t((val < 40 || val > 47) && (val < 100 || val > 107) && val != 49)\n\n\t\t\tif keep {\n\t\t\t\tif sb.Len() > 0 {\n\t\t\t\t\tsb.WriteByte(';')\n\t\t\t\t}\n\t\t\t\tsb.WriteString(token)\n\t\t\t}\n\t\t\t// advance past this token (and the semicolon)\n\t\t\ti = j + 1\n\t\t}\n\n\t\t// append our new background\n\t\tif sb.Len() > 0 {\n\t\t\tsb.WriteByte(';')\n\t\t}\n\t\tsb.WriteString(newBg)\n\n\t\treturn \"\\x1b[\" + sb.String() + \"m\"\n\t})\n}\n"], ["/opencode/internal/tui/components/dialog/quit.go", "package dialog\n\nimport (\n\t\"strings\"\n\n\t\"github.com/charmbracelet/bubbles/key\"\n\ttea \"github.com/charmbracelet/bubbletea\"\n\t\"github.com/charmbracelet/lipgloss\"\n\t\"github.com/opencode-ai/opencode/internal/tui/layout\"\n\t\"github.com/opencode-ai/opencode/internal/tui/styles\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n\t\"github.com/opencode-ai/opencode/internal/tui/util\"\n)\n\nconst question = \"Are you sure you want to quit?\"\n\ntype CloseQuitMsg struct{}\n\ntype QuitDialog interface {\n\ttea.Model\n\tlayout.Bindings\n}\n\ntype quitDialogCmp struct {\n\tselectedNo bool\n}\n\ntype helpMapping struct {\n\tLeftRight key.Binding\n\tEnterSpace key.Binding\n\tYes key.Binding\n\tNo key.Binding\n\tTab key.Binding\n}\n\nvar helpKeys = helpMapping{\n\tLeftRight: key.NewBinding(\n\t\tkey.WithKeys(\"left\", \"right\"),\n\t\tkey.WithHelp(\"←/→\", \"switch options\"),\n\t),\n\tEnterSpace: key.NewBinding(\n\t\tkey.WithKeys(\"enter\", \" \"),\n\t\tkey.WithHelp(\"enter/space\", \"confirm\"),\n\t),\n\tYes: key.NewBinding(\n\t\tkey.WithKeys(\"y\", \"Y\"),\n\t\tkey.WithHelp(\"y/Y\", \"yes\"),\n\t),\n\tNo: key.NewBinding(\n\t\tkey.WithKeys(\"n\", \"N\"),\n\t\tkey.WithHelp(\"n/N\", \"no\"),\n\t),\n\tTab: key.NewBinding(\n\t\tkey.WithKeys(\"tab\"),\n\t\tkey.WithHelp(\"tab\", \"switch options\"),\n\t),\n}\n\nfunc (q *quitDialogCmp) Init() tea.Cmd {\n\treturn nil\n}\n\nfunc (q *quitDialogCmp) Update(msg tea.Msg) (tea.Model, tea.Cmd) {\n\tswitch msg := msg.(type) {\n\tcase tea.KeyMsg:\n\t\tswitch {\n\t\tcase key.Matches(msg, helpKeys.LeftRight) || key.Matches(msg, helpKeys.Tab):\n\t\t\tq.selectedNo = !q.selectedNo\n\t\t\treturn q, nil\n\t\tcase key.Matches(msg, helpKeys.EnterSpace):\n\t\t\tif !q.selectedNo {\n\t\t\t\treturn q, tea.Quit\n\t\t\t}\n\t\t\treturn q, util.CmdHandler(CloseQuitMsg{})\n\t\tcase key.Matches(msg, helpKeys.Yes):\n\t\t\treturn q, tea.Quit\n\t\tcase key.Matches(msg, helpKeys.No):\n\t\t\treturn q, util.CmdHandler(CloseQuitMsg{})\n\t\t}\n\t}\n\treturn q, nil\n}\n\nfunc (q *quitDialogCmp) View() string {\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\t\n\tyesStyle := baseStyle\n\tnoStyle := baseStyle\n\tspacerStyle := baseStyle.Background(t.Background())\n\n\tif q.selectedNo {\n\t\tnoStyle = noStyle.Background(t.Primary()).Foreground(t.Background())\n\t\tyesStyle = yesStyle.Background(t.Background()).Foreground(t.Primary())\n\t} else {\n\t\tyesStyle = yesStyle.Background(t.Primary()).Foreground(t.Background())\n\t\tnoStyle = noStyle.Background(t.Background()).Foreground(t.Primary())\n\t}\n\n\tyesButton := yesStyle.Padding(0, 1).Render(\"Yes\")\n\tnoButton := noStyle.Padding(0, 1).Render(\"No\")\n\n\tbuttons := lipgloss.JoinHorizontal(lipgloss.Left, yesButton, spacerStyle.Render(\" \"), noButton)\n\n\twidth := lipgloss.Width(question)\n\tremainingWidth := width - lipgloss.Width(buttons)\n\tif remainingWidth > 0 {\n\t\tbuttons = spacerStyle.Render(strings.Repeat(\" \", remainingWidth)) + buttons\n\t}\n\n\tcontent := baseStyle.Render(\n\t\tlipgloss.JoinVertical(\n\t\t\tlipgloss.Center,\n\t\t\tquestion,\n\t\t\t\"\",\n\t\t\tbuttons,\n\t\t),\n\t)\n\n\treturn baseStyle.Padding(1, 2).\n\t\tBorder(lipgloss.RoundedBorder()).\n\t\tBorderBackground(t.Background()).\n\t\tBorderForeground(t.TextMuted()).\n\t\tWidth(lipgloss.Width(content) + 4).\n\t\tRender(content)\n}\n\nfunc (q *quitDialogCmp) BindingKeys() []key.Binding {\n\treturn layout.KeyMapToSlice(helpKeys)\n}\n\nfunc NewQuitCmp() QuitDialog {\n\treturn &quitDialogCmp{\n\t\tselectedNo: true,\n\t}\n}\n"], ["/opencode/internal/llm/provider/azure.go", "package provider\n\nimport (\n\t\"os\"\n\n\t\"github.com/Azure/azure-sdk-for-go/sdk/azidentity\"\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/azure\"\n\t\"github.com/openai/openai-go/option\"\n)\n\ntype azureClient struct {\n\t*openaiClient\n}\n\ntype AzureClient ProviderClient\n\nfunc newAzureClient(opts providerClientOptions) AzureClient {\n\n\tendpoint := os.Getenv(\"AZURE_OPENAI_ENDPOINT\") // ex: https://foo.openai.azure.com\n\tapiVersion := os.Getenv(\"AZURE_OPENAI_API_VERSION\") // ex: 2025-04-01-preview\n\n\tif endpoint == \"\" || apiVersion == \"\" {\n\t\treturn &azureClient{openaiClient: newOpenAIClient(opts).(*openaiClient)}\n\t}\n\n\treqOpts := []option.RequestOption{\n\t\tazure.WithEndpoint(endpoint, apiVersion),\n\t}\n\n\tif opts.apiKey != \"\" || os.Getenv(\"AZURE_OPENAI_API_KEY\") != \"\" {\n\t\tkey := opts.apiKey\n\t\tif key == \"\" {\n\t\t\tkey = os.Getenv(\"AZURE_OPENAI_API_KEY\")\n\t\t}\n\t\treqOpts = append(reqOpts, azure.WithAPIKey(key))\n\t} else if cred, err := azidentity.NewDefaultAzureCredential(nil); err == nil {\n\t\treqOpts = append(reqOpts, azure.WithTokenCredential(cred))\n\t}\n\n\tbase := &openaiClient{\n\t\tproviderOptions: opts,\n\t\tclient: openai.NewClient(reqOpts...),\n\t}\n\n\treturn &azureClient{openaiClient: base}\n}\n"], ["/opencode/internal/tui/components/dialog/commands.go", "package dialog\n\nimport (\n\t\"github.com/charmbracelet/bubbles/key\"\n\ttea \"github.com/charmbracelet/bubbletea\"\n\t\"github.com/charmbracelet/lipgloss\"\n\tutilComponents \"github.com/opencode-ai/opencode/internal/tui/components/util\"\n\t\"github.com/opencode-ai/opencode/internal/tui/layout\"\n\t\"github.com/opencode-ai/opencode/internal/tui/styles\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n\t\"github.com/opencode-ai/opencode/internal/tui/util\"\n)\n\n// Command represents a command that can be executed\ntype Command struct {\n\tID string\n\tTitle string\n\tDescription string\n\tHandler func(cmd Command) tea.Cmd\n}\n\nfunc (ci Command) Render(selected bool, width int) string {\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\n\tdescStyle := baseStyle.Width(width).Foreground(t.TextMuted())\n\titemStyle := baseStyle.Width(width).\n\t\tForeground(t.Text()).\n\t\tBackground(t.Background())\n\n\tif selected {\n\t\titemStyle = itemStyle.\n\t\t\tBackground(t.Primary()).\n\t\t\tForeground(t.Background()).\n\t\t\tBold(true)\n\t\tdescStyle = descStyle.\n\t\t\tBackground(t.Primary()).\n\t\t\tForeground(t.Background())\n\t}\n\n\ttitle := itemStyle.Padding(0, 1).Render(ci.Title)\n\tif ci.Description != \"\" {\n\t\tdescription := descStyle.Padding(0, 1).Render(ci.Description)\n\t\treturn lipgloss.JoinVertical(lipgloss.Left, title, description)\n\t}\n\treturn title\n}\n\n// CommandSelectedMsg is sent when a command is selected\ntype CommandSelectedMsg struct {\n\tCommand Command\n}\n\n// CloseCommandDialogMsg is sent when the command dialog is closed\ntype CloseCommandDialogMsg struct{}\n\n// CommandDialog interface for the command selection dialog\ntype CommandDialog interface {\n\ttea.Model\n\tlayout.Bindings\n\tSetCommands(commands []Command)\n}\n\ntype commandDialogCmp struct {\n\tlistView utilComponents.SimpleList[Command]\n\twidth int\n\theight int\n}\n\ntype commandKeyMap struct {\n\tEnter key.Binding\n\tEscape key.Binding\n}\n\nvar commandKeys = commandKeyMap{\n\tEnter: key.NewBinding(\n\t\tkey.WithKeys(\"enter\"),\n\t\tkey.WithHelp(\"enter\", \"select command\"),\n\t),\n\tEscape: key.NewBinding(\n\t\tkey.WithKeys(\"esc\"),\n\t\tkey.WithHelp(\"esc\", \"close\"),\n\t),\n}\n\nfunc (c *commandDialogCmp) Init() tea.Cmd {\n\treturn c.listView.Init()\n}\n\nfunc (c *commandDialogCmp) Update(msg tea.Msg) (tea.Model, tea.Cmd) {\n\tvar cmds []tea.Cmd\n\tswitch msg := msg.(type) {\n\tcase tea.KeyMsg:\n\t\tswitch {\n\t\tcase key.Matches(msg, commandKeys.Enter):\n\t\t\tselectedItem, idx := c.listView.GetSelectedItem()\n\t\t\tif idx != -1 {\n\t\t\t\treturn c, util.CmdHandler(CommandSelectedMsg{\n\t\t\t\t\tCommand: selectedItem,\n\t\t\t\t})\n\t\t\t}\n\t\tcase key.Matches(msg, commandKeys.Escape):\n\t\t\treturn c, util.CmdHandler(CloseCommandDialogMsg{})\n\t\t}\n\tcase tea.WindowSizeMsg:\n\t\tc.width = msg.Width\n\t\tc.height = msg.Height\n\t}\n\n\tu, cmd := c.listView.Update(msg)\n\tc.listView = u.(utilComponents.SimpleList[Command])\n\tcmds = append(cmds, cmd)\n\n\treturn c, tea.Batch(cmds...)\n}\n\nfunc (c *commandDialogCmp) View() string {\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\n\tmaxWidth := 40\n\n\tcommands := c.listView.GetItems()\n\n\tfor _, cmd := range commands {\n\t\tif len(cmd.Title) > maxWidth-4 {\n\t\t\tmaxWidth = len(cmd.Title) + 4\n\t\t}\n\t\tif cmd.Description != \"\" {\n\t\t\tif len(cmd.Description) > maxWidth-4 {\n\t\t\t\tmaxWidth = len(cmd.Description) + 4\n\t\t\t}\n\t\t}\n\t}\n\n\tc.listView.SetMaxWidth(maxWidth)\n\n\ttitle := baseStyle.\n\t\tForeground(t.Primary()).\n\t\tBold(true).\n\t\tWidth(maxWidth).\n\t\tPadding(0, 1).\n\t\tRender(\"Commands\")\n\n\tcontent := lipgloss.JoinVertical(\n\t\tlipgloss.Left,\n\t\ttitle,\n\t\tbaseStyle.Width(maxWidth).Render(\"\"),\n\t\tbaseStyle.Width(maxWidth).Render(c.listView.View()),\n\t\tbaseStyle.Width(maxWidth).Render(\"\"),\n\t)\n\n\treturn baseStyle.Padding(1, 2).\n\t\tBorder(lipgloss.RoundedBorder()).\n\t\tBorderBackground(t.Background()).\n\t\tBorderForeground(t.TextMuted()).\n\t\tWidth(lipgloss.Width(content) + 4).\n\t\tRender(content)\n}\n\nfunc (c *commandDialogCmp) BindingKeys() []key.Binding {\n\treturn layout.KeyMapToSlice(commandKeys)\n}\n\nfunc (c *commandDialogCmp) SetCommands(commands []Command) {\n\tc.listView.SetItems(commands)\n}\n\n// NewCommandDialogCmp creates a new command selection dialog\nfunc NewCommandDialogCmp() CommandDialog {\n\tlistView := utilComponents.NewSimpleList[Command](\n\t\t[]Command{},\n\t\t10,\n\t\t\"No commands available\",\n\t\ttrue,\n\t)\n\treturn &commandDialogCmp{\n\t\tlistView: listView,\n\t}\n}\n"], ["/opencode/internal/tui/components/util/simple-list.go", "package utilComponents\n\nimport (\n\t\"github.com/charmbracelet/bubbles/key\"\n\ttea \"github.com/charmbracelet/bubbletea\"\n\t\"github.com/charmbracelet/lipgloss\"\n\t\"github.com/opencode-ai/opencode/internal/tui/layout\"\n\t\"github.com/opencode-ai/opencode/internal/tui/styles\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n)\n\ntype SimpleListItem interface {\n\tRender(selected bool, width int) string\n}\n\ntype SimpleList[T SimpleListItem] interface {\n\ttea.Model\n\tlayout.Bindings\n\tSetMaxWidth(maxWidth int)\n\tGetSelectedItem() (item T, idx int)\n\tSetItems(items []T)\n\tGetItems() []T\n}\n\ntype simpleListCmp[T SimpleListItem] struct {\n\tfallbackMsg string\n\titems []T\n\tselectedIdx int\n\tmaxWidth int\n\tmaxVisibleItems int\n\tuseAlphaNumericKeys bool\n\twidth int\n\theight int\n}\n\ntype simpleListKeyMap struct {\n\tUp key.Binding\n\tDown key.Binding\n\tUpAlpha key.Binding\n\tDownAlpha key.Binding\n}\n\nvar simpleListKeys = simpleListKeyMap{\n\tUp: key.NewBinding(\n\t\tkey.WithKeys(\"up\"),\n\t\tkey.WithHelp(\"↑\", \"previous list item\"),\n\t),\n\tDown: key.NewBinding(\n\t\tkey.WithKeys(\"down\"),\n\t\tkey.WithHelp(\"↓\", \"next list item\"),\n\t),\n\tUpAlpha: key.NewBinding(\n\t\tkey.WithKeys(\"k\"),\n\t\tkey.WithHelp(\"k\", \"previous list item\"),\n\t),\n\tDownAlpha: key.NewBinding(\n\t\tkey.WithKeys(\"j\"),\n\t\tkey.WithHelp(\"j\", \"next list item\"),\n\t),\n}\n\nfunc (c *simpleListCmp[T]) Init() tea.Cmd {\n\treturn nil\n}\n\nfunc (c *simpleListCmp[T]) Update(msg tea.Msg) (tea.Model, tea.Cmd) {\n\tswitch msg := msg.(type) {\n\tcase tea.KeyMsg:\n\t\tswitch {\n\t\tcase key.Matches(msg, simpleListKeys.Up) || (c.useAlphaNumericKeys && key.Matches(msg, simpleListKeys.UpAlpha)):\n\t\t\tif c.selectedIdx > 0 {\n\t\t\t\tc.selectedIdx--\n\t\t\t}\n\t\t\treturn c, nil\n\t\tcase key.Matches(msg, simpleListKeys.Down) || (c.useAlphaNumericKeys && key.Matches(msg, simpleListKeys.DownAlpha)):\n\t\t\tif c.selectedIdx < len(c.items)-1 {\n\t\t\t\tc.selectedIdx++\n\t\t\t}\n\t\t\treturn c, nil\n\t\t}\n\t}\n\n\treturn c, nil\n}\n\nfunc (c *simpleListCmp[T]) BindingKeys() []key.Binding {\n\treturn layout.KeyMapToSlice(simpleListKeys)\n}\n\nfunc (c *simpleListCmp[T]) GetSelectedItem() (T, int) {\n\tif len(c.items) > 0 {\n\t\treturn c.items[c.selectedIdx], c.selectedIdx\n\t}\n\n\tvar zero T\n\treturn zero, -1\n}\n\nfunc (c *simpleListCmp[T]) SetItems(items []T) {\n\tc.selectedIdx = 0\n\tc.items = items\n}\n\nfunc (c *simpleListCmp[T]) GetItems() []T {\n\treturn c.items\n}\n\nfunc (c *simpleListCmp[T]) SetMaxWidth(width int) {\n\tc.maxWidth = width\n}\n\nfunc (c *simpleListCmp[T]) View() string {\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\n\titems := c.items\n\tmaxWidth := c.maxWidth\n\tmaxVisibleItems := min(c.maxVisibleItems, len(items))\n\tstartIdx := 0\n\n\tif len(items) <= 0 {\n\t\treturn baseStyle.\n\t\t\tBackground(t.Background()).\n\t\t\tPadding(0, 1).\n\t\t\tWidth(maxWidth).\n\t\t\tRender(c.fallbackMsg)\n\t}\n\n\tif len(items) > maxVisibleItems {\n\t\thalfVisible := maxVisibleItems / 2\n\t\tif c.selectedIdx >= halfVisible && c.selectedIdx < len(items)-halfVisible {\n\t\t\tstartIdx = c.selectedIdx - halfVisible\n\t\t} else if c.selectedIdx >= len(items)-halfVisible {\n\t\t\tstartIdx = len(items) - maxVisibleItems\n\t\t}\n\t}\n\n\tendIdx := min(startIdx+maxVisibleItems, len(items))\n\n\tlistItems := make([]string, 0, maxVisibleItems)\n\n\tfor i := startIdx; i < endIdx; i++ {\n\t\titem := items[i]\n\t\ttitle := item.Render(i == c.selectedIdx, maxWidth)\n\t\tlistItems = append(listItems, title)\n\t}\n\n\treturn lipgloss.JoinVertical(lipgloss.Left, listItems...)\n}\n\nfunc NewSimpleList[T SimpleListItem](items []T, maxVisibleItems int, fallbackMsg string, useAlphaNumericKeys bool) SimpleList[T] {\n\treturn &simpleListCmp[T]{\n\t\tfallbackMsg: fallbackMsg,\n\t\titems: items,\n\t\tmaxVisibleItems: maxVisibleItems,\n\t\tuseAlphaNumericKeys: useAlphaNumericKeys,\n\t\tselectedIdx: 0,\n\t}\n}\n"], ["/opencode/internal/tui/components/dialog/help.go", "package dialog\n\nimport (\n\t\"strings\"\n\n\t\"github.com/charmbracelet/bubbles/key\"\n\ttea \"github.com/charmbracelet/bubbletea\"\n\t\"github.com/charmbracelet/lipgloss\"\n\t\"github.com/opencode-ai/opencode/internal/tui/styles\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n)\n\ntype helpCmp struct {\n\twidth int\n\theight int\n\tkeys []key.Binding\n}\n\nfunc (h *helpCmp) Init() tea.Cmd {\n\treturn nil\n}\n\nfunc (h *helpCmp) SetBindings(k []key.Binding) {\n\th.keys = k\n}\n\nfunc (h *helpCmp) Update(msg tea.Msg) (tea.Model, tea.Cmd) {\n\tswitch msg := msg.(type) {\n\tcase tea.WindowSizeMsg:\n\t\th.width = 90\n\t\th.height = msg.Height\n\t}\n\treturn h, nil\n}\n\nfunc removeDuplicateBindings(bindings []key.Binding) []key.Binding {\n\tseen := make(map[string]struct{})\n\tresult := make([]key.Binding, 0, len(bindings))\n\n\t// Process bindings in reverse order\n\tfor i := len(bindings) - 1; i >= 0; i-- {\n\t\tb := bindings[i]\n\t\tk := strings.Join(b.Keys(), \" \")\n\t\tif _, ok := seen[k]; ok {\n\t\t\t// duplicate, skip\n\t\t\tcontinue\n\t\t}\n\t\tseen[k] = struct{}{}\n\t\t// Add to the beginning of result to maintain original order\n\t\tresult = append([]key.Binding{b}, result...)\n\t}\n\n\treturn result\n}\n\nfunc (h *helpCmp) render() string {\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\n\thelpKeyStyle := styles.Bold().\n\t\tBackground(t.Background()).\n\t\tForeground(t.Text()).\n\t\tPadding(0, 1, 0, 0)\n\n\thelpDescStyle := styles.Regular().\n\t\tBackground(t.Background()).\n\t\tForeground(t.TextMuted())\n\n\t// Compile list of bindings to render\n\tbindings := removeDuplicateBindings(h.keys)\n\n\t// Enumerate through each group of bindings, populating a series of\n\t// pairs of columns, one for keys, one for descriptions\n\tvar (\n\t\tpairs []string\n\t\twidth int\n\t\trows = 12 - 2\n\t)\n\n\tfor i := 0; i < len(bindings); i += rows {\n\t\tvar (\n\t\t\tkeys []string\n\t\t\tdescs []string\n\t\t)\n\t\tfor j := i; j < min(i+rows, len(bindings)); j++ {\n\t\t\tkeys = append(keys, helpKeyStyle.Render(bindings[j].Help().Key))\n\t\t\tdescs = append(descs, helpDescStyle.Render(bindings[j].Help().Desc))\n\t\t}\n\n\t\t// Render pair of columns; beyond the first pair, render a three space\n\t\t// left margin, in order to visually separate the pairs.\n\t\tvar cols []string\n\t\tif len(pairs) > 0 {\n\t\t\tcols = []string{baseStyle.Render(\" \")}\n\t\t}\n\n\t\tmaxDescWidth := 0\n\t\tfor _, desc := range descs {\n\t\t\tif maxDescWidth < lipgloss.Width(desc) {\n\t\t\t\tmaxDescWidth = lipgloss.Width(desc)\n\t\t\t}\n\t\t}\n\t\tfor i := range descs {\n\t\t\tremainingWidth := maxDescWidth - lipgloss.Width(descs[i])\n\t\t\tif remainingWidth > 0 {\n\t\t\t\tdescs[i] = descs[i] + baseStyle.Render(strings.Repeat(\" \", remainingWidth))\n\t\t\t}\n\t\t}\n\t\tmaxKeyWidth := 0\n\t\tfor _, key := range keys {\n\t\t\tif maxKeyWidth < lipgloss.Width(key) {\n\t\t\t\tmaxKeyWidth = lipgloss.Width(key)\n\t\t\t}\n\t\t}\n\t\tfor i := range keys {\n\t\t\tremainingWidth := maxKeyWidth - lipgloss.Width(keys[i])\n\t\t\tif remainingWidth > 0 {\n\t\t\t\tkeys[i] = keys[i] + baseStyle.Render(strings.Repeat(\" \", remainingWidth))\n\t\t\t}\n\t\t}\n\n\t\tcols = append(cols,\n\t\t\tstrings.Join(keys, \"\\n\"),\n\t\t\tstrings.Join(descs, \"\\n\"),\n\t\t)\n\n\t\tpair := baseStyle.Render(lipgloss.JoinHorizontal(lipgloss.Top, cols...))\n\t\t// check whether it exceeds the maximum width avail (the width of the\n\t\t// terminal, subtracting 2 for the borders).\n\t\twidth += lipgloss.Width(pair)\n\t\tif width > h.width-2 {\n\t\t\tbreak\n\t\t}\n\t\tpairs = append(pairs, pair)\n\t}\n\n\t// https://github.com/charmbracelet/lipgloss/issues/209\n\tif len(pairs) > 1 {\n\t\tprefix := pairs[:len(pairs)-1]\n\t\tlastPair := pairs[len(pairs)-1]\n\t\tprefix = append(prefix, lipgloss.Place(\n\t\t\tlipgloss.Width(lastPair), // width\n\t\t\tlipgloss.Height(prefix[0]), // height\n\t\t\tlipgloss.Left, // x\n\t\t\tlipgloss.Top, // y\n\t\t\tlastPair, // content\n\t\t\tlipgloss.WithWhitespaceBackground(t.Background()),\n\t\t))\n\t\tcontent := baseStyle.Width(h.width).Render(\n\t\t\tlipgloss.JoinHorizontal(\n\t\t\t\tlipgloss.Top,\n\t\t\t\tprefix...,\n\t\t\t),\n\t\t)\n\t\treturn content\n\t}\n\n\t// Join pairs of columns and enclose in a border\n\tcontent := baseStyle.Width(h.width).Render(\n\t\tlipgloss.JoinHorizontal(\n\t\t\tlipgloss.Top,\n\t\t\tpairs...,\n\t\t),\n\t)\n\treturn content\n}\n\nfunc (h *helpCmp) View() string {\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\n\tcontent := h.render()\n\theader := baseStyle.\n\t\tBold(true).\n\t\tWidth(lipgloss.Width(content)).\n\t\tForeground(t.Primary()).\n\t\tRender(\"Keyboard Shortcuts\")\n\n\treturn baseStyle.Padding(1).\n\t\tBorder(lipgloss.RoundedBorder()).\n\t\tBorderForeground(t.TextMuted()).\n\t\tWidth(h.width).\n\t\tBorderBackground(t.Background()).\n\t\tRender(\n\t\t\tlipgloss.JoinVertical(lipgloss.Center,\n\t\t\t\theader,\n\t\t\t\tbaseStyle.Render(strings.Repeat(\" \", lipgloss.Width(header))),\n\t\t\t\tcontent,\n\t\t\t),\n\t\t)\n}\n\ntype HelpCmp interface {\n\ttea.Model\n\tSetBindings([]key.Binding)\n}\n\nfunc NewHelpCmp() HelpCmp {\n\treturn &helpCmp{}\n}\n"], ["/opencode/internal/message/content.go", "package message\n\nimport (\n\t\"encoding/base64\"\n\t\"slices\"\n\t\"time\"\n\n\t\"github.com/opencode-ai/opencode/internal/llm/models\"\n)\n\ntype MessageRole string\n\nconst (\n\tAssistant MessageRole = \"assistant\"\n\tUser MessageRole = \"user\"\n\tSystem MessageRole = \"system\"\n\tTool MessageRole = \"tool\"\n)\n\ntype FinishReason string\n\nconst (\n\tFinishReasonEndTurn FinishReason = \"end_turn\"\n\tFinishReasonMaxTokens FinishReason = \"max_tokens\"\n\tFinishReasonToolUse FinishReason = \"tool_use\"\n\tFinishReasonCanceled FinishReason = \"canceled\"\n\tFinishReasonError FinishReason = \"error\"\n\tFinishReasonPermissionDenied FinishReason = \"permission_denied\"\n\n\t// Should never happen\n\tFinishReasonUnknown FinishReason = \"unknown\"\n)\n\ntype ContentPart interface {\n\tisPart()\n}\n\ntype ReasoningContent struct {\n\tThinking string `json:\"thinking\"`\n}\n\nfunc (tc ReasoningContent) String() string {\n\treturn tc.Thinking\n}\nfunc (ReasoningContent) isPart() {}\n\ntype TextContent struct {\n\tText string `json:\"text\"`\n}\n\nfunc (tc TextContent) String() string {\n\treturn tc.Text\n}\n\nfunc (TextContent) isPart() {}\n\ntype ImageURLContent struct {\n\tURL string `json:\"url\"`\n\tDetail string `json:\"detail,omitempty\"`\n}\n\nfunc (iuc ImageURLContent) String() string {\n\treturn iuc.URL\n}\n\nfunc (ImageURLContent) isPart() {}\n\ntype BinaryContent struct {\n\tPath string\n\tMIMEType string\n\tData []byte\n}\n\nfunc (bc BinaryContent) String(provider models.ModelProvider) string {\n\tbase64Encoded := base64.StdEncoding.EncodeToString(bc.Data)\n\tif provider == models.ProviderOpenAI {\n\t\treturn \"data:\" + bc.MIMEType + \";base64,\" + base64Encoded\n\t}\n\treturn base64Encoded\n}\n\nfunc (BinaryContent) isPart() {}\n\ntype ToolCall struct {\n\tID string `json:\"id\"`\n\tName string `json:\"name\"`\n\tInput string `json:\"input\"`\n\tType string `json:\"type\"`\n\tFinished bool `json:\"finished\"`\n}\n\nfunc (ToolCall) isPart() {}\n\ntype ToolResult struct {\n\tToolCallID string `json:\"tool_call_id\"`\n\tName string `json:\"name\"`\n\tContent string `json:\"content\"`\n\tMetadata string `json:\"metadata\"`\n\tIsError bool `json:\"is_error\"`\n}\n\nfunc (ToolResult) isPart() {}\n\ntype Finish struct {\n\tReason FinishReason `json:\"reason\"`\n\tTime int64 `json:\"time\"`\n}\n\nfunc (Finish) isPart() {}\n\ntype Message struct {\n\tID string\n\tRole MessageRole\n\tSessionID string\n\tParts []ContentPart\n\tModel models.ModelID\n\tCreatedAt int64\n\tUpdatedAt int64\n}\n\nfunc (m *Message) Content() TextContent {\n\tfor _, part := range m.Parts {\n\t\tif c, ok := part.(TextContent); ok {\n\t\t\treturn c\n\t\t}\n\t}\n\treturn TextContent{}\n}\n\nfunc (m *Message) ReasoningContent() ReasoningContent {\n\tfor _, part := range m.Parts {\n\t\tif c, ok := part.(ReasoningContent); ok {\n\t\t\treturn c\n\t\t}\n\t}\n\treturn ReasoningContent{}\n}\n\nfunc (m *Message) ImageURLContent() []ImageURLContent {\n\timageURLContents := make([]ImageURLContent, 0)\n\tfor _, part := range m.Parts {\n\t\tif c, ok := part.(ImageURLContent); ok {\n\t\t\timageURLContents = append(imageURLContents, c)\n\t\t}\n\t}\n\treturn imageURLContents\n}\n\nfunc (m *Message) BinaryContent() []BinaryContent {\n\tbinaryContents := make([]BinaryContent, 0)\n\tfor _, part := range m.Parts {\n\t\tif c, ok := part.(BinaryContent); ok {\n\t\t\tbinaryContents = append(binaryContents, c)\n\t\t}\n\t}\n\treturn binaryContents\n}\n\nfunc (m *Message) ToolCalls() []ToolCall {\n\ttoolCalls := make([]ToolCall, 0)\n\tfor _, part := range m.Parts {\n\t\tif c, ok := part.(ToolCall); ok {\n\t\t\ttoolCalls = append(toolCalls, c)\n\t\t}\n\t}\n\treturn toolCalls\n}\n\nfunc (m *Message) ToolResults() []ToolResult {\n\ttoolResults := make([]ToolResult, 0)\n\tfor _, part := range m.Parts {\n\t\tif c, ok := part.(ToolResult); ok {\n\t\t\ttoolResults = append(toolResults, c)\n\t\t}\n\t}\n\treturn toolResults\n}\n\nfunc (m *Message) IsFinished() bool {\n\tfor _, part := range m.Parts {\n\t\tif _, ok := part.(Finish); ok {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc (m *Message) FinishPart() *Finish {\n\tfor _, part := range m.Parts {\n\t\tif c, ok := part.(Finish); ok {\n\t\t\treturn &c\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (m *Message) FinishReason() FinishReason {\n\tfor _, part := range m.Parts {\n\t\tif c, ok := part.(Finish); ok {\n\t\t\treturn c.Reason\n\t\t}\n\t}\n\treturn \"\"\n}\n\nfunc (m *Message) IsThinking() bool {\n\tif m.ReasoningContent().Thinking != \"\" && m.Content().Text == \"\" && !m.IsFinished() {\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc (m *Message) AppendContent(delta string) {\n\tfound := false\n\tfor i, part := range m.Parts {\n\t\tif c, ok := part.(TextContent); ok {\n\t\t\tm.Parts[i] = TextContent{Text: c.Text + delta}\n\t\t\tfound = true\n\t\t}\n\t}\n\tif !found {\n\t\tm.Parts = append(m.Parts, TextContent{Text: delta})\n\t}\n}\n\nfunc (m *Message) AppendReasoningContent(delta string) {\n\tfound := false\n\tfor i, part := range m.Parts {\n\t\tif c, ok := part.(ReasoningContent); ok {\n\t\t\tm.Parts[i] = ReasoningContent{Thinking: c.Thinking + delta}\n\t\t\tfound = true\n\t\t}\n\t}\n\tif !found {\n\t\tm.Parts = append(m.Parts, ReasoningContent{Thinking: delta})\n\t}\n}\n\nfunc (m *Message) FinishToolCall(toolCallID string) {\n\tfor i, part := range m.Parts {\n\t\tif c, ok := part.(ToolCall); ok {\n\t\t\tif c.ID == toolCallID {\n\t\t\t\tm.Parts[i] = ToolCall{\n\t\t\t\t\tID: c.ID,\n\t\t\t\t\tName: c.Name,\n\t\t\t\t\tInput: c.Input,\n\t\t\t\t\tType: c.Type,\n\t\t\t\t\tFinished: true,\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc (m *Message) AppendToolCallInput(toolCallID string, inputDelta string) {\n\tfor i, part := range m.Parts {\n\t\tif c, ok := part.(ToolCall); ok {\n\t\t\tif c.ID == toolCallID {\n\t\t\t\tm.Parts[i] = ToolCall{\n\t\t\t\t\tID: c.ID,\n\t\t\t\t\tName: c.Name,\n\t\t\t\t\tInput: c.Input + inputDelta,\n\t\t\t\t\tType: c.Type,\n\t\t\t\t\tFinished: c.Finished,\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc (m *Message) AddToolCall(tc ToolCall) {\n\tfor i, part := range m.Parts {\n\t\tif c, ok := part.(ToolCall); ok {\n\t\t\tif c.ID == tc.ID {\n\t\t\t\tm.Parts[i] = tc\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\tm.Parts = append(m.Parts, tc)\n}\n\nfunc (m *Message) SetToolCalls(tc []ToolCall) {\n\t// remove any existing tool call part it could have multiple\n\tparts := make([]ContentPart, 0)\n\tfor _, part := range m.Parts {\n\t\tif _, ok := part.(ToolCall); ok {\n\t\t\tcontinue\n\t\t}\n\t\tparts = append(parts, part)\n\t}\n\tm.Parts = parts\n\tfor _, toolCall := range tc {\n\t\tm.Parts = append(m.Parts, toolCall)\n\t}\n}\n\nfunc (m *Message) AddToolResult(tr ToolResult) {\n\tm.Parts = append(m.Parts, tr)\n}\n\nfunc (m *Message) SetToolResults(tr []ToolResult) {\n\tfor _, toolResult := range tr {\n\t\tm.Parts = append(m.Parts, toolResult)\n\t}\n}\n\nfunc (m *Message) AddFinish(reason FinishReason) {\n\t// remove any existing finish part\n\tfor i, part := range m.Parts {\n\t\tif _, ok := part.(Finish); ok {\n\t\t\tm.Parts = slices.Delete(m.Parts, i, i+1)\n\t\t\tbreak\n\t\t}\n\t}\n\tm.Parts = append(m.Parts, Finish{Reason: reason, Time: time.Now().Unix()})\n}\n\nfunc (m *Message) AddImageURL(url, detail string) {\n\tm.Parts = append(m.Parts, ImageURLContent{URL: url, Detail: detail})\n}\n\nfunc (m *Message) AddBinary(mimeType string, data []byte) {\n\tm.Parts = append(m.Parts, BinaryContent{MIMEType: mimeType, Data: data})\n}\n"], ["/opencode/internal/lsp/protocol/tsprotocol.go", "// Copyright 2023 The Go Authors. All rights reserved.\n// Use of this source code is governed by a BSD-style\n// license that can be found in the LICENSE file.\n\n// Code generated for LSP. DO NOT EDIT.\n\npackage protocol\n\n// Code generated from protocol/metaModel.json at ref release/protocol/3.17.6-next.9 (hash c94395b5da53729e6dff931293b051009ccaaaa4).\n// https://github.com/microsoft/vscode-languageserver-node/blob/release/protocol/3.17.6-next.9/protocol/metaModel.json\n// LSP metaData.version = 3.17.0.\n\nimport \"encoding/json\"\n\n// created for And\ntype And_RegOpt_textDocument_colorPresentation struct {\n\tWorkDoneProgressOptions\n\tTextDocumentRegistrationOptions\n}\n\n// A special text edit with an additional change annotation.\n//\n// @since 3.16.0.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#annotatedTextEdit\ntype AnnotatedTextEdit struct {\n\t// The actual identifier of the change annotation\n\tAnnotationID *ChangeAnnotationIdentifier `json:\"annotationId,omitempty\"`\n\tTextEdit\n}\n\n// The parameters passed via an apply workspace edit request.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#applyWorkspaceEditParams\ntype ApplyWorkspaceEditParams struct {\n\t// An optional label of the workspace edit. This label is\n\t// presented in the user interface for example on an undo\n\t// stack to undo the workspace edit.\n\tLabel string `json:\"label,omitempty\"`\n\t// The edits to apply.\n\tEdit WorkspaceEdit `json:\"edit\"`\n\t// Additional data about the edit.\n\t//\n\t// @since 3.18.0\n\t// @proposed\n\tMetadata *WorkspaceEditMetadata `json:\"metadata,omitempty\"`\n}\n\n// The result returned from the apply workspace edit request.\n//\n// @since 3.17 renamed from ApplyWorkspaceEditResponse\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#applyWorkspaceEditResult\ntype ApplyWorkspaceEditResult struct {\n\t// Indicates whether the edit was applied or not.\n\tApplied bool `json:\"applied\"`\n\t// An optional textual description for why the edit was not applied.\n\t// This may be used by the server for diagnostic logging or to provide\n\t// a suitable error for a request that triggered the edit.\n\tFailureReason string `json:\"failureReason,omitempty\"`\n\t// Depending on the client's failure handling strategy `failedChange` might\n\t// contain the index of the change that failed. This property is only available\n\t// if the client signals a `failureHandlingStrategy` in its client capabilities.\n\tFailedChange uint32 `json:\"failedChange,omitempty\"`\n}\n\n// A base for all symbol information.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#baseSymbolInformation\ntype BaseSymbolInformation struct {\n\t// The name of this symbol.\n\tName string `json:\"name\"`\n\t// The kind of this symbol.\n\tKind SymbolKind `json:\"kind\"`\n\t// Tags for this symbol.\n\t//\n\t// @since 3.16.0\n\tTags []SymbolTag `json:\"tags,omitempty\"`\n\t// The name of the symbol containing this symbol. This information is for\n\t// user interface purposes (e.g. to render a qualifier in the user interface\n\t// if necessary). It can't be used to re-infer a hierarchy for the document\n\t// symbols.\n\tContainerName string `json:\"containerName,omitempty\"`\n}\n\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#callHierarchyClientCapabilities\ntype CallHierarchyClientCapabilities struct {\n\t// Whether implementation supports dynamic registration. If this is set to `true`\n\t// the client supports the new `(TextDocumentRegistrationOptions & StaticRegistrationOptions)`\n\t// return value for the corresponding server capability as well.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n}\n\n// Represents an incoming call, e.g. a caller of a method or constructor.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#callHierarchyIncomingCall\ntype CallHierarchyIncomingCall struct {\n\t// The item that makes the call.\n\tFrom CallHierarchyItem `json:\"from\"`\n\t// The ranges at which the calls appear. This is relative to the caller\n\t// denoted by {@link CallHierarchyIncomingCall.from `this.from`}.\n\tFromRanges []Range `json:\"fromRanges\"`\n}\n\n// The parameter of a `callHierarchy/incomingCalls` request.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#callHierarchyIncomingCallsParams\ntype CallHierarchyIncomingCallsParams struct {\n\tItem CallHierarchyItem `json:\"item\"`\n\tWorkDoneProgressParams\n\tPartialResultParams\n}\n\n// Represents programming constructs like functions or constructors in the context\n// of call hierarchy.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#callHierarchyItem\ntype CallHierarchyItem struct {\n\t// The name of this item.\n\tName string `json:\"name\"`\n\t// The kind of this item.\n\tKind SymbolKind `json:\"kind\"`\n\t// Tags for this item.\n\tTags []SymbolTag `json:\"tags,omitempty\"`\n\t// More detail for this item, e.g. the signature of a function.\n\tDetail string `json:\"detail,omitempty\"`\n\t// The resource identifier of this item.\n\tURI DocumentUri `json:\"uri\"`\n\t// The range enclosing this symbol not including leading/trailing whitespace but everything else, e.g. comments and code.\n\tRange Range `json:\"range\"`\n\t// The range that should be selected and revealed when this symbol is being picked, e.g. the name of a function.\n\t// Must be contained by the {@link CallHierarchyItem.range `range`}.\n\tSelectionRange Range `json:\"selectionRange\"`\n\t// A data entry field that is preserved between a call hierarchy prepare and\n\t// incoming calls or outgoing calls requests.\n\tData interface{} `json:\"data,omitempty\"`\n}\n\n// Call hierarchy options used during static registration.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#callHierarchyOptions\ntype CallHierarchyOptions struct {\n\tWorkDoneProgressOptions\n}\n\n// Represents an outgoing call, e.g. calling a getter from a method or a method from a constructor etc.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#callHierarchyOutgoingCall\ntype CallHierarchyOutgoingCall struct {\n\t// The item that is called.\n\tTo CallHierarchyItem `json:\"to\"`\n\t// The range at which this item is called. This is the range relative to the caller, e.g the item\n\t// passed to {@link CallHierarchyItemProvider.provideCallHierarchyOutgoingCalls `provideCallHierarchyOutgoingCalls`}\n\t// and not {@link CallHierarchyOutgoingCall.to `this.to`}.\n\tFromRanges []Range `json:\"fromRanges\"`\n}\n\n// The parameter of a `callHierarchy/outgoingCalls` request.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#callHierarchyOutgoingCallsParams\ntype CallHierarchyOutgoingCallsParams struct {\n\tItem CallHierarchyItem `json:\"item\"`\n\tWorkDoneProgressParams\n\tPartialResultParams\n}\n\n// The parameter of a `textDocument/prepareCallHierarchy` request.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#callHierarchyPrepareParams\ntype CallHierarchyPrepareParams struct {\n\tTextDocumentPositionParams\n\tWorkDoneProgressParams\n}\n\n// Call hierarchy options used during static or dynamic registration.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#callHierarchyRegistrationOptions\ntype CallHierarchyRegistrationOptions struct {\n\tTextDocumentRegistrationOptions\n\tCallHierarchyOptions\n\tStaticRegistrationOptions\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#cancelParams\ntype CancelParams struct {\n\t// The request id to cancel.\n\tID interface{} `json:\"id\"`\n}\n\n// Additional information that describes document changes.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#changeAnnotation\ntype ChangeAnnotation struct {\n\t// A human-readable string describing the actual change. The string\n\t// is rendered prominent in the user interface.\n\tLabel string `json:\"label\"`\n\t// A flag which indicates that user confirmation is needed\n\t// before applying the change.\n\tNeedsConfirmation bool `json:\"needsConfirmation,omitempty\"`\n\t// A human-readable string which is rendered less prominent in\n\t// the user interface.\n\tDescription string `json:\"description,omitempty\"`\n}\n\n// An identifier to refer to a change annotation stored with a workspace edit.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#changeAnnotationIdentifier\ntype ChangeAnnotationIdentifier = string // (alias)\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#changeAnnotationsSupportOptions\ntype ChangeAnnotationsSupportOptions struct {\n\t// Whether the client groups edits with equal labels into tree nodes,\n\t// for instance all edits labelled with \"Changes in Strings\" would\n\t// be a tree node.\n\tGroupsOnLabel bool `json:\"groupsOnLabel,omitempty\"`\n}\n\n// Defines the capabilities provided by the client.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#clientCapabilities\ntype ClientCapabilities struct {\n\t// Workspace specific client capabilities.\n\tWorkspace WorkspaceClientCapabilities `json:\"workspace,omitempty\"`\n\t// Text document specific client capabilities.\n\tTextDocument TextDocumentClientCapabilities `json:\"textDocument,omitempty\"`\n\t// Capabilities specific to the notebook document support.\n\t//\n\t// @since 3.17.0\n\tNotebookDocument *NotebookDocumentClientCapabilities `json:\"notebookDocument,omitempty\"`\n\t// Window specific client capabilities.\n\tWindow WindowClientCapabilities `json:\"window,omitempty\"`\n\t// General client capabilities.\n\t//\n\t// @since 3.16.0\n\tGeneral *GeneralClientCapabilities `json:\"general,omitempty\"`\n\t// Experimental client capabilities.\n\tExperimental interface{} `json:\"experimental,omitempty\"`\n}\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#clientCodeActionKindOptions\ntype ClientCodeActionKindOptions struct {\n\t// The code action kind values the client supports. When this\n\t// property exists the client also guarantees that it will\n\t// handle values outside its set gracefully and falls back\n\t// to a default value when unknown.\n\tValueSet []CodeActionKind `json:\"valueSet\"`\n}\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#clientCodeActionLiteralOptions\ntype ClientCodeActionLiteralOptions struct {\n\t// The code action kind is support with the following value\n\t// set.\n\tCodeActionKind ClientCodeActionKindOptions `json:\"codeActionKind\"`\n}\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#clientCodeActionResolveOptions\ntype ClientCodeActionResolveOptions struct {\n\t// The properties that a client can resolve lazily.\n\tProperties []string `json:\"properties\"`\n}\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#clientCodeLensResolveOptions\ntype ClientCodeLensResolveOptions struct {\n\t// The properties that a client can resolve lazily.\n\tProperties []string `json:\"properties\"`\n}\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#clientCompletionItemInsertTextModeOptions\ntype ClientCompletionItemInsertTextModeOptions struct {\n\tValueSet []InsertTextMode `json:\"valueSet\"`\n}\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#clientCompletionItemOptions\ntype ClientCompletionItemOptions struct {\n\t// Client supports snippets as insert text.\n\t//\n\t// A snippet can define tab stops and placeholders with `$1`, `$2`\n\t// and `${3:foo}`. `$0` defines the final tab stop, it defaults to\n\t// the end of the snippet. Placeholders with equal identifiers are linked,\n\t// that is typing in one will update others too.\n\tSnippetSupport bool `json:\"snippetSupport,omitempty\"`\n\t// Client supports commit characters on a completion item.\n\tCommitCharactersSupport bool `json:\"commitCharactersSupport,omitempty\"`\n\t// Client supports the following content formats for the documentation\n\t// property. The order describes the preferred format of the client.\n\tDocumentationFormat []MarkupKind `json:\"documentationFormat,omitempty\"`\n\t// Client supports the deprecated property on a completion item.\n\tDeprecatedSupport bool `json:\"deprecatedSupport,omitempty\"`\n\t// Client supports the preselect property on a completion item.\n\tPreselectSupport bool `json:\"preselectSupport,omitempty\"`\n\t// Client supports the tag property on a completion item. Clients supporting\n\t// tags have to handle unknown tags gracefully. Clients especially need to\n\t// preserve unknown tags when sending a completion item back to the server in\n\t// a resolve call.\n\t//\n\t// @since 3.15.0\n\tTagSupport *CompletionItemTagOptions `json:\"tagSupport,omitempty\"`\n\t// Client support insert replace edit to control different behavior if a\n\t// completion item is inserted in the text or should replace text.\n\t//\n\t// @since 3.16.0\n\tInsertReplaceSupport bool `json:\"insertReplaceSupport,omitempty\"`\n\t// Indicates which properties a client can resolve lazily on a completion\n\t// item. Before version 3.16.0 only the predefined properties `documentation`\n\t// and `details` could be resolved lazily.\n\t//\n\t// @since 3.16.0\n\tResolveSupport *ClientCompletionItemResolveOptions `json:\"resolveSupport,omitempty\"`\n\t// The client supports the `insertTextMode` property on\n\t// a completion item to override the whitespace handling mode\n\t// as defined by the client (see `insertTextMode`).\n\t//\n\t// @since 3.16.0\n\tInsertTextModeSupport *ClientCompletionItemInsertTextModeOptions `json:\"insertTextModeSupport,omitempty\"`\n\t// The client has support for completion item label\n\t// details (see also `CompletionItemLabelDetails`).\n\t//\n\t// @since 3.17.0\n\tLabelDetailsSupport bool `json:\"labelDetailsSupport,omitempty\"`\n}\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#clientCompletionItemOptionsKind\ntype ClientCompletionItemOptionsKind struct {\n\t// The completion item kind values the client supports. When this\n\t// property exists the client also guarantees that it will\n\t// handle values outside its set gracefully and falls back\n\t// to a default value when unknown.\n\t//\n\t// If this property is not present the client only supports\n\t// the completion items kinds from `Text` to `Reference` as defined in\n\t// the initial version of the protocol.\n\tValueSet []CompletionItemKind `json:\"valueSet,omitempty\"`\n}\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#clientCompletionItemResolveOptions\ntype ClientCompletionItemResolveOptions struct {\n\t// The properties that a client can resolve lazily.\n\tProperties []string `json:\"properties\"`\n}\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#clientDiagnosticsTagOptions\ntype ClientDiagnosticsTagOptions struct {\n\t// The tags supported by the client.\n\tValueSet []DiagnosticTag `json:\"valueSet\"`\n}\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#clientFoldingRangeKindOptions\ntype ClientFoldingRangeKindOptions struct {\n\t// The folding range kind values the client supports. When this\n\t// property exists the client also guarantees that it will\n\t// handle values outside its set gracefully and falls back\n\t// to a default value when unknown.\n\tValueSet []FoldingRangeKind `json:\"valueSet,omitempty\"`\n}\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#clientFoldingRangeOptions\ntype ClientFoldingRangeOptions struct {\n\t// If set, the client signals that it supports setting collapsedText on\n\t// folding ranges to display custom labels instead of the default text.\n\t//\n\t// @since 3.17.0\n\tCollapsedText bool `json:\"collapsedText,omitempty\"`\n}\n\n// Information about the client\n//\n// @since 3.15.0\n// @since 3.18.0 ClientInfo type name added.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#clientInfo\ntype ClientInfo struct {\n\t// The name of the client as defined by the client.\n\tName string `json:\"name\"`\n\t// The client's version as defined by the client.\n\tVersion string `json:\"version,omitempty\"`\n}\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#clientInlayHintResolveOptions\ntype ClientInlayHintResolveOptions struct {\n\t// The properties that a client can resolve lazily.\n\tProperties []string `json:\"properties\"`\n}\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#clientSemanticTokensRequestFullDelta\ntype ClientSemanticTokensRequestFullDelta struct {\n\t// The client will send the `textDocument/semanticTokens/full/delta` request if\n\t// the server provides a corresponding handler.\n\tDelta bool `json:\"delta,omitempty\"`\n}\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#clientSemanticTokensRequestOptions\ntype ClientSemanticTokensRequestOptions struct {\n\t// The client will send the `textDocument/semanticTokens/range` request if\n\t// the server provides a corresponding handler.\n\tRange *Or_ClientSemanticTokensRequestOptions_range `json:\"range,omitempty\"`\n\t// The client will send the `textDocument/semanticTokens/full` request if\n\t// the server provides a corresponding handler.\n\tFull *Or_ClientSemanticTokensRequestOptions_full `json:\"full,omitempty\"`\n}\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#clientShowMessageActionItemOptions\ntype ClientShowMessageActionItemOptions struct {\n\t// Whether the client supports additional attributes which\n\t// are preserved and send back to the server in the\n\t// request's response.\n\tAdditionalPropertiesSupport bool `json:\"additionalPropertiesSupport,omitempty\"`\n}\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#clientSignatureInformationOptions\ntype ClientSignatureInformationOptions struct {\n\t// Client supports the following content formats for the documentation\n\t// property. The order describes the preferred format of the client.\n\tDocumentationFormat []MarkupKind `json:\"documentationFormat,omitempty\"`\n\t// Client capabilities specific to parameter information.\n\tParameterInformation *ClientSignatureParameterInformationOptions `json:\"parameterInformation,omitempty\"`\n\t// The client supports the `activeParameter` property on `SignatureInformation`\n\t// literal.\n\t//\n\t// @since 3.16.0\n\tActiveParameterSupport bool `json:\"activeParameterSupport,omitempty\"`\n\t// The client supports the `activeParameter` property on\n\t// `SignatureHelp`/`SignatureInformation` being set to `null` to\n\t// indicate that no parameter should be active.\n\t//\n\t// @since 3.18.0\n\t// @proposed\n\tNoActiveParameterSupport bool `json:\"noActiveParameterSupport,omitempty\"`\n}\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#clientSignatureParameterInformationOptions\ntype ClientSignatureParameterInformationOptions struct {\n\t// The client supports processing label offsets instead of a\n\t// simple label string.\n\t//\n\t// @since 3.14.0\n\tLabelOffsetSupport bool `json:\"labelOffsetSupport,omitempty\"`\n}\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#clientSymbolKindOptions\ntype ClientSymbolKindOptions struct {\n\t// The symbol kind values the client supports. When this\n\t// property exists the client also guarantees that it will\n\t// handle values outside its set gracefully and falls back\n\t// to a default value when unknown.\n\t//\n\t// If this property is not present the client only supports\n\t// the symbol kinds from `File` to `Array` as defined in\n\t// the initial version of the protocol.\n\tValueSet []SymbolKind `json:\"valueSet,omitempty\"`\n}\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#clientSymbolResolveOptions\ntype ClientSymbolResolveOptions struct {\n\t// The properties that a client can resolve lazily. Usually\n\t// `location.range`\n\tProperties []string `json:\"properties\"`\n}\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#clientSymbolTagOptions\ntype ClientSymbolTagOptions struct {\n\t// The tags supported by the client.\n\tValueSet []SymbolTag `json:\"valueSet\"`\n}\n\n// A code action represents a change that can be performed in code, e.g. to fix a problem or\n// to refactor code.\n//\n// A CodeAction must set either `edit` and/or a `command`. If both are supplied, the `edit` is applied first, then the `command` is executed.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#codeAction\ntype CodeAction struct {\n\t// A short, human-readable, title for this code action.\n\tTitle string `json:\"title\"`\n\t// The kind of the code action.\n\t//\n\t// Used to filter code actions.\n\tKind CodeActionKind `json:\"kind,omitempty\"`\n\t// The diagnostics that this code action resolves.\n\tDiagnostics []Diagnostic `json:\"diagnostics,omitempty\"`\n\t// Marks this as a preferred action. Preferred actions are used by the `auto fix` command and can be targeted\n\t// by keybindings.\n\t//\n\t// A quick fix should be marked preferred if it properly addresses the underlying error.\n\t// A refactoring should be marked preferred if it is the most reasonable choice of actions to take.\n\t//\n\t// @since 3.15.0\n\tIsPreferred bool `json:\"isPreferred,omitempty\"`\n\t// Marks that the code action cannot currently be applied.\n\t//\n\t// Clients should follow the following guidelines regarding disabled code actions:\n\t//\n\t// - Disabled code actions are not shown in automatic [lightbulbs](https://code.visualstudio.com/docs/editor/editingevolved#_code-action)\n\t// code action menus.\n\t//\n\t// - Disabled actions are shown as faded out in the code action menu when the user requests a more specific type\n\t// of code action, such as refactorings.\n\t//\n\t// - If the user has a [keybinding](https://code.visualstudio.com/docs/editor/refactoring#_keybindings-for-code-actions)\n\t// that auto applies a code action and only disabled code actions are returned, the client should show the user an\n\t// error message with `reason` in the editor.\n\t//\n\t// @since 3.16.0\n\tDisabled *CodeActionDisabled `json:\"disabled,omitempty\"`\n\t// The workspace edit this code action performs.\n\tEdit *WorkspaceEdit `json:\"edit,omitempty\"`\n\t// A command this code action executes. If a code action\n\t// provides an edit and a command, first the edit is\n\t// executed and then the command.\n\tCommand *Command `json:\"command,omitempty\"`\n\t// A data entry field that is preserved on a code action between\n\t// a `textDocument/codeAction` and a `codeAction/resolve` request.\n\t//\n\t// @since 3.16.0\n\tData *json.RawMessage `json:\"data,omitempty\"`\n}\n\n// The Client Capabilities of a {@link CodeActionRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#codeActionClientCapabilities\ntype CodeActionClientCapabilities struct {\n\t// Whether code action supports dynamic registration.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n\t// The client support code action literals of type `CodeAction` as a valid\n\t// response of the `textDocument/codeAction` request. If the property is not\n\t// set the request can only return `Command` literals.\n\t//\n\t// @since 3.8.0\n\tCodeActionLiteralSupport ClientCodeActionLiteralOptions `json:\"codeActionLiteralSupport,omitempty\"`\n\t// Whether code action supports the `isPreferred` property.\n\t//\n\t// @since 3.15.0\n\tIsPreferredSupport bool `json:\"isPreferredSupport,omitempty\"`\n\t// Whether code action supports the `disabled` property.\n\t//\n\t// @since 3.16.0\n\tDisabledSupport bool `json:\"disabledSupport,omitempty\"`\n\t// Whether code action supports the `data` property which is\n\t// preserved between a `textDocument/codeAction` and a\n\t// `codeAction/resolve` request.\n\t//\n\t// @since 3.16.0\n\tDataSupport bool `json:\"dataSupport,omitempty\"`\n\t// Whether the client supports resolving additional code action\n\t// properties via a separate `codeAction/resolve` request.\n\t//\n\t// @since 3.16.0\n\tResolveSupport *ClientCodeActionResolveOptions `json:\"resolveSupport,omitempty\"`\n\t// Whether the client honors the change annotations in\n\t// text edits and resource operations returned via the\n\t// `CodeAction#edit` property by for example presenting\n\t// the workspace edit in the user interface and asking\n\t// for confirmation.\n\t//\n\t// @since 3.16.0\n\tHonorsChangeAnnotations bool `json:\"honorsChangeAnnotations,omitempty\"`\n\t// Whether the client supports documentation for a class of\n\t// code actions.\n\t//\n\t// @since 3.18.0\n\t// @proposed\n\tDocumentationSupport bool `json:\"documentationSupport,omitempty\"`\n}\n\n// Contains additional diagnostic information about the context in which\n// a {@link CodeActionProvider.provideCodeActions code action} is run.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#codeActionContext\ntype CodeActionContext struct {\n\t// An array of diagnostics known on the client side overlapping the range provided to the\n\t// `textDocument/codeAction` request. They are provided so that the server knows which\n\t// errors are currently presented to the user for the given range. There is no guarantee\n\t// that these accurately reflect the error state of the resource. The primary parameter\n\t// to compute code actions is the provided range.\n\tDiagnostics []Diagnostic `json:\"diagnostics\"`\n\t// Requested kind of actions to return.\n\t//\n\t// Actions not of this kind are filtered out by the client before being shown. So servers\n\t// can omit computing them.\n\tOnly []CodeActionKind `json:\"only,omitempty\"`\n\t// The reason why code actions were requested.\n\t//\n\t// @since 3.17.0\n\tTriggerKind *CodeActionTriggerKind `json:\"triggerKind,omitempty\"`\n}\n\n// Captures why the code action is currently disabled.\n//\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#codeActionDisabled\ntype CodeActionDisabled struct {\n\t// Human readable description of why the code action is currently disabled.\n\t//\n\t// This is displayed in the code actions UI.\n\tReason string `json:\"reason\"`\n}\n\n// A set of predefined code action kinds\ntype CodeActionKind string\n\n// Documentation for a class of code actions.\n//\n// @since 3.18.0\n// @proposed\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#codeActionKindDocumentation\ntype CodeActionKindDocumentation struct {\n\t// The kind of the code action being documented.\n\t//\n\t// If the kind is generic, such as `CodeActionKind.Refactor`, the documentation will be shown whenever any\n\t// refactorings are returned. If the kind if more specific, such as `CodeActionKind.RefactorExtract`, the\n\t// documentation will only be shown when extract refactoring code actions are returned.\n\tKind CodeActionKind `json:\"kind\"`\n\t// Command that is ued to display the documentation to the user.\n\t//\n\t// The title of this documentation code action is taken from {@linkcode Command.title}\n\tCommand Command `json:\"command\"`\n}\n\n// Provider options for a {@link CodeActionRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#codeActionOptions\ntype CodeActionOptions struct {\n\t// CodeActionKinds that this server may return.\n\t//\n\t// The list of kinds may be generic, such as `CodeActionKind.Refactor`, or the server\n\t// may list out every specific kind they provide.\n\tCodeActionKinds []CodeActionKind `json:\"codeActionKinds,omitempty\"`\n\t// Static documentation for a class of code actions.\n\t//\n\t// Documentation from the provider should be shown in the code actions menu if either:\n\t//\n\t//\n\t// - Code actions of `kind` are requested by the editor. In this case, the editor will show the documentation that\n\t// most closely matches the requested code action kind. For example, if a provider has documentation for\n\t// both `Refactor` and `RefactorExtract`, when the user requests code actions for `RefactorExtract`,\n\t// the editor will use the documentation for `RefactorExtract` instead of the documentation for `Refactor`.\n\t//\n\t//\n\t// - Any code actions of `kind` are returned by the provider.\n\t//\n\t// At most one documentation entry should be shown per provider.\n\t//\n\t// @since 3.18.0\n\t// @proposed\n\tDocumentation []CodeActionKindDocumentation `json:\"documentation,omitempty\"`\n\t// The server provides support to resolve additional\n\t// information for a code action.\n\t//\n\t// @since 3.16.0\n\tResolveProvider bool `json:\"resolveProvider,omitempty\"`\n\tWorkDoneProgressOptions\n}\n\n// The parameters of a {@link CodeActionRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#codeActionParams\ntype CodeActionParams struct {\n\t// The document in which the command was invoked.\n\tTextDocument TextDocumentIdentifier `json:\"textDocument\"`\n\t// The range for which the command was invoked.\n\tRange Range `json:\"range\"`\n\t// Context carrying additional information.\n\tContext CodeActionContext `json:\"context\"`\n\tWorkDoneProgressParams\n\tPartialResultParams\n}\n\n// Registration options for a {@link CodeActionRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#codeActionRegistrationOptions\ntype CodeActionRegistrationOptions struct {\n\tTextDocumentRegistrationOptions\n\tCodeActionOptions\n}\n\n// The reason why code actions were requested.\n//\n// @since 3.17.0\ntype CodeActionTriggerKind uint32\n\n// Structure to capture a description for an error code.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#codeDescription\ntype CodeDescription struct {\n\t// An URI to open with more information about the diagnostic error.\n\tHref URI `json:\"href\"`\n}\n\n// A code lens represents a {@link Command command} that should be shown along with\n// source text, like the number of references, a way to run tests, etc.\n//\n// A code lens is _unresolved_ when no command is associated to it. For performance\n// reasons the creation of a code lens and resolving should be done in two stages.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#codeLens\ntype CodeLens struct {\n\t// The range in which this code lens is valid. Should only span a single line.\n\tRange Range `json:\"range\"`\n\t// The command this code lens represents.\n\tCommand *Command `json:\"command,omitempty\"`\n\t// A data entry field that is preserved on a code lens item between\n\t// a {@link CodeLensRequest} and a {@link CodeLensResolveRequest}\n\tData interface{} `json:\"data,omitempty\"`\n}\n\n// The client capabilities of a {@link CodeLensRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#codeLensClientCapabilities\ntype CodeLensClientCapabilities struct {\n\t// Whether code lens supports dynamic registration.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n\t// Whether the client supports resolving additional code lens\n\t// properties via a separate `codeLens/resolve` request.\n\t//\n\t// @since 3.18.0\n\tResolveSupport *ClientCodeLensResolveOptions `json:\"resolveSupport,omitempty\"`\n}\n\n// Code Lens provider options of a {@link CodeLensRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#codeLensOptions\ntype CodeLensOptions struct {\n\t// Code lens has a resolve provider as well.\n\tResolveProvider bool `json:\"resolveProvider,omitempty\"`\n\tWorkDoneProgressOptions\n}\n\n// The parameters of a {@link CodeLensRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#codeLensParams\ntype CodeLensParams struct {\n\t// The document to request code lens for.\n\tTextDocument TextDocumentIdentifier `json:\"textDocument\"`\n\tWorkDoneProgressParams\n\tPartialResultParams\n}\n\n// Registration options for a {@link CodeLensRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#codeLensRegistrationOptions\ntype CodeLensRegistrationOptions struct {\n\tTextDocumentRegistrationOptions\n\tCodeLensOptions\n}\n\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#codeLensWorkspaceClientCapabilities\ntype CodeLensWorkspaceClientCapabilities struct {\n\t// Whether the client implementation supports a refresh request sent from the\n\t// server to the client.\n\t//\n\t// Note that this event is global and will force the client to refresh all\n\t// code lenses currently shown. It should be used with absolute care and is\n\t// useful for situation where a server for example detect a project wide\n\t// change that requires such a calculation.\n\tRefreshSupport bool `json:\"refreshSupport,omitempty\"`\n}\n\n// Represents a color in RGBA space.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#color\ntype Color struct {\n\t// The red component of this color in the range [0-1].\n\tRed float64 `json:\"red\"`\n\t// The green component of this color in the range [0-1].\n\tGreen float64 `json:\"green\"`\n\t// The blue component of this color in the range [0-1].\n\tBlue float64 `json:\"blue\"`\n\t// The alpha component of this color in the range [0-1].\n\tAlpha float64 `json:\"alpha\"`\n}\n\n// Represents a color range from a document.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#colorInformation\ntype ColorInformation struct {\n\t// The range in the document where this color appears.\n\tRange Range `json:\"range\"`\n\t// The actual color value for this color range.\n\tColor Color `json:\"color\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#colorPresentation\ntype ColorPresentation struct {\n\t// The label of this color presentation. It will be shown on the color\n\t// picker header. By default this is also the text that is inserted when selecting\n\t// this color presentation.\n\tLabel string `json:\"label\"`\n\t// An {@link TextEdit edit} which is applied to a document when selecting\n\t// this presentation for the color. When `falsy` the {@link ColorPresentation.label label}\n\t// is used.\n\tTextEdit *TextEdit `json:\"textEdit,omitempty\"`\n\t// An optional array of additional {@link TextEdit text edits} that are applied when\n\t// selecting this color presentation. Edits must not overlap with the main {@link ColorPresentation.textEdit edit} nor with themselves.\n\tAdditionalTextEdits []TextEdit `json:\"additionalTextEdits,omitempty\"`\n}\n\n// Parameters for a {@link ColorPresentationRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#colorPresentationParams\ntype ColorPresentationParams struct {\n\t// The text document.\n\tTextDocument TextDocumentIdentifier `json:\"textDocument\"`\n\t// The color to request presentations for.\n\tColor Color `json:\"color\"`\n\t// The range where the color would be inserted. Serves as a context.\n\tRange Range `json:\"range\"`\n\tWorkDoneProgressParams\n\tPartialResultParams\n}\n\n// Represents a reference to a command. Provides a title which\n// will be used to represent a command in the UI and, optionally,\n// an array of arguments which will be passed to the command handler\n// function when invoked.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#command\ntype Command struct {\n\t// Title of the command, like `save`.\n\tTitle string `json:\"title\"`\n\t// An optional tooltip.\n\t//\n\t// @since 3.18.0\n\t// @proposed\n\tTooltip string `json:\"tooltip,omitempty\"`\n\t// The identifier of the actual command handler.\n\tCommand string `json:\"command\"`\n\t// Arguments that the command handler should be\n\t// invoked with.\n\tArguments []json.RawMessage `json:\"arguments,omitempty\"`\n}\n\n// Completion client capabilities\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#completionClientCapabilities\ntype CompletionClientCapabilities struct {\n\t// Whether completion supports dynamic registration.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n\t// The client supports the following `CompletionItem` specific\n\t// capabilities.\n\tCompletionItem ClientCompletionItemOptions `json:\"completionItem,omitempty\"`\n\tCompletionItemKind *ClientCompletionItemOptionsKind `json:\"completionItemKind,omitempty\"`\n\t// Defines how the client handles whitespace and indentation\n\t// when accepting a completion item that uses multi line\n\t// text in either `insertText` or `textEdit`.\n\t//\n\t// @since 3.17.0\n\tInsertTextMode InsertTextMode `json:\"insertTextMode,omitempty\"`\n\t// The client supports to send additional context information for a\n\t// `textDocument/completion` request.\n\tContextSupport bool `json:\"contextSupport,omitempty\"`\n\t// The client supports the following `CompletionList` specific\n\t// capabilities.\n\t//\n\t// @since 3.17.0\n\tCompletionList *CompletionListCapabilities `json:\"completionList,omitempty\"`\n}\n\n// Contains additional information about the context in which a completion request is triggered.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#completionContext\ntype CompletionContext struct {\n\t// How the completion was triggered.\n\tTriggerKind CompletionTriggerKind `json:\"triggerKind\"`\n\t// The trigger character (a single character) that has trigger code complete.\n\t// Is undefined if `triggerKind !== CompletionTriggerKind.TriggerCharacter`\n\tTriggerCharacter string `json:\"triggerCharacter,omitempty\"`\n}\n\n// A completion item represents a text snippet that is\n// proposed to complete text that is being typed.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#completionItem\ntype CompletionItem struct {\n\t// The label of this completion item.\n\t//\n\t// The label property is also by default the text that\n\t// is inserted when selecting this completion.\n\t//\n\t// If label details are provided the label itself should\n\t// be an unqualified name of the completion item.\n\tLabel string `json:\"label\"`\n\t// Additional details for the label\n\t//\n\t// @since 3.17.0\n\tLabelDetails *CompletionItemLabelDetails `json:\"labelDetails,omitempty\"`\n\t// The kind of this completion item. Based of the kind\n\t// an icon is chosen by the editor.\n\tKind CompletionItemKind `json:\"kind,omitempty\"`\n\t// Tags for this completion item.\n\t//\n\t// @since 3.15.0\n\tTags []CompletionItemTag `json:\"tags,omitempty\"`\n\t// A human-readable string with additional information\n\t// about this item, like type or symbol information.\n\tDetail string `json:\"detail,omitempty\"`\n\t// A human-readable string that represents a doc-comment.\n\tDocumentation *Or_CompletionItem_documentation `json:\"documentation,omitempty\"`\n\t// Indicates if this item is deprecated.\n\t// @deprecated Use `tags` instead.\n\tDeprecated bool `json:\"deprecated,omitempty\"`\n\t// Select this item when showing.\n\t//\n\t// *Note* that only one completion item can be selected and that the\n\t// tool / client decides which item that is. The rule is that the *first*\n\t// item of those that match best is selected.\n\tPreselect bool `json:\"preselect,omitempty\"`\n\t// A string that should be used when comparing this item\n\t// with other items. When `falsy` the {@link CompletionItem.label label}\n\t// is used.\n\tSortText string `json:\"sortText,omitempty\"`\n\t// A string that should be used when filtering a set of\n\t// completion items. When `falsy` the {@link CompletionItem.label label}\n\t// is used.\n\tFilterText string `json:\"filterText,omitempty\"`\n\t// A string that should be inserted into a document when selecting\n\t// this completion. When `falsy` the {@link CompletionItem.label label}\n\t// is used.\n\t//\n\t// The `insertText` is subject to interpretation by the client side.\n\t// Some tools might not take the string literally. For example\n\t// VS Code when code complete is requested in this example\n\t// `con` and a completion item with an `insertText` of\n\t// `console` is provided it will only insert `sole`. Therefore it is\n\t// recommended to use `textEdit` instead since it avoids additional client\n\t// side interpretation.\n\tInsertText string `json:\"insertText,omitempty\"`\n\t// The format of the insert text. The format applies to both the\n\t// `insertText` property and the `newText` property of a provided\n\t// `textEdit`. If omitted defaults to `InsertTextFormat.PlainText`.\n\t//\n\t// Please note that the insertTextFormat doesn't apply to\n\t// `additionalTextEdits`.\n\tInsertTextFormat *InsertTextFormat `json:\"insertTextFormat,omitempty\"`\n\t// How whitespace and indentation is handled during completion\n\t// item insertion. If not provided the clients default value depends on\n\t// the `textDocument.completion.insertTextMode` client capability.\n\t//\n\t// @since 3.16.0\n\tInsertTextMode *InsertTextMode `json:\"insertTextMode,omitempty\"`\n\t// An {@link TextEdit edit} which is applied to a document when selecting\n\t// this completion. When an edit is provided the value of\n\t// {@link CompletionItem.insertText insertText} is ignored.\n\t//\n\t// Most editors support two different operations when accepting a completion\n\t// item. One is to insert a completion text and the other is to replace an\n\t// existing text with a completion text. Since this can usually not be\n\t// predetermined by a server it can report both ranges. Clients need to\n\t// signal support for `InsertReplaceEdits` via the\n\t// `textDocument.completion.insertReplaceSupport` client capability\n\t// property.\n\t//\n\t// *Note 1:* The text edit's range as well as both ranges from an insert\n\t// replace edit must be a [single line] and they must contain the position\n\t// at which completion has been requested.\n\t// *Note 2:* If an `InsertReplaceEdit` is returned the edit's insert range\n\t// must be a prefix of the edit's replace range, that means it must be\n\t// contained and starting at the same position.\n\t//\n\t// @since 3.16.0 additional type `InsertReplaceEdit`\n\tTextEdit *Or_CompletionItem_textEdit `json:\"textEdit,omitempty\"`\n\t// The edit text used if the completion item is part of a CompletionList and\n\t// CompletionList defines an item default for the text edit range.\n\t//\n\t// Clients will only honor this property if they opt into completion list\n\t// item defaults using the capability `completionList.itemDefaults`.\n\t//\n\t// If not provided and a list's default range is provided the label\n\t// property is used as a text.\n\t//\n\t// @since 3.17.0\n\tTextEditText string `json:\"textEditText,omitempty\"`\n\t// An optional array of additional {@link TextEdit text edits} that are applied when\n\t// selecting this completion. Edits must not overlap (including the same insert position)\n\t// with the main {@link CompletionItem.textEdit edit} nor with themselves.\n\t//\n\t// Additional text edits should be used to change text unrelated to the current cursor position\n\t// (for example adding an import statement at the top of the file if the completion item will\n\t// insert an unqualified type).\n\tAdditionalTextEdits []TextEdit `json:\"additionalTextEdits,omitempty\"`\n\t// An optional set of characters that when pressed while this completion is active will accept it first and\n\t// then type that character. *Note* that all commit characters should have `length=1` and that superfluous\n\t// characters will be ignored.\n\tCommitCharacters []string `json:\"commitCharacters,omitempty\"`\n\t// An optional {@link Command command} that is executed *after* inserting this completion. *Note* that\n\t// additional modifications to the current document should be described with the\n\t// {@link CompletionItem.additionalTextEdits additionalTextEdits}-property.\n\tCommand *Command `json:\"command,omitempty\"`\n\t// A data entry field that is preserved on a completion item between a\n\t// {@link CompletionRequest} and a {@link CompletionResolveRequest}.\n\tData interface{} `json:\"data,omitempty\"`\n}\n\n// In many cases the items of an actual completion result share the same\n// value for properties like `commitCharacters` or the range of a text\n// edit. A completion list can therefore define item defaults which will\n// be used if a completion item itself doesn't specify the value.\n//\n// If a completion list specifies a default value and a completion item\n// also specifies a corresponding value the one from the item is used.\n//\n// Servers are only allowed to return default values if the client\n// signals support for this via the `completionList.itemDefaults`\n// capability.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#completionItemDefaults\ntype CompletionItemDefaults struct {\n\t// A default commit character set.\n\t//\n\t// @since 3.17.0\n\tCommitCharacters []string `json:\"commitCharacters,omitempty\"`\n\t// A default edit range.\n\t//\n\t// @since 3.17.0\n\tEditRange *Or_CompletionItemDefaults_editRange `json:\"editRange,omitempty\"`\n\t// A default insert text format.\n\t//\n\t// @since 3.17.0\n\tInsertTextFormat *InsertTextFormat `json:\"insertTextFormat,omitempty\"`\n\t// A default insert text mode.\n\t//\n\t// @since 3.17.0\n\tInsertTextMode *InsertTextMode `json:\"insertTextMode,omitempty\"`\n\t// A default data value.\n\t//\n\t// @since 3.17.0\n\tData interface{} `json:\"data,omitempty\"`\n}\n\n// The kind of a completion entry.\ntype CompletionItemKind uint32\n\n// Additional details for a completion item label.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#completionItemLabelDetails\ntype CompletionItemLabelDetails struct {\n\t// An optional string which is rendered less prominently directly after {@link CompletionItem.label label},\n\t// without any spacing. Should be used for function signatures and type annotations.\n\tDetail string `json:\"detail,omitempty\"`\n\t// An optional string which is rendered less prominently after {@link CompletionItem.detail}. Should be used\n\t// for fully qualified names and file paths.\n\tDescription string `json:\"description,omitempty\"`\n}\n\n// Completion item tags are extra annotations that tweak the rendering of a completion\n// item.\n//\n// @since 3.15.0\ntype CompletionItemTag uint32\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#completionItemTagOptions\ntype CompletionItemTagOptions struct {\n\t// The tags supported by the client.\n\tValueSet []CompletionItemTag `json:\"valueSet\"`\n}\n\n// Represents a collection of {@link CompletionItem completion items} to be presented\n// in the editor.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#completionList\ntype CompletionList struct {\n\t// This list it not complete. Further typing results in recomputing this list.\n\t//\n\t// Recomputed lists have all their items replaced (not appended) in the\n\t// incomplete completion sessions.\n\tIsIncomplete bool `json:\"isIncomplete\"`\n\t// In many cases the items of an actual completion result share the same\n\t// value for properties like `commitCharacters` or the range of a text\n\t// edit. A completion list can therefore define item defaults which will\n\t// be used if a completion item itself doesn't specify the value.\n\t//\n\t// If a completion list specifies a default value and a completion item\n\t// also specifies a corresponding value the one from the item is used.\n\t//\n\t// Servers are only allowed to return default values if the client\n\t// signals support for this via the `completionList.itemDefaults`\n\t// capability.\n\t//\n\t// @since 3.17.0\n\tItemDefaults *CompletionItemDefaults `json:\"itemDefaults,omitempty\"`\n\t// The completion items.\n\tItems []CompletionItem `json:\"items\"`\n}\n\n// The client supports the following `CompletionList` specific\n// capabilities.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#completionListCapabilities\ntype CompletionListCapabilities struct {\n\t// The client supports the following itemDefaults on\n\t// a completion list.\n\t//\n\t// The value lists the supported property names of the\n\t// `CompletionList.itemDefaults` object. If omitted\n\t// no properties are supported.\n\t//\n\t// @since 3.17.0\n\tItemDefaults []string `json:\"itemDefaults,omitempty\"`\n}\n\n// Completion options.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#completionOptions\ntype CompletionOptions struct {\n\t// Most tools trigger completion request automatically without explicitly requesting\n\t// it using a keyboard shortcut (e.g. Ctrl+Space). Typically they do so when the user\n\t// starts to type an identifier. For example if the user types `c` in a JavaScript file\n\t// code complete will automatically pop up present `console` besides others as a\n\t// completion item. Characters that make up identifiers don't need to be listed here.\n\t//\n\t// If code complete should automatically be trigger on characters not being valid inside\n\t// an identifier (for example `.` in JavaScript) list them in `triggerCharacters`.\n\tTriggerCharacters []string `json:\"triggerCharacters,omitempty\"`\n\t// The list of all possible characters that commit a completion. This field can be used\n\t// if clients don't support individual commit characters per completion item. See\n\t// `ClientCapabilities.textDocument.completion.completionItem.commitCharactersSupport`\n\t//\n\t// If a server provides both `allCommitCharacters` and commit characters on an individual\n\t// completion item the ones on the completion item win.\n\t//\n\t// @since 3.2.0\n\tAllCommitCharacters []string `json:\"allCommitCharacters,omitempty\"`\n\t// The server provides support to resolve additional\n\t// information for a completion item.\n\tResolveProvider bool `json:\"resolveProvider,omitempty\"`\n\t// The server supports the following `CompletionItem` specific\n\t// capabilities.\n\t//\n\t// @since 3.17.0\n\tCompletionItem *ServerCompletionItemOptions `json:\"completionItem,omitempty\"`\n\tWorkDoneProgressOptions\n}\n\n// Completion parameters\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#completionParams\ntype CompletionParams struct {\n\t// The completion context. This is only available it the client specifies\n\t// to send this using the client capability `textDocument.completion.contextSupport === true`\n\tContext CompletionContext `json:\"context,omitempty\"`\n\tTextDocumentPositionParams\n\tWorkDoneProgressParams\n\tPartialResultParams\n}\n\n// Registration options for a {@link CompletionRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#completionRegistrationOptions\ntype CompletionRegistrationOptions struct {\n\tTextDocumentRegistrationOptions\n\tCompletionOptions\n}\n\n// How a completion was triggered\ntype CompletionTriggerKind uint32\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#configurationItem\ntype ConfigurationItem struct {\n\t// The scope to get the configuration section for.\n\tScopeURI *URI `json:\"scopeUri,omitempty\"`\n\t// The configuration section asked for.\n\tSection string `json:\"section,omitempty\"`\n}\n\n// The parameters of a configuration request.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#configurationParams\ntype ConfigurationParams struct {\n\tItems []ConfigurationItem `json:\"items\"`\n}\n\n// Create file operation.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#createFile\ntype CreateFile struct {\n\t// A create\n\tKind string `json:\"kind\"`\n\t// The resource to create.\n\tURI DocumentUri `json:\"uri\"`\n\t// Additional options\n\tOptions *CreateFileOptions `json:\"options,omitempty\"`\n\tResourceOperation\n}\n\n// Options to create a file.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#createFileOptions\ntype CreateFileOptions struct {\n\t// Overwrite existing file. Overwrite wins over `ignoreIfExists`\n\tOverwrite bool `json:\"overwrite,omitempty\"`\n\t// Ignore if exists.\n\tIgnoreIfExists bool `json:\"ignoreIfExists,omitempty\"`\n}\n\n// The parameters sent in notifications/requests for user-initiated creation of\n// files.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#createFilesParams\ntype CreateFilesParams struct {\n\t// An array of all files/folders created in this operation.\n\tFiles []FileCreate `json:\"files\"`\n}\n\n// The declaration of a symbol representation as one or many {@link Location locations}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#declaration\ntype Declaration = Or_Declaration // (alias)\n// @since 3.14.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#declarationClientCapabilities\ntype DeclarationClientCapabilities struct {\n\t// Whether declaration supports dynamic registration. If this is set to `true`\n\t// the client supports the new `DeclarationRegistrationOptions` return value\n\t// for the corresponding server capability as well.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n\t// The client supports additional metadata in the form of declaration links.\n\tLinkSupport bool `json:\"linkSupport,omitempty\"`\n}\n\n// Information about where a symbol is declared.\n//\n// Provides additional metadata over normal {@link Location location} declarations, including the range of\n// the declaring symbol.\n//\n// Servers should prefer returning `DeclarationLink` over `Declaration` if supported\n// by the client.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#declarationLink\ntype DeclarationLink = LocationLink // (alias)\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#declarationOptions\ntype DeclarationOptions struct {\n\tWorkDoneProgressOptions\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#declarationParams\ntype DeclarationParams struct {\n\tTextDocumentPositionParams\n\tWorkDoneProgressParams\n\tPartialResultParams\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#declarationRegistrationOptions\ntype DeclarationRegistrationOptions struct {\n\tDeclarationOptions\n\tTextDocumentRegistrationOptions\n\tStaticRegistrationOptions\n}\n\n// The definition of a symbol represented as one or many {@link Location locations}.\n// For most programming languages there is only one location at which a symbol is\n// defined.\n//\n// Servers should prefer returning `DefinitionLink` over `Definition` if supported\n// by the client.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#definition\ntype Definition = Or_Definition // (alias)\n// Client Capabilities for a {@link DefinitionRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#definitionClientCapabilities\ntype DefinitionClientCapabilities struct {\n\t// Whether definition supports dynamic registration.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n\t// The client supports additional metadata in the form of definition links.\n\t//\n\t// @since 3.14.0\n\tLinkSupport bool `json:\"linkSupport,omitempty\"`\n}\n\n// Information about where a symbol is defined.\n//\n// Provides additional metadata over normal {@link Location location} definitions, including the range of\n// the defining symbol\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#definitionLink\ntype DefinitionLink = LocationLink // (alias)\n// Server Capabilities for a {@link DefinitionRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#definitionOptions\ntype DefinitionOptions struct {\n\tWorkDoneProgressOptions\n}\n\n// Parameters for a {@link DefinitionRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#definitionParams\ntype DefinitionParams struct {\n\tTextDocumentPositionParams\n\tWorkDoneProgressParams\n\tPartialResultParams\n}\n\n// Registration options for a {@link DefinitionRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#definitionRegistrationOptions\ntype DefinitionRegistrationOptions struct {\n\tTextDocumentRegistrationOptions\n\tDefinitionOptions\n}\n\n// Delete file operation\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#deleteFile\ntype DeleteFile struct {\n\t// A delete\n\tKind string `json:\"kind\"`\n\t// The file to delete.\n\tURI DocumentUri `json:\"uri\"`\n\t// Delete options.\n\tOptions *DeleteFileOptions `json:\"options,omitempty\"`\n\tResourceOperation\n}\n\n// Delete file options\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#deleteFileOptions\ntype DeleteFileOptions struct {\n\t// Delete the content recursively if a folder is denoted.\n\tRecursive bool `json:\"recursive,omitempty\"`\n\t// Ignore the operation if the file doesn't exist.\n\tIgnoreIfNotExists bool `json:\"ignoreIfNotExists,omitempty\"`\n}\n\n// The parameters sent in notifications/requests for user-initiated deletes of\n// files.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#deleteFilesParams\ntype DeleteFilesParams struct {\n\t// An array of all files/folders deleted in this operation.\n\tFiles []FileDelete `json:\"files\"`\n}\n\n// Represents a diagnostic, such as a compiler error or warning. Diagnostic objects\n// are only valid in the scope of a resource.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#diagnostic\ntype Diagnostic struct {\n\t// The range at which the message applies\n\tRange Range `json:\"range\"`\n\t// The diagnostic's severity. To avoid interpretation mismatches when a\n\t// server is used with different clients it is highly recommended that servers\n\t// always provide a severity value.\n\tSeverity DiagnosticSeverity `json:\"severity,omitempty\"`\n\t// The diagnostic's code, which usually appear in the user interface.\n\tCode interface{} `json:\"code,omitempty\"`\n\t// An optional property to describe the error code.\n\t// Requires the code field (above) to be present/not null.\n\t//\n\t// @since 3.16.0\n\tCodeDescription *CodeDescription `json:\"codeDescription,omitempty\"`\n\t// A human-readable string describing the source of this\n\t// diagnostic, e.g. 'typescript' or 'super lint'. It usually\n\t// appears in the user interface.\n\tSource string `json:\"source,omitempty\"`\n\t// The diagnostic's message. It usually appears in the user interface\n\tMessage string `json:\"message\"`\n\t// Additional metadata about the diagnostic.\n\t//\n\t// @since 3.15.0\n\tTags []DiagnosticTag `json:\"tags,omitempty\"`\n\t// An array of related diagnostic information, e.g. when symbol-names within\n\t// a scope collide all definitions can be marked via this property.\n\tRelatedInformation []DiagnosticRelatedInformation `json:\"relatedInformation,omitempty\"`\n\t// A data entry field that is preserved between a `textDocument/publishDiagnostics`\n\t// notification and `textDocument/codeAction` request.\n\t//\n\t// @since 3.16.0\n\tData *json.RawMessage `json:\"data,omitempty\"`\n}\n\n// Client capabilities specific to diagnostic pull requests.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#diagnosticClientCapabilities\ntype DiagnosticClientCapabilities struct {\n\t// Whether implementation supports dynamic registration. If this is set to `true`\n\t// the client supports the new `(TextDocumentRegistrationOptions & StaticRegistrationOptions)`\n\t// return value for the corresponding server capability as well.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n\t// Whether the clients supports related documents for document diagnostic pulls.\n\tRelatedDocumentSupport bool `json:\"relatedDocumentSupport,omitempty\"`\n\tDiagnosticsCapabilities\n}\n\n// Diagnostic options.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#diagnosticOptions\ntype DiagnosticOptions struct {\n\t// An optional identifier under which the diagnostics are\n\t// managed by the client.\n\tIdentifier string `json:\"identifier,omitempty\"`\n\t// Whether the language has inter file dependencies meaning that\n\t// editing code in one file can result in a different diagnostic\n\t// set in another file. Inter file dependencies are common for\n\t// most programming languages and typically uncommon for linters.\n\tInterFileDependencies bool `json:\"interFileDependencies\"`\n\t// The server provides support for workspace diagnostics as well.\n\tWorkspaceDiagnostics bool `json:\"workspaceDiagnostics\"`\n\tWorkDoneProgressOptions\n}\n\n// Diagnostic registration options.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#diagnosticRegistrationOptions\ntype DiagnosticRegistrationOptions struct {\n\tTextDocumentRegistrationOptions\n\tDiagnosticOptions\n\tStaticRegistrationOptions\n}\n\n// Represents a related message and source code location for a diagnostic. This should be\n// used to point to code locations that cause or related to a diagnostics, e.g when duplicating\n// a symbol in a scope.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#diagnosticRelatedInformation\ntype DiagnosticRelatedInformation struct {\n\t// The location of this related diagnostic information.\n\tLocation Location `json:\"location\"`\n\t// The message of this related diagnostic information.\n\tMessage string `json:\"message\"`\n}\n\n// Cancellation data returned from a diagnostic request.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#diagnosticServerCancellationData\ntype DiagnosticServerCancellationData struct {\n\tRetriggerRequest bool `json:\"retriggerRequest\"`\n}\n\n// The diagnostic's severity.\ntype DiagnosticSeverity uint32\n\n// The diagnostic tags.\n//\n// @since 3.15.0\ntype DiagnosticTag uint32\n\n// Workspace client capabilities specific to diagnostic pull requests.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#diagnosticWorkspaceClientCapabilities\ntype DiagnosticWorkspaceClientCapabilities struct {\n\t// Whether the client implementation supports a refresh request sent from\n\t// the server to the client.\n\t//\n\t// Note that this event is global and will force the client to refresh all\n\t// pulled diagnostics currently shown. It should be used with absolute care and\n\t// is useful for situation where a server for example detects a project wide\n\t// change that requires such a calculation.\n\tRefreshSupport bool `json:\"refreshSupport,omitempty\"`\n}\n\n// General diagnostics capabilities for pull and push model.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#diagnosticsCapabilities\ntype DiagnosticsCapabilities struct {\n\t// Whether the clients accepts diagnostics with related information.\n\tRelatedInformation bool `json:\"relatedInformation,omitempty\"`\n\t// Client supports the tag property to provide meta data about a diagnostic.\n\t// Clients supporting tags have to handle unknown tags gracefully.\n\t//\n\t// @since 3.15.0\n\tTagSupport *ClientDiagnosticsTagOptions `json:\"tagSupport,omitempty\"`\n\t// Client supports a codeDescription property\n\t//\n\t// @since 3.16.0\n\tCodeDescriptionSupport bool `json:\"codeDescriptionSupport,omitempty\"`\n\t// Whether code action supports the `data` property which is\n\t// preserved between a `textDocument/publishDiagnostics` and\n\t// `textDocument/codeAction` request.\n\t//\n\t// @since 3.16.0\n\tDataSupport bool `json:\"dataSupport,omitempty\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#didChangeConfigurationClientCapabilities\ntype DidChangeConfigurationClientCapabilities struct {\n\t// Did change configuration notification supports dynamic registration.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n}\n\n// The parameters of a change configuration notification.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#didChangeConfigurationParams\ntype DidChangeConfigurationParams struct {\n\t// The actual changed settings\n\tSettings interface{} `json:\"settings\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#didChangeConfigurationRegistrationOptions\ntype DidChangeConfigurationRegistrationOptions struct {\n\tSection *Or_DidChangeConfigurationRegistrationOptions_section `json:\"section,omitempty\"`\n}\n\n// The params sent in a change notebook document notification.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#didChangeNotebookDocumentParams\ntype DidChangeNotebookDocumentParams struct {\n\t// The notebook document that did change. The version number points\n\t// to the version after all provided changes have been applied. If\n\t// only the text document content of a cell changes the notebook version\n\t// doesn't necessarily have to change.\n\tNotebookDocument VersionedNotebookDocumentIdentifier `json:\"notebookDocument\"`\n\t// The actual changes to the notebook document.\n\t//\n\t// The changes describe single state changes to the notebook document.\n\t// So if there are two changes c1 (at array index 0) and c2 (at array\n\t// index 1) for a notebook in state S then c1 moves the notebook from\n\t// S to S' and c2 from S' to S''. So c1 is computed on the state S and\n\t// c2 is computed on the state S'.\n\t//\n\t// To mirror the content of a notebook using change events use the following approach:\n\t//\n\t// - start with the same initial content\n\t// - apply the 'notebookDocument/didChange' notifications in the order you receive them.\n\t// - apply the `NotebookChangeEvent`s in a single notification in the order\n\t// you receive them.\n\tChange NotebookDocumentChangeEvent `json:\"change\"`\n}\n\n// The change text document notification's parameters.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#didChangeTextDocumentParams\ntype DidChangeTextDocumentParams struct {\n\t// The document that did change. The version number points\n\t// to the version after all provided content changes have\n\t// been applied.\n\tTextDocument VersionedTextDocumentIdentifier `json:\"textDocument\"`\n\t// The actual content changes. The content changes describe single state changes\n\t// to the document. So if there are two content changes c1 (at array index 0) and\n\t// c2 (at array index 1) for a document in state S then c1 moves the document from\n\t// S to S' and c2 from S' to S''. So c1 is computed on the state S and c2 is computed\n\t// on the state S'.\n\t//\n\t// To mirror the content of a document using change events use the following approach:\n\t//\n\t// - start with the same initial content\n\t// - apply the 'textDocument/didChange' notifications in the order you receive them.\n\t// - apply the `TextDocumentContentChangeEvent`s in a single notification in the order\n\t// you receive them.\n\tContentChanges []TextDocumentContentChangeEvent `json:\"contentChanges\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#didChangeWatchedFilesClientCapabilities\ntype DidChangeWatchedFilesClientCapabilities struct {\n\t// Did change watched files notification supports dynamic registration. Please note\n\t// that the current protocol doesn't support static configuration for file changes\n\t// from the server side.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n\t// Whether the client has support for {@link RelativePattern relative pattern}\n\t// or not.\n\t//\n\t// @since 3.17.0\n\tRelativePatternSupport bool `json:\"relativePatternSupport,omitempty\"`\n}\n\n// The watched files change notification's parameters.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#didChangeWatchedFilesParams\ntype DidChangeWatchedFilesParams struct {\n\t// The actual file events.\n\tChanges []FileEvent `json:\"changes\"`\n}\n\n// Describe options to be used when registered for text document change events.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#didChangeWatchedFilesRegistrationOptions\ntype DidChangeWatchedFilesRegistrationOptions struct {\n\t// The watchers to register.\n\tWatchers []FileSystemWatcher `json:\"watchers\"`\n}\n\n// The parameters of a `workspace/didChangeWorkspaceFolders` notification.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#didChangeWorkspaceFoldersParams\ntype DidChangeWorkspaceFoldersParams struct {\n\t// The actual workspace folder change event.\n\tEvent WorkspaceFoldersChangeEvent `json:\"event\"`\n}\n\n// The params sent in a close notebook document notification.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#didCloseNotebookDocumentParams\ntype DidCloseNotebookDocumentParams struct {\n\t// The notebook document that got closed.\n\tNotebookDocument NotebookDocumentIdentifier `json:\"notebookDocument\"`\n\t// The text documents that represent the content\n\t// of a notebook cell that got closed.\n\tCellTextDocuments []TextDocumentIdentifier `json:\"cellTextDocuments\"`\n}\n\n// The parameters sent in a close text document notification\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#didCloseTextDocumentParams\ntype DidCloseTextDocumentParams struct {\n\t// The document that was closed.\n\tTextDocument TextDocumentIdentifier `json:\"textDocument\"`\n}\n\n// The params sent in an open notebook document notification.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#didOpenNotebookDocumentParams\ntype DidOpenNotebookDocumentParams struct {\n\t// The notebook document that got opened.\n\tNotebookDocument NotebookDocument `json:\"notebookDocument\"`\n\t// The text documents that represent the content\n\t// of a notebook cell.\n\tCellTextDocuments []TextDocumentItem `json:\"cellTextDocuments\"`\n}\n\n// The parameters sent in an open text document notification\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#didOpenTextDocumentParams\ntype DidOpenTextDocumentParams struct {\n\t// The document that was opened.\n\tTextDocument TextDocumentItem `json:\"textDocument\"`\n}\n\n// The params sent in a save notebook document notification.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#didSaveNotebookDocumentParams\ntype DidSaveNotebookDocumentParams struct {\n\t// The notebook document that got saved.\n\tNotebookDocument NotebookDocumentIdentifier `json:\"notebookDocument\"`\n}\n\n// The parameters sent in a save text document notification\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#didSaveTextDocumentParams\ntype DidSaveTextDocumentParams struct {\n\t// The document that was saved.\n\tTextDocument TextDocumentIdentifier `json:\"textDocument\"`\n\t// Optional the content when saved. Depends on the includeText value\n\t// when the save notification was requested.\n\tText *string `json:\"text,omitempty\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentColorClientCapabilities\ntype DocumentColorClientCapabilities struct {\n\t// Whether implementation supports dynamic registration. If this is set to `true`\n\t// the client supports the new `DocumentColorRegistrationOptions` return value\n\t// for the corresponding server capability as well.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentColorOptions\ntype DocumentColorOptions struct {\n\tWorkDoneProgressOptions\n}\n\n// Parameters for a {@link DocumentColorRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentColorParams\ntype DocumentColorParams struct {\n\t// The text document.\n\tTextDocument TextDocumentIdentifier `json:\"textDocument\"`\n\tWorkDoneProgressParams\n\tPartialResultParams\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentColorRegistrationOptions\ntype DocumentColorRegistrationOptions struct {\n\tTextDocumentRegistrationOptions\n\tDocumentColorOptions\n\tStaticRegistrationOptions\n}\n\n// Parameters of the document diagnostic request.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentDiagnosticParams\ntype DocumentDiagnosticParams struct {\n\t// The text document.\n\tTextDocument TextDocumentIdentifier `json:\"textDocument\"`\n\t// The additional identifier provided during registration.\n\tIdentifier string `json:\"identifier,omitempty\"`\n\t// The result id of a previous response if provided.\n\tPreviousResultID string `json:\"previousResultId,omitempty\"`\n\tWorkDoneProgressParams\n\tPartialResultParams\n}\n\n// The result of a document diagnostic pull request. A report can\n// either be a full report containing all diagnostics for the\n// requested document or an unchanged report indicating that nothing\n// has changed in terms of diagnostics in comparison to the last\n// pull request.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentDiagnosticReport\ntype DocumentDiagnosticReport = Or_DocumentDiagnosticReport // (alias)\n// The document diagnostic report kinds.\n//\n// @since 3.17.0\ntype DocumentDiagnosticReportKind string\n\n// A partial result for a document diagnostic report.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentDiagnosticReportPartialResult\ntype DocumentDiagnosticReportPartialResult struct {\n\tRelatedDocuments map[DocumentUri]interface{} `json:\"relatedDocuments\"`\n}\n\n// A document filter describes a top level text document or\n// a notebook cell document.\n//\n// @since 3.17.0 - proposed support for NotebookCellTextDocumentFilter.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentFilter\ntype DocumentFilter = Or_DocumentFilter // (alias)\n// Client capabilities of a {@link DocumentFormattingRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentFormattingClientCapabilities\ntype DocumentFormattingClientCapabilities struct {\n\t// Whether formatting supports dynamic registration.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n}\n\n// Provider options for a {@link DocumentFormattingRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentFormattingOptions\ntype DocumentFormattingOptions struct {\n\tWorkDoneProgressOptions\n}\n\n// The parameters of a {@link DocumentFormattingRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentFormattingParams\ntype DocumentFormattingParams struct {\n\t// The document to format.\n\tTextDocument TextDocumentIdentifier `json:\"textDocument\"`\n\t// The format options.\n\tOptions FormattingOptions `json:\"options\"`\n\tWorkDoneProgressParams\n}\n\n// Registration options for a {@link DocumentFormattingRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentFormattingRegistrationOptions\ntype DocumentFormattingRegistrationOptions struct {\n\tTextDocumentRegistrationOptions\n\tDocumentFormattingOptions\n}\n\n// A document highlight is a range inside a text document which deserves\n// special attention. Usually a document highlight is visualized by changing\n// the background color of its range.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentHighlight\ntype DocumentHighlight struct {\n\t// The range this highlight applies to.\n\tRange Range `json:\"range\"`\n\t// The highlight kind, default is {@link DocumentHighlightKind.Text text}.\n\tKind DocumentHighlightKind `json:\"kind,omitempty\"`\n}\n\n// Client Capabilities for a {@link DocumentHighlightRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentHighlightClientCapabilities\ntype DocumentHighlightClientCapabilities struct {\n\t// Whether document highlight supports dynamic registration.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n}\n\n// A document highlight kind.\ntype DocumentHighlightKind uint32\n\n// Provider options for a {@link DocumentHighlightRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentHighlightOptions\ntype DocumentHighlightOptions struct {\n\tWorkDoneProgressOptions\n}\n\n// Parameters for a {@link DocumentHighlightRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentHighlightParams\ntype DocumentHighlightParams struct {\n\tTextDocumentPositionParams\n\tWorkDoneProgressParams\n\tPartialResultParams\n}\n\n// Registration options for a {@link DocumentHighlightRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentHighlightRegistrationOptions\ntype DocumentHighlightRegistrationOptions struct {\n\tTextDocumentRegistrationOptions\n\tDocumentHighlightOptions\n}\n\n// A document link is a range in a text document that links to an internal or external resource, like another\n// text document or a web site.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentLink\ntype DocumentLink struct {\n\t// The range this link applies to.\n\tRange Range `json:\"range\"`\n\t// The uri this link points to. If missing a resolve request is sent later.\n\tTarget *URI `json:\"target,omitempty\"`\n\t// The tooltip text when you hover over this link.\n\t//\n\t// If a tooltip is provided, is will be displayed in a string that includes instructions on how to\n\t// trigger the link, such as `{0} (ctrl + click)`. The specific instructions vary depending on OS,\n\t// user settings, and localization.\n\t//\n\t// @since 3.15.0\n\tTooltip string `json:\"tooltip,omitempty\"`\n\t// A data entry field that is preserved on a document link between a\n\t// DocumentLinkRequest and a DocumentLinkResolveRequest.\n\tData interface{} `json:\"data,omitempty\"`\n}\n\n// The client capabilities of a {@link DocumentLinkRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentLinkClientCapabilities\ntype DocumentLinkClientCapabilities struct {\n\t// Whether document link supports dynamic registration.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n\t// Whether the client supports the `tooltip` property on `DocumentLink`.\n\t//\n\t// @since 3.15.0\n\tTooltipSupport bool `json:\"tooltipSupport,omitempty\"`\n}\n\n// Provider options for a {@link DocumentLinkRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentLinkOptions\ntype DocumentLinkOptions struct {\n\t// Document links have a resolve provider as well.\n\tResolveProvider bool `json:\"resolveProvider,omitempty\"`\n\tWorkDoneProgressOptions\n}\n\n// The parameters of a {@link DocumentLinkRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentLinkParams\ntype DocumentLinkParams struct {\n\t// The document to provide document links for.\n\tTextDocument TextDocumentIdentifier `json:\"textDocument\"`\n\tWorkDoneProgressParams\n\tPartialResultParams\n}\n\n// Registration options for a {@link DocumentLinkRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentLinkRegistrationOptions\ntype DocumentLinkRegistrationOptions struct {\n\tTextDocumentRegistrationOptions\n\tDocumentLinkOptions\n}\n\n// Client capabilities of a {@link DocumentOnTypeFormattingRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentOnTypeFormattingClientCapabilities\ntype DocumentOnTypeFormattingClientCapabilities struct {\n\t// Whether on type formatting supports dynamic registration.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n}\n\n// Provider options for a {@link DocumentOnTypeFormattingRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentOnTypeFormattingOptions\ntype DocumentOnTypeFormattingOptions struct {\n\t// A character on which formatting should be triggered, like `{`.\n\tFirstTriggerCharacter string `json:\"firstTriggerCharacter\"`\n\t// More trigger characters.\n\tMoreTriggerCharacter []string `json:\"moreTriggerCharacter,omitempty\"`\n}\n\n// The parameters of a {@link DocumentOnTypeFormattingRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentOnTypeFormattingParams\ntype DocumentOnTypeFormattingParams struct {\n\t// The document to format.\n\tTextDocument TextDocumentIdentifier `json:\"textDocument\"`\n\t// The position around which the on type formatting should happen.\n\t// This is not necessarily the exact position where the character denoted\n\t// by the property `ch` got typed.\n\tPosition Position `json:\"position\"`\n\t// The character that has been typed that triggered the formatting\n\t// on type request. That is not necessarily the last character that\n\t// got inserted into the document since the client could auto insert\n\t// characters as well (e.g. like automatic brace completion).\n\tCh string `json:\"ch\"`\n\t// The formatting options.\n\tOptions FormattingOptions `json:\"options\"`\n}\n\n// Registration options for a {@link DocumentOnTypeFormattingRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentOnTypeFormattingRegistrationOptions\ntype DocumentOnTypeFormattingRegistrationOptions struct {\n\tTextDocumentRegistrationOptions\n\tDocumentOnTypeFormattingOptions\n}\n\n// Client capabilities of a {@link DocumentRangeFormattingRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentRangeFormattingClientCapabilities\ntype DocumentRangeFormattingClientCapabilities struct {\n\t// Whether range formatting supports dynamic registration.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n\t// Whether the client supports formatting multiple ranges at once.\n\t//\n\t// @since 3.18.0\n\t// @proposed\n\tRangesSupport bool `json:\"rangesSupport,omitempty\"`\n}\n\n// Provider options for a {@link DocumentRangeFormattingRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentRangeFormattingOptions\ntype DocumentRangeFormattingOptions struct {\n\t// Whether the server supports formatting multiple ranges at once.\n\t//\n\t// @since 3.18.0\n\t// @proposed\n\tRangesSupport bool `json:\"rangesSupport,omitempty\"`\n\tWorkDoneProgressOptions\n}\n\n// The parameters of a {@link DocumentRangeFormattingRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentRangeFormattingParams\ntype DocumentRangeFormattingParams struct {\n\t// The document to format.\n\tTextDocument TextDocumentIdentifier `json:\"textDocument\"`\n\t// The range to format\n\tRange Range `json:\"range\"`\n\t// The format options\n\tOptions FormattingOptions `json:\"options\"`\n\tWorkDoneProgressParams\n}\n\n// Registration options for a {@link DocumentRangeFormattingRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentRangeFormattingRegistrationOptions\ntype DocumentRangeFormattingRegistrationOptions struct {\n\tTextDocumentRegistrationOptions\n\tDocumentRangeFormattingOptions\n}\n\n// The parameters of a {@link DocumentRangesFormattingRequest}.\n//\n// @since 3.18.0\n// @proposed\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentRangesFormattingParams\ntype DocumentRangesFormattingParams struct {\n\t// The document to format.\n\tTextDocument TextDocumentIdentifier `json:\"textDocument\"`\n\t// The ranges to format\n\tRanges []Range `json:\"ranges\"`\n\t// The format options\n\tOptions FormattingOptions `json:\"options\"`\n\tWorkDoneProgressParams\n}\n\n// A document selector is the combination of one or many document filters.\n//\n// @sample `let sel:DocumentSelector = [{ language: 'typescript' }, { language: 'json', pattern: '**∕tsconfig.json' }]`;\n//\n// The use of a string as a document filter is deprecated @since 3.16.0.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentSelector\ntype DocumentSelector = []DocumentFilter // (alias)\n// Represents programming constructs like variables, classes, interfaces etc.\n// that appear in a document. Document symbols can be hierarchical and they\n// have two ranges: one that encloses its definition and one that points to\n// its most interesting range, e.g. the range of an identifier.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentSymbol\ntype DocumentSymbol struct {\n\t// The name of this symbol. Will be displayed in the user interface and therefore must not be\n\t// an empty string or a string only consisting of white spaces.\n\tName string `json:\"name\"`\n\t// More detail for this symbol, e.g the signature of a function.\n\tDetail string `json:\"detail,omitempty\"`\n\t// The kind of this symbol.\n\tKind SymbolKind `json:\"kind\"`\n\t// Tags for this document symbol.\n\t//\n\t// @since 3.16.0\n\tTags []SymbolTag `json:\"tags,omitempty\"`\n\t// Indicates if this symbol is deprecated.\n\t//\n\t// @deprecated Use tags instead\n\tDeprecated bool `json:\"deprecated,omitempty\"`\n\t// The range enclosing this symbol not including leading/trailing whitespace but everything else\n\t// like comments. This information is typically used to determine if the clients cursor is\n\t// inside the symbol to reveal in the symbol in the UI.\n\tRange Range `json:\"range\"`\n\t// The range that should be selected and revealed when this symbol is being picked, e.g the name of a function.\n\t// Must be contained by the `range`.\n\tSelectionRange Range `json:\"selectionRange\"`\n\t// Children of this symbol, e.g. properties of a class.\n\tChildren []DocumentSymbol `json:\"children,omitempty\"`\n}\n\n// Client Capabilities for a {@link DocumentSymbolRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentSymbolClientCapabilities\ntype DocumentSymbolClientCapabilities struct {\n\t// Whether document symbol supports dynamic registration.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n\t// Specific capabilities for the `SymbolKind` in the\n\t// `textDocument/documentSymbol` request.\n\tSymbolKind *ClientSymbolKindOptions `json:\"symbolKind,omitempty\"`\n\t// The client supports hierarchical document symbols.\n\tHierarchicalDocumentSymbolSupport bool `json:\"hierarchicalDocumentSymbolSupport,omitempty\"`\n\t// The client supports tags on `SymbolInformation`. Tags are supported on\n\t// `DocumentSymbol` if `hierarchicalDocumentSymbolSupport` is set to true.\n\t// Clients supporting tags have to handle unknown tags gracefully.\n\t//\n\t// @since 3.16.0\n\tTagSupport *ClientSymbolTagOptions `json:\"tagSupport,omitempty\"`\n\t// The client supports an additional label presented in the UI when\n\t// registering a document symbol provider.\n\t//\n\t// @since 3.16.0\n\tLabelSupport bool `json:\"labelSupport,omitempty\"`\n}\n\n// Provider options for a {@link DocumentSymbolRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentSymbolOptions\ntype DocumentSymbolOptions struct {\n\t// A human-readable string that is shown when multiple outlines trees\n\t// are shown for the same document.\n\t//\n\t// @since 3.16.0\n\tLabel string `json:\"label,omitempty\"`\n\tWorkDoneProgressOptions\n}\n\n// Parameters for a {@link DocumentSymbolRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentSymbolParams\ntype DocumentSymbolParams struct {\n\t// The text document.\n\tTextDocument TextDocumentIdentifier `json:\"textDocument\"`\n\tWorkDoneProgressParams\n\tPartialResultParams\n}\n\n// Registration options for a {@link DocumentSymbolRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentSymbolRegistrationOptions\ntype DocumentSymbolRegistrationOptions struct {\n\tTextDocumentRegistrationOptions\n\tDocumentSymbolOptions\n}\n\n// Edit range variant that includes ranges for insert and replace operations.\n//\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#editRangeWithInsertReplace\ntype EditRangeWithInsertReplace struct {\n\tInsert Range `json:\"insert\"`\n\tReplace Range `json:\"replace\"`\n}\n\n// Predefined error codes.\ntype ErrorCodes int32\n\n// The client capabilities of a {@link ExecuteCommandRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#executeCommandClientCapabilities\ntype ExecuteCommandClientCapabilities struct {\n\t// Execute command supports dynamic registration.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n}\n\n// The server capabilities of a {@link ExecuteCommandRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#executeCommandOptions\ntype ExecuteCommandOptions struct {\n\t// The commands to be executed on the server\n\tCommands []string `json:\"commands\"`\n\tWorkDoneProgressOptions\n}\n\n// The parameters of a {@link ExecuteCommandRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#executeCommandParams\ntype ExecuteCommandParams struct {\n\t// The identifier of the actual command handler.\n\tCommand string `json:\"command\"`\n\t// Arguments that the command should be invoked with.\n\tArguments []json.RawMessage `json:\"arguments,omitempty\"`\n\tWorkDoneProgressParams\n}\n\n// Registration options for a {@link ExecuteCommandRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#executeCommandRegistrationOptions\ntype ExecuteCommandRegistrationOptions struct {\n\tExecuteCommandOptions\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#executionSummary\ntype ExecutionSummary struct {\n\t// A strict monotonically increasing value\n\t// indicating the execution order of a cell\n\t// inside a notebook.\n\tExecutionOrder uint32 `json:\"executionOrder\"`\n\t// Whether the execution was successful or\n\t// not if known by the client.\n\tSuccess bool `json:\"success,omitempty\"`\n}\ntype FailureHandlingKind string\n\n// The file event type\ntype FileChangeType uint32\n\n// Represents information on a file/folder create.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#fileCreate\ntype FileCreate struct {\n\t// A file:// URI for the location of the file/folder being created.\n\tURI string `json:\"uri\"`\n}\n\n// Represents information on a file/folder delete.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#fileDelete\ntype FileDelete struct {\n\t// A file:// URI for the location of the file/folder being deleted.\n\tURI string `json:\"uri\"`\n}\n\n// An event describing a file change.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#fileEvent\ntype FileEvent struct {\n\t// The file's uri.\n\tURI DocumentUri `json:\"uri\"`\n\t// The change type.\n\tType FileChangeType `json:\"type\"`\n}\n\n// Capabilities relating to events from file operations by the user in the client.\n//\n// These events do not come from the file system, they come from user operations\n// like renaming a file in the UI.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#fileOperationClientCapabilities\ntype FileOperationClientCapabilities struct {\n\t// Whether the client supports dynamic registration for file requests/notifications.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n\t// The client has support for sending didCreateFiles notifications.\n\tDidCreate bool `json:\"didCreate,omitempty\"`\n\t// The client has support for sending willCreateFiles requests.\n\tWillCreate bool `json:\"willCreate,omitempty\"`\n\t// The client has support for sending didRenameFiles notifications.\n\tDidRename bool `json:\"didRename,omitempty\"`\n\t// The client has support for sending willRenameFiles requests.\n\tWillRename bool `json:\"willRename,omitempty\"`\n\t// The client has support for sending didDeleteFiles notifications.\n\tDidDelete bool `json:\"didDelete,omitempty\"`\n\t// The client has support for sending willDeleteFiles requests.\n\tWillDelete bool `json:\"willDelete,omitempty\"`\n}\n\n// A filter to describe in which file operation requests or notifications\n// the server is interested in receiving.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#fileOperationFilter\ntype FileOperationFilter struct {\n\t// A Uri scheme like `file` or `untitled`.\n\tScheme string `json:\"scheme,omitempty\"`\n\t// The actual file operation pattern.\n\tPattern FileOperationPattern `json:\"pattern\"`\n}\n\n// Options for notifications/requests for user operations on files.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#fileOperationOptions\ntype FileOperationOptions struct {\n\t// The server is interested in receiving didCreateFiles notifications.\n\tDidCreate *FileOperationRegistrationOptions `json:\"didCreate,omitempty\"`\n\t// The server is interested in receiving willCreateFiles requests.\n\tWillCreate *FileOperationRegistrationOptions `json:\"willCreate,omitempty\"`\n\t// The server is interested in receiving didRenameFiles notifications.\n\tDidRename *FileOperationRegistrationOptions `json:\"didRename,omitempty\"`\n\t// The server is interested in receiving willRenameFiles requests.\n\tWillRename *FileOperationRegistrationOptions `json:\"willRename,omitempty\"`\n\t// The server is interested in receiving didDeleteFiles file notifications.\n\tDidDelete *FileOperationRegistrationOptions `json:\"didDelete,omitempty\"`\n\t// The server is interested in receiving willDeleteFiles file requests.\n\tWillDelete *FileOperationRegistrationOptions `json:\"willDelete,omitempty\"`\n}\n\n// A pattern to describe in which file operation requests or notifications\n// the server is interested in receiving.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#fileOperationPattern\ntype FileOperationPattern struct {\n\t// The glob pattern to match. Glob patterns can have the following syntax:\n\t//\n\t// - `*` to match one or more characters in a path segment\n\t// - `?` to match on one character in a path segment\n\t// - `**` to match any number of path segments, including none\n\t// - `{}` to group sub patterns into an OR expression. (e.g. `**/*.{ts,js}` matches all TypeScript and JavaScript files)\n\t// - `[]` to declare a range of characters to match in a path segment (e.g., `example.[0-9]` to match on `example.0`, `example.1`, …)\n\t// - `[!...]` to negate a range of characters to match in a path segment (e.g., `example.[!0-9]` to match on `example.a`, `example.b`, but not `example.0`)\n\tGlob string `json:\"glob\"`\n\t// Whether to match files or folders with this pattern.\n\t//\n\t// Matches both if undefined.\n\tMatches *FileOperationPatternKind `json:\"matches,omitempty\"`\n\t// Additional options used during matching.\n\tOptions *FileOperationPatternOptions `json:\"options,omitempty\"`\n}\n\n// A pattern kind describing if a glob pattern matches a file a folder or\n// both.\n//\n// @since 3.16.0\ntype FileOperationPatternKind string\n\n// Matching options for the file operation pattern.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#fileOperationPatternOptions\ntype FileOperationPatternOptions struct {\n\t// The pattern should be matched ignoring casing.\n\tIgnoreCase bool `json:\"ignoreCase,omitempty\"`\n}\n\n// The options to register for file operations.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#fileOperationRegistrationOptions\ntype FileOperationRegistrationOptions struct {\n\t// The actual filters.\n\tFilters []FileOperationFilter `json:\"filters\"`\n}\n\n// Represents information on a file/folder rename.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#fileRename\ntype FileRename struct {\n\t// A file:// URI for the original location of the file/folder being renamed.\n\tOldURI string `json:\"oldUri\"`\n\t// A file:// URI for the new location of the file/folder being renamed.\n\tNewURI string `json:\"newUri\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#fileSystemWatcher\ntype FileSystemWatcher struct {\n\t// The glob pattern to watch. See {@link GlobPattern glob pattern} for more detail.\n\t//\n\t// @since 3.17.0 support for relative patterns.\n\tGlobPattern GlobPattern `json:\"globPattern\"`\n\t// The kind of events of interest. If omitted it defaults\n\t// to WatchKind.Create | WatchKind.Change | WatchKind.Delete\n\t// which is 7.\n\tKind *WatchKind `json:\"kind,omitempty\"`\n}\n\n// Represents a folding range. To be valid, start and end line must be bigger than zero and smaller\n// than the number of lines in the document. Clients are free to ignore invalid ranges.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#foldingRange\ntype FoldingRange struct {\n\t// The zero-based start line of the range to fold. The folded area starts after the line's last character.\n\t// To be valid, the end must be zero or larger and smaller than the number of lines in the document.\n\tStartLine uint32 `json:\"startLine\"`\n\t// The zero-based character offset from where the folded range starts. If not defined, defaults to the length of the start line.\n\tStartCharacter uint32 `json:\"startCharacter,omitempty\"`\n\t// The zero-based end line of the range to fold. The folded area ends with the line's last character.\n\t// To be valid, the end must be zero or larger and smaller than the number of lines in the document.\n\tEndLine uint32 `json:\"endLine\"`\n\t// The zero-based character offset before the folded range ends. If not defined, defaults to the length of the end line.\n\tEndCharacter uint32 `json:\"endCharacter,omitempty\"`\n\t// Describes the kind of the folding range such as 'comment' or 'region'. The kind\n\t// is used to categorize folding ranges and used by commands like 'Fold all comments'.\n\t// See {@link FoldingRangeKind} for an enumeration of standardized kinds.\n\tKind string `json:\"kind,omitempty\"`\n\t// The text that the client should show when the specified range is\n\t// collapsed. If not defined or not supported by the client, a default\n\t// will be chosen by the client.\n\t//\n\t// @since 3.17.0\n\tCollapsedText string `json:\"collapsedText,omitempty\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#foldingRangeClientCapabilities\ntype FoldingRangeClientCapabilities struct {\n\t// Whether implementation supports dynamic registration for folding range\n\t// providers. If this is set to `true` the client supports the new\n\t// `FoldingRangeRegistrationOptions` return value for the corresponding\n\t// server capability as well.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n\t// The maximum number of folding ranges that the client prefers to receive\n\t// per document. The value serves as a hint, servers are free to follow the\n\t// limit.\n\tRangeLimit uint32 `json:\"rangeLimit,omitempty\"`\n\t// If set, the client signals that it only supports folding complete lines.\n\t// If set, client will ignore specified `startCharacter` and `endCharacter`\n\t// properties in a FoldingRange.\n\tLineFoldingOnly bool `json:\"lineFoldingOnly,omitempty\"`\n\t// Specific options for the folding range kind.\n\t//\n\t// @since 3.17.0\n\tFoldingRangeKind *ClientFoldingRangeKindOptions `json:\"foldingRangeKind,omitempty\"`\n\t// Specific options for the folding range.\n\t//\n\t// @since 3.17.0\n\tFoldingRange *ClientFoldingRangeOptions `json:\"foldingRange,omitempty\"`\n}\n\n// A set of predefined range kinds.\ntype FoldingRangeKind string\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#foldingRangeOptions\ntype FoldingRangeOptions struct {\n\tWorkDoneProgressOptions\n}\n\n// Parameters for a {@link FoldingRangeRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#foldingRangeParams\ntype FoldingRangeParams struct {\n\t// The text document.\n\tTextDocument TextDocumentIdentifier `json:\"textDocument\"`\n\tWorkDoneProgressParams\n\tPartialResultParams\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#foldingRangeRegistrationOptions\ntype FoldingRangeRegistrationOptions struct {\n\tTextDocumentRegistrationOptions\n\tFoldingRangeOptions\n\tStaticRegistrationOptions\n}\n\n// Client workspace capabilities specific to folding ranges\n//\n// @since 3.18.0\n// @proposed\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#foldingRangeWorkspaceClientCapabilities\ntype FoldingRangeWorkspaceClientCapabilities struct {\n\t// Whether the client implementation supports a refresh request sent from the\n\t// server to the client.\n\t//\n\t// Note that this event is global and will force the client to refresh all\n\t// folding ranges currently shown. It should be used with absolute care and is\n\t// useful for situation where a server for example detects a project wide\n\t// change that requires such a calculation.\n\t//\n\t// @since 3.18.0\n\t// @proposed\n\tRefreshSupport bool `json:\"refreshSupport,omitempty\"`\n}\n\n// Value-object describing what options formatting should use.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#formattingOptions\ntype FormattingOptions struct {\n\t// Size of a tab in spaces.\n\tTabSize uint32 `json:\"tabSize\"`\n\t// Prefer spaces over tabs.\n\tInsertSpaces bool `json:\"insertSpaces\"`\n\t// Trim trailing whitespace on a line.\n\t//\n\t// @since 3.15.0\n\tTrimTrailingWhitespace bool `json:\"trimTrailingWhitespace,omitempty\"`\n\t// Insert a newline character at the end of the file if one does not exist.\n\t//\n\t// @since 3.15.0\n\tInsertFinalNewline bool `json:\"insertFinalNewline,omitempty\"`\n\t// Trim all newlines after the final newline at the end of the file.\n\t//\n\t// @since 3.15.0\n\tTrimFinalNewlines bool `json:\"trimFinalNewlines,omitempty\"`\n}\n\n// A diagnostic report with a full set of problems.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#fullDocumentDiagnosticReport\ntype FullDocumentDiagnosticReport struct {\n\t// A full document diagnostic report.\n\tKind string `json:\"kind\"`\n\t// An optional result id. If provided it will\n\t// be sent on the next diagnostic request for the\n\t// same document.\n\tResultID string `json:\"resultId,omitempty\"`\n\t// The actual items.\n\tItems []Diagnostic `json:\"items\"`\n}\n\n// General client capabilities.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#generalClientCapabilities\ntype GeneralClientCapabilities struct {\n\t// Client capability that signals how the client\n\t// handles stale requests (e.g. a request\n\t// for which the client will not process the response\n\t// anymore since the information is outdated).\n\t//\n\t// @since 3.17.0\n\tStaleRequestSupport *StaleRequestSupportOptions `json:\"staleRequestSupport,omitempty\"`\n\t// Client capabilities specific to regular expressions.\n\t//\n\t// @since 3.16.0\n\tRegularExpressions *RegularExpressionsClientCapabilities `json:\"regularExpressions,omitempty\"`\n\t// Client capabilities specific to the client's markdown parser.\n\t//\n\t// @since 3.16.0\n\tMarkdown *MarkdownClientCapabilities `json:\"markdown,omitempty\"`\n\t// The position encodings supported by the client. Client and server\n\t// have to agree on the same position encoding to ensure that offsets\n\t// (e.g. character position in a line) are interpreted the same on both\n\t// sides.\n\t//\n\t// To keep the protocol backwards compatible the following applies: if\n\t// the value 'utf-16' is missing from the array of position encodings\n\t// servers can assume that the client supports UTF-16. UTF-16 is\n\t// therefore a mandatory encoding.\n\t//\n\t// If omitted it defaults to ['utf-16'].\n\t//\n\t// Implementation considerations: since the conversion from one encoding\n\t// into another requires the content of the file / line the conversion\n\t// is best done where the file is read which is usually on the server\n\t// side.\n\t//\n\t// @since 3.17.0\n\tPositionEncodings []PositionEncodingKind `json:\"positionEncodings,omitempty\"`\n}\n\n// The glob pattern. Either a string pattern or a relative pattern.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#globPattern\ntype GlobPattern = Or_GlobPattern // (alias)\n// The result of a hover request.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#hover\ntype Hover struct {\n\t// The hover's content\n\tContents MarkupContent `json:\"contents\"`\n\t// An optional range inside the text document that is used to\n\t// visualize the hover, e.g. by changing the background color.\n\tRange Range `json:\"range,omitempty\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#hoverClientCapabilities\ntype HoverClientCapabilities struct {\n\t// Whether hover supports dynamic registration.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n\t// Client supports the following content formats for the content\n\t// property. The order describes the preferred format of the client.\n\tContentFormat []MarkupKind `json:\"contentFormat,omitempty\"`\n}\n\n// Hover options.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#hoverOptions\ntype HoverOptions struct {\n\tWorkDoneProgressOptions\n}\n\n// Parameters for a {@link HoverRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#hoverParams\ntype HoverParams struct {\n\tTextDocumentPositionParams\n\tWorkDoneProgressParams\n}\n\n// Registration options for a {@link HoverRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#hoverRegistrationOptions\ntype HoverRegistrationOptions struct {\n\tTextDocumentRegistrationOptions\n\tHoverOptions\n}\n\n// @since 3.6.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#implementationClientCapabilities\ntype ImplementationClientCapabilities struct {\n\t// Whether implementation supports dynamic registration. If this is set to `true`\n\t// the client supports the new `ImplementationRegistrationOptions` return value\n\t// for the corresponding server capability as well.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n\t// The client supports additional metadata in the form of definition links.\n\t//\n\t// @since 3.14.0\n\tLinkSupport bool `json:\"linkSupport,omitempty\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#implementationOptions\ntype ImplementationOptions struct {\n\tWorkDoneProgressOptions\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#implementationParams\ntype ImplementationParams struct {\n\tTextDocumentPositionParams\n\tWorkDoneProgressParams\n\tPartialResultParams\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#implementationRegistrationOptions\ntype ImplementationRegistrationOptions struct {\n\tTextDocumentRegistrationOptions\n\tImplementationOptions\n\tStaticRegistrationOptions\n}\n\n// The data type of the ResponseError if the\n// initialize request fails.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#initializeError\ntype InitializeError struct {\n\t// Indicates whether the client execute the following retry logic:\n\t// (1) show the message provided by the ResponseError to the user\n\t// (2) user selects retry or cancel\n\t// (3) if user selected retry the initialize method is sent again.\n\tRetry bool `json:\"retry\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#initializeParams\ntype InitializeParams struct {\n\tXInitializeParams\n\tWorkspaceFoldersInitializeParams\n}\n\n// The result returned from an initialize request.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#initializeResult\ntype InitializeResult struct {\n\t// The capabilities the language server provides.\n\tCapabilities ServerCapabilities `json:\"capabilities\"`\n\t// Information about the server.\n\t//\n\t// @since 3.15.0\n\tServerInfo *ServerInfo `json:\"serverInfo,omitempty\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#initializedParams\ntype InitializedParams struct {\n}\n\n// Inlay hint information.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#inlayHint\ntype InlayHint struct {\n\t// The position of this hint.\n\t//\n\t// If multiple hints have the same position, they will be shown in the order\n\t// they appear in the response.\n\tPosition Position `json:\"position\"`\n\t// The label of this hint. A human readable string or an array of\n\t// InlayHintLabelPart label parts.\n\t//\n\t// *Note* that neither the string nor the label part can be empty.\n\tLabel []InlayHintLabelPart `json:\"label\"`\n\t// The kind of this hint. Can be omitted in which case the client\n\t// should fall back to a reasonable default.\n\tKind InlayHintKind `json:\"kind,omitempty\"`\n\t// Optional text edits that are performed when accepting this inlay hint.\n\t//\n\t// *Note* that edits are expected to change the document so that the inlay\n\t// hint (or its nearest variant) is now part of the document and the inlay\n\t// hint itself is now obsolete.\n\tTextEdits []TextEdit `json:\"textEdits,omitempty\"`\n\t// The tooltip text when you hover over this item.\n\tTooltip *Or_InlayHint_tooltip `json:\"tooltip,omitempty\"`\n\t// Render padding before the hint.\n\t//\n\t// Note: Padding should use the editor's background color, not the\n\t// background color of the hint itself. That means padding can be used\n\t// to visually align/separate an inlay hint.\n\tPaddingLeft bool `json:\"paddingLeft,omitempty\"`\n\t// Render padding after the hint.\n\t//\n\t// Note: Padding should use the editor's background color, not the\n\t// background color of the hint itself. That means padding can be used\n\t// to visually align/separate an inlay hint.\n\tPaddingRight bool `json:\"paddingRight,omitempty\"`\n\t// A data entry field that is preserved on an inlay hint between\n\t// a `textDocument/inlayHint` and a `inlayHint/resolve` request.\n\tData interface{} `json:\"data,omitempty\"`\n}\n\n// Inlay hint client capabilities.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#inlayHintClientCapabilities\ntype InlayHintClientCapabilities struct {\n\t// Whether inlay hints support dynamic registration.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n\t// Indicates which properties a client can resolve lazily on an inlay\n\t// hint.\n\tResolveSupport *ClientInlayHintResolveOptions `json:\"resolveSupport,omitempty\"`\n}\n\n// Inlay hint kinds.\n//\n// @since 3.17.0\ntype InlayHintKind uint32\n\n// An inlay hint label part allows for interactive and composite labels\n// of inlay hints.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#inlayHintLabelPart\ntype InlayHintLabelPart struct {\n\t// The value of this label part.\n\tValue string `json:\"value\"`\n\t// The tooltip text when you hover over this label part. Depending on\n\t// the client capability `inlayHint.resolveSupport` clients might resolve\n\t// this property late using the resolve request.\n\tTooltip *Or_InlayHintLabelPart_tooltip `json:\"tooltip,omitempty\"`\n\t// An optional source code location that represents this\n\t// label part.\n\t//\n\t// The editor will use this location for the hover and for code navigation\n\t// features: This part will become a clickable link that resolves to the\n\t// definition of the symbol at the given location (not necessarily the\n\t// location itself), it shows the hover that shows at the given location,\n\t// and it shows a context menu with further code navigation commands.\n\t//\n\t// Depending on the client capability `inlayHint.resolveSupport` clients\n\t// might resolve this property late using the resolve request.\n\tLocation *Location `json:\"location,omitempty\"`\n\t// An optional command for this label part.\n\t//\n\t// Depending on the client capability `inlayHint.resolveSupport` clients\n\t// might resolve this property late using the resolve request.\n\tCommand *Command `json:\"command,omitempty\"`\n}\n\n// Inlay hint options used during static registration.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#inlayHintOptions\ntype InlayHintOptions struct {\n\t// The server provides support to resolve additional\n\t// information for an inlay hint item.\n\tResolveProvider bool `json:\"resolveProvider,omitempty\"`\n\tWorkDoneProgressOptions\n}\n\n// A parameter literal used in inlay hint requests.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#inlayHintParams\ntype InlayHintParams struct {\n\t// The text document.\n\tTextDocument TextDocumentIdentifier `json:\"textDocument\"`\n\t// The document range for which inlay hints should be computed.\n\tRange Range `json:\"range\"`\n\tWorkDoneProgressParams\n}\n\n// Inlay hint options used during static or dynamic registration.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#inlayHintRegistrationOptions\ntype InlayHintRegistrationOptions struct {\n\tInlayHintOptions\n\tTextDocumentRegistrationOptions\n\tStaticRegistrationOptions\n}\n\n// Client workspace capabilities specific to inlay hints.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#inlayHintWorkspaceClientCapabilities\ntype InlayHintWorkspaceClientCapabilities struct {\n\t// Whether the client implementation supports a refresh request sent from\n\t// the server to the client.\n\t//\n\t// Note that this event is global and will force the client to refresh all\n\t// inlay hints currently shown. It should be used with absolute care and\n\t// is useful for situation where a server for example detects a project wide\n\t// change that requires such a calculation.\n\tRefreshSupport bool `json:\"refreshSupport,omitempty\"`\n}\n\n// Client capabilities specific to inline completions.\n//\n// @since 3.18.0\n// @proposed\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#inlineCompletionClientCapabilities\ntype InlineCompletionClientCapabilities struct {\n\t// Whether implementation supports dynamic registration for inline completion providers.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n}\n\n// Provides information about the context in which an inline completion was requested.\n//\n// @since 3.18.0\n// @proposed\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#inlineCompletionContext\ntype InlineCompletionContext struct {\n\t// Describes how the inline completion was triggered.\n\tTriggerKind InlineCompletionTriggerKind `json:\"triggerKind\"`\n\t// Provides information about the currently selected item in the autocomplete widget if it is visible.\n\tSelectedCompletionInfo *SelectedCompletionInfo `json:\"selectedCompletionInfo,omitempty\"`\n}\n\n// An inline completion item represents a text snippet that is proposed inline to complete text that is being typed.\n//\n// @since 3.18.0\n// @proposed\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#inlineCompletionItem\ntype InlineCompletionItem struct {\n\t// The text to replace the range with. Must be set.\n\tInsertText Or_InlineCompletionItem_insertText `json:\"insertText\"`\n\t// A text that is used to decide if this inline completion should be shown. When `falsy` the {@link InlineCompletionItem.insertText} is used.\n\tFilterText string `json:\"filterText,omitempty\"`\n\t// The range to replace. Must begin and end on the same line.\n\tRange *Range `json:\"range,omitempty\"`\n\t// An optional {@link Command} that is executed *after* inserting this completion.\n\tCommand *Command `json:\"command,omitempty\"`\n}\n\n// Represents a collection of {@link InlineCompletionItem inline completion items} to be presented in the editor.\n//\n// @since 3.18.0\n// @proposed\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#inlineCompletionList\ntype InlineCompletionList struct {\n\t// The inline completion items\n\tItems []InlineCompletionItem `json:\"items\"`\n}\n\n// Inline completion options used during static registration.\n//\n// @since 3.18.0\n// @proposed\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#inlineCompletionOptions\ntype InlineCompletionOptions struct {\n\tWorkDoneProgressOptions\n}\n\n// A parameter literal used in inline completion requests.\n//\n// @since 3.18.0\n// @proposed\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#inlineCompletionParams\ntype InlineCompletionParams struct {\n\t// Additional information about the context in which inline completions were\n\t// requested.\n\tContext InlineCompletionContext `json:\"context\"`\n\tTextDocumentPositionParams\n\tWorkDoneProgressParams\n}\n\n// Inline completion options used during static or dynamic registration.\n//\n// @since 3.18.0\n// @proposed\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#inlineCompletionRegistrationOptions\ntype InlineCompletionRegistrationOptions struct {\n\tInlineCompletionOptions\n\tTextDocumentRegistrationOptions\n\tStaticRegistrationOptions\n}\n\n// Describes how an {@link InlineCompletionItemProvider inline completion provider} was triggered.\n//\n// @since 3.18.0\n// @proposed\ntype InlineCompletionTriggerKind uint32\n\n// Inline value information can be provided by different means:\n//\n// - directly as a text value (class InlineValueText).\n// - as a name to use for a variable lookup (class InlineValueVariableLookup)\n// - as an evaluatable expression (class InlineValueEvaluatableExpression)\n//\n// The InlineValue types combines all inline value types into one type.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#inlineValue\ntype InlineValue = Or_InlineValue // (alias)\n// Client capabilities specific to inline values.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#inlineValueClientCapabilities\ntype InlineValueClientCapabilities struct {\n\t// Whether implementation supports dynamic registration for inline value providers.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n}\n\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#inlineValueContext\ntype InlineValueContext struct {\n\t// The stack frame (as a DAP Id) where the execution has stopped.\n\tFrameID int32 `json:\"frameId\"`\n\t// The document range where execution has stopped.\n\t// Typically the end position of the range denotes the line where the inline values are shown.\n\tStoppedLocation Range `json:\"stoppedLocation\"`\n}\n\n// Provide an inline value through an expression evaluation.\n// If only a range is specified, the expression will be extracted from the underlying document.\n// An optional expression can be used to override the extracted expression.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#inlineValueEvaluatableExpression\ntype InlineValueEvaluatableExpression struct {\n\t// The document range for which the inline value applies.\n\t// The range is used to extract the evaluatable expression from the underlying document.\n\tRange Range `json:\"range\"`\n\t// If specified the expression overrides the extracted expression.\n\tExpression string `json:\"expression,omitempty\"`\n}\n\n// Inline value options used during static registration.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#inlineValueOptions\ntype InlineValueOptions struct {\n\tWorkDoneProgressOptions\n}\n\n// A parameter literal used in inline value requests.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#inlineValueParams\ntype InlineValueParams struct {\n\t// The text document.\n\tTextDocument TextDocumentIdentifier `json:\"textDocument\"`\n\t// The document range for which inline values should be computed.\n\tRange Range `json:\"range\"`\n\t// Additional information about the context in which inline values were\n\t// requested.\n\tContext InlineValueContext `json:\"context\"`\n\tWorkDoneProgressParams\n}\n\n// Inline value options used during static or dynamic registration.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#inlineValueRegistrationOptions\ntype InlineValueRegistrationOptions struct {\n\tInlineValueOptions\n\tTextDocumentRegistrationOptions\n\tStaticRegistrationOptions\n}\n\n// Provide inline value as text.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#inlineValueText\ntype InlineValueText struct {\n\t// The document range for which the inline value applies.\n\tRange Range `json:\"range\"`\n\t// The text of the inline value.\n\tText string `json:\"text\"`\n}\n\n// Provide inline value through a variable lookup.\n// If only a range is specified, the variable name will be extracted from the underlying document.\n// An optional variable name can be used to override the extracted name.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#inlineValueVariableLookup\ntype InlineValueVariableLookup struct {\n\t// The document range for which the inline value applies.\n\t// The range is used to extract the variable name from the underlying document.\n\tRange Range `json:\"range\"`\n\t// If specified the name of the variable to look up.\n\tVariableName string `json:\"variableName,omitempty\"`\n\t// How to perform the lookup.\n\tCaseSensitiveLookup bool `json:\"caseSensitiveLookup\"`\n}\n\n// Client workspace capabilities specific to inline values.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#inlineValueWorkspaceClientCapabilities\ntype InlineValueWorkspaceClientCapabilities struct {\n\t// Whether the client implementation supports a refresh request sent from the\n\t// server to the client.\n\t//\n\t// Note that this event is global and will force the client to refresh all\n\t// inline values currently shown. It should be used with absolute care and is\n\t// useful for situation where a server for example detects a project wide\n\t// change that requires such a calculation.\n\tRefreshSupport bool `json:\"refreshSupport,omitempty\"`\n}\n\n// A special text edit to provide an insert and a replace operation.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#insertReplaceEdit\ntype InsertReplaceEdit struct {\n\t// The string to be inserted.\n\tNewText string `json:\"newText\"`\n\t// The range if the insert is requested\n\tInsert Range `json:\"insert\"`\n\t// The range if the replace is requested.\n\tReplace Range `json:\"replace\"`\n}\n\n// Defines whether the insert text in a completion item should be interpreted as\n// plain text or a snippet.\ntype InsertTextFormat uint32\n\n// How whitespace and indentation is handled during completion\n// item insertion.\n//\n// @since 3.16.0\ntype InsertTextMode uint32\ntype LSPAny = interface{}\n\n// LSP arrays.\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#lSPArray\ntype LSPArray = []interface{} // (alias)\ntype LSPErrorCodes int32\n\n// LSP object definition.\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#lSPObject\ntype LSPObject = map[string]LSPAny // (alias)\n// Predefined Language kinds\n// @since 3.18.0\n// @proposed\ntype LanguageKind string\n\n// Client capabilities for the linked editing range request.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#linkedEditingRangeClientCapabilities\ntype LinkedEditingRangeClientCapabilities struct {\n\t// Whether implementation supports dynamic registration. If this is set to `true`\n\t// the client supports the new `(TextDocumentRegistrationOptions & StaticRegistrationOptions)`\n\t// return value for the corresponding server capability as well.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#linkedEditingRangeOptions\ntype LinkedEditingRangeOptions struct {\n\tWorkDoneProgressOptions\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#linkedEditingRangeParams\ntype LinkedEditingRangeParams struct {\n\tTextDocumentPositionParams\n\tWorkDoneProgressParams\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#linkedEditingRangeRegistrationOptions\ntype LinkedEditingRangeRegistrationOptions struct {\n\tTextDocumentRegistrationOptions\n\tLinkedEditingRangeOptions\n\tStaticRegistrationOptions\n}\n\n// The result of a linked editing range request.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#linkedEditingRanges\ntype LinkedEditingRanges struct {\n\t// A list of ranges that can be edited together. The ranges must have\n\t// identical length and contain identical text content. The ranges cannot overlap.\n\tRanges []Range `json:\"ranges\"`\n\t// An optional word pattern (regular expression) that describes valid contents for\n\t// the given ranges. If no pattern is provided, the client configuration's word\n\t// pattern will be used.\n\tWordPattern string `json:\"wordPattern,omitempty\"`\n}\n\n// created for Literal (Lit_ClientSemanticTokensRequestOptions_range_Item1)\ntype Lit_ClientSemanticTokensRequestOptions_range_Item1 struct {\n}\n\n// created for Literal (Lit_SemanticTokensOptions_range_Item1)\ntype Lit_SemanticTokensOptions_range_Item1 struct {\n}\n\n// Represents a location inside a resource, such as a line\n// inside a text file.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#location\ntype Location struct {\n\tURI DocumentUri `json:\"uri\"`\n\tRange Range `json:\"range\"`\n}\n\n// Represents the connection of two locations. Provides additional metadata over normal {@link Location locations},\n// including an origin range.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#locationLink\ntype LocationLink struct {\n\t// Span of the origin of this link.\n\t//\n\t// Used as the underlined span for mouse interaction. Defaults to the word range at\n\t// the definition position.\n\tOriginSelectionRange *Range `json:\"originSelectionRange,omitempty\"`\n\t// The target resource identifier of this link.\n\tTargetURI DocumentUri `json:\"targetUri\"`\n\t// The full target range of this link. If the target for example is a symbol then target range is the\n\t// range enclosing this symbol not including leading/trailing whitespace but everything else\n\t// like comments. This information is typically used to highlight the range in the editor.\n\tTargetRange Range `json:\"targetRange\"`\n\t// The range that should be selected and revealed when this link is being followed, e.g the name of a function.\n\t// Must be contained by the `targetRange`. See also `DocumentSymbol#range`\n\tTargetSelectionRange Range `json:\"targetSelectionRange\"`\n}\n\n// Location with only uri and does not include range.\n//\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#locationUriOnly\ntype LocationUriOnly struct {\n\tURI DocumentUri `json:\"uri\"`\n}\n\n// The log message parameters.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#logMessageParams\ntype LogMessageParams struct {\n\t// The message type. See {@link MessageType}\n\tType MessageType `json:\"type\"`\n\t// The actual message.\n\tMessage string `json:\"message\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#logTraceParams\ntype LogTraceParams struct {\n\tMessage string `json:\"message\"`\n\tVerbose string `json:\"verbose,omitempty\"`\n}\n\n// Client capabilities specific to the used markdown parser.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#markdownClientCapabilities\ntype MarkdownClientCapabilities struct {\n\t// The name of the parser.\n\tParser string `json:\"parser\"`\n\t// The version of the parser.\n\tVersion string `json:\"version,omitempty\"`\n\t// A list of HTML tags that the client allows / supports in\n\t// Markdown.\n\t//\n\t// @since 3.17.0\n\tAllowedTags []string `json:\"allowedTags,omitempty\"`\n}\n\n// MarkedString can be used to render human readable text. It is either a markdown string\n// or a code-block that provides a language and a code snippet. The language identifier\n// is semantically equal to the optional language identifier in fenced code blocks in GitHub\n// issues. See https://help.github.com/articles/creating-and-highlighting-code-blocks/#syntax-highlighting\n//\n// The pair of a language and a value is an equivalent to markdown:\n// ```${language}\n// ${value}\n// ```\n//\n// Note that markdown strings will be sanitized - that means html will be escaped.\n// @deprecated use MarkupContent instead.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#markedString\ntype MarkedString = Or_MarkedString // (alias)\n// @since 3.18.0\n// @deprecated use MarkupContent instead.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#markedStringWithLanguage\ntype MarkedStringWithLanguage struct {\n\tLanguage string `json:\"language\"`\n\tValue string `json:\"value\"`\n}\n\n// A `MarkupContent` literal represents a string value which content is interpreted base on its\n// kind flag. Currently the protocol supports `plaintext` and `markdown` as markup kinds.\n//\n// If the kind is `markdown` then the value can contain fenced code blocks like in GitHub issues.\n// See https://help.github.com/articles/creating-and-highlighting-code-blocks/#syntax-highlighting\n//\n// Here is an example how such a string can be constructed using JavaScript / TypeScript:\n// ```ts\n//\n//\tlet markdown: MarkdownContent = {\n//\t kind: MarkupKind.Markdown,\n//\t value: [\n//\t '# Header',\n//\t 'Some text',\n//\t '```typescript',\n//\t 'someCode();',\n//\t '```'\n//\t ].join('\\n')\n//\t};\n//\n// ```\n//\n// *Please Note* that clients might sanitize the return markdown. A client could decide to\n// remove HTML from the markdown to avoid script execution.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#markupContent\ntype MarkupContent struct {\n\t// The type of the Markup\n\tKind MarkupKind `json:\"kind\"`\n\t// The content itself\n\tValue string `json:\"value\"`\n}\n\n// Describes the content type that a client supports in various\n// result literals like `Hover`, `ParameterInfo` or `CompletionItem`.\n//\n// Please note that `MarkupKinds` must not start with a `$`. This kinds\n// are reserved for internal usage.\ntype MarkupKind string\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#messageActionItem\ntype MessageActionItem struct {\n\t// A short title like 'Retry', 'Open Log' etc.\n\tTitle string `json:\"title\"`\n}\n\n// The message type\ntype MessageType uint32\n\n// Moniker definition to match LSIF 0.5 moniker definition.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#moniker\ntype Moniker struct {\n\t// The scheme of the moniker. For example tsc or .Net\n\tScheme string `json:\"scheme\"`\n\t// The identifier of the moniker. The value is opaque in LSIF however\n\t// schema owners are allowed to define the structure if they want.\n\tIdentifier string `json:\"identifier\"`\n\t// The scope in which the moniker is unique\n\tUnique UniquenessLevel `json:\"unique\"`\n\t// The moniker kind if known.\n\tKind *MonikerKind `json:\"kind,omitempty\"`\n}\n\n// Client capabilities specific to the moniker request.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#monikerClientCapabilities\ntype MonikerClientCapabilities struct {\n\t// Whether moniker supports dynamic registration. If this is set to `true`\n\t// the client supports the new `MonikerRegistrationOptions` return value\n\t// for the corresponding server capability as well.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n}\n\n// The moniker kind.\n//\n// @since 3.16.0\ntype MonikerKind string\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#monikerOptions\ntype MonikerOptions struct {\n\tWorkDoneProgressOptions\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#monikerParams\ntype MonikerParams struct {\n\tTextDocumentPositionParams\n\tWorkDoneProgressParams\n\tPartialResultParams\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#monikerRegistrationOptions\ntype MonikerRegistrationOptions struct {\n\tTextDocumentRegistrationOptions\n\tMonikerOptions\n}\n\n// A notebook cell.\n//\n// A cell's document URI must be unique across ALL notebook\n// cells and can therefore be used to uniquely identify a\n// notebook cell or the cell's text document.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#notebookCell\ntype NotebookCell struct {\n\t// The cell's kind\n\tKind NotebookCellKind `json:\"kind\"`\n\t// The URI of the cell's text document\n\t// content.\n\tDocument DocumentUri `json:\"document\"`\n\t// Additional metadata stored with the cell.\n\t//\n\t// Note: should always be an object literal (e.g. LSPObject)\n\tMetadata *LSPObject `json:\"metadata,omitempty\"`\n\t// Additional execution summary information\n\t// if supported by the client.\n\tExecutionSummary *ExecutionSummary `json:\"executionSummary,omitempty\"`\n}\n\n// A change describing how to move a `NotebookCell`\n// array from state S to S'.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#notebookCellArrayChange\ntype NotebookCellArrayChange struct {\n\t// The start oftest of the cell that changed.\n\tStart uint32 `json:\"start\"`\n\t// The deleted cells\n\tDeleteCount uint32 `json:\"deleteCount\"`\n\t// The new cells, if any\n\tCells []NotebookCell `json:\"cells,omitempty\"`\n}\n\n// A notebook cell kind.\n//\n// @since 3.17.0\ntype NotebookCellKind uint32\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#notebookCellLanguage\ntype NotebookCellLanguage struct {\n\tLanguage string `json:\"language\"`\n}\n\n// A notebook cell text document filter denotes a cell text\n// document by different properties.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#notebookCellTextDocumentFilter\ntype NotebookCellTextDocumentFilter struct {\n\t// A filter that matches against the notebook\n\t// containing the notebook cell. If a string\n\t// value is provided it matches against the\n\t// notebook type. '*' matches every notebook.\n\tNotebook Or_NotebookCellTextDocumentFilter_notebook `json:\"notebook\"`\n\t// A language id like `python`.\n\t//\n\t// Will be matched against the language id of the\n\t// notebook cell document. '*' matches every language.\n\tLanguage string `json:\"language,omitempty\"`\n}\n\n// A notebook document.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#notebookDocument\ntype NotebookDocument struct {\n\t// The notebook document's uri.\n\tURI URI `json:\"uri\"`\n\t// The type of the notebook.\n\tNotebookType string `json:\"notebookType\"`\n\t// The version number of this document (it will increase after each\n\t// change, including undo/redo).\n\tVersion int32 `json:\"version\"`\n\t// Additional metadata stored with the notebook\n\t// document.\n\t//\n\t// Note: should always be an object literal (e.g. LSPObject)\n\tMetadata *LSPObject `json:\"metadata,omitempty\"`\n\t// The cells of a notebook.\n\tCells []NotebookCell `json:\"cells\"`\n}\n\n// Structural changes to cells in a notebook document.\n//\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#notebookDocumentCellChangeStructure\ntype NotebookDocumentCellChangeStructure struct {\n\t// The change to the cell array.\n\tArray NotebookCellArrayChange `json:\"array\"`\n\t// Additional opened cell text documents.\n\tDidOpen []TextDocumentItem `json:\"didOpen,omitempty\"`\n\t// Additional closed cell text documents.\n\tDidClose []TextDocumentIdentifier `json:\"didClose,omitempty\"`\n}\n\n// Cell changes to a notebook document.\n//\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#notebookDocumentCellChanges\ntype NotebookDocumentCellChanges struct {\n\t// Changes to the cell structure to add or\n\t// remove cells.\n\tStructure *NotebookDocumentCellChangeStructure `json:\"structure,omitempty\"`\n\t// Changes to notebook cells properties like its\n\t// kind, execution summary or metadata.\n\tData []NotebookCell `json:\"data,omitempty\"`\n\t// Changes to the text content of notebook cells.\n\tTextContent []NotebookDocumentCellContentChanges `json:\"textContent,omitempty\"`\n}\n\n// Content changes to a cell in a notebook document.\n//\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#notebookDocumentCellContentChanges\ntype NotebookDocumentCellContentChanges struct {\n\tDocument VersionedTextDocumentIdentifier `json:\"document\"`\n\tChanges []TextDocumentContentChangeEvent `json:\"changes\"`\n}\n\n// A change event for a notebook document.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#notebookDocumentChangeEvent\ntype NotebookDocumentChangeEvent struct {\n\t// The changed meta data if any.\n\t//\n\t// Note: should always be an object literal (e.g. LSPObject)\n\tMetadata *LSPObject `json:\"metadata,omitempty\"`\n\t// Changes to cells\n\tCells *NotebookDocumentCellChanges `json:\"cells,omitempty\"`\n}\n\n// Capabilities specific to the notebook document support.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#notebookDocumentClientCapabilities\ntype NotebookDocumentClientCapabilities struct {\n\t// Capabilities specific to notebook document synchronization\n\t//\n\t// @since 3.17.0\n\tSynchronization NotebookDocumentSyncClientCapabilities `json:\"synchronization\"`\n}\n\n// A notebook document filter denotes a notebook document by\n// different properties. The properties will be match\n// against the notebook's URI (same as with documents)\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#notebookDocumentFilter\ntype NotebookDocumentFilter = Or_NotebookDocumentFilter // (alias)\n// A notebook document filter where `notebookType` is required field.\n//\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#notebookDocumentFilterNotebookType\ntype NotebookDocumentFilterNotebookType struct {\n\t// The type of the enclosing notebook.\n\tNotebookType string `json:\"notebookType\"`\n\t// A Uri {@link Uri.scheme scheme}, like `file` or `untitled`.\n\tScheme string `json:\"scheme,omitempty\"`\n\t// A glob pattern.\n\tPattern *GlobPattern `json:\"pattern,omitempty\"`\n}\n\n// A notebook document filter where `pattern` is required field.\n//\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#notebookDocumentFilterPattern\ntype NotebookDocumentFilterPattern struct {\n\t// The type of the enclosing notebook.\n\tNotebookType string `json:\"notebookType,omitempty\"`\n\t// A Uri {@link Uri.scheme scheme}, like `file` or `untitled`.\n\tScheme string `json:\"scheme,omitempty\"`\n\t// A glob pattern.\n\tPattern GlobPattern `json:\"pattern\"`\n}\n\n// A notebook document filter where `scheme` is required field.\n//\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#notebookDocumentFilterScheme\ntype NotebookDocumentFilterScheme struct {\n\t// The type of the enclosing notebook.\n\tNotebookType string `json:\"notebookType,omitempty\"`\n\t// A Uri {@link Uri.scheme scheme}, like `file` or `untitled`.\n\tScheme string `json:\"scheme\"`\n\t// A glob pattern.\n\tPattern *GlobPattern `json:\"pattern,omitempty\"`\n}\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#notebookDocumentFilterWithCells\ntype NotebookDocumentFilterWithCells struct {\n\t// The notebook to be synced If a string\n\t// value is provided it matches against the\n\t// notebook type. '*' matches every notebook.\n\tNotebook *Or_NotebookDocumentFilterWithCells_notebook `json:\"notebook,omitempty\"`\n\t// The cells of the matching notebook to be synced.\n\tCells []NotebookCellLanguage `json:\"cells\"`\n}\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#notebookDocumentFilterWithNotebook\ntype NotebookDocumentFilterWithNotebook struct {\n\t// The notebook to be synced If a string\n\t// value is provided it matches against the\n\t// notebook type. '*' matches every notebook.\n\tNotebook Or_NotebookDocumentFilterWithNotebook_notebook `json:\"notebook\"`\n\t// The cells of the matching notebook to be synced.\n\tCells []NotebookCellLanguage `json:\"cells,omitempty\"`\n}\n\n// A literal to identify a notebook document in the client.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#notebookDocumentIdentifier\ntype NotebookDocumentIdentifier struct {\n\t// The notebook document's uri.\n\tURI URI `json:\"uri\"`\n}\n\n// Notebook specific client capabilities.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#notebookDocumentSyncClientCapabilities\ntype NotebookDocumentSyncClientCapabilities struct {\n\t// Whether implementation supports dynamic registration. If this is\n\t// set to `true` the client supports the new\n\t// `(TextDocumentRegistrationOptions & StaticRegistrationOptions)`\n\t// return value for the corresponding server capability as well.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n\t// The client supports sending execution summary data per cell.\n\tExecutionSummarySupport bool `json:\"executionSummarySupport,omitempty\"`\n}\n\n// Options specific to a notebook plus its cells\n// to be synced to the server.\n//\n// If a selector provides a notebook document\n// filter but no cell selector all cells of a\n// matching notebook document will be synced.\n//\n// If a selector provides no notebook document\n// filter but only a cell selector all notebook\n// document that contain at least one matching\n// cell will be synced.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#notebookDocumentSyncOptions\ntype NotebookDocumentSyncOptions struct {\n\t// The notebooks to be synced\n\tNotebookSelector []Or_NotebookDocumentSyncOptions_notebookSelector_Elem `json:\"notebookSelector\"`\n\t// Whether save notification should be forwarded to\n\t// the server. Will only be honored if mode === `notebook`.\n\tSave bool `json:\"save,omitempty\"`\n}\n\n// Registration options specific to a notebook.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#notebookDocumentSyncRegistrationOptions\ntype NotebookDocumentSyncRegistrationOptions struct {\n\tNotebookDocumentSyncOptions\n\tStaticRegistrationOptions\n}\n\n// A text document identifier to optionally denote a specific version of a text document.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#optionalVersionedTextDocumentIdentifier\ntype OptionalVersionedTextDocumentIdentifier struct {\n\t// The version number of this document. If a versioned text document identifier\n\t// is sent from the server to the client and the file is not open in the editor\n\t// (the server has not received an open notification before) the server can send\n\t// `null` to indicate that the version is unknown and the content on disk is the\n\t// truth (as specified with document content ownership).\n\tVersion int32 `json:\"version\"`\n\tTextDocumentIdentifier\n}\n\n// created for Or [int32 string]\ntype Or_CancelParams_id struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [ClientSemanticTokensRequestFullDelta bool]\ntype Or_ClientSemanticTokensRequestOptions_full struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [Lit_ClientSemanticTokensRequestOptions_range_Item1 bool]\ntype Or_ClientSemanticTokensRequestOptions_range struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [EditRangeWithInsertReplace Range]\ntype Or_CompletionItemDefaults_editRange struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [MarkupContent string]\ntype Or_CompletionItem_documentation struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [InsertReplaceEdit TextEdit]\ntype Or_CompletionItem_textEdit struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [Location []Location]\ntype Or_Declaration struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [Location []Location]\ntype Or_Definition struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [int32 string]\ntype Or_Diagnostic_code struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [[]string string]\ntype Or_DidChangeConfigurationRegistrationOptions_section struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [RelatedFullDocumentDiagnosticReport RelatedUnchangedDocumentDiagnosticReport]\ntype Or_DocumentDiagnosticReport struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [FullDocumentDiagnosticReport UnchangedDocumentDiagnosticReport]\ntype Or_DocumentDiagnosticReportPartialResult_relatedDocuments_Value struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [NotebookCellTextDocumentFilter TextDocumentFilter]\ntype Or_DocumentFilter struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [Pattern RelativePattern]\ntype Or_GlobPattern struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [MarkedString MarkupContent []MarkedString]\ntype Or_Hover_contents struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [MarkupContent string]\ntype Or_InlayHintLabelPart_tooltip struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [[]InlayHintLabelPart string]\ntype Or_InlayHint_label struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [MarkupContent string]\ntype Or_InlayHint_tooltip struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [StringValue string]\ntype Or_InlineCompletionItem_insertText struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [InlineValueEvaluatableExpression InlineValueText InlineValueVariableLookup]\ntype Or_InlineValue struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [LSPArray LSPObject bool float64 int32 string uint32]\ntype Or_LSPAny struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [MarkedStringWithLanguage string]\ntype Or_MarkedString struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [NotebookDocumentFilter string]\ntype Or_NotebookCellTextDocumentFilter_notebook struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [NotebookDocumentFilterNotebookType NotebookDocumentFilterPattern NotebookDocumentFilterScheme]\ntype Or_NotebookDocumentFilter struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [NotebookDocumentFilter string]\ntype Or_NotebookDocumentFilterWithCells_notebook struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [NotebookDocumentFilter string]\ntype Or_NotebookDocumentFilterWithNotebook_notebook struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [NotebookDocumentFilterWithCells NotebookDocumentFilterWithNotebook]\ntype Or_NotebookDocumentSyncOptions_notebookSelector_Elem struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [MarkupContent string]\ntype Or_ParameterInformation_documentation struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [Tuple_ParameterInformation_label_Item1 string]\ntype Or_ParameterInformation_label struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [PrepareRenameDefaultBehavior PrepareRenamePlaceholder Range]\ntype Or_PrepareRenameResult struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [int32 string]\ntype Or_ProgressToken struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [FullDocumentDiagnosticReport UnchangedDocumentDiagnosticReport]\ntype Or_RelatedFullDocumentDiagnosticReport_relatedDocuments_Value struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [FullDocumentDiagnosticReport UnchangedDocumentDiagnosticReport]\ntype Or_RelatedUnchangedDocumentDiagnosticReport_relatedDocuments_Value struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [URI WorkspaceFolder]\ntype Or_RelativePattern_baseUri struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [CodeAction Command]\ntype Or_Result_textDocument_codeAction_Item0_Elem struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [CompletionList []CompletionItem]\ntype Or_Result_textDocument_completion struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [Declaration []DeclarationLink]\ntype Or_Result_textDocument_declaration struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [Definition []DefinitionLink]\ntype Or_Result_textDocument_definition struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [[]DocumentSymbol []SymbolInformation]\ntype Or_Result_textDocument_documentSymbol struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [Definition []DefinitionLink]\ntype Or_Result_textDocument_implementation struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [InlineCompletionList []InlineCompletionItem]\ntype Or_Result_textDocument_inlineCompletion struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [SemanticTokens SemanticTokensDelta]\ntype Or_Result_textDocument_semanticTokens_full_delta struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [Definition []DefinitionLink]\ntype Or_Result_textDocument_typeDefinition struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [[]SymbolInformation []WorkspaceSymbol]\ntype Or_Result_workspace_symbol struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [SemanticTokensFullDelta bool]\ntype Or_SemanticTokensOptions_full struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [Lit_SemanticTokensOptions_range_Item1 bool]\ntype Or_SemanticTokensOptions_range struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [CallHierarchyOptions CallHierarchyRegistrationOptions bool]\ntype Or_ServerCapabilities_callHierarchyProvider struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [CodeActionOptions bool]\ntype Or_ServerCapabilities_codeActionProvider struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [DocumentColorOptions DocumentColorRegistrationOptions bool]\ntype Or_ServerCapabilities_colorProvider struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [DeclarationOptions DeclarationRegistrationOptions bool]\ntype Or_ServerCapabilities_declarationProvider struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [DefinitionOptions bool]\ntype Or_ServerCapabilities_definitionProvider struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [DiagnosticOptions DiagnosticRegistrationOptions]\ntype Or_ServerCapabilities_diagnosticProvider struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [DocumentFormattingOptions bool]\ntype Or_ServerCapabilities_documentFormattingProvider struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [DocumentHighlightOptions bool]\ntype Or_ServerCapabilities_documentHighlightProvider struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [DocumentRangeFormattingOptions bool]\ntype Or_ServerCapabilities_documentRangeFormattingProvider struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [DocumentSymbolOptions bool]\ntype Or_ServerCapabilities_documentSymbolProvider struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [FoldingRangeOptions FoldingRangeRegistrationOptions bool]\ntype Or_ServerCapabilities_foldingRangeProvider struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [HoverOptions bool]\ntype Or_ServerCapabilities_hoverProvider struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [ImplementationOptions ImplementationRegistrationOptions bool]\ntype Or_ServerCapabilities_implementationProvider struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [InlayHintOptions InlayHintRegistrationOptions bool]\ntype Or_ServerCapabilities_inlayHintProvider struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [InlineCompletionOptions bool]\ntype Or_ServerCapabilities_inlineCompletionProvider struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [InlineValueOptions InlineValueRegistrationOptions bool]\ntype Or_ServerCapabilities_inlineValueProvider struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [LinkedEditingRangeOptions LinkedEditingRangeRegistrationOptions bool]\ntype Or_ServerCapabilities_linkedEditingRangeProvider struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [MonikerOptions MonikerRegistrationOptions bool]\ntype Or_ServerCapabilities_monikerProvider struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [NotebookDocumentSyncOptions NotebookDocumentSyncRegistrationOptions]\ntype Or_ServerCapabilities_notebookDocumentSync struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [ReferenceOptions bool]\ntype Or_ServerCapabilities_referencesProvider struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [RenameOptions bool]\ntype Or_ServerCapabilities_renameProvider struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [SelectionRangeOptions SelectionRangeRegistrationOptions bool]\ntype Or_ServerCapabilities_selectionRangeProvider struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [SemanticTokensOptions SemanticTokensRegistrationOptions]\ntype Or_ServerCapabilities_semanticTokensProvider struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [TextDocumentSyncKind TextDocumentSyncOptions]\ntype Or_ServerCapabilities_textDocumentSync struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [TypeDefinitionOptions TypeDefinitionRegistrationOptions bool]\ntype Or_ServerCapabilities_typeDefinitionProvider struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [TypeHierarchyOptions TypeHierarchyRegistrationOptions bool]\ntype Or_ServerCapabilities_typeHierarchyProvider struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [WorkspaceSymbolOptions bool]\ntype Or_ServerCapabilities_workspaceSymbolProvider struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [MarkupContent string]\ntype Or_SignatureInformation_documentation struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [TextDocumentContentChangePartial TextDocumentContentChangeWholeDocument]\ntype Or_TextDocumentContentChangeEvent struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [AnnotatedTextEdit SnippetTextEdit TextEdit]\ntype Or_TextDocumentEdit_edits_Elem struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [TextDocumentFilterLanguage TextDocumentFilterPattern TextDocumentFilterScheme]\ntype Or_TextDocumentFilter struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [SaveOptions bool]\ntype Or_TextDocumentSyncOptions_save struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [WorkspaceFullDocumentDiagnosticReport WorkspaceUnchangedDocumentDiagnosticReport]\ntype Or_WorkspaceDocumentDiagnosticReport struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [CreateFile DeleteFile RenameFile TextDocumentEdit]\ntype Or_WorkspaceEdit_documentChanges_Elem struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [bool string]\ntype Or_WorkspaceFoldersServerCapabilities_changeNotifications struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [TextDocumentContentOptions TextDocumentContentRegistrationOptions]\ntype Or_WorkspaceOptions_textDocumentContent struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [Location LocationUriOnly]\ntype Or_WorkspaceSymbol_location struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// The parameters of a configuration request.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#configurationParams\ntype ParamConfiguration struct {\n\tItems []ConfigurationItem `json:\"items\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#initializeParams\ntype ParamInitialize struct {\n\tXInitializeParams\n\tWorkspaceFoldersInitializeParams\n}\n\n// Represents a parameter of a callable-signature. A parameter can\n// have a label and a doc-comment.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#parameterInformation\ntype ParameterInformation struct {\n\t// The label of this parameter information.\n\t//\n\t// Either a string or an inclusive start and exclusive end offsets within its containing\n\t// signature label. (see SignatureInformation.label). The offsets are based on a UTF-16\n\t// string representation as `Position` and `Range` does.\n\t//\n\t// To avoid ambiguities a server should use the [start, end] offset value instead of using\n\t// a substring. Whether a client support this is controlled via `labelOffsetSupport` client\n\t// capability.\n\t//\n\t// *Note*: a label of type string should be a substring of its containing signature label.\n\t// Its intended use case is to highlight the parameter label part in the `SignatureInformation.label`.\n\tLabel Or_ParameterInformation_label `json:\"label\"`\n\t// The human-readable doc-comment of this parameter. Will be shown\n\t// in the UI but can be omitted.\n\tDocumentation *Or_ParameterInformation_documentation `json:\"documentation,omitempty\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#partialResultParams\ntype PartialResultParams struct {\n\t// An optional token that a server can use to report partial results (e.g. streaming) to\n\t// the client.\n\tPartialResultToken *ProgressToken `json:\"partialResultToken,omitempty\"`\n}\n\n// The glob pattern to watch relative to the base path. Glob patterns can have the following syntax:\n//\n// - `*` to match one or more characters in a path segment\n// - `?` to match on one character in a path segment\n// - `**` to match any number of path segments, including none\n// - `{}` to group conditions (e.g. `**/*.{ts,js}` matches all TypeScript and JavaScript files)\n// - `[]` to declare a range of characters to match in a path segment (e.g., `example.[0-9]` to match on `example.0`, `example.1`, …)\n// - `[!...]` to negate a range of characters to match in a path segment (e.g., `example.[!0-9]` to match on `example.a`, `example.b`, but not `example.0`)\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#pattern\ntype Pattern = string // (alias)\n// Position in a text document expressed as zero-based line and character\n// offset. Prior to 3.17 the offsets were always based on a UTF-16 string\n// representation. So a string of the form `a𐐀b` the character offset of the\n// character `a` is 0, the character offset of `𐐀` is 1 and the character\n// offset of b is 3 since `𐐀` is represented using two code units in UTF-16.\n// Since 3.17 clients and servers can agree on a different string encoding\n// representation (e.g. UTF-8). The client announces it's supported encoding\n// via the client capability [`general.positionEncodings`](https://microsoft.github.io/language-server-protocol/specifications/specification-current/#clientCapabilities).\n// The value is an array of position encodings the client supports, with\n// decreasing preference (e.g. the encoding at index `0` is the most preferred\n// one). To stay backwards compatible the only mandatory encoding is UTF-16\n// represented via the string `utf-16`. The server can pick one of the\n// encodings offered by the client and signals that encoding back to the\n// client via the initialize result's property\n// [`capabilities.positionEncoding`](https://microsoft.github.io/language-server-protocol/specifications/specification-current/#serverCapabilities). If the string value\n// `utf-16` is missing from the client's capability `general.positionEncodings`\n// servers can safely assume that the client supports UTF-16. If the server\n// omits the position encoding in its initialize result the encoding defaults\n// to the string value `utf-16`. Implementation considerations: since the\n// conversion from one encoding into another requires the content of the\n// file / line the conversion is best done where the file is read which is\n// usually on the server side.\n//\n// Positions are line end character agnostic. So you can not specify a position\n// that denotes `\\r|\\n` or `\\n|` where `|` represents the character offset.\n//\n// @since 3.17.0 - support for negotiated position encoding.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#position\ntype Position struct {\n\t// Line position in a document (zero-based).\n\t//\n\t// If a line number is greater than the number of lines in a document, it defaults back to the number of lines in the document.\n\t// If a line number is negative, it defaults to 0.\n\tLine uint32 `json:\"line\"`\n\t// Character offset on a line in a document (zero-based).\n\t//\n\t// The meaning of this offset is determined by the negotiated\n\t// `PositionEncodingKind`.\n\t//\n\t// If the character value is greater than the line length it defaults back to the\n\t// line length.\n\tCharacter uint32 `json:\"character\"`\n}\n\n// A set of predefined position encoding kinds.\n//\n// @since 3.17.0\ntype PositionEncodingKind string\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#prepareRenameDefaultBehavior\ntype PrepareRenameDefaultBehavior struct {\n\tDefaultBehavior bool `json:\"defaultBehavior\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#prepareRenameParams\ntype PrepareRenameParams struct {\n\tTextDocumentPositionParams\n\tWorkDoneProgressParams\n}\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#prepareRenamePlaceholder\ntype PrepareRenamePlaceholder struct {\n\tRange Range `json:\"range\"`\n\tPlaceholder string `json:\"placeholder\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#prepareRenameResult\ntype PrepareRenameResult = Or_PrepareRenameResult // (alias)\ntype PrepareSupportDefaultBehavior uint32\n\n// A previous result id in a workspace pull request.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#previousResultId\ntype PreviousResultID struct {\n\t// The URI for which the client knowns a\n\t// result id.\n\tURI DocumentUri `json:\"uri\"`\n\t// The value of the previous result id.\n\tValue string `json:\"value\"`\n}\n\n// A previous result id in a workspace pull request.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#previousResultId\ntype PreviousResultId struct {\n\t// The URI for which the client knowns a\n\t// result id.\n\tURI DocumentUri `json:\"uri\"`\n\t// The value of the previous result id.\n\tValue string `json:\"value\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#progressParams\ntype ProgressParams struct {\n\t// The progress token provided by the client or server.\n\tToken ProgressToken `json:\"token\"`\n\t// The progress data.\n\tValue interface{} `json:\"value\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#progressToken\ntype ProgressToken = Or_ProgressToken // (alias)\n// The publish diagnostic client capabilities.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#publishDiagnosticsClientCapabilities\ntype PublishDiagnosticsClientCapabilities struct {\n\t// Whether the client interprets the version property of the\n\t// `textDocument/publishDiagnostics` notification's parameter.\n\t//\n\t// @since 3.15.0\n\tVersionSupport bool `json:\"versionSupport,omitempty\"`\n\tDiagnosticsCapabilities\n}\n\n// The publish diagnostic notification's parameters.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#publishDiagnosticsParams\ntype PublishDiagnosticsParams struct {\n\t// The URI for which diagnostic information is reported.\n\tURI DocumentUri `json:\"uri\"`\n\t// Optional the version number of the document the diagnostics are published for.\n\t//\n\t// @since 3.15.0\n\tVersion int32 `json:\"version,omitempty\"`\n\t// An array of diagnostic information items.\n\tDiagnostics []Diagnostic `json:\"diagnostics\"`\n}\n\n// A range in a text document expressed as (zero-based) start and end positions.\n//\n// If you want to specify a range that contains a line including the line ending\n// character(s) then use an end position denoting the start of the next line.\n// For example:\n// ```ts\n//\n//\t{\n//\t start: { line: 5, character: 23 }\n//\t end : { line 6, character : 0 }\n//\t}\n//\n// ```\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#range\ntype Range struct {\n\t// The range's start position.\n\tStart Position `json:\"start\"`\n\t// The range's end position.\n\tEnd Position `json:\"end\"`\n}\n\n// Client Capabilities for a {@link ReferencesRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#referenceClientCapabilities\ntype ReferenceClientCapabilities struct {\n\t// Whether references supports dynamic registration.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n}\n\n// Value-object that contains additional information when\n// requesting references.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#referenceContext\ntype ReferenceContext struct {\n\t// Include the declaration of the current symbol.\n\tIncludeDeclaration bool `json:\"includeDeclaration\"`\n}\n\n// Reference options.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#referenceOptions\ntype ReferenceOptions struct {\n\tWorkDoneProgressOptions\n}\n\n// Parameters for a {@link ReferencesRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#referenceParams\ntype ReferenceParams struct {\n\tContext ReferenceContext `json:\"context\"`\n\tTextDocumentPositionParams\n\tWorkDoneProgressParams\n\tPartialResultParams\n}\n\n// Registration options for a {@link ReferencesRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#referenceRegistrationOptions\ntype ReferenceRegistrationOptions struct {\n\tTextDocumentRegistrationOptions\n\tReferenceOptions\n}\n\n// General parameters to register for a notification or to register a provider.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#registration\ntype Registration struct {\n\t// The id used to register the request. The id can be used to deregister\n\t// the request again.\n\tID string `json:\"id\"`\n\t// The method / capability to register for.\n\tMethod string `json:\"method\"`\n\t// Options necessary for the registration.\n\tRegisterOptions interface{} `json:\"registerOptions,omitempty\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#registrationParams\ntype RegistrationParams struct {\n\tRegistrations []Registration `json:\"registrations\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#regularExpressionEngineKind\ntype RegularExpressionEngineKind = string // (alias)\n// Client capabilities specific to regular expressions.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#regularExpressionsClientCapabilities\ntype RegularExpressionsClientCapabilities struct {\n\t// The engine's name.\n\tEngine RegularExpressionEngineKind `json:\"engine\"`\n\t// The engine's version.\n\tVersion string `json:\"version,omitempty\"`\n}\n\n// A full diagnostic report with a set of related documents.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#relatedFullDocumentDiagnosticReport\ntype RelatedFullDocumentDiagnosticReport struct {\n\t// Diagnostics of related documents. This information is useful\n\t// in programming languages where code in a file A can generate\n\t// diagnostics in a file B which A depends on. An example of\n\t// such a language is C/C++ where marco definitions in a file\n\t// a.cpp and result in errors in a header file b.hpp.\n\t//\n\t// @since 3.17.0\n\tRelatedDocuments map[DocumentUri]interface{} `json:\"relatedDocuments,omitempty\"`\n\tFullDocumentDiagnosticReport\n}\n\n// An unchanged diagnostic report with a set of related documents.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#relatedUnchangedDocumentDiagnosticReport\ntype RelatedUnchangedDocumentDiagnosticReport struct {\n\t// Diagnostics of related documents. This information is useful\n\t// in programming languages where code in a file A can generate\n\t// diagnostics in a file B which A depends on. An example of\n\t// such a language is C/C++ where marco definitions in a file\n\t// a.cpp and result in errors in a header file b.hpp.\n\t//\n\t// @since 3.17.0\n\tRelatedDocuments map[DocumentUri]interface{} `json:\"relatedDocuments,omitempty\"`\n\tUnchangedDocumentDiagnosticReport\n}\n\n// A relative pattern is a helper to construct glob patterns that are matched\n// relatively to a base URI. The common value for a `baseUri` is a workspace\n// folder root, but it can be another absolute URI as well.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#relativePattern\ntype RelativePattern struct {\n\t// A workspace folder or a base URI to which this pattern will be matched\n\t// against relatively.\n\tBaseURI Or_RelativePattern_baseUri `json:\"baseUri\"`\n\t// The actual glob pattern;\n\tPattern Pattern `json:\"pattern\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#renameClientCapabilities\ntype RenameClientCapabilities struct {\n\t// Whether rename supports dynamic registration.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n\t// Client supports testing for validity of rename operations\n\t// before execution.\n\t//\n\t// @since 3.12.0\n\tPrepareSupport bool `json:\"prepareSupport,omitempty\"`\n\t// Client supports the default behavior result.\n\t//\n\t// The value indicates the default behavior used by the\n\t// client.\n\t//\n\t// @since 3.16.0\n\tPrepareSupportDefaultBehavior *PrepareSupportDefaultBehavior `json:\"prepareSupportDefaultBehavior,omitempty\"`\n\t// Whether the client honors the change annotations in\n\t// text edits and resource operations returned via the\n\t// rename request's workspace edit by for example presenting\n\t// the workspace edit in the user interface and asking\n\t// for confirmation.\n\t//\n\t// @since 3.16.0\n\tHonorsChangeAnnotations bool `json:\"honorsChangeAnnotations,omitempty\"`\n}\n\n// Rename file operation\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#renameFile\ntype RenameFile struct {\n\t// A rename\n\tKind string `json:\"kind\"`\n\t// The old (existing) location.\n\tOldURI DocumentUri `json:\"oldUri\"`\n\t// The new location.\n\tNewURI DocumentUri `json:\"newUri\"`\n\t// Rename options.\n\tOptions *RenameFileOptions `json:\"options,omitempty\"`\n\tResourceOperation\n}\n\n// Rename file options\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#renameFileOptions\ntype RenameFileOptions struct {\n\t// Overwrite target if existing. Overwrite wins over `ignoreIfExists`\n\tOverwrite bool `json:\"overwrite,omitempty\"`\n\t// Ignores if target exists.\n\tIgnoreIfExists bool `json:\"ignoreIfExists,omitempty\"`\n}\n\n// The parameters sent in notifications/requests for user-initiated renames of\n// files.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#renameFilesParams\ntype RenameFilesParams struct {\n\t// An array of all files/folders renamed in this operation. When a folder is renamed, only\n\t// the folder will be included, and not its children.\n\tFiles []FileRename `json:\"files\"`\n}\n\n// Provider options for a {@link RenameRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#renameOptions\ntype RenameOptions struct {\n\t// Renames should be checked and tested before being executed.\n\t//\n\t// @since version 3.12.0\n\tPrepareProvider bool `json:\"prepareProvider,omitempty\"`\n\tWorkDoneProgressOptions\n}\n\n// The parameters of a {@link RenameRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#renameParams\ntype RenameParams struct {\n\t// The document to rename.\n\tTextDocument TextDocumentIdentifier `json:\"textDocument\"`\n\t// The position at which this request was sent.\n\tPosition Position `json:\"position\"`\n\t// The new name of the symbol. If the given name is not valid the\n\t// request must return a {@link ResponseError} with an\n\t// appropriate message set.\n\tNewName string `json:\"newName\"`\n\tWorkDoneProgressParams\n}\n\n// Registration options for a {@link RenameRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#renameRegistrationOptions\ntype RenameRegistrationOptions struct {\n\tTextDocumentRegistrationOptions\n\tRenameOptions\n}\n\n// A generic resource operation.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#resourceOperation\ntype ResourceOperation struct {\n\t// The resource operation kind.\n\tKind string `json:\"kind\"`\n\t// An optional annotation identifier describing the operation.\n\t//\n\t// @since 3.16.0\n\tAnnotationID *ChangeAnnotationIdentifier `json:\"annotationId,omitempty\"`\n}\ntype ResourceOperationKind string\n\n// Save options.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#saveOptions\ntype SaveOptions struct {\n\t// The client is supposed to include the content on save.\n\tIncludeText bool `json:\"includeText,omitempty\"`\n}\n\n// Describes the currently selected completion item.\n//\n// @since 3.18.0\n// @proposed\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#selectedCompletionInfo\ntype SelectedCompletionInfo struct {\n\t// The range that will be replaced if this completion item is accepted.\n\tRange Range `json:\"range\"`\n\t// The text the range will be replaced with if this completion is accepted.\n\tText string `json:\"text\"`\n}\n\n// A selection range represents a part of a selection hierarchy. A selection range\n// may have a parent selection range that contains it.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#selectionRange\ntype SelectionRange struct {\n\t// The {@link Range range} of this selection range.\n\tRange Range `json:\"range\"`\n\t// The parent selection range containing this range. Therefore `parent.range` must contain `this.range`.\n\tParent *SelectionRange `json:\"parent,omitempty\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#selectionRangeClientCapabilities\ntype SelectionRangeClientCapabilities struct {\n\t// Whether implementation supports dynamic registration for selection range providers. If this is set to `true`\n\t// the client supports the new `SelectionRangeRegistrationOptions` return value for the corresponding server\n\t// capability as well.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#selectionRangeOptions\ntype SelectionRangeOptions struct {\n\tWorkDoneProgressOptions\n}\n\n// A parameter literal used in selection range requests.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#selectionRangeParams\ntype SelectionRangeParams struct {\n\t// The text document.\n\tTextDocument TextDocumentIdentifier `json:\"textDocument\"`\n\t// The positions inside the text document.\n\tPositions []Position `json:\"positions\"`\n\tWorkDoneProgressParams\n\tPartialResultParams\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#selectionRangeRegistrationOptions\ntype SelectionRangeRegistrationOptions struct {\n\tSelectionRangeOptions\n\tTextDocumentRegistrationOptions\n\tStaticRegistrationOptions\n}\n\n// A set of predefined token modifiers. This set is not fixed\n// an clients can specify additional token types via the\n// corresponding client capabilities.\n//\n// @since 3.16.0\ntype SemanticTokenModifiers string\n\n// A set of predefined token types. This set is not fixed\n// an clients can specify additional token types via the\n// corresponding client capabilities.\n//\n// @since 3.16.0\ntype SemanticTokenTypes string\n\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#semanticTokens\ntype SemanticTokens struct {\n\t// An optional result id. If provided and clients support delta updating\n\t// the client will include the result id in the next semantic token request.\n\t// A server can then instead of computing all semantic tokens again simply\n\t// send a delta.\n\tResultID string `json:\"resultId,omitempty\"`\n\t// The actual tokens.\n\tData []uint32 `json:\"data\"`\n}\n\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#semanticTokensClientCapabilities\ntype SemanticTokensClientCapabilities struct {\n\t// Whether implementation supports dynamic registration. If this is set to `true`\n\t// the client supports the new `(TextDocumentRegistrationOptions & StaticRegistrationOptions)`\n\t// return value for the corresponding server capability as well.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n\t// Which requests the client supports and might send to the server\n\t// depending on the server's capability. Please note that clients might not\n\t// show semantic tokens or degrade some of the user experience if a range\n\t// or full request is advertised by the client but not provided by the\n\t// server. If for example the client capability `requests.full` and\n\t// `request.range` are both set to true but the server only provides a\n\t// range provider the client might not render a minimap correctly or might\n\t// even decide to not show any semantic tokens at all.\n\tRequests ClientSemanticTokensRequestOptions `json:\"requests\"`\n\t// The token types that the client supports.\n\tTokenTypes []string `json:\"tokenTypes\"`\n\t// The token modifiers that the client supports.\n\tTokenModifiers []string `json:\"tokenModifiers\"`\n\t// The token formats the clients supports.\n\tFormats []TokenFormat `json:\"formats\"`\n\t// Whether the client supports tokens that can overlap each other.\n\tOverlappingTokenSupport bool `json:\"overlappingTokenSupport,omitempty\"`\n\t// Whether the client supports tokens that can span multiple lines.\n\tMultilineTokenSupport bool `json:\"multilineTokenSupport,omitempty\"`\n\t// Whether the client allows the server to actively cancel a\n\t// semantic token request, e.g. supports returning\n\t// LSPErrorCodes.ServerCancelled. If a server does the client\n\t// needs to retrigger the request.\n\t//\n\t// @since 3.17.0\n\tServerCancelSupport bool `json:\"serverCancelSupport,omitempty\"`\n\t// Whether the client uses semantic tokens to augment existing\n\t// syntax tokens. If set to `true` client side created syntax\n\t// tokens and semantic tokens are both used for colorization. If\n\t// set to `false` the client only uses the returned semantic tokens\n\t// for colorization.\n\t//\n\t// If the value is `undefined` then the client behavior is not\n\t// specified.\n\t//\n\t// @since 3.17.0\n\tAugmentsSyntaxTokens bool `json:\"augmentsSyntaxTokens,omitempty\"`\n}\n\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#semanticTokensDelta\ntype SemanticTokensDelta struct {\n\tResultID string `json:\"resultId,omitempty\"`\n\t// The semantic token edits to transform a previous result into a new result.\n\tEdits []SemanticTokensEdit `json:\"edits\"`\n}\n\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#semanticTokensDeltaParams\ntype SemanticTokensDeltaParams struct {\n\t// The text document.\n\tTextDocument TextDocumentIdentifier `json:\"textDocument\"`\n\t// The result id of a previous response. The result Id can either point to a full response\n\t// or a delta response depending on what was received last.\n\tPreviousResultID string `json:\"previousResultId\"`\n\tWorkDoneProgressParams\n\tPartialResultParams\n}\n\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#semanticTokensDeltaPartialResult\ntype SemanticTokensDeltaPartialResult struct {\n\tEdits []SemanticTokensEdit `json:\"edits\"`\n}\n\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#semanticTokensEdit\ntype SemanticTokensEdit struct {\n\t// The start offset of the edit.\n\tStart uint32 `json:\"start\"`\n\t// The count of elements to remove.\n\tDeleteCount uint32 `json:\"deleteCount\"`\n\t// The elements to insert.\n\tData []uint32 `json:\"data,omitempty\"`\n}\n\n// Semantic tokens options to support deltas for full documents\n//\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#semanticTokensFullDelta\ntype SemanticTokensFullDelta struct {\n\t// The server supports deltas for full documents.\n\tDelta bool `json:\"delta,omitempty\"`\n}\n\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#semanticTokensLegend\ntype SemanticTokensLegend struct {\n\t// The token types a server uses.\n\tTokenTypes []string `json:\"tokenTypes\"`\n\t// The token modifiers a server uses.\n\tTokenModifiers []string `json:\"tokenModifiers\"`\n}\n\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#semanticTokensOptions\ntype SemanticTokensOptions struct {\n\t// The legend used by the server\n\tLegend SemanticTokensLegend `json:\"legend\"`\n\t// Server supports providing semantic tokens for a specific range\n\t// of a document.\n\tRange *Or_SemanticTokensOptions_range `json:\"range,omitempty\"`\n\t// Server supports providing semantic tokens for a full document.\n\tFull *Or_SemanticTokensOptions_full `json:\"full,omitempty\"`\n\tWorkDoneProgressOptions\n}\n\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#semanticTokensParams\ntype SemanticTokensParams struct {\n\t// The text document.\n\tTextDocument TextDocumentIdentifier `json:\"textDocument\"`\n\tWorkDoneProgressParams\n\tPartialResultParams\n}\n\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#semanticTokensPartialResult\ntype SemanticTokensPartialResult struct {\n\tData []uint32 `json:\"data\"`\n}\n\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#semanticTokensRangeParams\ntype SemanticTokensRangeParams struct {\n\t// The text document.\n\tTextDocument TextDocumentIdentifier `json:\"textDocument\"`\n\t// The range the semantic tokens are requested for.\n\tRange Range `json:\"range\"`\n\tWorkDoneProgressParams\n\tPartialResultParams\n}\n\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#semanticTokensRegistrationOptions\ntype SemanticTokensRegistrationOptions struct {\n\tTextDocumentRegistrationOptions\n\tSemanticTokensOptions\n\tStaticRegistrationOptions\n}\n\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#semanticTokensWorkspaceClientCapabilities\ntype SemanticTokensWorkspaceClientCapabilities struct {\n\t// Whether the client implementation supports a refresh request sent from\n\t// the server to the client.\n\t//\n\t// Note that this event is global and will force the client to refresh all\n\t// semantic tokens currently shown. It should be used with absolute care\n\t// and is useful for situation where a server for example detects a project\n\t// wide change that requires such a calculation.\n\tRefreshSupport bool `json:\"refreshSupport,omitempty\"`\n}\n\n// Defines the capabilities provided by a language\n// server.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#serverCapabilities\ntype ServerCapabilities struct {\n\t// The position encoding the server picked from the encodings offered\n\t// by the client via the client capability `general.positionEncodings`.\n\t//\n\t// If the client didn't provide any position encodings the only valid\n\t// value that a server can return is 'utf-16'.\n\t//\n\t// If omitted it defaults to 'utf-16'.\n\t//\n\t// @since 3.17.0\n\tPositionEncoding *PositionEncodingKind `json:\"positionEncoding,omitempty\"`\n\t// Defines how text documents are synced. Is either a detailed structure\n\t// defining each notification or for backwards compatibility the\n\t// TextDocumentSyncKind number.\n\tTextDocumentSync interface{} `json:\"textDocumentSync,omitempty\"`\n\t// Defines how notebook documents are synced.\n\t//\n\t// @since 3.17.0\n\tNotebookDocumentSync *Or_ServerCapabilities_notebookDocumentSync `json:\"notebookDocumentSync,omitempty\"`\n\t// The server provides completion support.\n\tCompletionProvider *CompletionOptions `json:\"completionProvider,omitempty\"`\n\t// The server provides hover support.\n\tHoverProvider *Or_ServerCapabilities_hoverProvider `json:\"hoverProvider,omitempty\"`\n\t// The server provides signature help support.\n\tSignatureHelpProvider *SignatureHelpOptions `json:\"signatureHelpProvider,omitempty\"`\n\t// The server provides Goto Declaration support.\n\tDeclarationProvider *Or_ServerCapabilities_declarationProvider `json:\"declarationProvider,omitempty\"`\n\t// The server provides goto definition support.\n\tDefinitionProvider *Or_ServerCapabilities_definitionProvider `json:\"definitionProvider,omitempty\"`\n\t// The server provides Goto Type Definition support.\n\tTypeDefinitionProvider *Or_ServerCapabilities_typeDefinitionProvider `json:\"typeDefinitionProvider,omitempty\"`\n\t// The server provides Goto Implementation support.\n\tImplementationProvider *Or_ServerCapabilities_implementationProvider `json:\"implementationProvider,omitempty\"`\n\t// The server provides find references support.\n\tReferencesProvider *Or_ServerCapabilities_referencesProvider `json:\"referencesProvider,omitempty\"`\n\t// The server provides document highlight support.\n\tDocumentHighlightProvider *Or_ServerCapabilities_documentHighlightProvider `json:\"documentHighlightProvider,omitempty\"`\n\t// The server provides document symbol support.\n\tDocumentSymbolProvider *Or_ServerCapabilities_documentSymbolProvider `json:\"documentSymbolProvider,omitempty\"`\n\t// The server provides code actions. CodeActionOptions may only be\n\t// specified if the client states that it supports\n\t// `codeActionLiteralSupport` in its initial `initialize` request.\n\tCodeActionProvider interface{} `json:\"codeActionProvider,omitempty\"`\n\t// The server provides code lens.\n\tCodeLensProvider *CodeLensOptions `json:\"codeLensProvider,omitempty\"`\n\t// The server provides document link support.\n\tDocumentLinkProvider *DocumentLinkOptions `json:\"documentLinkProvider,omitempty\"`\n\t// The server provides color provider support.\n\tColorProvider *Or_ServerCapabilities_colorProvider `json:\"colorProvider,omitempty\"`\n\t// The server provides workspace symbol support.\n\tWorkspaceSymbolProvider *Or_ServerCapabilities_workspaceSymbolProvider `json:\"workspaceSymbolProvider,omitempty\"`\n\t// The server provides document formatting.\n\tDocumentFormattingProvider *Or_ServerCapabilities_documentFormattingProvider `json:\"documentFormattingProvider,omitempty\"`\n\t// The server provides document range formatting.\n\tDocumentRangeFormattingProvider *Or_ServerCapabilities_documentRangeFormattingProvider `json:\"documentRangeFormattingProvider,omitempty\"`\n\t// The server provides document formatting on typing.\n\tDocumentOnTypeFormattingProvider *DocumentOnTypeFormattingOptions `json:\"documentOnTypeFormattingProvider,omitempty\"`\n\t// The server provides rename support. RenameOptions may only be\n\t// specified if the client states that it supports\n\t// `prepareSupport` in its initial `initialize` request.\n\tRenameProvider interface{} `json:\"renameProvider,omitempty\"`\n\t// The server provides folding provider support.\n\tFoldingRangeProvider *Or_ServerCapabilities_foldingRangeProvider `json:\"foldingRangeProvider,omitempty\"`\n\t// The server provides selection range support.\n\tSelectionRangeProvider *Or_ServerCapabilities_selectionRangeProvider `json:\"selectionRangeProvider,omitempty\"`\n\t// The server provides execute command support.\n\tExecuteCommandProvider *ExecuteCommandOptions `json:\"executeCommandProvider,omitempty\"`\n\t// The server provides call hierarchy support.\n\t//\n\t// @since 3.16.0\n\tCallHierarchyProvider *Or_ServerCapabilities_callHierarchyProvider `json:\"callHierarchyProvider,omitempty\"`\n\t// The server provides linked editing range support.\n\t//\n\t// @since 3.16.0\n\tLinkedEditingRangeProvider *Or_ServerCapabilities_linkedEditingRangeProvider `json:\"linkedEditingRangeProvider,omitempty\"`\n\t// The server provides semantic tokens support.\n\t//\n\t// @since 3.16.0\n\tSemanticTokensProvider interface{} `json:\"semanticTokensProvider,omitempty\"`\n\t// The server provides moniker support.\n\t//\n\t// @since 3.16.0\n\tMonikerProvider *Or_ServerCapabilities_monikerProvider `json:\"monikerProvider,omitempty\"`\n\t// The server provides type hierarchy support.\n\t//\n\t// @since 3.17.0\n\tTypeHierarchyProvider *Or_ServerCapabilities_typeHierarchyProvider `json:\"typeHierarchyProvider,omitempty\"`\n\t// The server provides inline values.\n\t//\n\t// @since 3.17.0\n\tInlineValueProvider *Or_ServerCapabilities_inlineValueProvider `json:\"inlineValueProvider,omitempty\"`\n\t// The server provides inlay hints.\n\t//\n\t// @since 3.17.0\n\tInlayHintProvider interface{} `json:\"inlayHintProvider,omitempty\"`\n\t// The server has support for pull model diagnostics.\n\t//\n\t// @since 3.17.0\n\tDiagnosticProvider *Or_ServerCapabilities_diagnosticProvider `json:\"diagnosticProvider,omitempty\"`\n\t// Inline completion options used during static registration.\n\t//\n\t// @since 3.18.0\n\t// @proposed\n\tInlineCompletionProvider *Or_ServerCapabilities_inlineCompletionProvider `json:\"inlineCompletionProvider,omitempty\"`\n\t// Workspace specific server capabilities.\n\tWorkspace *WorkspaceOptions `json:\"workspace,omitempty\"`\n\t// Experimental server capabilities.\n\tExperimental interface{} `json:\"experimental,omitempty\"`\n}\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#serverCompletionItemOptions\ntype ServerCompletionItemOptions struct {\n\t// The server has support for completion item label\n\t// details (see also `CompletionItemLabelDetails`) when\n\t// receiving a completion item in a resolve call.\n\t//\n\t// @since 3.17.0\n\tLabelDetailsSupport bool `json:\"labelDetailsSupport,omitempty\"`\n}\n\n// Information about the server\n//\n// @since 3.15.0\n// @since 3.18.0 ServerInfo type name added.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#serverInfo\ntype ServerInfo struct {\n\t// The name of the server as defined by the server.\n\tName string `json:\"name\"`\n\t// The server's version as defined by the server.\n\tVersion string `json:\"version,omitempty\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#setTraceParams\ntype SetTraceParams struct {\n\tValue TraceValue `json:\"value\"`\n}\n\n// Client capabilities for the showDocument request.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#showDocumentClientCapabilities\ntype ShowDocumentClientCapabilities struct {\n\t// The client has support for the showDocument\n\t// request.\n\tSupport bool `json:\"support\"`\n}\n\n// Params to show a resource in the UI.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#showDocumentParams\ntype ShowDocumentParams struct {\n\t// The uri to show.\n\tURI URI `json:\"uri\"`\n\t// Indicates to show the resource in an external program.\n\t// To show, for example, `https://code.visualstudio.com/`\n\t// in the default WEB browser set `external` to `true`.\n\tExternal bool `json:\"external,omitempty\"`\n\t// An optional property to indicate whether the editor\n\t// showing the document should take focus or not.\n\t// Clients might ignore this property if an external\n\t// program is started.\n\tTakeFocus bool `json:\"takeFocus,omitempty\"`\n\t// An optional selection range if the document is a text\n\t// document. Clients might ignore the property if an\n\t// external program is started or the file is not a text\n\t// file.\n\tSelection *Range `json:\"selection,omitempty\"`\n}\n\n// The result of a showDocument request.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#showDocumentResult\ntype ShowDocumentResult struct {\n\t// A boolean indicating if the show was successful.\n\tSuccess bool `json:\"success\"`\n}\n\n// The parameters of a notification message.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#showMessageParams\ntype ShowMessageParams struct {\n\t// The message type. See {@link MessageType}\n\tType MessageType `json:\"type\"`\n\t// The actual message.\n\tMessage string `json:\"message\"`\n}\n\n// Show message request client capabilities\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#showMessageRequestClientCapabilities\ntype ShowMessageRequestClientCapabilities struct {\n\t// Capabilities specific to the `MessageActionItem` type.\n\tMessageActionItem *ClientShowMessageActionItemOptions `json:\"messageActionItem,omitempty\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#showMessageRequestParams\ntype ShowMessageRequestParams struct {\n\t// The message type. See {@link MessageType}\n\tType MessageType `json:\"type\"`\n\t// The actual message.\n\tMessage string `json:\"message\"`\n\t// The message action items to present.\n\tActions []MessageActionItem `json:\"actions,omitempty\"`\n}\n\n// Signature help represents the signature of something\n// callable. There can be multiple signature but only one\n// active and only one active parameter.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#signatureHelp\ntype SignatureHelp struct {\n\t// One or more signatures.\n\tSignatures []SignatureInformation `json:\"signatures\"`\n\t// The active signature. If omitted or the value lies outside the\n\t// range of `signatures` the value defaults to zero or is ignored if\n\t// the `SignatureHelp` has no signatures.\n\t//\n\t// Whenever possible implementors should make an active decision about\n\t// the active signature and shouldn't rely on a default value.\n\t//\n\t// In future version of the protocol this property might become\n\t// mandatory to better express this.\n\tActiveSignature uint32 `json:\"activeSignature,omitempty\"`\n\t// The active parameter of the active signature.\n\t//\n\t// If `null`, no parameter of the signature is active (for example a named\n\t// argument that does not match any declared parameters). This is only valid\n\t// if the client specifies the client capability\n\t// `textDocument.signatureHelp.noActiveParameterSupport === true`\n\t//\n\t// If omitted or the value lies outside the range of\n\t// `signatures[activeSignature].parameters` defaults to 0 if the active\n\t// signature has parameters.\n\t//\n\t// If the active signature has no parameters it is ignored.\n\t//\n\t// In future version of the protocol this property might become\n\t// mandatory (but still nullable) to better express the active parameter if\n\t// the active signature does have any.\n\tActiveParameter uint32 `json:\"activeParameter,omitempty\"`\n}\n\n// Client Capabilities for a {@link SignatureHelpRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#signatureHelpClientCapabilities\ntype SignatureHelpClientCapabilities struct {\n\t// Whether signature help supports dynamic registration.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n\t// The client supports the following `SignatureInformation`\n\t// specific properties.\n\tSignatureInformation *ClientSignatureInformationOptions `json:\"signatureInformation,omitempty\"`\n\t// The client supports to send additional context information for a\n\t// `textDocument/signatureHelp` request. A client that opts into\n\t// contextSupport will also support the `retriggerCharacters` on\n\t// `SignatureHelpOptions`.\n\t//\n\t// @since 3.15.0\n\tContextSupport bool `json:\"contextSupport,omitempty\"`\n}\n\n// Additional information about the context in which a signature help request was triggered.\n//\n// @since 3.15.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#signatureHelpContext\ntype SignatureHelpContext struct {\n\t// Action that caused signature help to be triggered.\n\tTriggerKind SignatureHelpTriggerKind `json:\"triggerKind\"`\n\t// Character that caused signature help to be triggered.\n\t//\n\t// This is undefined when `triggerKind !== SignatureHelpTriggerKind.TriggerCharacter`\n\tTriggerCharacter string `json:\"triggerCharacter,omitempty\"`\n\t// `true` if signature help was already showing when it was triggered.\n\t//\n\t// Retriggers occurs when the signature help is already active and can be caused by actions such as\n\t// typing a trigger character, a cursor move, or document content changes.\n\tIsRetrigger bool `json:\"isRetrigger\"`\n\t// The currently active `SignatureHelp`.\n\t//\n\t// The `activeSignatureHelp` has its `SignatureHelp.activeSignature` field updated based on\n\t// the user navigating through available signatures.\n\tActiveSignatureHelp *SignatureHelp `json:\"activeSignatureHelp,omitempty\"`\n}\n\n// Server Capabilities for a {@link SignatureHelpRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#signatureHelpOptions\ntype SignatureHelpOptions struct {\n\t// List of characters that trigger signature help automatically.\n\tTriggerCharacters []string `json:\"triggerCharacters,omitempty\"`\n\t// List of characters that re-trigger signature help.\n\t//\n\t// These trigger characters are only active when signature help is already showing. All trigger characters\n\t// are also counted as re-trigger characters.\n\t//\n\t// @since 3.15.0\n\tRetriggerCharacters []string `json:\"retriggerCharacters,omitempty\"`\n\tWorkDoneProgressOptions\n}\n\n// Parameters for a {@link SignatureHelpRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#signatureHelpParams\ntype SignatureHelpParams struct {\n\t// The signature help context. This is only available if the client specifies\n\t// to send this using the client capability `textDocument.signatureHelp.contextSupport === true`\n\t//\n\t// @since 3.15.0\n\tContext *SignatureHelpContext `json:\"context,omitempty\"`\n\tTextDocumentPositionParams\n\tWorkDoneProgressParams\n}\n\n// Registration options for a {@link SignatureHelpRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#signatureHelpRegistrationOptions\ntype SignatureHelpRegistrationOptions struct {\n\tTextDocumentRegistrationOptions\n\tSignatureHelpOptions\n}\n\n// How a signature help was triggered.\n//\n// @since 3.15.0\ntype SignatureHelpTriggerKind uint32\n\n// Represents the signature of something callable. A signature\n// can have a label, like a function-name, a doc-comment, and\n// a set of parameters.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#signatureInformation\ntype SignatureInformation struct {\n\t// The label of this signature. Will be shown in\n\t// the UI.\n\tLabel string `json:\"label\"`\n\t// The human-readable doc-comment of this signature. Will be shown\n\t// in the UI but can be omitted.\n\tDocumentation *Or_SignatureInformation_documentation `json:\"documentation,omitempty\"`\n\t// The parameters of this signature.\n\tParameters []ParameterInformation `json:\"parameters,omitempty\"`\n\t// The index of the active parameter.\n\t//\n\t// If `null`, no parameter of the signature is active (for example a named\n\t// argument that does not match any declared parameters). This is only valid\n\t// if the client specifies the client capability\n\t// `textDocument.signatureHelp.noActiveParameterSupport === true`\n\t//\n\t// If provided (or `null`), this is used in place of\n\t// `SignatureHelp.activeParameter`.\n\t//\n\t// @since 3.16.0\n\tActiveParameter uint32 `json:\"activeParameter,omitempty\"`\n}\n\n// An interactive text edit.\n//\n// @since 3.18.0\n// @proposed\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#snippetTextEdit\ntype SnippetTextEdit struct {\n\t// The range of the text document to be manipulated.\n\tRange Range `json:\"range\"`\n\t// The snippet to be inserted.\n\tSnippet StringValue `json:\"snippet\"`\n\t// The actual identifier of the snippet edit.\n\tAnnotationID *ChangeAnnotationIdentifier `json:\"annotationId,omitempty\"`\n}\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#staleRequestSupportOptions\ntype StaleRequestSupportOptions struct {\n\t// The client will actively cancel the request.\n\tCancel bool `json:\"cancel\"`\n\t// The list of requests for which the client\n\t// will retry the request if it receives a\n\t// response with error code `ContentModified`\n\tRetryOnContentModified []string `json:\"retryOnContentModified\"`\n}\n\n// Static registration options to be returned in the initialize\n// request.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#staticRegistrationOptions\ntype StaticRegistrationOptions struct {\n\t// The id used to register the request. The id can be used to deregister\n\t// the request again. See also Registration#id.\n\tID string `json:\"id,omitempty\"`\n}\n\n// A string value used as a snippet is a template which allows to insert text\n// and to control the editor cursor when insertion happens.\n//\n// A snippet can define tab stops and placeholders with `$1`, `$2`\n// and `${3:foo}`. `$0` defines the final tab stop, it defaults to\n// the end of the snippet. Variables are defined with `$name` and\n// `${name:default value}`.\n//\n// @since 3.18.0\n// @proposed\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#stringValue\ntype StringValue struct {\n\t// The kind of string value.\n\tKind string `json:\"kind\"`\n\t// The snippet string.\n\tValue string `json:\"value\"`\n}\n\n// Represents information about programming constructs like variables, classes,\n// interfaces etc.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#symbolInformation\ntype SymbolInformation struct {\n\t// extends BaseSymbolInformation\n\t// Indicates if this symbol is deprecated.\n\t//\n\t// @deprecated Use tags instead\n\tDeprecated bool `json:\"deprecated,omitempty\"`\n\t// The location of this symbol. The location's range is used by a tool\n\t// to reveal the location in the editor. If the symbol is selected in the\n\t// tool the range's start information is used to position the cursor. So\n\t// the range usually spans more than the actual symbol's name and does\n\t// normally include things like visibility modifiers.\n\t//\n\t// The range doesn't have to denote a node range in the sense of an abstract\n\t// syntax tree. It can therefore not be used to re-construct a hierarchy of\n\t// the symbols.\n\tLocation Location `json:\"location\"`\n\t// The name of this symbol.\n\tName string `json:\"name\"`\n\t// The kind of this symbol.\n\tKind SymbolKind `json:\"kind\"`\n\t// Tags for this symbol.\n\t//\n\t// @since 3.16.0\n\tTags []SymbolTag `json:\"tags,omitempty\"`\n\t// The name of the symbol containing this symbol. This information is for\n\t// user interface purposes (e.g. to render a qualifier in the user interface\n\t// if necessary). It can't be used to re-infer a hierarchy for the document\n\t// symbols.\n\tContainerName string `json:\"containerName,omitempty\"`\n}\n\n// A symbol kind.\ntype SymbolKind uint32\n\n// Symbol tags are extra annotations that tweak the rendering of a symbol.\n//\n// @since 3.16\ntype SymbolTag uint32\n\n// Describe options to be used when registered for text document change events.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#textDocumentChangeRegistrationOptions\ntype TextDocumentChangeRegistrationOptions struct {\n\t// How documents are synced to the server.\n\tSyncKind TextDocumentSyncKind `json:\"syncKind\"`\n\tTextDocumentRegistrationOptions\n}\n\n// Text document specific client capabilities.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#textDocumentClientCapabilities\ntype TextDocumentClientCapabilities struct {\n\t// Defines which synchronization capabilities the client supports.\n\tSynchronization *TextDocumentSyncClientCapabilities `json:\"synchronization,omitempty\"`\n\t// Capabilities specific to the `textDocument/completion` request.\n\tCompletion CompletionClientCapabilities `json:\"completion,omitempty\"`\n\t// Capabilities specific to the `textDocument/hover` request.\n\tHover *HoverClientCapabilities `json:\"hover,omitempty\"`\n\t// Capabilities specific to the `textDocument/signatureHelp` request.\n\tSignatureHelp *SignatureHelpClientCapabilities `json:\"signatureHelp,omitempty\"`\n\t// Capabilities specific to the `textDocument/declaration` request.\n\t//\n\t// @since 3.14.0\n\tDeclaration *DeclarationClientCapabilities `json:\"declaration,omitempty\"`\n\t// Capabilities specific to the `textDocument/definition` request.\n\tDefinition *DefinitionClientCapabilities `json:\"definition,omitempty\"`\n\t// Capabilities specific to the `textDocument/typeDefinition` request.\n\t//\n\t// @since 3.6.0\n\tTypeDefinition *TypeDefinitionClientCapabilities `json:\"typeDefinition,omitempty\"`\n\t// Capabilities specific to the `textDocument/implementation` request.\n\t//\n\t// @since 3.6.0\n\tImplementation *ImplementationClientCapabilities `json:\"implementation,omitempty\"`\n\t// Capabilities specific to the `textDocument/references` request.\n\tReferences *ReferenceClientCapabilities `json:\"references,omitempty\"`\n\t// Capabilities specific to the `textDocument/documentHighlight` request.\n\tDocumentHighlight *DocumentHighlightClientCapabilities `json:\"documentHighlight,omitempty\"`\n\t// Capabilities specific to the `textDocument/documentSymbol` request.\n\tDocumentSymbol DocumentSymbolClientCapabilities `json:\"documentSymbol,omitempty\"`\n\t// Capabilities specific to the `textDocument/codeAction` request.\n\tCodeAction CodeActionClientCapabilities `json:\"codeAction,omitempty\"`\n\t// Capabilities specific to the `textDocument/codeLens` request.\n\tCodeLens *CodeLensClientCapabilities `json:\"codeLens,omitempty\"`\n\t// Capabilities specific to the `textDocument/documentLink` request.\n\tDocumentLink *DocumentLinkClientCapabilities `json:\"documentLink,omitempty\"`\n\t// Capabilities specific to the `textDocument/documentColor` and the\n\t// `textDocument/colorPresentation` request.\n\t//\n\t// @since 3.6.0\n\tColorProvider *DocumentColorClientCapabilities `json:\"colorProvider,omitempty\"`\n\t// Capabilities specific to the `textDocument/formatting` request.\n\tFormatting *DocumentFormattingClientCapabilities `json:\"formatting,omitempty\"`\n\t// Capabilities specific to the `textDocument/rangeFormatting` request.\n\tRangeFormatting *DocumentRangeFormattingClientCapabilities `json:\"rangeFormatting,omitempty\"`\n\t// Capabilities specific to the `textDocument/onTypeFormatting` request.\n\tOnTypeFormatting *DocumentOnTypeFormattingClientCapabilities `json:\"onTypeFormatting,omitempty\"`\n\t// Capabilities specific to the `textDocument/rename` request.\n\tRename *RenameClientCapabilities `json:\"rename,omitempty\"`\n\t// Capabilities specific to the `textDocument/foldingRange` request.\n\t//\n\t// @since 3.10.0\n\tFoldingRange *FoldingRangeClientCapabilities `json:\"foldingRange,omitempty\"`\n\t// Capabilities specific to the `textDocument/selectionRange` request.\n\t//\n\t// @since 3.15.0\n\tSelectionRange *SelectionRangeClientCapabilities `json:\"selectionRange,omitempty\"`\n\t// Capabilities specific to the `textDocument/publishDiagnostics` notification.\n\tPublishDiagnostics PublishDiagnosticsClientCapabilities `json:\"publishDiagnostics,omitempty\"`\n\t// Capabilities specific to the various call hierarchy requests.\n\t//\n\t// @since 3.16.0\n\tCallHierarchy *CallHierarchyClientCapabilities `json:\"callHierarchy,omitempty\"`\n\t// Capabilities specific to the various semantic token request.\n\t//\n\t// @since 3.16.0\n\tSemanticTokens SemanticTokensClientCapabilities `json:\"semanticTokens,omitempty\"`\n\t// Capabilities specific to the `textDocument/linkedEditingRange` request.\n\t//\n\t// @since 3.16.0\n\tLinkedEditingRange *LinkedEditingRangeClientCapabilities `json:\"linkedEditingRange,omitempty\"`\n\t// Client capabilities specific to the `textDocument/moniker` request.\n\t//\n\t// @since 3.16.0\n\tMoniker *MonikerClientCapabilities `json:\"moniker,omitempty\"`\n\t// Capabilities specific to the various type hierarchy requests.\n\t//\n\t// @since 3.17.0\n\tTypeHierarchy *TypeHierarchyClientCapabilities `json:\"typeHierarchy,omitempty\"`\n\t// Capabilities specific to the `textDocument/inlineValue` request.\n\t//\n\t// @since 3.17.0\n\tInlineValue *InlineValueClientCapabilities `json:\"inlineValue,omitempty\"`\n\t// Capabilities specific to the `textDocument/inlayHint` request.\n\t//\n\t// @since 3.17.0\n\tInlayHint *InlayHintClientCapabilities `json:\"inlayHint,omitempty\"`\n\t// Capabilities specific to the diagnostic pull model.\n\t//\n\t// @since 3.17.0\n\tDiagnostic *DiagnosticClientCapabilities `json:\"diagnostic,omitempty\"`\n\t// Client capabilities specific to inline completions.\n\t//\n\t// @since 3.18.0\n\t// @proposed\n\tInlineCompletion *InlineCompletionClientCapabilities `json:\"inlineCompletion,omitempty\"`\n}\n\n// An event describing a change to a text document. If only a text is provided\n// it is considered to be the full content of the document.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#textDocumentContentChangeEvent\ntype TextDocumentContentChangeEvent = Or_TextDocumentContentChangeEvent // (alias)\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#textDocumentContentChangePartial\ntype TextDocumentContentChangePartial struct {\n\t// The range of the document that changed.\n\tRange *Range `json:\"range,omitempty\"`\n\t// The optional length of the range that got replaced.\n\t//\n\t// @deprecated use range instead.\n\tRangeLength uint32 `json:\"rangeLength,omitempty\"`\n\t// The new text for the provided range.\n\tText string `json:\"text\"`\n}\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#textDocumentContentChangeWholeDocument\ntype TextDocumentContentChangeWholeDocument struct {\n\t// The new text of the whole document.\n\tText string `json:\"text\"`\n}\n\n// Client capabilities for a text document content provider.\n//\n// @since 3.18.0\n// @proposed\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#textDocumentContentClientCapabilities\ntype TextDocumentContentClientCapabilities struct {\n\t// Text document content provider supports dynamic registration.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n}\n\n// Text document content provider options.\n//\n// @since 3.18.0\n// @proposed\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#textDocumentContentOptions\ntype TextDocumentContentOptions struct {\n\t// The scheme for which the server provides content.\n\tScheme string `json:\"scheme\"`\n}\n\n// Parameters for the `workspace/textDocumentContent` request.\n//\n// @since 3.18.0\n// @proposed\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#textDocumentContentParams\ntype TextDocumentContentParams struct {\n\t// The uri of the text document.\n\tURI DocumentUri `json:\"uri\"`\n}\n\n// Parameters for the `workspace/textDocumentContent/refresh` request.\n//\n// @since 3.18.0\n// @proposed\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#textDocumentContentRefreshParams\ntype TextDocumentContentRefreshParams struct {\n\t// The uri of the text document to refresh.\n\tURI DocumentUri `json:\"uri\"`\n}\n\n// Text document content provider registration options.\n//\n// @since 3.18.0\n// @proposed\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#textDocumentContentRegistrationOptions\ntype TextDocumentContentRegistrationOptions struct {\n\tTextDocumentContentOptions\n\tStaticRegistrationOptions\n}\n\n// Describes textual changes on a text document. A TextDocumentEdit describes all changes\n// on a document version Si and after they are applied move the document to version Si+1.\n// So the creator of a TextDocumentEdit doesn't need to sort the array of edits or do any\n// kind of ordering. However the edits must be non overlapping.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#textDocumentEdit\ntype TextDocumentEdit struct {\n\t// The text document to change.\n\tTextDocument OptionalVersionedTextDocumentIdentifier `json:\"textDocument\"`\n\t// The edits to be applied.\n\t//\n\t// @since 3.16.0 - support for AnnotatedTextEdit. This is guarded using a\n\t// client capability.\n\t//\n\t// @since 3.18.0 - support for SnippetTextEdit. This is guarded using a\n\t// client capability.\n\tEdits []Or_TextDocumentEdit_edits_Elem `json:\"edits\"`\n}\n\n// A document filter denotes a document by different properties like\n// the {@link TextDocument.languageId language}, the {@link Uri.scheme scheme} of\n// its resource, or a glob-pattern that is applied to the {@link TextDocument.fileName path}.\n//\n// Glob patterns can have the following syntax:\n//\n// - `*` to match one or more characters in a path segment\n// - `?` to match on one character in a path segment\n// - `**` to match any number of path segments, including none\n// - `{}` to group sub patterns into an OR expression. (e.g. `**/*.{ts,js}` matches all TypeScript and JavaScript files)\n// - `[]` to declare a range of characters to match in a path segment (e.g., `example.[0-9]` to match on `example.0`, `example.1`, …)\n// - `[!...]` to negate a range of characters to match in a path segment (e.g., `example.[!0-9]` to match on `example.a`, `example.b`, but not `example.0`)\n//\n// @sample A language filter that applies to typescript files on disk: `{ language: 'typescript', scheme: 'file' }`\n// @sample A language filter that applies to all package.json paths: `{ language: 'json', pattern: '**package.json' }`\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#textDocumentFilter\ntype TextDocumentFilter = Or_TextDocumentFilter // (alias)\n// A document filter where `language` is required field.\n//\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#textDocumentFilterLanguage\ntype TextDocumentFilterLanguage struct {\n\t// A language id, like `typescript`.\n\tLanguage string `json:\"language\"`\n\t// A Uri {@link Uri.scheme scheme}, like `file` or `untitled`.\n\tScheme string `json:\"scheme,omitempty\"`\n\t// A glob pattern, like **/*.{ts,js}. See TextDocumentFilter for examples.\n\t//\n\t// @since 3.18.0 - support for relative patterns.\n\tPattern *GlobPattern `json:\"pattern,omitempty\"`\n}\n\n// A document filter where `pattern` is required field.\n//\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#textDocumentFilterPattern\ntype TextDocumentFilterPattern struct {\n\t// A language id, like `typescript`.\n\tLanguage string `json:\"language,omitempty\"`\n\t// A Uri {@link Uri.scheme scheme}, like `file` or `untitled`.\n\tScheme string `json:\"scheme,omitempty\"`\n\t// A glob pattern, like **/*.{ts,js}. See TextDocumentFilter for examples.\n\t//\n\t// @since 3.18.0 - support for relative patterns.\n\tPattern GlobPattern `json:\"pattern\"`\n}\n\n// A document filter where `scheme` is required field.\n//\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#textDocumentFilterScheme\ntype TextDocumentFilterScheme struct {\n\t// A language id, like `typescript`.\n\tLanguage string `json:\"language,omitempty\"`\n\t// A Uri {@link Uri.scheme scheme}, like `file` or `untitled`.\n\tScheme string `json:\"scheme\"`\n\t// A glob pattern, like **/*.{ts,js}. See TextDocumentFilter for examples.\n\t//\n\t// @since 3.18.0 - support for relative patterns.\n\tPattern *GlobPattern `json:\"pattern,omitempty\"`\n}\n\n// A literal to identify a text document in the client.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#textDocumentIdentifier\ntype TextDocumentIdentifier struct {\n\t// The text document's uri.\n\tURI DocumentUri `json:\"uri\"`\n}\n\n// An item to transfer a text document from the client to the\n// server.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#textDocumentItem\ntype TextDocumentItem struct {\n\t// The text document's uri.\n\tURI DocumentUri `json:\"uri\"`\n\t// The text document's language identifier.\n\tLanguageID LanguageKind `json:\"languageId\"`\n\t// The version number of this document (it will increase after each\n\t// change, including undo/redo).\n\tVersion int32 `json:\"version\"`\n\t// The content of the opened text document.\n\tText string `json:\"text\"`\n}\n\n// A parameter literal used in requests to pass a text document and a position inside that\n// document.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#textDocumentPositionParams\ntype TextDocumentPositionParams struct {\n\t// The text document.\n\tTextDocument TextDocumentIdentifier `json:\"textDocument\"`\n\t// The position inside the text document.\n\tPosition Position `json:\"position\"`\n}\n\n// General text document registration options.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#textDocumentRegistrationOptions\ntype TextDocumentRegistrationOptions struct {\n\t// A document selector to identify the scope of the registration. If set to null\n\t// the document selector provided on the client side will be used.\n\tDocumentSelector DocumentSelector `json:\"documentSelector\"`\n}\n\n// Represents reasons why a text document is saved.\ntype TextDocumentSaveReason uint32\n\n// Save registration options.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#textDocumentSaveRegistrationOptions\ntype TextDocumentSaveRegistrationOptions struct {\n\tTextDocumentRegistrationOptions\n\tSaveOptions\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#textDocumentSyncClientCapabilities\ntype TextDocumentSyncClientCapabilities struct {\n\t// Whether text document synchronization supports dynamic registration.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n\t// The client supports sending will save notifications.\n\tWillSave bool `json:\"willSave,omitempty\"`\n\t// The client supports sending a will save request and\n\t// waits for a response providing text edits which will\n\t// be applied to the document before it is saved.\n\tWillSaveWaitUntil bool `json:\"willSaveWaitUntil,omitempty\"`\n\t// The client supports did save notifications.\n\tDidSave bool `json:\"didSave,omitempty\"`\n}\n\n// Defines how the host (editor) should sync\n// document changes to the language server.\ntype TextDocumentSyncKind uint32\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#textDocumentSyncOptions\ntype TextDocumentSyncOptions struct {\n\t// Open and close notifications are sent to the server. If omitted open close notification should not\n\t// be sent.\n\tOpenClose bool `json:\"openClose,omitempty\"`\n\t// Change notifications are sent to the server. See TextDocumentSyncKind.None, TextDocumentSyncKind.Full\n\t// and TextDocumentSyncKind.Incremental. If omitted it defaults to TextDocumentSyncKind.None.\n\tChange TextDocumentSyncKind `json:\"change,omitempty\"`\n\t// If present will save notifications are sent to the server. If omitted the notification should not be\n\t// sent.\n\tWillSave bool `json:\"willSave,omitempty\"`\n\t// If present will save wait until requests are sent to the server. If omitted the request should not be\n\t// sent.\n\tWillSaveWaitUntil bool `json:\"willSaveWaitUntil,omitempty\"`\n\t// If present save notifications are sent to the server. If omitted the notification should not be\n\t// sent.\n\tSave *SaveOptions `json:\"save,omitempty\"`\n}\n\n// A text edit applicable to a text document.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#textEdit\ntype TextEdit struct {\n\t// The range of the text document to be manipulated. To insert\n\t// text into a document create a range where start === end.\n\tRange Range `json:\"range\"`\n\t// The string to be inserted. For delete operations use an\n\t// empty string.\n\tNewText string `json:\"newText\"`\n}\ntype TokenFormat string\ntype TraceValue string\n\n// created for Tuple\ntype Tuple_ParameterInformation_label_Item1 struct {\n\tFld0 uint32 `json:\"fld0\"`\n\tFld1 uint32 `json:\"fld1\"`\n}\n\n// Since 3.6.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#typeDefinitionClientCapabilities\ntype TypeDefinitionClientCapabilities struct {\n\t// Whether implementation supports dynamic registration. If this is set to `true`\n\t// the client supports the new `TypeDefinitionRegistrationOptions` return value\n\t// for the corresponding server capability as well.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n\t// The client supports additional metadata in the form of definition links.\n\t//\n\t// Since 3.14.0\n\tLinkSupport bool `json:\"linkSupport,omitempty\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#typeDefinitionOptions\ntype TypeDefinitionOptions struct {\n\tWorkDoneProgressOptions\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#typeDefinitionParams\ntype TypeDefinitionParams struct {\n\tTextDocumentPositionParams\n\tWorkDoneProgressParams\n\tPartialResultParams\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#typeDefinitionRegistrationOptions\ntype TypeDefinitionRegistrationOptions struct {\n\tTextDocumentRegistrationOptions\n\tTypeDefinitionOptions\n\tStaticRegistrationOptions\n}\n\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#typeHierarchyClientCapabilities\ntype TypeHierarchyClientCapabilities struct {\n\t// Whether implementation supports dynamic registration. If this is set to `true`\n\t// the client supports the new `(TextDocumentRegistrationOptions & StaticRegistrationOptions)`\n\t// return value for the corresponding server capability as well.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n}\n\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#typeHierarchyItem\ntype TypeHierarchyItem struct {\n\t// The name of this item.\n\tName string `json:\"name\"`\n\t// The kind of this item.\n\tKind SymbolKind `json:\"kind\"`\n\t// Tags for this item.\n\tTags []SymbolTag `json:\"tags,omitempty\"`\n\t// More detail for this item, e.g. the signature of a function.\n\tDetail string `json:\"detail,omitempty\"`\n\t// The resource identifier of this item.\n\tURI DocumentUri `json:\"uri\"`\n\t// The range enclosing this symbol not including leading/trailing whitespace\n\t// but everything else, e.g. comments and code.\n\tRange Range `json:\"range\"`\n\t// The range that should be selected and revealed when this symbol is being\n\t// picked, e.g. the name of a function. Must be contained by the\n\t// {@link TypeHierarchyItem.range `range`}.\n\tSelectionRange Range `json:\"selectionRange\"`\n\t// A data entry field that is preserved between a type hierarchy prepare and\n\t// supertypes or subtypes requests. It could also be used to identify the\n\t// type hierarchy in the server, helping improve the performance on\n\t// resolving supertypes and subtypes.\n\tData interface{} `json:\"data,omitempty\"`\n}\n\n// Type hierarchy options used during static registration.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#typeHierarchyOptions\ntype TypeHierarchyOptions struct {\n\tWorkDoneProgressOptions\n}\n\n// The parameter of a `textDocument/prepareTypeHierarchy` request.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#typeHierarchyPrepareParams\ntype TypeHierarchyPrepareParams struct {\n\tTextDocumentPositionParams\n\tWorkDoneProgressParams\n}\n\n// Type hierarchy options used during static or dynamic registration.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#typeHierarchyRegistrationOptions\ntype TypeHierarchyRegistrationOptions struct {\n\tTextDocumentRegistrationOptions\n\tTypeHierarchyOptions\n\tStaticRegistrationOptions\n}\n\n// The parameter of a `typeHierarchy/subtypes` request.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#typeHierarchySubtypesParams\ntype TypeHierarchySubtypesParams struct {\n\tItem TypeHierarchyItem `json:\"item\"`\n\tWorkDoneProgressParams\n\tPartialResultParams\n}\n\n// The parameter of a `typeHierarchy/supertypes` request.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#typeHierarchySupertypesParams\ntype TypeHierarchySupertypesParams struct {\n\tItem TypeHierarchyItem `json:\"item\"`\n\tWorkDoneProgressParams\n\tPartialResultParams\n}\n\n// A diagnostic report indicating that the last returned\n// report is still accurate.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#unchangedDocumentDiagnosticReport\ntype UnchangedDocumentDiagnosticReport struct {\n\t// A document diagnostic report indicating\n\t// no changes to the last result. A server can\n\t// only return `unchanged` if result ids are\n\t// provided.\n\tKind string `json:\"kind\"`\n\t// A result id which will be sent on the next\n\t// diagnostic request for the same document.\n\tResultID string `json:\"resultId\"`\n}\n\n// Moniker uniqueness level to define scope of the moniker.\n//\n// @since 3.16.0\ntype UniquenessLevel string\n\n// General parameters to unregister a request or notification.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#unregistration\ntype Unregistration struct {\n\t// The id used to unregister the request or notification. Usually an id\n\t// provided during the register request.\n\tID string `json:\"id\"`\n\t// The method to unregister for.\n\tMethod string `json:\"method\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#unregistrationParams\ntype UnregistrationParams struct {\n\tUnregisterations []Unregistration `json:\"unregisterations\"`\n}\n\n// A versioned notebook document identifier.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#versionedNotebookDocumentIdentifier\ntype VersionedNotebookDocumentIdentifier struct {\n\t// The version number of this notebook document.\n\tVersion int32 `json:\"version\"`\n\t// The notebook document's uri.\n\tURI URI `json:\"uri\"`\n}\n\n// A text document identifier to denote a specific version of a text document.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#versionedTextDocumentIdentifier\ntype VersionedTextDocumentIdentifier struct {\n\t// The version number of this document.\n\tVersion int32 `json:\"version\"`\n\tTextDocumentIdentifier\n}\ntype WatchKind = uint32 // The parameters sent in a will save text document notification.\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#willSaveTextDocumentParams\ntype WillSaveTextDocumentParams struct {\n\t// The document that will be saved.\n\tTextDocument TextDocumentIdentifier `json:\"textDocument\"`\n\t// The 'TextDocumentSaveReason'.\n\tReason TextDocumentSaveReason `json:\"reason\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#windowClientCapabilities\ntype WindowClientCapabilities struct {\n\t// It indicates whether the client supports server initiated\n\t// progress using the `window/workDoneProgress/create` request.\n\t//\n\t// The capability also controls Whether client supports handling\n\t// of progress notifications. If set servers are allowed to report a\n\t// `workDoneProgress` property in the request specific server\n\t// capabilities.\n\t//\n\t// @since 3.15.0\n\tWorkDoneProgress bool `json:\"workDoneProgress,omitempty\"`\n\t// Capabilities specific to the showMessage request.\n\t//\n\t// @since 3.16.0\n\tShowMessage *ShowMessageRequestClientCapabilities `json:\"showMessage,omitempty\"`\n\t// Capabilities specific to the showDocument request.\n\t//\n\t// @since 3.16.0\n\tShowDocument *ShowDocumentClientCapabilities `json:\"showDocument,omitempty\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#workDoneProgressBegin\ntype WorkDoneProgressBegin struct {\n\tKind string `json:\"kind\"`\n\t// Mandatory title of the progress operation. Used to briefly inform about\n\t// the kind of operation being performed.\n\t//\n\t// Examples: \"Indexing\" or \"Linking dependencies\".\n\tTitle string `json:\"title\"`\n\t// Controls if a cancel button should show to allow the user to cancel the\n\t// long running operation. Clients that don't support cancellation are allowed\n\t// to ignore the setting.\n\tCancellable bool `json:\"cancellable,omitempty\"`\n\t// Optional, more detailed associated progress message. Contains\n\t// complementary information to the `title`.\n\t//\n\t// Examples: \"3/25 files\", \"project/src/module2\", \"node_modules/some_dep\".\n\t// If unset, the previous progress message (if any) is still valid.\n\tMessage string `json:\"message,omitempty\"`\n\t// Optional progress percentage to display (value 100 is considered 100%).\n\t// If not provided infinite progress is assumed and clients are allowed\n\t// to ignore the `percentage` value in subsequent in report notifications.\n\t//\n\t// The value should be steadily rising. Clients are free to ignore values\n\t// that are not following this rule. The value range is [0, 100].\n\tPercentage uint32 `json:\"percentage,omitempty\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#workDoneProgressCancelParams\ntype WorkDoneProgressCancelParams struct {\n\t// The token to be used to report progress.\n\tToken ProgressToken `json:\"token\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#workDoneProgressCreateParams\ntype WorkDoneProgressCreateParams struct {\n\t// The token to be used to report progress.\n\tToken ProgressToken `json:\"token\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#workDoneProgressEnd\ntype WorkDoneProgressEnd struct {\n\tKind string `json:\"kind\"`\n\t// Optional, a final message indicating to for example indicate the outcome\n\t// of the operation.\n\tMessage string `json:\"message,omitempty\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#workDoneProgressOptions\ntype WorkDoneProgressOptions struct {\n\tWorkDoneProgress bool `json:\"workDoneProgress,omitempty\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#workDoneProgressParams\ntype WorkDoneProgressParams struct {\n\t// An optional token that a server can use to report work done progress.\n\tWorkDoneToken ProgressToken `json:\"workDoneToken,omitempty\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#workDoneProgressReport\ntype WorkDoneProgressReport struct {\n\tKind string `json:\"kind\"`\n\t// Controls enablement state of a cancel button.\n\t//\n\t// Clients that don't support cancellation or don't support controlling the button's\n\t// enablement state are allowed to ignore the property.\n\tCancellable bool `json:\"cancellable,omitempty\"`\n\t// Optional, more detailed associated progress message. Contains\n\t// complementary information to the `title`.\n\t//\n\t// Examples: \"3/25 files\", \"project/src/module2\", \"node_modules/some_dep\".\n\t// If unset, the previous progress message (if any) is still valid.\n\tMessage string `json:\"message,omitempty\"`\n\t// Optional progress percentage to display (value 100 is considered 100%).\n\t// If not provided infinite progress is assumed and clients are allowed\n\t// to ignore the `percentage` value in subsequent in report notifications.\n\t//\n\t// The value should be steadily rising. Clients are free to ignore values\n\t// that are not following this rule. The value range is [0, 100]\n\tPercentage uint32 `json:\"percentage,omitempty\"`\n}\n\n// Workspace specific client capabilities.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#workspaceClientCapabilities\ntype WorkspaceClientCapabilities struct {\n\t// The client supports applying batch edits\n\t// to the workspace by supporting the request\n\t// 'workspace/applyEdit'\n\tApplyEdit bool `json:\"applyEdit,omitempty\"`\n\t// Capabilities specific to `WorkspaceEdit`s.\n\tWorkspaceEdit *WorkspaceEditClientCapabilities `json:\"workspaceEdit,omitempty\"`\n\t// Capabilities specific to the `workspace/didChangeConfiguration` notification.\n\tDidChangeConfiguration DidChangeConfigurationClientCapabilities `json:\"didChangeConfiguration,omitempty\"`\n\t// Capabilities specific to the `workspace/didChangeWatchedFiles` notification.\n\tDidChangeWatchedFiles DidChangeWatchedFilesClientCapabilities `json:\"didChangeWatchedFiles,omitempty\"`\n\t// Capabilities specific to the `workspace/symbol` request.\n\tSymbol *WorkspaceSymbolClientCapabilities `json:\"symbol,omitempty\"`\n\t// Capabilities specific to the `workspace/executeCommand` request.\n\tExecuteCommand *ExecuteCommandClientCapabilities `json:\"executeCommand,omitempty\"`\n\t// The client has support for workspace folders.\n\t//\n\t// @since 3.6.0\n\tWorkspaceFolders bool `json:\"workspaceFolders,omitempty\"`\n\t// The client supports `workspace/configuration` requests.\n\t//\n\t// @since 3.6.0\n\tConfiguration bool `json:\"configuration,omitempty\"`\n\t// Capabilities specific to the semantic token requests scoped to the\n\t// workspace.\n\t//\n\t// @since 3.16.0.\n\tSemanticTokens *SemanticTokensWorkspaceClientCapabilities `json:\"semanticTokens,omitempty\"`\n\t// Capabilities specific to the code lens requests scoped to the\n\t// workspace.\n\t//\n\t// @since 3.16.0.\n\tCodeLens *CodeLensWorkspaceClientCapabilities `json:\"codeLens,omitempty\"`\n\t// The client has support for file notifications/requests for user operations on files.\n\t//\n\t// Since 3.16.0\n\tFileOperations *FileOperationClientCapabilities `json:\"fileOperations,omitempty\"`\n\t// Capabilities specific to the inline values requests scoped to the\n\t// workspace.\n\t//\n\t// @since 3.17.0.\n\tInlineValue *InlineValueWorkspaceClientCapabilities `json:\"inlineValue,omitempty\"`\n\t// Capabilities specific to the inlay hint requests scoped to the\n\t// workspace.\n\t//\n\t// @since 3.17.0.\n\tInlayHint *InlayHintWorkspaceClientCapabilities `json:\"inlayHint,omitempty\"`\n\t// Capabilities specific to the diagnostic requests scoped to the\n\t// workspace.\n\t//\n\t// @since 3.17.0.\n\tDiagnostics *DiagnosticWorkspaceClientCapabilities `json:\"diagnostics,omitempty\"`\n\t// Capabilities specific to the folding range requests scoped to the workspace.\n\t//\n\t// @since 3.18.0\n\t// @proposed\n\tFoldingRange *FoldingRangeWorkspaceClientCapabilities `json:\"foldingRange,omitempty\"`\n\t// Capabilities specific to the `workspace/textDocumentContent` request.\n\t//\n\t// @since 3.18.0\n\t// @proposed\n\tTextDocumentContent *TextDocumentContentClientCapabilities `json:\"textDocumentContent,omitempty\"`\n}\n\n// Parameters of the workspace diagnostic request.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#workspaceDiagnosticParams\ntype WorkspaceDiagnosticParams struct {\n\t// The additional identifier provided during registration.\n\tIdentifier string `json:\"identifier,omitempty\"`\n\t// The currently known diagnostic reports with their\n\t// previous result ids.\n\tPreviousResultIds []PreviousResultId `json:\"previousResultIds\"`\n\tWorkDoneProgressParams\n\tPartialResultParams\n}\n\n// A workspace diagnostic report.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#workspaceDiagnosticReport\ntype WorkspaceDiagnosticReport struct {\n\tItems []WorkspaceDocumentDiagnosticReport `json:\"items\"`\n}\n\n// A partial result for a workspace diagnostic report.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#workspaceDiagnosticReportPartialResult\ntype WorkspaceDiagnosticReportPartialResult struct {\n\tItems []WorkspaceDocumentDiagnosticReport `json:\"items\"`\n}\n\n// A workspace diagnostic document report.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#workspaceDocumentDiagnosticReport\ntype WorkspaceDocumentDiagnosticReport = Or_WorkspaceDocumentDiagnosticReport // (alias)\n// A workspace edit represents changes to many resources managed in the workspace. The edit\n// should either provide `changes` or `documentChanges`. If documentChanges are present\n// they are preferred over `changes` if the client can handle versioned document edits.\n//\n// Since version 3.13.0 a workspace edit can contain resource operations as well. If resource\n// operations are present clients need to execute the operations in the order in which they\n// are provided. So a workspace edit for example can consist of the following two changes:\n// (1) a create file a.txt and (2) a text document edit which insert text into file a.txt.\n//\n// An invalid sequence (e.g. (1) delete file a.txt and (2) insert text into file a.txt) will\n// cause failure of the operation. How the client recovers from the failure is described by\n// the client capability: `workspace.workspaceEdit.failureHandling`\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#workspaceEdit\ntype WorkspaceEdit struct {\n\t// Holds changes to existing resources.\n\tChanges map[DocumentUri][]TextEdit `json:\"changes,omitempty\"`\n\t// Depending on the client capability `workspace.workspaceEdit.resourceOperations` document changes\n\t// are either an array of `TextDocumentEdit`s to express changes to n different text documents\n\t// where each text document edit addresses a specific version of a text document. Or it can contain\n\t// above `TextDocumentEdit`s mixed with create, rename and delete file / folder operations.\n\t//\n\t// Whether a client supports versioned document edits is expressed via\n\t// `workspace.workspaceEdit.documentChanges` client capability.\n\t//\n\t// If a client neither supports `documentChanges` nor `workspace.workspaceEdit.resourceOperations` then\n\t// only plain `TextEdit`s using the `changes` property are supported.\n\tDocumentChanges []DocumentChange `json:\"documentChanges,omitempty\"`\n\t// A map of change annotations that can be referenced in `AnnotatedTextEdit`s or create, rename and\n\t// delete file / folder operations.\n\t//\n\t// Whether clients honor this property depends on the client capability `workspace.changeAnnotationSupport`.\n\t//\n\t// @since 3.16.0\n\tChangeAnnotations map[ChangeAnnotationIdentifier]ChangeAnnotation `json:\"changeAnnotations,omitempty\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#workspaceEditClientCapabilities\ntype WorkspaceEditClientCapabilities struct {\n\t// The client supports versioned document changes in `WorkspaceEdit`s\n\tDocumentChanges bool `json:\"documentChanges,omitempty\"`\n\t// The resource operations the client supports. Clients should at least\n\t// support 'create', 'rename' and 'delete' files and folders.\n\t//\n\t// @since 3.13.0\n\tResourceOperations []ResourceOperationKind `json:\"resourceOperations,omitempty\"`\n\t// The failure handling strategy of a client if applying the workspace edit\n\t// fails.\n\t//\n\t// @since 3.13.0\n\tFailureHandling *FailureHandlingKind `json:\"failureHandling,omitempty\"`\n\t// Whether the client normalizes line endings to the client specific\n\t// setting.\n\t// If set to `true` the client will normalize line ending characters\n\t// in a workspace edit to the client-specified new line\n\t// character.\n\t//\n\t// @since 3.16.0\n\tNormalizesLineEndings bool `json:\"normalizesLineEndings,omitempty\"`\n\t// Whether the client in general supports change annotations on text edits,\n\t// create file, rename file and delete file changes.\n\t//\n\t// @since 3.16.0\n\tChangeAnnotationSupport *ChangeAnnotationsSupportOptions `json:\"changeAnnotationSupport,omitempty\"`\n\t// Whether the client supports `WorkspaceEditMetadata` in `WorkspaceEdit`s.\n\t//\n\t// @since 3.18.0\n\t// @proposed\n\tMetadataSupport bool `json:\"metadataSupport,omitempty\"`\n\t// Whether the client supports snippets as text edits.\n\t//\n\t// @since 3.18.0\n\t// @proposed\n\tSnippetEditSupport bool `json:\"snippetEditSupport,omitempty\"`\n}\n\n// Additional data about a workspace edit.\n//\n// @since 3.18.0\n// @proposed\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#workspaceEditMetadata\ntype WorkspaceEditMetadata struct {\n\t// Signal to the editor that this edit is a refactoring.\n\tIsRefactoring bool `json:\"isRefactoring,omitempty\"`\n}\n\n// A workspace folder inside a client.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#workspaceFolder\ntype WorkspaceFolder struct {\n\t// The associated URI for this workspace folder.\n\tURI URI `json:\"uri\"`\n\t// The name of the workspace folder. Used to refer to this\n\t// workspace folder in the user interface.\n\tName string `json:\"name\"`\n}\n\n// The workspace folder change event.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#workspaceFoldersChangeEvent\ntype WorkspaceFoldersChangeEvent struct {\n\t// The array of added workspace folders\n\tAdded []WorkspaceFolder `json:\"added\"`\n\t// The array of the removed workspace folders\n\tRemoved []WorkspaceFolder `json:\"removed\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#workspaceFoldersInitializeParams\ntype WorkspaceFoldersInitializeParams struct {\n\t// The workspace folders configured in the client when the server starts.\n\t//\n\t// This property is only available if the client supports workspace folders.\n\t// It can be `null` if the client supports workspace folders but none are\n\t// configured.\n\t//\n\t// @since 3.6.0\n\tWorkspaceFolders []WorkspaceFolder `json:\"workspaceFolders,omitempty\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#workspaceFoldersServerCapabilities\ntype WorkspaceFoldersServerCapabilities struct {\n\t// The server has support for workspace folders\n\tSupported bool `json:\"supported,omitempty\"`\n\t// Whether the server wants to receive workspace folder\n\t// change notifications.\n\t//\n\t// If a string is provided the string is treated as an ID\n\t// under which the notification is registered on the client\n\t// side. The ID can be used to unregister for these events\n\t// using the `client/unregisterCapability` request.\n\tChangeNotifications *Or_WorkspaceFoldersServerCapabilities_changeNotifications `json:\"changeNotifications,omitempty\"`\n}\n\n// A full document diagnostic report for a workspace diagnostic result.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#workspaceFullDocumentDiagnosticReport\ntype WorkspaceFullDocumentDiagnosticReport struct {\n\t// The URI for which diagnostic information is reported.\n\tURI DocumentUri `json:\"uri\"`\n\t// The version number for which the diagnostics are reported.\n\t// If the document is not marked as open `null` can be provided.\n\tVersion int32 `json:\"version\"`\n\tFullDocumentDiagnosticReport\n}\n\n// Defines workspace specific capabilities of the server.\n//\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#workspaceOptions\ntype WorkspaceOptions struct {\n\t// The server supports workspace folder.\n\t//\n\t// @since 3.6.0\n\tWorkspaceFolders *WorkspaceFoldersServerCapabilities `json:\"workspaceFolders,omitempty\"`\n\t// The server is interested in notifications/requests for operations on files.\n\t//\n\t// @since 3.16.0\n\tFileOperations *FileOperationOptions `json:\"fileOperations,omitempty\"`\n\t// The server supports the `workspace/textDocumentContent` request.\n\t//\n\t// @since 3.18.0\n\t// @proposed\n\tTextDocumentContent *Or_WorkspaceOptions_textDocumentContent `json:\"textDocumentContent,omitempty\"`\n}\n\n// A special workspace symbol that supports locations without a range.\n//\n// See also SymbolInformation.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#workspaceSymbol\ntype WorkspaceSymbol struct {\n\t// The location of the symbol. Whether a server is allowed to\n\t// return a location without a range depends on the client\n\t// capability `workspace.symbol.resolveSupport`.\n\t//\n\t// See SymbolInformation#location for more details.\n\tLocation Or_WorkspaceSymbol_location `json:\"location\"`\n\t// A data entry field that is preserved on a workspace symbol between a\n\t// workspace symbol request and a workspace symbol resolve request.\n\tData interface{} `json:\"data,omitempty\"`\n\tBaseSymbolInformation\n}\n\n// Client capabilities for a {@link WorkspaceSymbolRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#workspaceSymbolClientCapabilities\ntype WorkspaceSymbolClientCapabilities struct {\n\t// Symbol request supports dynamic registration.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n\t// Specific capabilities for the `SymbolKind` in the `workspace/symbol` request.\n\tSymbolKind *ClientSymbolKindOptions `json:\"symbolKind,omitempty\"`\n\t// The client supports tags on `SymbolInformation`.\n\t// Clients supporting tags have to handle unknown tags gracefully.\n\t//\n\t// @since 3.16.0\n\tTagSupport *ClientSymbolTagOptions `json:\"tagSupport,omitempty\"`\n\t// The client support partial workspace symbols. The client will send the\n\t// request `workspaceSymbol/resolve` to the server to resolve additional\n\t// properties.\n\t//\n\t// @since 3.17.0\n\tResolveSupport *ClientSymbolResolveOptions `json:\"resolveSupport,omitempty\"`\n}\n\n// Server capabilities for a {@link WorkspaceSymbolRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#workspaceSymbolOptions\ntype WorkspaceSymbolOptions struct {\n\t// The server provides support to resolve additional\n\t// information for a workspace symbol.\n\t//\n\t// @since 3.17.0\n\tResolveProvider bool `json:\"resolveProvider,omitempty\"`\n\tWorkDoneProgressOptions\n}\n\n// The parameters of a {@link WorkspaceSymbolRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#workspaceSymbolParams\ntype WorkspaceSymbolParams struct {\n\t// A query string to filter symbols by. Clients may send an empty\n\t// string here to request all symbols.\n\t//\n\t// The `query`-parameter should be interpreted in a *relaxed way* as editors\n\t// will apply their own highlighting and scoring on the results. A good rule\n\t// of thumb is to match case-insensitive and to simply check that the\n\t// characters of *query* appear in their order in a candidate symbol.\n\t// Servers shouldn't use prefix, substring, or similar strict matching.\n\tQuery string `json:\"query\"`\n\tWorkDoneProgressParams\n\tPartialResultParams\n}\n\n// Registration options for a {@link WorkspaceSymbolRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#workspaceSymbolRegistrationOptions\ntype WorkspaceSymbolRegistrationOptions struct {\n\tWorkspaceSymbolOptions\n}\n\n// An unchanged document diagnostic report for a workspace diagnostic result.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#workspaceUnchangedDocumentDiagnosticReport\ntype WorkspaceUnchangedDocumentDiagnosticReport struct {\n\t// The URI for which diagnostic information is reported.\n\tURI DocumentUri `json:\"uri\"`\n\t// The version number for which the diagnostics are reported.\n\t// If the document is not marked as open `null` can be provided.\n\tVersion int32 `json:\"version\"`\n\tUnchangedDocumentDiagnosticReport\n}\n\n// The initialize parameters\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#_InitializeParams\ntype XInitializeParams struct {\n\t// The process Id of the parent process that started\n\t// the server.\n\t//\n\t// Is `null` if the process has not been started by another process.\n\t// If the parent process is not alive then the server should exit.\n\tProcessID int32 `json:\"processId\"`\n\t// Information about the client\n\t//\n\t// @since 3.15.0\n\tClientInfo *ClientInfo `json:\"clientInfo,omitempty\"`\n\t// The locale the client is currently showing the user interface\n\t// in. This must not necessarily be the locale of the operating\n\t// system.\n\t//\n\t// Uses IETF language tags as the value's syntax\n\t// (See https://en.wikipedia.org/wiki/IETF_language_tag)\n\t//\n\t// @since 3.16.0\n\tLocale string `json:\"locale,omitempty\"`\n\t// The rootPath of the workspace. Is null\n\t// if no folder is open.\n\t//\n\t// @deprecated in favour of rootUri.\n\tRootPath string `json:\"rootPath,omitempty\"`\n\t// The rootUri of the workspace. Is null if no\n\t// folder is open. If both `rootPath` and `rootUri` are set\n\t// `rootUri` wins.\n\t//\n\t// @deprecated in favour of workspaceFolders.\n\tRootURI DocumentUri `json:\"rootUri\"`\n\t// The capabilities provided by the client (editor or tool)\n\tCapabilities ClientCapabilities `json:\"capabilities\"`\n\t// User provided initialization options.\n\tInitializationOptions interface{} `json:\"initializationOptions,omitempty\"`\n\t// The initial trace setting. If omitted trace is disabled ('off').\n\tTrace *TraceValue `json:\"trace,omitempty\"`\n\tWorkDoneProgressParams\n}\n\n// The initialize parameters\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#_InitializeParams\ntype _InitializeParams struct {\n\t// The process Id of the parent process that started\n\t// the server.\n\t//\n\t// Is `null` if the process has not been started by another process.\n\t// If the parent process is not alive then the server should exit.\n\tProcessID int32 `json:\"processId\"`\n\t// Information about the client\n\t//\n\t// @since 3.15.0\n\tClientInfo *ClientInfo `json:\"clientInfo,omitempty\"`\n\t// The locale the client is currently showing the user interface\n\t// in. This must not necessarily be the locale of the operating\n\t// system.\n\t//\n\t// Uses IETF language tags as the value's syntax\n\t// (See https://en.wikipedia.org/wiki/IETF_language_tag)\n\t//\n\t// @since 3.16.0\n\tLocale string `json:\"locale,omitempty\"`\n\t// The rootPath of the workspace. Is null\n\t// if no folder is open.\n\t//\n\t// @deprecated in favour of rootUri.\n\tRootPath string `json:\"rootPath,omitempty\"`\n\t// The rootUri of the workspace. Is null if no\n\t// folder is open. If both `rootPath` and `rootUri` are set\n\t// `rootUri` wins.\n\t//\n\t// @deprecated in favour of workspaceFolders.\n\tRootURI DocumentUri `json:\"rootUri\"`\n\t// The capabilities provided by the client (editor or tool)\n\tCapabilities ClientCapabilities `json:\"capabilities\"`\n\t// User provided initialization options.\n\tInitializationOptions interface{} `json:\"initializationOptions,omitempty\"`\n\t// The initial trace setting. If omitted trace is disabled ('off').\n\tTrace *TraceValue `json:\"trace,omitempty\"`\n\tWorkDoneProgressParams\n}\n\nconst (\n\t// A set of predefined code action kinds\n\t// Empty kind.\n\tEmpty CodeActionKind = \"\"\n\t// Base kind for quickfix actions: 'quickfix'\n\tQuickFix CodeActionKind = \"quickfix\"\n\t// Base kind for refactoring actions: 'refactor'\n\tRefactor CodeActionKind = \"refactor\"\n\t// Base kind for refactoring extraction actions: 'refactor.extract'\n\t//\n\t// Example extract actions:\n\t//\n\t//\n\t// - Extract method\n\t// - Extract function\n\t// - Extract variable\n\t// - Extract interface from class\n\t// - ...\n\tRefactorExtract CodeActionKind = \"refactor.extract\"\n\t// Base kind for refactoring inline actions: 'refactor.inline'\n\t//\n\t// Example inline actions:\n\t//\n\t//\n\t// - Inline function\n\t// - Inline variable\n\t// - Inline constant\n\t// - ...\n\tRefactorInline CodeActionKind = \"refactor.inline\"\n\t// Base kind for refactoring move actions: `refactor.move`\n\t//\n\t// Example move actions:\n\t//\n\t//\n\t// - Move a function to a new file\n\t// - Move a property between classes\n\t// - Move method to base class\n\t// - ...\n\t//\n\t// @since 3.18.0\n\t// @proposed\n\tRefactorMove CodeActionKind = \"refactor.move\"\n\t// Base kind for refactoring rewrite actions: 'refactor.rewrite'\n\t//\n\t// Example rewrite actions:\n\t//\n\t//\n\t// - Convert JavaScript function to class\n\t// - Add or remove parameter\n\t// - Encapsulate field\n\t// - Make method static\n\t// - Move method to base class\n\t// - ...\n\tRefactorRewrite CodeActionKind = \"refactor.rewrite\"\n\t// Base kind for source actions: `source`\n\t//\n\t// Source code actions apply to the entire file.\n\tSource CodeActionKind = \"source\"\n\t// Base kind for an organize imports source action: `source.organizeImports`\n\tSourceOrganizeImports CodeActionKind = \"source.organizeImports\"\n\t// Base kind for auto-fix source actions: `source.fixAll`.\n\t//\n\t// Fix all actions automatically fix errors that have a clear fix that do not require user input.\n\t// They should not suppress errors or perform unsafe fixes such as generating new types or classes.\n\t//\n\t// @since 3.15.0\n\tSourceFixAll CodeActionKind = \"source.fixAll\"\n\t// Base kind for all code actions applying to the entire notebook's scope. CodeActionKinds using\n\t// this should always begin with `notebook.`\n\t//\n\t// @since 3.18.0\n\tNotebook CodeActionKind = \"notebook\"\n\t// The reason why code actions were requested.\n\t//\n\t// @since 3.17.0\n\t// Code actions were explicitly requested by the user or by an extension.\n\tCodeActionInvoked CodeActionTriggerKind = 1\n\t// Code actions were requested automatically.\n\t//\n\t// This typically happens when current selection in a file changes, but can\n\t// also be triggered when file content changes.\n\tCodeActionAutomatic CodeActionTriggerKind = 2\n\t// The kind of a completion entry.\n\tTextCompletion CompletionItemKind = 1\n\tMethodCompletion CompletionItemKind = 2\n\tFunctionCompletion CompletionItemKind = 3\n\tConstructorCompletion CompletionItemKind = 4\n\tFieldCompletion CompletionItemKind = 5\n\tVariableCompletion CompletionItemKind = 6\n\tClassCompletion CompletionItemKind = 7\n\tInterfaceCompletion CompletionItemKind = 8\n\tModuleCompletion CompletionItemKind = 9\n\tPropertyCompletion CompletionItemKind = 10\n\tUnitCompletion CompletionItemKind = 11\n\tValueCompletion CompletionItemKind = 12\n\tEnumCompletion CompletionItemKind = 13\n\tKeywordCompletion CompletionItemKind = 14\n\tSnippetCompletion CompletionItemKind = 15\n\tColorCompletion CompletionItemKind = 16\n\tFileCompletion CompletionItemKind = 17\n\tReferenceCompletion CompletionItemKind = 18\n\tFolderCompletion CompletionItemKind = 19\n\tEnumMemberCompletion CompletionItemKind = 20\n\tConstantCompletion CompletionItemKind = 21\n\tStructCompletion CompletionItemKind = 22\n\tEventCompletion CompletionItemKind = 23\n\tOperatorCompletion CompletionItemKind = 24\n\tTypeParameterCompletion CompletionItemKind = 25\n\t// Completion item tags are extra annotations that tweak the rendering of a completion\n\t// item.\n\t//\n\t// @since 3.15.0\n\t// Render a completion as obsolete, usually using a strike-out.\n\tComplDeprecated CompletionItemTag = 1\n\t// How a completion was triggered\n\t// Completion was triggered by typing an identifier (24x7 code\n\t// complete), manual invocation (e.g Ctrl+Space) or via API.\n\tInvoked CompletionTriggerKind = 1\n\t// Completion was triggered by a trigger character specified by\n\t// the `triggerCharacters` properties of the `CompletionRegistrationOptions`.\n\tTriggerCharacter CompletionTriggerKind = 2\n\t// Completion was re-triggered as current completion list is incomplete\n\tTriggerForIncompleteCompletions CompletionTriggerKind = 3\n\t// The diagnostic's severity.\n\t// Reports an error.\n\tSeverityError DiagnosticSeverity = 1\n\t// Reports a warning.\n\tSeverityWarning DiagnosticSeverity = 2\n\t// Reports an information.\n\tSeverityInformation DiagnosticSeverity = 3\n\t// Reports a hint.\n\tSeverityHint DiagnosticSeverity = 4\n\t// The diagnostic tags.\n\t//\n\t// @since 3.15.0\n\t// Unused or unnecessary code.\n\t//\n\t// Clients are allowed to render diagnostics with this tag faded out instead of having\n\t// an error squiggle.\n\tUnnecessary DiagnosticTag = 1\n\t// Deprecated or obsolete code.\n\t//\n\t// Clients are allowed to rendered diagnostics with this tag strike through.\n\tDeprecated DiagnosticTag = 2\n\t// The document diagnostic report kinds.\n\t//\n\t// @since 3.17.0\n\t// A diagnostic report with a full\n\t// set of problems.\n\tDiagnosticFull DocumentDiagnosticReportKind = \"full\"\n\t// A report indicating that the last\n\t// returned report is still accurate.\n\tDiagnosticUnchanged DocumentDiagnosticReportKind = \"unchanged\"\n\t// A document highlight kind.\n\t// A textual occurrence.\n\tText DocumentHighlightKind = 1\n\t// Read-access of a symbol, like reading a variable.\n\tRead DocumentHighlightKind = 2\n\t// Write-access of a symbol, like writing to a variable.\n\tWrite DocumentHighlightKind = 3\n\t// Predefined error codes.\n\tParseError ErrorCodes = -32700\n\tInvalidRequest ErrorCodes = -32600\n\tMethodNotFound ErrorCodes = -32601\n\tInvalidParams ErrorCodes = -32602\n\tInternalError ErrorCodes = -32603\n\t// Error code indicating that a server received a notification or\n\t// request before the server has received the `initialize` request.\n\tServerNotInitialized ErrorCodes = -32002\n\tUnknownErrorCode ErrorCodes = -32001\n\t// Applying the workspace change is simply aborted if one of the changes provided\n\t// fails. All operations executed before the failing operation stay executed.\n\tAbort FailureHandlingKind = \"abort\"\n\t// All operations are executed transactional. That means they either all\n\t// succeed or no changes at all are applied to the workspace.\n\tTransactional FailureHandlingKind = \"transactional\"\n\t// If the workspace edit contains only textual file changes they are executed transactional.\n\t// If resource changes (create, rename or delete file) are part of the change the failure\n\t// handling strategy is abort.\n\tTextOnlyTransactional FailureHandlingKind = \"textOnlyTransactional\"\n\t// The client tries to undo the operations already executed. But there is no\n\t// guarantee that this is succeeding.\n\tUndo FailureHandlingKind = \"undo\"\n\t// The file event type\n\t// The file got created.\n\tCreated FileChangeType = 1\n\t// The file got changed.\n\tChanged FileChangeType = 2\n\t// The file got deleted.\n\tDeleted FileChangeType = 3\n\t// A pattern kind describing if a glob pattern matches a file a folder or\n\t// both.\n\t//\n\t// @since 3.16.0\n\t// The pattern matches a file only.\n\tFilePattern FileOperationPatternKind = \"file\"\n\t// The pattern matches a folder only.\n\tFolderPattern FileOperationPatternKind = \"folder\"\n\t// A set of predefined range kinds.\n\t// Folding range for a comment\n\tComment FoldingRangeKind = \"comment\"\n\t// Folding range for an import or include\n\tImports FoldingRangeKind = \"imports\"\n\t// Folding range for a region (e.g. `#region`)\n\tRegion FoldingRangeKind = \"region\"\n\t// Inlay hint kinds.\n\t//\n\t// @since 3.17.0\n\t// An inlay hint that for a type annotation.\n\tType InlayHintKind = 1\n\t// An inlay hint that is for a parameter.\n\tParameter InlayHintKind = 2\n\t// Describes how an {@link InlineCompletionItemProvider inline completion provider} was triggered.\n\t//\n\t// @since 3.18.0\n\t// @proposed\n\t// Completion was triggered explicitly by a user gesture.\n\tInlineInvoked InlineCompletionTriggerKind = 1\n\t// Completion was triggered automatically while editing.\n\tInlineAutomatic InlineCompletionTriggerKind = 2\n\t// Defines whether the insert text in a completion item should be interpreted as\n\t// plain text or a snippet.\n\t// The primary text to be inserted is treated as a plain string.\n\tPlainTextTextFormat InsertTextFormat = 1\n\t// The primary text to be inserted is treated as a snippet.\n\t//\n\t// A snippet can define tab stops and placeholders with `$1`, `$2`\n\t// and `${3:foo}`. `$0` defines the final tab stop, it defaults to\n\t// the end of the snippet. Placeholders with equal identifiers are linked,\n\t// that is typing in one will update others too.\n\t//\n\t// See also: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#snippet_syntax\n\tSnippetTextFormat InsertTextFormat = 2\n\t// How whitespace and indentation is handled during completion\n\t// item insertion.\n\t//\n\t// @since 3.16.0\n\t// The insertion or replace strings is taken as it is. If the\n\t// value is multi line the lines below the cursor will be\n\t// inserted using the indentation defined in the string value.\n\t// The client will not apply any kind of adjustments to the\n\t// string.\n\tAsIs InsertTextMode = 1\n\t// The editor adjusts leading whitespace of new lines so that\n\t// they match the indentation up to the cursor of the line for\n\t// which the item is accepted.\n\t//\n\t// Consider a line like this: <2tabs><3tabs>foo. Accepting a\n\t// multi line completion item is indented using 2 tabs and all\n\t// following lines inserted will be indented using 2 tabs as well.\n\tAdjustIndentation InsertTextMode = 2\n\t// A request failed but it was syntactically correct, e.g the\n\t// method name was known and the parameters were valid. The error\n\t// message should contain human readable information about why\n\t// the request failed.\n\t//\n\t// @since 3.17.0\n\tRequestFailed LSPErrorCodes = -32803\n\t// The server cancelled the request. This error code should\n\t// only be used for requests that explicitly support being\n\t// server cancellable.\n\t//\n\t// @since 3.17.0\n\tServerCancelled LSPErrorCodes = -32802\n\t// The server detected that the content of a document got\n\t// modified outside normal conditions. A server should\n\t// NOT send this error code if it detects a content change\n\t// in it unprocessed messages. The result even computed\n\t// on an older state might still be useful for the client.\n\t//\n\t// If a client decides that a result is not of any use anymore\n\t// the client should cancel the request.\n\tContentModified LSPErrorCodes = -32801\n\t// The client has canceled a request and a server has detected\n\t// the cancel.\n\tRequestCancelled LSPErrorCodes = -32800\n\t// Predefined Language kinds\n\t// @since 3.18.0\n\t// @proposed\n\tLangABAP LanguageKind = \"abap\"\n\tLangWindowsBat LanguageKind = \"bat\"\n\tLangBibTeX LanguageKind = \"bibtex\"\n\tLangClojure LanguageKind = \"clojure\"\n\tLangCoffeescript LanguageKind = \"coffeescript\"\n\tLangC LanguageKind = \"c\"\n\tLangCPP LanguageKind = \"cpp\"\n\tLangCSharp LanguageKind = \"csharp\"\n\tLangCSS LanguageKind = \"css\"\n\t// @since 3.18.0\n\t// @proposed\n\tLangD LanguageKind = \"d\"\n\t// @since 3.18.0\n\t// @proposed\n\tLangDelphi LanguageKind = \"pascal\"\n\tLangDiff LanguageKind = \"diff\"\n\tLangDart LanguageKind = \"dart\"\n\tLangDockerfile LanguageKind = \"dockerfile\"\n\tLangElixir LanguageKind = \"elixir\"\n\tLangErlang LanguageKind = \"erlang\"\n\tLangFSharp LanguageKind = \"fsharp\"\n\tLangGitCommit LanguageKind = \"git-commit\"\n\tLangGitRebase LanguageKind = \"rebase\"\n\tLangGo LanguageKind = \"go\"\n\tLangGroovy LanguageKind = \"groovy\"\n\tLangHandlebars LanguageKind = \"handlebars\"\n\tLangHaskell LanguageKind = \"haskell\"\n\tLangHTML LanguageKind = \"html\"\n\tLangIni LanguageKind = \"ini\"\n\tLangJava LanguageKind = \"java\"\n\tLangJavaScript LanguageKind = \"javascript\"\n\tLangJavaScriptReact LanguageKind = \"javascriptreact\"\n\tLangJSON LanguageKind = \"json\"\n\tLangLaTeX LanguageKind = \"latex\"\n\tLangLess LanguageKind = \"less\"\n\tLangLua LanguageKind = \"lua\"\n\tLangMakefile LanguageKind = \"makefile\"\n\tLangMarkdown LanguageKind = \"markdown\"\n\tLangObjectiveC LanguageKind = \"objective-c\"\n\tLangObjectiveCPP LanguageKind = \"objective-cpp\"\n\t// @since 3.18.0\n\t// @proposed\n\tLangPascal LanguageKind = \"pascal\"\n\tLangPerl LanguageKind = \"perl\"\n\tLangPerl6 LanguageKind = \"perl6\"\n\tLangPHP LanguageKind = \"php\"\n\tLangPowershell LanguageKind = \"powershell\"\n\tLangPug LanguageKind = \"jade\"\n\tLangPython LanguageKind = \"python\"\n\tLangR LanguageKind = \"r\"\n\tLangRazor LanguageKind = \"razor\"\n\tLangRuby LanguageKind = \"ruby\"\n\tLangRust LanguageKind = \"rust\"\n\tLangSCSS LanguageKind = \"scss\"\n\tLangSASS LanguageKind = \"sass\"\n\tLangScala LanguageKind = \"scala\"\n\tLangShaderLab LanguageKind = \"shaderlab\"\n\tLangShellScript LanguageKind = \"shellscript\"\n\tLangSQL LanguageKind = \"sql\"\n\tLangSwift LanguageKind = \"swift\"\n\tLangTypeScript LanguageKind = \"typescript\"\n\tLangTypeScriptReact LanguageKind = \"typescriptreact\"\n\tLangTeX LanguageKind = \"tex\"\n\tLangVisualBasic LanguageKind = \"vb\"\n\tLangXML LanguageKind = \"xml\"\n\tLangXSL LanguageKind = \"xsl\"\n\tLangYAML LanguageKind = \"yaml\"\n\t// Describes the content type that a client supports in various\n\t// result literals like `Hover`, `ParameterInfo` or `CompletionItem`.\n\t//\n\t// Please note that `MarkupKinds` must not start with a `$`. This kinds\n\t// are reserved for internal usage.\n\t// Plain text is supported as a content format\n\tPlainText MarkupKind = \"plaintext\"\n\t// Markdown is supported as a content format\n\tMarkdown MarkupKind = \"markdown\"\n\t// The message type\n\t// An error message.\n\tError MessageType = 1\n\t// A warning message.\n\tWarning MessageType = 2\n\t// An information message.\n\tInfo MessageType = 3\n\t// A log message.\n\tLog MessageType = 4\n\t// A debug message.\n\t//\n\t// @since 3.18.0\n\t// @proposed\n\tDebug MessageType = 5\n\t// The moniker kind.\n\t//\n\t// @since 3.16.0\n\t// The moniker represent a symbol that is imported into a project\n\tImport MonikerKind = \"import\"\n\t// The moniker represents a symbol that is exported from a project\n\tExport MonikerKind = \"export\"\n\t// The moniker represents a symbol that is local to a project (e.g. a local\n\t// variable of a function, a class not visible outside the project, ...)\n\tLocal MonikerKind = \"local\"\n\t// A notebook cell kind.\n\t//\n\t// @since 3.17.0\n\t// A markup-cell is formatted source that is used for display.\n\tMarkup NotebookCellKind = 1\n\t// A code-cell is source code.\n\tCode NotebookCellKind = 2\n\t// A set of predefined position encoding kinds.\n\t//\n\t// @since 3.17.0\n\t// Character offsets count UTF-8 code units (e.g. bytes).\n\tUTF8 PositionEncodingKind = \"utf-8\"\n\t// Character offsets count UTF-16 code units.\n\t//\n\t// This is the default and must always be supported\n\t// by servers\n\tUTF16 PositionEncodingKind = \"utf-16\"\n\t// Character offsets count UTF-32 code units.\n\t//\n\t// Implementation note: these are the same as Unicode codepoints,\n\t// so this `PositionEncodingKind` may also be used for an\n\t// encoding-agnostic representation of character offsets.\n\tUTF32 PositionEncodingKind = \"utf-32\"\n\t// The client's default behavior is to select the identifier\n\t// according the to language's syntax rule.\n\tIdentifier PrepareSupportDefaultBehavior = 1\n\t// Supports creating new files and folders.\n\tCreate ResourceOperationKind = \"create\"\n\t// Supports renaming existing files and folders.\n\tRename ResourceOperationKind = \"rename\"\n\t// Supports deleting existing files and folders.\n\tDelete ResourceOperationKind = \"delete\"\n\t// A set of predefined token modifiers. This set is not fixed\n\t// an clients can specify additional token types via the\n\t// corresponding client capabilities.\n\t//\n\t// @since 3.16.0\n\tModDeclaration SemanticTokenModifiers = \"declaration\"\n\tModDefinition SemanticTokenModifiers = \"definition\"\n\tModReadonly SemanticTokenModifiers = \"readonly\"\n\tModStatic SemanticTokenModifiers = \"static\"\n\tModDeprecated SemanticTokenModifiers = \"deprecated\"\n\tModAbstract SemanticTokenModifiers = \"abstract\"\n\tModAsync SemanticTokenModifiers = \"async\"\n\tModModification SemanticTokenModifiers = \"modification\"\n\tModDocumentation SemanticTokenModifiers = \"documentation\"\n\tModDefaultLibrary SemanticTokenModifiers = \"defaultLibrary\"\n\t// A set of predefined token types. This set is not fixed\n\t// an clients can specify additional token types via the\n\t// corresponding client capabilities.\n\t//\n\t// @since 3.16.0\n\tNamespaceType SemanticTokenTypes = \"namespace\"\n\t// Represents a generic type. Acts as a fallback for types which can't be mapped to\n\t// a specific type like class or enum.\n\tTypeType SemanticTokenTypes = \"type\"\n\tClassType SemanticTokenTypes = \"class\"\n\tEnumType SemanticTokenTypes = \"enum\"\n\tInterfaceType SemanticTokenTypes = \"interface\"\n\tStructType SemanticTokenTypes = \"struct\"\n\tTypeParameterType SemanticTokenTypes = \"typeParameter\"\n\tParameterType SemanticTokenTypes = \"parameter\"\n\tVariableType SemanticTokenTypes = \"variable\"\n\tPropertyType SemanticTokenTypes = \"property\"\n\tEnumMemberType SemanticTokenTypes = \"enumMember\"\n\tEventType SemanticTokenTypes = \"event\"\n\tFunctionType SemanticTokenTypes = \"function\"\n\tMethodType SemanticTokenTypes = \"method\"\n\tMacroType SemanticTokenTypes = \"macro\"\n\tKeywordType SemanticTokenTypes = \"keyword\"\n\tModifierType SemanticTokenTypes = \"modifier\"\n\tCommentType SemanticTokenTypes = \"comment\"\n\tStringType SemanticTokenTypes = \"string\"\n\tNumberType SemanticTokenTypes = \"number\"\n\tRegexpType SemanticTokenTypes = \"regexp\"\n\tOperatorType SemanticTokenTypes = \"operator\"\n\t// @since 3.17.0\n\tDecoratorType SemanticTokenTypes = \"decorator\"\n\t// @since 3.18.0\n\tLabelType SemanticTokenTypes = \"label\"\n\t// How a signature help was triggered.\n\t//\n\t// @since 3.15.0\n\t// Signature help was invoked manually by the user or by a command.\n\tSigInvoked SignatureHelpTriggerKind = 1\n\t// Signature help was triggered by a trigger character.\n\tSigTriggerCharacter SignatureHelpTriggerKind = 2\n\t// Signature help was triggered by the cursor moving or by the document content changing.\n\tSigContentChange SignatureHelpTriggerKind = 3\n\t// A symbol kind.\n\tFile SymbolKind = 1\n\tModule SymbolKind = 2\n\tNamespace SymbolKind = 3\n\tPackage SymbolKind = 4\n\tClass SymbolKind = 5\n\tMethod SymbolKind = 6\n\tProperty SymbolKind = 7\n\tField SymbolKind = 8\n\tConstructor SymbolKind = 9\n\tEnum SymbolKind = 10\n\tInterface SymbolKind = 11\n\tFunction SymbolKind = 12\n\tVariable SymbolKind = 13\n\tConstant SymbolKind = 14\n\tString SymbolKind = 15\n\tNumber SymbolKind = 16\n\tBoolean SymbolKind = 17\n\tArray SymbolKind = 18\n\tObject SymbolKind = 19\n\tKey SymbolKind = 20\n\tNull SymbolKind = 21\n\tEnumMember SymbolKind = 22\n\tStruct SymbolKind = 23\n\tEvent SymbolKind = 24\n\tOperator SymbolKind = 25\n\tTypeParameter SymbolKind = 26\n\t// Symbol tags are extra annotations that tweak the rendering of a symbol.\n\t//\n\t// @since 3.16\n\t// Render a symbol as obsolete, usually using a strike-out.\n\tDeprecatedSymbol SymbolTag = 1\n\t// Represents reasons why a text document is saved.\n\t// Manually triggered, e.g. by the user pressing save, by starting debugging,\n\t// or by an API call.\n\tManual TextDocumentSaveReason = 1\n\t// Automatic after a delay.\n\tAfterDelay TextDocumentSaveReason = 2\n\t// When the editor lost focus.\n\tFocusOut TextDocumentSaveReason = 3\n\t// Defines how the host (editor) should sync\n\t// document changes to the language server.\n\t// Documents should not be synced at all.\n\tNone TextDocumentSyncKind = 0\n\t// Documents are synced by always sending the full content\n\t// of the document.\n\tFull TextDocumentSyncKind = 1\n\t// Documents are synced by sending the full content on open.\n\t// After that only incremental updates to the document are\n\t// send.\n\tIncremental TextDocumentSyncKind = 2\n\tRelative TokenFormat = \"relative\"\n\t// Turn tracing off.\n\tOff TraceValue = \"off\"\n\t// Trace messages only.\n\tMessages TraceValue = \"messages\"\n\t// Verbose message tracing.\n\tVerbose TraceValue = \"verbose\"\n\t// Moniker uniqueness level to define scope of the moniker.\n\t//\n\t// @since 3.16.0\n\t// The moniker is only unique inside a document\n\tDocument UniquenessLevel = \"document\"\n\t// The moniker is unique inside a project for which a dump got created\n\tProject UniquenessLevel = \"project\"\n\t// The moniker is unique inside the group to which a project belongs\n\tGroup UniquenessLevel = \"group\"\n\t// The moniker is unique inside the moniker scheme.\n\tScheme UniquenessLevel = \"scheme\"\n\t// The moniker is globally unique\n\tGlobal UniquenessLevel = \"global\"\n\t// Interested in create events.\n\tWatchCreate WatchKind = 1\n\t// Interested in change events\n\tWatchChange WatchKind = 2\n\t// Interested in delete events\n\tWatchDelete WatchKind = 4\n)\n"], ["/opencode/internal/tui/layout/split.go", "package layout\n\nimport (\n\t\"github.com/charmbracelet/bubbles/key\"\n\ttea \"github.com/charmbracelet/bubbletea\"\n\t\"github.com/charmbracelet/lipgloss\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n)\n\ntype SplitPaneLayout interface {\n\ttea.Model\n\tSizeable\n\tBindings\n\tSetLeftPanel(panel Container) tea.Cmd\n\tSetRightPanel(panel Container) tea.Cmd\n\tSetBottomPanel(panel Container) tea.Cmd\n\n\tClearLeftPanel() tea.Cmd\n\tClearRightPanel() tea.Cmd\n\tClearBottomPanel() tea.Cmd\n}\n\ntype splitPaneLayout struct {\n\twidth int\n\theight int\n\tratio float64\n\tverticalRatio float64\n\n\trightPanel Container\n\tleftPanel Container\n\tbottomPanel Container\n}\n\ntype SplitPaneOption func(*splitPaneLayout)\n\nfunc (s *splitPaneLayout) Init() tea.Cmd {\n\tvar cmds []tea.Cmd\n\n\tif s.leftPanel != nil {\n\t\tcmds = append(cmds, s.leftPanel.Init())\n\t}\n\n\tif s.rightPanel != nil {\n\t\tcmds = append(cmds, s.rightPanel.Init())\n\t}\n\n\tif s.bottomPanel != nil {\n\t\tcmds = append(cmds, s.bottomPanel.Init())\n\t}\n\n\treturn tea.Batch(cmds...)\n}\n\nfunc (s *splitPaneLayout) Update(msg tea.Msg) (tea.Model, tea.Cmd) {\n\tvar cmds []tea.Cmd\n\tswitch msg := msg.(type) {\n\tcase tea.WindowSizeMsg:\n\t\treturn s, s.SetSize(msg.Width, msg.Height)\n\t}\n\n\tif s.rightPanel != nil {\n\t\tu, cmd := s.rightPanel.Update(msg)\n\t\ts.rightPanel = u.(Container)\n\t\tif cmd != nil {\n\t\t\tcmds = append(cmds, cmd)\n\t\t}\n\t}\n\n\tif s.leftPanel != nil {\n\t\tu, cmd := s.leftPanel.Update(msg)\n\t\ts.leftPanel = u.(Container)\n\t\tif cmd != nil {\n\t\t\tcmds = append(cmds, cmd)\n\t\t}\n\t}\n\n\tif s.bottomPanel != nil {\n\t\tu, cmd := s.bottomPanel.Update(msg)\n\t\ts.bottomPanel = u.(Container)\n\t\tif cmd != nil {\n\t\t\tcmds = append(cmds, cmd)\n\t\t}\n\t}\n\n\treturn s, tea.Batch(cmds...)\n}\n\nfunc (s *splitPaneLayout) View() string {\n\tvar topSection string\n\n\tif s.leftPanel != nil && s.rightPanel != nil {\n\t\tleftView := s.leftPanel.View()\n\t\trightView := s.rightPanel.View()\n\t\ttopSection = lipgloss.JoinHorizontal(lipgloss.Top, leftView, rightView)\n\t} else if s.leftPanel != nil {\n\t\ttopSection = s.leftPanel.View()\n\t} else if s.rightPanel != nil {\n\t\ttopSection = s.rightPanel.View()\n\t} else {\n\t\ttopSection = \"\"\n\t}\n\n\tvar finalView string\n\n\tif s.bottomPanel != nil && topSection != \"\" {\n\t\tbottomView := s.bottomPanel.View()\n\t\tfinalView = lipgloss.JoinVertical(lipgloss.Left, topSection, bottomView)\n\t} else if s.bottomPanel != nil {\n\t\tfinalView = s.bottomPanel.View()\n\t} else {\n\t\tfinalView = topSection\n\t}\n\n\tif finalView != \"\" {\n\t\tt := theme.CurrentTheme()\n\n\t\tstyle := lipgloss.NewStyle().\n\t\t\tWidth(s.width).\n\t\t\tHeight(s.height).\n\t\t\tBackground(t.Background())\n\n\t\treturn style.Render(finalView)\n\t}\n\n\treturn finalView\n}\n\nfunc (s *splitPaneLayout) SetSize(width, height int) tea.Cmd {\n\ts.width = width\n\ts.height = height\n\n\tvar topHeight, bottomHeight int\n\tif s.bottomPanel != nil {\n\t\ttopHeight = int(float64(height) * s.verticalRatio)\n\t\tbottomHeight = height - topHeight\n\t} else {\n\t\ttopHeight = height\n\t\tbottomHeight = 0\n\t}\n\n\tvar leftWidth, rightWidth int\n\tif s.leftPanel != nil && s.rightPanel != nil {\n\t\tleftWidth = int(float64(width) * s.ratio)\n\t\trightWidth = width - leftWidth\n\t} else if s.leftPanel != nil {\n\t\tleftWidth = width\n\t\trightWidth = 0\n\t} else if s.rightPanel != nil {\n\t\tleftWidth = 0\n\t\trightWidth = width\n\t}\n\n\tvar cmds []tea.Cmd\n\tif s.leftPanel != nil {\n\t\tcmd := s.leftPanel.SetSize(leftWidth, topHeight)\n\t\tcmds = append(cmds, cmd)\n\t}\n\n\tif s.rightPanel != nil {\n\t\tcmd := s.rightPanel.SetSize(rightWidth, topHeight)\n\t\tcmds = append(cmds, cmd)\n\t}\n\n\tif s.bottomPanel != nil {\n\t\tcmd := s.bottomPanel.SetSize(width, bottomHeight)\n\t\tcmds = append(cmds, cmd)\n\t}\n\treturn tea.Batch(cmds...)\n}\n\nfunc (s *splitPaneLayout) GetSize() (int, int) {\n\treturn s.width, s.height\n}\n\nfunc (s *splitPaneLayout) SetLeftPanel(panel Container) tea.Cmd {\n\ts.leftPanel = panel\n\tif s.width > 0 && s.height > 0 {\n\t\treturn s.SetSize(s.width, s.height)\n\t}\n\treturn nil\n}\n\nfunc (s *splitPaneLayout) SetRightPanel(panel Container) tea.Cmd {\n\ts.rightPanel = panel\n\tif s.width > 0 && s.height > 0 {\n\t\treturn s.SetSize(s.width, s.height)\n\t}\n\treturn nil\n}\n\nfunc (s *splitPaneLayout) SetBottomPanel(panel Container) tea.Cmd {\n\ts.bottomPanel = panel\n\tif s.width > 0 && s.height > 0 {\n\t\treturn s.SetSize(s.width, s.height)\n\t}\n\treturn nil\n}\n\nfunc (s *splitPaneLayout) ClearLeftPanel() tea.Cmd {\n\ts.leftPanel = nil\n\tif s.width > 0 && s.height > 0 {\n\t\treturn s.SetSize(s.width, s.height)\n\t}\n\treturn nil\n}\n\nfunc (s *splitPaneLayout) ClearRightPanel() tea.Cmd {\n\ts.rightPanel = nil\n\tif s.width > 0 && s.height > 0 {\n\t\treturn s.SetSize(s.width, s.height)\n\t}\n\treturn nil\n}\n\nfunc (s *splitPaneLayout) ClearBottomPanel() tea.Cmd {\n\ts.bottomPanel = nil\n\tif s.width > 0 && s.height > 0 {\n\t\treturn s.SetSize(s.width, s.height)\n\t}\n\treturn nil\n}\n\nfunc (s *splitPaneLayout) BindingKeys() []key.Binding {\n\tkeys := []key.Binding{}\n\tif s.leftPanel != nil {\n\t\tif b, ok := s.leftPanel.(Bindings); ok {\n\t\t\tkeys = append(keys, b.BindingKeys()...)\n\t\t}\n\t}\n\tif s.rightPanel != nil {\n\t\tif b, ok := s.rightPanel.(Bindings); ok {\n\t\t\tkeys = append(keys, b.BindingKeys()...)\n\t\t}\n\t}\n\tif s.bottomPanel != nil {\n\t\tif b, ok := s.bottomPanel.(Bindings); ok {\n\t\t\tkeys = append(keys, b.BindingKeys()...)\n\t\t}\n\t}\n\treturn keys\n}\n\nfunc NewSplitPane(options ...SplitPaneOption) SplitPaneLayout {\n\n\tlayout := &splitPaneLayout{\n\t\tratio: 0.7,\n\t\tverticalRatio: 0.9, // Default 90% for top section, 10% for bottom\n\t}\n\tfor _, option := range options {\n\t\toption(layout)\n\t}\n\treturn layout\n}\n\nfunc WithLeftPanel(panel Container) SplitPaneOption {\n\treturn func(s *splitPaneLayout) {\n\t\ts.leftPanel = panel\n\t}\n}\n\nfunc WithRightPanel(panel Container) SplitPaneOption {\n\treturn func(s *splitPaneLayout) {\n\t\ts.rightPanel = panel\n\t}\n}\n\nfunc WithRatio(ratio float64) SplitPaneOption {\n\treturn func(s *splitPaneLayout) {\n\t\ts.ratio = ratio\n\t}\n}\n\nfunc WithBottomPanel(panel Container) SplitPaneOption {\n\treturn func(s *splitPaneLayout) {\n\t\ts.bottomPanel = panel\n\t}\n}\n\nfunc WithVerticalRatio(ratio float64) SplitPaneOption {\n\treturn func(s *splitPaneLayout) {\n\t\ts.verticalRatio = ratio\n\t}\n}\n"], ["/opencode/internal/tui/layout/overlay.go", "package layout\n\nimport (\n\t\"strings\"\n\n\t\"github.com/charmbracelet/lipgloss\"\n\tchAnsi \"github.com/charmbracelet/x/ansi\"\n\t\"github.com/muesli/ansi\"\n\t\"github.com/muesli/reflow/truncate\"\n\t\"github.com/muesli/termenv\"\n\t\"github.com/opencode-ai/opencode/internal/tui/styles\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n\t\"github.com/opencode-ai/opencode/internal/tui/util\"\n)\n\n// Most of this code is borrowed from\n// https://github.com/charmbracelet/lipgloss/pull/102\n// as well as the lipgloss library, with some modification for what I needed.\n\n// Split a string into lines, additionally returning the size of the widest\n// line.\nfunc getLines(s string) (lines []string, widest int) {\n\tlines = strings.Split(s, \"\\n\")\n\n\tfor _, l := range lines {\n\t\tw := ansi.PrintableRuneWidth(l)\n\t\tif widest < w {\n\t\t\twidest = w\n\t\t}\n\t}\n\n\treturn lines, widest\n}\n\n// PlaceOverlay places fg on top of bg.\nfunc PlaceOverlay(\n\tx, y int,\n\tfg, bg string,\n\tshadow bool, opts ...WhitespaceOption,\n) string {\n\tfgLines, fgWidth := getLines(fg)\n\tbgLines, bgWidth := getLines(bg)\n\tbgHeight := len(bgLines)\n\tfgHeight := len(fgLines)\n\n\tif shadow {\n\t\tt := theme.CurrentTheme()\n\t\tbaseStyle := styles.BaseStyle()\n\n\t\tvar shadowbg string = \"\"\n\t\tshadowchar := lipgloss.NewStyle().\n\t\t\tBackground(t.BackgroundDarker()).\n\t\t\tForeground(t.Background()).\n\t\t\tRender(\"░\")\n\t\tbgchar := baseStyle.Render(\" \")\n\t\tfor i := 0; i <= fgHeight; i++ {\n\t\t\tif i == 0 {\n\t\t\t\tshadowbg += bgchar + strings.Repeat(bgchar, fgWidth) + \"\\n\"\n\t\t\t} else {\n\t\t\t\tshadowbg += bgchar + strings.Repeat(shadowchar, fgWidth) + \"\\n\"\n\t\t\t}\n\t\t}\n\n\t\tfg = PlaceOverlay(0, 0, fg, shadowbg, false, opts...)\n\t\tfgLines, fgWidth = getLines(fg)\n\t\tfgHeight = len(fgLines)\n\t}\n\n\tif fgWidth >= bgWidth && fgHeight >= bgHeight {\n\t\t// FIXME: return fg or bg?\n\t\treturn fg\n\t}\n\t// TODO: allow placement outside of the bg box?\n\tx = util.Clamp(x, 0, bgWidth-fgWidth)\n\ty = util.Clamp(y, 0, bgHeight-fgHeight)\n\n\tws := &whitespace{}\n\tfor _, opt := range opts {\n\t\topt(ws)\n\t}\n\n\tvar b strings.Builder\n\tfor i, bgLine := range bgLines {\n\t\tif i > 0 {\n\t\t\tb.WriteByte('\\n')\n\t\t}\n\t\tif i < y || i >= y+fgHeight {\n\t\t\tb.WriteString(bgLine)\n\t\t\tcontinue\n\t\t}\n\n\t\tpos := 0\n\t\tif x > 0 {\n\t\t\tleft := truncate.String(bgLine, uint(x))\n\t\t\tpos = ansi.PrintableRuneWidth(left)\n\t\t\tb.WriteString(left)\n\t\t\tif pos < x {\n\t\t\t\tb.WriteString(ws.render(x - pos))\n\t\t\t\tpos = x\n\t\t\t}\n\t\t}\n\n\t\tfgLine := fgLines[i-y]\n\t\tb.WriteString(fgLine)\n\t\tpos += ansi.PrintableRuneWidth(fgLine)\n\n\t\tright := cutLeft(bgLine, pos)\n\t\tbgWidth := ansi.PrintableRuneWidth(bgLine)\n\t\trightWidth := ansi.PrintableRuneWidth(right)\n\t\tif rightWidth <= bgWidth-pos {\n\t\t\tb.WriteString(ws.render(bgWidth - rightWidth - pos))\n\t\t}\n\n\t\tb.WriteString(right)\n\t}\n\n\treturn b.String()\n}\n\n// cutLeft cuts printable characters from the left.\n// This function is heavily based on muesli's ansi and truncate packages.\nfunc cutLeft(s string, cutWidth int) string {\n\treturn chAnsi.Cut(s, cutWidth, lipgloss.Width(s))\n}\n\nfunc max(a, b int) int {\n\tif a > b {\n\t\treturn a\n\t}\n\treturn b\n}\n\ntype whitespace struct {\n\tstyle termenv.Style\n\tchars string\n}\n\n// Render whitespaces.\nfunc (w whitespace) render(width int) string {\n\tif w.chars == \"\" {\n\t\tw.chars = \" \"\n\t}\n\n\tr := []rune(w.chars)\n\tj := 0\n\tb := strings.Builder{}\n\n\t// Cycle through runes and print them into the whitespace.\n\tfor i := 0; i < width; {\n\t\tb.WriteRune(r[j])\n\t\tj++\n\t\tif j >= len(r) {\n\t\t\tj = 0\n\t\t}\n\t\ti += ansi.PrintableRuneWidth(string(r[j]))\n\t}\n\n\t// Fill any extra gaps white spaces. This might be necessary if any runes\n\t// are more than one cell wide, which could leave a one-rune gap.\n\tshort := width - ansi.PrintableRuneWidth(b.String())\n\tif short > 0 {\n\t\tb.WriteString(strings.Repeat(\" \", short))\n\t}\n\n\treturn w.style.Styled(b.String())\n}\n\n// WhitespaceOption sets a styling rule for rendering whitespace.\ntype WhitespaceOption func(*whitespace)\n"], ["/opencode/internal/lsp/protocol.go", "package lsp\n\nimport (\n\t\"encoding/json\"\n)\n\n// Message represents a JSON-RPC 2.0 message\ntype Message struct {\n\tJSONRPC string `json:\"jsonrpc\"`\n\tID int32 `json:\"id,omitempty\"`\n\tMethod string `json:\"method,omitempty\"`\n\tParams json.RawMessage `json:\"params,omitempty\"`\n\tResult json.RawMessage `json:\"result,omitempty\"`\n\tError *ResponseError `json:\"error,omitempty\"`\n}\n\n// ResponseError represents a JSON-RPC 2.0 error\ntype ResponseError struct {\n\tCode int `json:\"code\"`\n\tMessage string `json:\"message\"`\n}\n\nfunc NewRequest(id int32, method string, params any) (*Message, error) {\n\tparamsJSON, err := json.Marshal(params)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Message{\n\t\tJSONRPC: \"2.0\",\n\t\tID: id,\n\t\tMethod: method,\n\t\tParams: paramsJSON,\n\t}, nil\n}\n\nfunc NewNotification(method string, params any) (*Message, error) {\n\tparamsJSON, err := json.Marshal(params)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Message{\n\t\tJSONRPC: \"2.0\",\n\t\tMethod: method,\n\t\tParams: paramsJSON,\n\t}, nil\n}\n"], ["/opencode/internal/tui/layout/container.go", "package layout\n\nimport (\n\t\"github.com/charmbracelet/bubbles/key\"\n\ttea \"github.com/charmbracelet/bubbletea\"\n\t\"github.com/charmbracelet/lipgloss\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n)\n\ntype Container interface {\n\ttea.Model\n\tSizeable\n\tBindings\n}\ntype container struct {\n\twidth int\n\theight int\n\n\tcontent tea.Model\n\n\t// Style options\n\tpaddingTop int\n\tpaddingRight int\n\tpaddingBottom int\n\tpaddingLeft int\n\n\tborderTop bool\n\tborderRight bool\n\tborderBottom bool\n\tborderLeft bool\n\tborderStyle lipgloss.Border\n}\n\nfunc (c *container) Init() tea.Cmd {\n\treturn c.content.Init()\n}\n\nfunc (c *container) Update(msg tea.Msg) (tea.Model, tea.Cmd) {\n\tu, cmd := c.content.Update(msg)\n\tc.content = u\n\treturn c, cmd\n}\n\nfunc (c *container) View() string {\n\tt := theme.CurrentTheme()\n\tstyle := lipgloss.NewStyle()\n\twidth := c.width\n\theight := c.height\n\n\tstyle = style.Background(t.Background())\n\n\t// Apply border if any side is enabled\n\tif c.borderTop || c.borderRight || c.borderBottom || c.borderLeft {\n\t\t// Adjust width and height for borders\n\t\tif c.borderTop {\n\t\t\theight--\n\t\t}\n\t\tif c.borderBottom {\n\t\t\theight--\n\t\t}\n\t\tif c.borderLeft {\n\t\t\twidth--\n\t\t}\n\t\tif c.borderRight {\n\t\t\twidth--\n\t\t}\n\t\tstyle = style.Border(c.borderStyle, c.borderTop, c.borderRight, c.borderBottom, c.borderLeft)\n\t\tstyle = style.BorderBackground(t.Background()).BorderForeground(t.BorderNormal())\n\t}\n\tstyle = style.\n\t\tWidth(width).\n\t\tHeight(height).\n\t\tPaddingTop(c.paddingTop).\n\t\tPaddingRight(c.paddingRight).\n\t\tPaddingBottom(c.paddingBottom).\n\t\tPaddingLeft(c.paddingLeft)\n\n\treturn style.Render(c.content.View())\n}\n\nfunc (c *container) SetSize(width, height int) tea.Cmd {\n\tc.width = width\n\tc.height = height\n\n\t// If the content implements Sizeable, adjust its size to account for padding and borders\n\tif sizeable, ok := c.content.(Sizeable); ok {\n\t\t// Calculate horizontal space taken by padding and borders\n\t\thorizontalSpace := c.paddingLeft + c.paddingRight\n\t\tif c.borderLeft {\n\t\t\thorizontalSpace++\n\t\t}\n\t\tif c.borderRight {\n\t\t\thorizontalSpace++\n\t\t}\n\n\t\t// Calculate vertical space taken by padding and borders\n\t\tverticalSpace := c.paddingTop + c.paddingBottom\n\t\tif c.borderTop {\n\t\t\tverticalSpace++\n\t\t}\n\t\tif c.borderBottom {\n\t\t\tverticalSpace++\n\t\t}\n\n\t\t// Set content size with adjusted dimensions\n\t\tcontentWidth := max(0, width-horizontalSpace)\n\t\tcontentHeight := max(0, height-verticalSpace)\n\t\treturn sizeable.SetSize(contentWidth, contentHeight)\n\t}\n\treturn nil\n}\n\nfunc (c *container) GetSize() (int, int) {\n\treturn c.width, c.height\n}\n\nfunc (c *container) BindingKeys() []key.Binding {\n\tif b, ok := c.content.(Bindings); ok {\n\t\treturn b.BindingKeys()\n\t}\n\treturn []key.Binding{}\n}\n\ntype ContainerOption func(*container)\n\nfunc NewContainer(content tea.Model, options ...ContainerOption) Container {\n\n\tc := &container{\n\t\tcontent: content,\n\t\tborderStyle: lipgloss.NormalBorder(),\n\t}\n\n\tfor _, option := range options {\n\t\toption(c)\n\t}\n\n\treturn c\n}\n\n// Padding options\nfunc WithPadding(top, right, bottom, left int) ContainerOption {\n\treturn func(c *container) {\n\t\tc.paddingTop = top\n\t\tc.paddingRight = right\n\t\tc.paddingBottom = bottom\n\t\tc.paddingLeft = left\n\t}\n}\n\nfunc WithPaddingAll(padding int) ContainerOption {\n\treturn WithPadding(padding, padding, padding, padding)\n}\n\nfunc WithPaddingHorizontal(padding int) ContainerOption {\n\treturn func(c *container) {\n\t\tc.paddingLeft = padding\n\t\tc.paddingRight = padding\n\t}\n}\n\nfunc WithPaddingVertical(padding int) ContainerOption {\n\treturn func(c *container) {\n\t\tc.paddingTop = padding\n\t\tc.paddingBottom = padding\n\t}\n}\n\nfunc WithBorder(top, right, bottom, left bool) ContainerOption {\n\treturn func(c *container) {\n\t\tc.borderTop = top\n\t\tc.borderRight = right\n\t\tc.borderBottom = bottom\n\t\tc.borderLeft = left\n\t}\n}\n\nfunc WithBorderAll() ContainerOption {\n\treturn WithBorder(true, true, true, true)\n}\n\nfunc WithBorderHorizontal() ContainerOption {\n\treturn WithBorder(true, false, true, false)\n}\n\nfunc WithBorderVertical() ContainerOption {\n\treturn WithBorder(false, true, false, true)\n}\n\nfunc WithBorderStyle(style lipgloss.Border) ContainerOption {\n\treturn func(c *container) {\n\t\tc.borderStyle = style\n\t}\n}\n\nfunc WithRoundedBorder() ContainerOption {\n\treturn WithBorderStyle(lipgloss.RoundedBorder())\n}\n\nfunc WithThickBorder() ContainerOption {\n\treturn WithBorderStyle(lipgloss.ThickBorder())\n}\n\nfunc WithDoubleBorder() ContainerOption {\n\treturn WithBorderStyle(lipgloss.DoubleBorder())\n}\n"], ["/opencode/internal/tui/theme/flexoki.go", "package theme\n\nimport (\n\t\"github.com/charmbracelet/lipgloss\"\n)\n\n// Flexoki color palette constants\nconst (\n\t// Base colors\n\tflexokiPaper = \"#FFFCF0\" // Paper (lightest)\n\tflexokiBase50 = \"#F2F0E5\" // bg-2 (light)\n\tflexokiBase100 = \"#E6E4D9\" // ui (light)\n\tflexokiBase150 = \"#DAD8CE\" // ui-2 (light)\n\tflexokiBase200 = \"#CECDC3\" // ui-3 (light)\n\tflexokiBase300 = \"#B7B5AC\" // tx-3 (light)\n\tflexokiBase500 = \"#878580\" // tx-2 (light)\n\tflexokiBase600 = \"#6F6E69\" // tx (light)\n\tflexokiBase700 = \"#575653\" // tx-3 (dark)\n\tflexokiBase800 = \"#403E3C\" // ui-3 (dark)\n\tflexokiBase850 = \"#343331\" // ui-2 (dark)\n\tflexokiBase900 = \"#282726\" // ui (dark)\n\tflexokiBase950 = \"#1C1B1A\" // bg-2 (dark)\n\tflexokiBlack = \"#100F0F\" // bg (darkest)\n\n\t// Accent colors - Light theme (600)\n\tflexokiRed600 = \"#AF3029\"\n\tflexokiOrange600 = \"#BC5215\"\n\tflexokiYellow600 = \"#AD8301\"\n\tflexokiGreen600 = \"#66800B\"\n\tflexokiCyan600 = \"#24837B\"\n\tflexokiBlue600 = \"#205EA6\"\n\tflexokiPurple600 = \"#5E409D\"\n\tflexokiMagenta600 = \"#A02F6F\"\n\n\t// Accent colors - Dark theme (400)\n\tflexokiRed400 = \"#D14D41\"\n\tflexokiOrange400 = \"#DA702C\"\n\tflexokiYellow400 = \"#D0A215\"\n\tflexokiGreen400 = \"#879A39\"\n\tflexokiCyan400 = \"#3AA99F\"\n\tflexokiBlue400 = \"#4385BE\"\n\tflexokiPurple400 = \"#8B7EC8\"\n\tflexokiMagenta400 = \"#CE5D97\"\n)\n\n// FlexokiTheme implements the Theme interface with Flexoki colors.\n// It provides both dark and light variants.\ntype FlexokiTheme struct {\n\tBaseTheme\n}\n\n// NewFlexokiTheme creates a new instance of the Flexoki theme.\nfunc NewFlexokiTheme() *FlexokiTheme {\n\ttheme := &FlexokiTheme{}\n\n\t// Base colors\n\ttheme.PrimaryColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiBlue400,\n\t\tLight: flexokiBlue600,\n\t}\n\ttheme.SecondaryColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiPurple400,\n\t\tLight: flexokiPurple600,\n\t}\n\ttheme.AccentColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiOrange400,\n\t\tLight: flexokiOrange600,\n\t}\n\n\t// Status colors\n\ttheme.ErrorColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiRed400,\n\t\tLight: flexokiRed600,\n\t}\n\ttheme.WarningColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiYellow400,\n\t\tLight: flexokiYellow600,\n\t}\n\ttheme.SuccessColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiGreen400,\n\t\tLight: flexokiGreen600,\n\t}\n\ttheme.InfoColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiCyan400,\n\t\tLight: flexokiCyan600,\n\t}\n\n\t// Text colors\n\ttheme.TextColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiBase300,\n\t\tLight: flexokiBase600,\n\t}\n\ttheme.TextMutedColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiBase700,\n\t\tLight: flexokiBase500,\n\t}\n\ttheme.TextEmphasizedColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiYellow400,\n\t\tLight: flexokiYellow600,\n\t}\n\n\t// Background colors\n\ttheme.BackgroundColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiBlack,\n\t\tLight: flexokiPaper,\n\t}\n\ttheme.BackgroundSecondaryColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiBase950,\n\t\tLight: flexokiBase50,\n\t}\n\ttheme.BackgroundDarkerColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiBase900,\n\t\tLight: flexokiBase100,\n\t}\n\n\t// Border colors\n\ttheme.BorderNormalColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiBase900,\n\t\tLight: flexokiBase100,\n\t}\n\ttheme.BorderFocusedColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiBlue400,\n\t\tLight: flexokiBlue600,\n\t}\n\ttheme.BorderDimColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiBase850,\n\t\tLight: flexokiBase150,\n\t}\n\n\t// Diff view colors\n\ttheme.DiffAddedColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiGreen400,\n\t\tLight: flexokiGreen600,\n\t}\n\ttheme.DiffRemovedColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiRed400,\n\t\tLight: flexokiRed600,\n\t}\n\ttheme.DiffContextColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiBase700,\n\t\tLight: flexokiBase500,\n\t}\n\ttheme.DiffHunkHeaderColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiBase700,\n\t\tLight: flexokiBase500,\n\t}\n\ttheme.DiffHighlightAddedColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiGreen400,\n\t\tLight: flexokiGreen600,\n\t}\n\ttheme.DiffHighlightRemovedColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiRed400,\n\t\tLight: flexokiRed600,\n\t}\n\ttheme.DiffAddedBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#1D2419\", // Darker green background\n\t\tLight: \"#EFF2E2\", // Light green background\n\t}\n\ttheme.DiffRemovedBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#241919\", // Darker red background\n\t\tLight: \"#F2E2E2\", // Light red background\n\t}\n\ttheme.DiffContextBgColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiBlack,\n\t\tLight: flexokiPaper,\n\t}\n\ttheme.DiffLineNumberColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiBase700,\n\t\tLight: flexokiBase500,\n\t}\n\ttheme.DiffAddedLineNumberBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#1A2017\", // Slightly darker green\n\t\tLight: \"#E5EBD9\", // Light green\n\t}\n\ttheme.DiffRemovedLineNumberBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#201717\", // Slightly darker red\n\t\tLight: \"#EBD9D9\", // Light red\n\t}\n\n\t// Markdown colors\n\ttheme.MarkdownTextColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiBase300,\n\t\tLight: flexokiBase600,\n\t}\n\ttheme.MarkdownHeadingColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiYellow400,\n\t\tLight: flexokiYellow600,\n\t}\n\ttheme.MarkdownLinkColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiCyan400,\n\t\tLight: flexokiCyan600,\n\t}\n\ttheme.MarkdownLinkTextColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiMagenta400,\n\t\tLight: flexokiMagenta600,\n\t}\n\ttheme.MarkdownCodeColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiGreen400,\n\t\tLight: flexokiGreen600,\n\t}\n\ttheme.MarkdownBlockQuoteColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiCyan400,\n\t\tLight: flexokiCyan600,\n\t}\n\ttheme.MarkdownEmphColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiYellow400,\n\t\tLight: flexokiYellow600,\n\t}\n\ttheme.MarkdownStrongColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiOrange400,\n\t\tLight: flexokiOrange600,\n\t}\n\ttheme.MarkdownHorizontalRuleColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiBase800,\n\t\tLight: flexokiBase200,\n\t}\n\ttheme.MarkdownListItemColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiBlue400,\n\t\tLight: flexokiBlue600,\n\t}\n\ttheme.MarkdownListEnumerationColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiBlue400,\n\t\tLight: flexokiBlue600,\n\t}\n\ttheme.MarkdownImageColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiPurple400,\n\t\tLight: flexokiPurple600,\n\t}\n\ttheme.MarkdownImageTextColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiMagenta400,\n\t\tLight: flexokiMagenta600,\n\t}\n\ttheme.MarkdownCodeBlockColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiBase300,\n\t\tLight: flexokiBase600,\n\t}\n\n\t// Syntax highlighting colors (based on Flexoki's mappings)\n\ttheme.SyntaxCommentColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiBase700, // tx-3\n\t\tLight: flexokiBase300, // tx-3\n\t}\n\ttheme.SyntaxKeywordColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiGreen400, // gr\n\t\tLight: flexokiGreen600, // gr\n\t}\n\ttheme.SyntaxFunctionColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiOrange400, // or\n\t\tLight: flexokiOrange600, // or\n\t}\n\ttheme.SyntaxVariableColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiBlue400, // bl\n\t\tLight: flexokiBlue600, // bl\n\t}\n\ttheme.SyntaxStringColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiCyan400, // cy\n\t\tLight: flexokiCyan600, // cy\n\t}\n\ttheme.SyntaxNumberColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiPurple400, // pu\n\t\tLight: flexokiPurple600, // pu\n\t}\n\ttheme.SyntaxTypeColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiYellow400, // ye\n\t\tLight: flexokiYellow600, // ye\n\t}\n\ttheme.SyntaxOperatorColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiBase500, // tx-2\n\t\tLight: flexokiBase500, // tx-2\n\t}\n\ttheme.SyntaxPunctuationColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiBase500, // tx-2\n\t\tLight: flexokiBase500, // tx-2\n\t}\n\n\treturn theme\n}\n\nfunc init() {\n\t// Register the Flexoki theme with the theme manager\n\tRegisterTheme(\"flexoki\", NewFlexokiTheme())\n}"], ["/opencode/internal/permission/permission.go", "package permission\n\nimport (\n\t\"errors\"\n\t\"path/filepath\"\n\t\"slices\"\n\t\"sync\"\n\n\t\"github.com/google/uuid\"\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/pubsub\"\n)\n\nvar ErrorPermissionDenied = errors.New(\"permission denied\")\n\ntype CreatePermissionRequest struct {\n\tSessionID string `json:\"session_id\"`\n\tToolName string `json:\"tool_name\"`\n\tDescription string `json:\"description\"`\n\tAction string `json:\"action\"`\n\tParams any `json:\"params\"`\n\tPath string `json:\"path\"`\n}\n\ntype PermissionRequest struct {\n\tID string `json:\"id\"`\n\tSessionID string `json:\"session_id\"`\n\tToolName string `json:\"tool_name\"`\n\tDescription string `json:\"description\"`\n\tAction string `json:\"action\"`\n\tParams any `json:\"params\"`\n\tPath string `json:\"path\"`\n}\n\ntype Service interface {\n\tpubsub.Suscriber[PermissionRequest]\n\tGrantPersistant(permission PermissionRequest)\n\tGrant(permission PermissionRequest)\n\tDeny(permission PermissionRequest)\n\tRequest(opts CreatePermissionRequest) bool\n\tAutoApproveSession(sessionID string)\n}\n\ntype permissionService struct {\n\t*pubsub.Broker[PermissionRequest]\n\n\tsessionPermissions []PermissionRequest\n\tpendingRequests sync.Map\n\tautoApproveSessions []string\n}\n\nfunc (s *permissionService) GrantPersistant(permission PermissionRequest) {\n\trespCh, ok := s.pendingRequests.Load(permission.ID)\n\tif ok {\n\t\trespCh.(chan bool) <- true\n\t}\n\ts.sessionPermissions = append(s.sessionPermissions, permission)\n}\n\nfunc (s *permissionService) Grant(permission PermissionRequest) {\n\trespCh, ok := s.pendingRequests.Load(permission.ID)\n\tif ok {\n\t\trespCh.(chan bool) <- true\n\t}\n}\n\nfunc (s *permissionService) Deny(permission PermissionRequest) {\n\trespCh, ok := s.pendingRequests.Load(permission.ID)\n\tif ok {\n\t\trespCh.(chan bool) <- false\n\t}\n}\n\nfunc (s *permissionService) Request(opts CreatePermissionRequest) bool {\n\tif slices.Contains(s.autoApproveSessions, opts.SessionID) {\n\t\treturn true\n\t}\n\tdir := filepath.Dir(opts.Path)\n\tif dir == \".\" {\n\t\tdir = config.WorkingDirectory()\n\t}\n\tpermission := PermissionRequest{\n\t\tID: uuid.New().String(),\n\t\tPath: dir,\n\t\tSessionID: opts.SessionID,\n\t\tToolName: opts.ToolName,\n\t\tDescription: opts.Description,\n\t\tAction: opts.Action,\n\t\tParams: opts.Params,\n\t}\n\n\tfor _, p := range s.sessionPermissions {\n\t\tif p.ToolName == permission.ToolName && p.Action == permission.Action && p.SessionID == permission.SessionID && p.Path == permission.Path {\n\t\t\treturn true\n\t\t}\n\t}\n\n\trespCh := make(chan bool, 1)\n\n\ts.pendingRequests.Store(permission.ID, respCh)\n\tdefer s.pendingRequests.Delete(permission.ID)\n\n\ts.Publish(pubsub.CreatedEvent, permission)\n\n\t// Wait for the response with a timeout\n\tresp := <-respCh\n\treturn resp\n}\n\nfunc (s *permissionService) AutoApproveSession(sessionID string) {\n\ts.autoApproveSessions = append(s.autoApproveSessions, sessionID)\n}\n\nfunc NewPermissionService() Service {\n\treturn &permissionService{\n\t\tBroker: pubsub.NewBroker[PermissionRequest](),\n\t\tsessionPermissions: make([]PermissionRequest, 0),\n\t}\n}\n"], ["/opencode/internal/tui/theme/catppuccin.go", "package theme\n\nimport (\n\tcatppuccin \"github.com/catppuccin/go\"\n\t\"github.com/charmbracelet/lipgloss\"\n)\n\n// CatppuccinTheme implements the Theme interface with Catppuccin colors.\n// It provides both dark (Mocha) and light (Latte) variants.\ntype CatppuccinTheme struct {\n\tBaseTheme\n}\n\n// NewCatppuccinTheme creates a new instance of the Catppuccin theme.\nfunc NewCatppuccinTheme() *CatppuccinTheme {\n\t// Get the Catppuccin palettes\n\tmocha := catppuccin.Mocha\n\tlatte := catppuccin.Latte\n\n\ttheme := &CatppuccinTheme{}\n\n\t// Base colors\n\ttheme.PrimaryColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Blue().Hex,\n\t\tLight: latte.Blue().Hex,\n\t}\n\ttheme.SecondaryColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Mauve().Hex,\n\t\tLight: latte.Mauve().Hex,\n\t}\n\ttheme.AccentColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Peach().Hex,\n\t\tLight: latte.Peach().Hex,\n\t}\n\n\t// Status colors\n\ttheme.ErrorColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Red().Hex,\n\t\tLight: latte.Red().Hex,\n\t}\n\ttheme.WarningColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Peach().Hex,\n\t\tLight: latte.Peach().Hex,\n\t}\n\ttheme.SuccessColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Green().Hex,\n\t\tLight: latte.Green().Hex,\n\t}\n\ttheme.InfoColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Blue().Hex,\n\t\tLight: latte.Blue().Hex,\n\t}\n\n\t// Text colors\n\ttheme.TextColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Text().Hex,\n\t\tLight: latte.Text().Hex,\n\t}\n\ttheme.TextMutedColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Subtext0().Hex,\n\t\tLight: latte.Subtext0().Hex,\n\t}\n\ttheme.TextEmphasizedColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Lavender().Hex,\n\t\tLight: latte.Lavender().Hex,\n\t}\n\n\t// Background colors\n\ttheme.BackgroundColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#212121\", // From existing styles\n\t\tLight: \"#EEEEEE\", // Light equivalent\n\t}\n\ttheme.BackgroundSecondaryColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#2c2c2c\", // From existing styles\n\t\tLight: \"#E0E0E0\", // Light equivalent\n\t}\n\ttheme.BackgroundDarkerColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#181818\", // From existing styles\n\t\tLight: \"#F5F5F5\", // Light equivalent\n\t}\n\n\t// Border colors\n\ttheme.BorderNormalColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#4b4c5c\", // From existing styles\n\t\tLight: \"#BDBDBD\", // Light equivalent\n\t}\n\ttheme.BorderFocusedColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Blue().Hex,\n\t\tLight: latte.Blue().Hex,\n\t}\n\ttheme.BorderDimColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Surface0().Hex,\n\t\tLight: latte.Surface0().Hex,\n\t}\n\n\t// Diff view colors\n\ttheme.DiffAddedColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#478247\", // From existing diff.go\n\t\tLight: \"#2E7D32\", // Light equivalent\n\t}\n\ttheme.DiffRemovedColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#7C4444\", // From existing diff.go\n\t\tLight: \"#C62828\", // Light equivalent\n\t}\n\ttheme.DiffContextColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#a0a0a0\", // From existing diff.go\n\t\tLight: \"#757575\", // Light equivalent\n\t}\n\ttheme.DiffHunkHeaderColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#a0a0a0\", // From existing diff.go\n\t\tLight: \"#757575\", // Light equivalent\n\t}\n\ttheme.DiffHighlightAddedColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#DAFADA\", // From existing diff.go\n\t\tLight: \"#A5D6A7\", // Light equivalent\n\t}\n\ttheme.DiffHighlightRemovedColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#FADADD\", // From existing diff.go\n\t\tLight: \"#EF9A9A\", // Light equivalent\n\t}\n\ttheme.DiffAddedBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#303A30\", // From existing diff.go\n\t\tLight: \"#E8F5E9\", // Light equivalent\n\t}\n\ttheme.DiffRemovedBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#3A3030\", // From existing diff.go\n\t\tLight: \"#FFEBEE\", // Light equivalent\n\t}\n\ttheme.DiffContextBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#212121\", // From existing diff.go\n\t\tLight: \"#F5F5F5\", // Light equivalent\n\t}\n\ttheme.DiffLineNumberColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#888888\", // From existing diff.go\n\t\tLight: \"#9E9E9E\", // Light equivalent\n\t}\n\ttheme.DiffAddedLineNumberBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#293229\", // From existing diff.go\n\t\tLight: \"#C8E6C9\", // Light equivalent\n\t}\n\ttheme.DiffRemovedLineNumberBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#332929\", // From existing diff.go\n\t\tLight: \"#FFCDD2\", // Light equivalent\n\t}\n\n\t// Markdown colors\n\ttheme.MarkdownTextColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Text().Hex,\n\t\tLight: latte.Text().Hex,\n\t}\n\ttheme.MarkdownHeadingColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Mauve().Hex,\n\t\tLight: latte.Mauve().Hex,\n\t}\n\ttheme.MarkdownLinkColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Sky().Hex,\n\t\tLight: latte.Sky().Hex,\n\t}\n\ttheme.MarkdownLinkTextColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Pink().Hex,\n\t\tLight: latte.Pink().Hex,\n\t}\n\ttheme.MarkdownCodeColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Green().Hex,\n\t\tLight: latte.Green().Hex,\n\t}\n\ttheme.MarkdownBlockQuoteColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Yellow().Hex,\n\t\tLight: latte.Yellow().Hex,\n\t}\n\ttheme.MarkdownEmphColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Yellow().Hex,\n\t\tLight: latte.Yellow().Hex,\n\t}\n\ttheme.MarkdownStrongColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Peach().Hex,\n\t\tLight: latte.Peach().Hex,\n\t}\n\ttheme.MarkdownHorizontalRuleColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Overlay0().Hex,\n\t\tLight: latte.Overlay0().Hex,\n\t}\n\ttheme.MarkdownListItemColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Blue().Hex,\n\t\tLight: latte.Blue().Hex,\n\t}\n\ttheme.MarkdownListEnumerationColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Sky().Hex,\n\t\tLight: latte.Sky().Hex,\n\t}\n\ttheme.MarkdownImageColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Sapphire().Hex,\n\t\tLight: latte.Sapphire().Hex,\n\t}\n\ttheme.MarkdownImageTextColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Pink().Hex,\n\t\tLight: latte.Pink().Hex,\n\t}\n\ttheme.MarkdownCodeBlockColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Text().Hex,\n\t\tLight: latte.Text().Hex,\n\t}\n\n\t// Syntax highlighting colors\n\ttheme.SyntaxCommentColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Overlay1().Hex,\n\t\tLight: latte.Overlay1().Hex,\n\t}\n\ttheme.SyntaxKeywordColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Pink().Hex,\n\t\tLight: latte.Pink().Hex,\n\t}\n\ttheme.SyntaxFunctionColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Green().Hex,\n\t\tLight: latte.Green().Hex,\n\t}\n\ttheme.SyntaxVariableColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Sky().Hex,\n\t\tLight: latte.Sky().Hex,\n\t}\n\ttheme.SyntaxStringColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Yellow().Hex,\n\t\tLight: latte.Yellow().Hex,\n\t}\n\ttheme.SyntaxNumberColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Teal().Hex,\n\t\tLight: latte.Teal().Hex,\n\t}\n\ttheme.SyntaxTypeColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Sky().Hex,\n\t\tLight: latte.Sky().Hex,\n\t}\n\ttheme.SyntaxOperatorColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Pink().Hex,\n\t\tLight: latte.Pink().Hex,\n\t}\n\ttheme.SyntaxPunctuationColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Text().Hex,\n\t\tLight: latte.Text().Hex,\n\t}\n\n\treturn theme\n}\n\nfunc init() {\n\t// Register the Catppuccin theme with the theme manager\n\tRegisterTheme(\"catppuccin\", NewCatppuccinTheme())\n}"], ["/opencode/internal/llm/models/groq.go", "package models\n\nconst (\n\tProviderGROQ ModelProvider = \"groq\"\n\n\t// GROQ\n\tQWENQwq ModelID = \"qwen-qwq\"\n\n\t// GROQ preview models\n\tLlama4Scout ModelID = \"meta-llama/llama-4-scout-17b-16e-instruct\"\n\tLlama4Maverick ModelID = \"meta-llama/llama-4-maverick-17b-128e-instruct\"\n\tLlama3_3_70BVersatile ModelID = \"llama-3.3-70b-versatile\"\n\tDeepseekR1DistillLlama70b ModelID = \"deepseek-r1-distill-llama-70b\"\n)\n\nvar GroqModels = map[ModelID]Model{\n\t//\n\t// GROQ\n\tQWENQwq: {\n\t\tID: QWENQwq,\n\t\tName: \"Qwen Qwq\",\n\t\tProvider: ProviderGROQ,\n\t\tAPIModel: \"qwen-qwq-32b\",\n\t\tCostPer1MIn: 0.29,\n\t\tCostPer1MInCached: 0.275,\n\t\tCostPer1MOutCached: 0.0,\n\t\tCostPer1MOut: 0.39,\n\t\tContextWindow: 128_000,\n\t\tDefaultMaxTokens: 50000,\n\t\t// for some reason, the groq api doesn't like the reasoningEffort parameter\n\t\tCanReason: false,\n\t\tSupportsAttachments: false,\n\t},\n\n\tLlama4Scout: {\n\t\tID: Llama4Scout,\n\t\tName: \"Llama4Scout\",\n\t\tProvider: ProviderGROQ,\n\t\tAPIModel: \"meta-llama/llama-4-scout-17b-16e-instruct\",\n\t\tCostPer1MIn: 0.11,\n\t\tCostPer1MInCached: 0,\n\t\tCostPer1MOutCached: 0,\n\t\tCostPer1MOut: 0.34,\n\t\tContextWindow: 128_000, // 10M when?\n\t\tSupportsAttachments: true,\n\t},\n\n\tLlama4Maverick: {\n\t\tID: Llama4Maverick,\n\t\tName: \"Llama4Maverick\",\n\t\tProvider: ProviderGROQ,\n\t\tAPIModel: \"meta-llama/llama-4-maverick-17b-128e-instruct\",\n\t\tCostPer1MIn: 0.20,\n\t\tCostPer1MInCached: 0,\n\t\tCostPer1MOutCached: 0,\n\t\tCostPer1MOut: 0.20,\n\t\tContextWindow: 128_000,\n\t\tSupportsAttachments: true,\n\t},\n\n\tLlama3_3_70BVersatile: {\n\t\tID: Llama3_3_70BVersatile,\n\t\tName: \"Llama3_3_70BVersatile\",\n\t\tProvider: ProviderGROQ,\n\t\tAPIModel: \"llama-3.3-70b-versatile\",\n\t\tCostPer1MIn: 0.59,\n\t\tCostPer1MInCached: 0,\n\t\tCostPer1MOutCached: 0,\n\t\tCostPer1MOut: 0.79,\n\t\tContextWindow: 128_000,\n\t\tSupportsAttachments: false,\n\t},\n\n\tDeepseekR1DistillLlama70b: {\n\t\tID: DeepseekR1DistillLlama70b,\n\t\tName: \"DeepseekR1DistillLlama70b\",\n\t\tProvider: ProviderGROQ,\n\t\tAPIModel: \"deepseek-r1-distill-llama-70b\",\n\t\tCostPer1MIn: 0.75,\n\t\tCostPer1MInCached: 0,\n\t\tCostPer1MOutCached: 0,\n\t\tCostPer1MOut: 0.99,\n\t\tContextWindow: 128_000,\n\t\tCanReason: true,\n\t\tSupportsAttachments: false,\n\t},\n}\n"], ["/opencode/internal/llm/prompt/task.go", "package prompt\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/opencode-ai/opencode/internal/llm/models\"\n)\n\nfunc TaskPrompt(_ models.ModelProvider) string {\n\tagentPrompt := `You are an agent for OpenCode. Given the user's prompt, you should use the tools available to you to answer the user's question.\nNotes:\n1. IMPORTANT: You should be concise, direct, and to the point, since your responses will be displayed on a command line interface. Answer the user's question directly, without elaboration, explanation, or details. One word answers are best. Avoid introductions, conclusions, and explanations. You MUST avoid text before/after your response, such as \"The answer is .\", \"Here is the content of the file...\" or \"Based on the information provided, the answer is...\" or \"Here is what I will do next...\".\n2. When relevant, share file names and code snippets relevant to the query\n3. Any file paths you return in your final response MUST be absolute. DO NOT use relative paths.`\n\n\treturn fmt.Sprintf(\"%s\\n%s\\n\", agentPrompt, getEnvironmentInfo())\n}\n"], ["/opencode/internal/tui/page/logs.go", "package page\n\nimport (\n\t\"github.com/charmbracelet/bubbles/key\"\n\ttea \"github.com/charmbracelet/bubbletea\"\n\t\"github.com/charmbracelet/lipgloss\"\n\t\"github.com/opencode-ai/opencode/internal/tui/components/logs\"\n\t\"github.com/opencode-ai/opencode/internal/tui/layout\"\n\t\"github.com/opencode-ai/opencode/internal/tui/styles\"\n)\n\nvar LogsPage PageID = \"logs\"\n\ntype LogPage interface {\n\ttea.Model\n\tlayout.Sizeable\n\tlayout.Bindings\n}\ntype logsPage struct {\n\twidth, height int\n\ttable layout.Container\n\tdetails layout.Container\n}\n\nfunc (p *logsPage) Update(msg tea.Msg) (tea.Model, tea.Cmd) {\n\tvar cmds []tea.Cmd\n\tswitch msg := msg.(type) {\n\tcase tea.WindowSizeMsg:\n\t\tp.width = msg.Width\n\t\tp.height = msg.Height\n\t\treturn p, p.SetSize(msg.Width, msg.Height)\n\t}\n\n\ttable, cmd := p.table.Update(msg)\n\tcmds = append(cmds, cmd)\n\tp.table = table.(layout.Container)\n\tdetails, cmd := p.details.Update(msg)\n\tcmds = append(cmds, cmd)\n\tp.details = details.(layout.Container)\n\n\treturn p, tea.Batch(cmds...)\n}\n\nfunc (p *logsPage) View() string {\n\tstyle := styles.BaseStyle().Width(p.width).Height(p.height)\n\treturn style.Render(lipgloss.JoinVertical(lipgloss.Top,\n\t\tp.table.View(),\n\t\tp.details.View(),\n\t))\n}\n\nfunc (p *logsPage) BindingKeys() []key.Binding {\n\treturn p.table.BindingKeys()\n}\n\n// GetSize implements LogPage.\nfunc (p *logsPage) GetSize() (int, int) {\n\treturn p.width, p.height\n}\n\n// SetSize implements LogPage.\nfunc (p *logsPage) SetSize(width int, height int) tea.Cmd {\n\tp.width = width\n\tp.height = height\n\treturn tea.Batch(\n\t\tp.table.SetSize(width, height/2),\n\t\tp.details.SetSize(width, height/2),\n\t)\n}\n\nfunc (p *logsPage) Init() tea.Cmd {\n\treturn tea.Batch(\n\t\tp.table.Init(),\n\t\tp.details.Init(),\n\t)\n}\n\nfunc NewLogsPage() LogPage {\n\treturn &logsPage{\n\t\ttable: layout.NewContainer(logs.NewLogsTable(), layout.WithBorderAll()),\n\t\tdetails: layout.NewContainer(logs.NewLogsDetails(), layout.WithBorderAll()),\n\t}\n}\n"], ["/opencode/internal/tui/theme/opencode.go", "package theme\n\nimport (\n\t\"github.com/charmbracelet/lipgloss\"\n)\n\n// OpenCodeTheme implements the Theme interface with OpenCode brand colors.\n// It provides both dark and light variants.\ntype OpenCodeTheme struct {\n\tBaseTheme\n}\n\n// NewOpenCodeTheme creates a new instance of the OpenCode theme.\nfunc NewOpenCodeTheme() *OpenCodeTheme {\n\t// OpenCode color palette\n\t// Dark mode colors\n\tdarkBackground := \"#212121\"\n\tdarkCurrentLine := \"#252525\"\n\tdarkSelection := \"#303030\"\n\tdarkForeground := \"#e0e0e0\"\n\tdarkComment := \"#6a6a6a\"\n\tdarkPrimary := \"#fab283\" // Primary orange/gold\n\tdarkSecondary := \"#5c9cf5\" // Secondary blue\n\tdarkAccent := \"#9d7cd8\" // Accent purple\n\tdarkRed := \"#e06c75\" // Error red\n\tdarkOrange := \"#f5a742\" // Warning orange\n\tdarkGreen := \"#7fd88f\" // Success green\n\tdarkCyan := \"#56b6c2\" // Info cyan\n\tdarkYellow := \"#e5c07b\" // Emphasized text\n\tdarkBorder := \"#4b4c5c\" // Border color\n\n\t// Light mode colors\n\tlightBackground := \"#f8f8f8\"\n\tlightCurrentLine := \"#f0f0f0\"\n\tlightSelection := \"#e5e5e6\"\n\tlightForeground := \"#2a2a2a\"\n\tlightComment := \"#8a8a8a\"\n\tlightPrimary := \"#3b7dd8\" // Primary blue\n\tlightSecondary := \"#7b5bb6\" // Secondary purple\n\tlightAccent := \"#d68c27\" // Accent orange/gold\n\tlightRed := \"#d1383d\" // Error red\n\tlightOrange := \"#d68c27\" // Warning orange\n\tlightGreen := \"#3d9a57\" // Success green\n\tlightCyan := \"#318795\" // Info cyan\n\tlightYellow := \"#b0851f\" // Emphasized text\n\tlightBorder := \"#d3d3d3\" // Border color\n\n\ttheme := &OpenCodeTheme{}\n\n\t// Base colors\n\ttheme.PrimaryColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPrimary,\n\t\tLight: lightPrimary,\n\t}\n\ttheme.SecondaryColor = lipgloss.AdaptiveColor{\n\t\tDark: darkSecondary,\n\t\tLight: lightSecondary,\n\t}\n\ttheme.AccentColor = lipgloss.AdaptiveColor{\n\t\tDark: darkAccent,\n\t\tLight: lightAccent,\n\t}\n\n\t// Status colors\n\ttheme.ErrorColor = lipgloss.AdaptiveColor{\n\t\tDark: darkRed,\n\t\tLight: lightRed,\n\t}\n\ttheme.WarningColor = lipgloss.AdaptiveColor{\n\t\tDark: darkOrange,\n\t\tLight: lightOrange,\n\t}\n\ttheme.SuccessColor = lipgloss.AdaptiveColor{\n\t\tDark: darkGreen,\n\t\tLight: lightGreen,\n\t}\n\ttheme.InfoColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\n\t// Text colors\n\ttheme.TextColor = lipgloss.AdaptiveColor{\n\t\tDark: darkForeground,\n\t\tLight: lightForeground,\n\t}\n\ttheme.TextMutedColor = lipgloss.AdaptiveColor{\n\t\tDark: darkComment,\n\t\tLight: lightComment,\n\t}\n\ttheme.TextEmphasizedColor = lipgloss.AdaptiveColor{\n\t\tDark: darkYellow,\n\t\tLight: lightYellow,\n\t}\n\n\t// Background colors\n\ttheme.BackgroundColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBackground,\n\t\tLight: lightBackground,\n\t}\n\ttheme.BackgroundSecondaryColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCurrentLine,\n\t\tLight: lightCurrentLine,\n\t}\n\ttheme.BackgroundDarkerColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#121212\", // Slightly darker than background\n\t\tLight: \"#ffffff\", // Slightly lighter than background\n\t}\n\n\t// Border colors\n\ttheme.BorderNormalColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBorder,\n\t\tLight: lightBorder,\n\t}\n\ttheme.BorderFocusedColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPrimary,\n\t\tLight: lightPrimary,\n\t}\n\ttheme.BorderDimColor = lipgloss.AdaptiveColor{\n\t\tDark: darkSelection,\n\t\tLight: lightSelection,\n\t}\n\n\t// Diff view colors\n\ttheme.DiffAddedColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#478247\",\n\t\tLight: \"#2E7D32\",\n\t}\n\ttheme.DiffRemovedColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#7C4444\",\n\t\tLight: \"#C62828\",\n\t}\n\ttheme.DiffContextColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#a0a0a0\",\n\t\tLight: \"#757575\",\n\t}\n\ttheme.DiffHunkHeaderColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#a0a0a0\",\n\t\tLight: \"#757575\",\n\t}\n\ttheme.DiffHighlightAddedColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#DAFADA\",\n\t\tLight: \"#A5D6A7\",\n\t}\n\ttheme.DiffHighlightRemovedColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#FADADD\",\n\t\tLight: \"#EF9A9A\",\n\t}\n\ttheme.DiffAddedBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#303A30\",\n\t\tLight: \"#E8F5E9\",\n\t}\n\ttheme.DiffRemovedBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#3A3030\",\n\t\tLight: \"#FFEBEE\",\n\t}\n\ttheme.DiffContextBgColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBackground,\n\t\tLight: lightBackground,\n\t}\n\ttheme.DiffLineNumberColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#888888\",\n\t\tLight: \"#9E9E9E\",\n\t}\n\ttheme.DiffAddedLineNumberBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#293229\",\n\t\tLight: \"#C8E6C9\",\n\t}\n\ttheme.DiffRemovedLineNumberBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#332929\",\n\t\tLight: \"#FFCDD2\",\n\t}\n\n\t// Markdown colors\n\ttheme.MarkdownTextColor = lipgloss.AdaptiveColor{\n\t\tDark: darkForeground,\n\t\tLight: lightForeground,\n\t}\n\ttheme.MarkdownHeadingColor = lipgloss.AdaptiveColor{\n\t\tDark: darkSecondary,\n\t\tLight: lightSecondary,\n\t}\n\ttheme.MarkdownLinkColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPrimary,\n\t\tLight: lightPrimary,\n\t}\n\ttheme.MarkdownLinkTextColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.MarkdownCodeColor = lipgloss.AdaptiveColor{\n\t\tDark: darkGreen,\n\t\tLight: lightGreen,\n\t}\n\ttheme.MarkdownBlockQuoteColor = lipgloss.AdaptiveColor{\n\t\tDark: darkYellow,\n\t\tLight: lightYellow,\n\t}\n\ttheme.MarkdownEmphColor = lipgloss.AdaptiveColor{\n\t\tDark: darkYellow,\n\t\tLight: lightYellow,\n\t}\n\ttheme.MarkdownStrongColor = lipgloss.AdaptiveColor{\n\t\tDark: darkAccent,\n\t\tLight: lightAccent,\n\t}\n\ttheme.MarkdownHorizontalRuleColor = lipgloss.AdaptiveColor{\n\t\tDark: darkComment,\n\t\tLight: lightComment,\n\t}\n\ttheme.MarkdownListItemColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPrimary,\n\t\tLight: lightPrimary,\n\t}\n\ttheme.MarkdownListEnumerationColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.MarkdownImageColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPrimary,\n\t\tLight: lightPrimary,\n\t}\n\ttheme.MarkdownImageTextColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.MarkdownCodeBlockColor = lipgloss.AdaptiveColor{\n\t\tDark: darkForeground,\n\t\tLight: lightForeground,\n\t}\n\n\t// Syntax highlighting colors\n\ttheme.SyntaxCommentColor = lipgloss.AdaptiveColor{\n\t\tDark: darkComment,\n\t\tLight: lightComment,\n\t}\n\ttheme.SyntaxKeywordColor = lipgloss.AdaptiveColor{\n\t\tDark: darkSecondary,\n\t\tLight: lightSecondary,\n\t}\n\ttheme.SyntaxFunctionColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPrimary,\n\t\tLight: lightPrimary,\n\t}\n\ttheme.SyntaxVariableColor = lipgloss.AdaptiveColor{\n\t\tDark: darkRed,\n\t\tLight: lightRed,\n\t}\n\ttheme.SyntaxStringColor = lipgloss.AdaptiveColor{\n\t\tDark: darkGreen,\n\t\tLight: lightGreen,\n\t}\n\ttheme.SyntaxNumberColor = lipgloss.AdaptiveColor{\n\t\tDark: darkAccent,\n\t\tLight: lightAccent,\n\t}\n\ttheme.SyntaxTypeColor = lipgloss.AdaptiveColor{\n\t\tDark: darkYellow,\n\t\tLight: lightYellow,\n\t}\n\ttheme.SyntaxOperatorColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.SyntaxPunctuationColor = lipgloss.AdaptiveColor{\n\t\tDark: darkForeground,\n\t\tLight: lightForeground,\n\t}\n\n\treturn theme\n}\n\nfunc init() {\n\t// Register the OpenCode theme with the theme manager\n\tRegisterTheme(\"opencode\", NewOpenCodeTheme())\n}\n\n"], ["/opencode/internal/tui/layout/layout.go", "package layout\n\nimport (\n\t\"reflect\"\n\n\t\"github.com/charmbracelet/bubbles/key\"\n\ttea \"github.com/charmbracelet/bubbletea\"\n)\n\ntype Focusable interface {\n\tFocus() tea.Cmd\n\tBlur() tea.Cmd\n\tIsFocused() bool\n}\n\ntype Sizeable interface {\n\tSetSize(width, height int) tea.Cmd\n\tGetSize() (int, int)\n}\n\ntype Bindings interface {\n\tBindingKeys() []key.Binding\n}\n\nfunc KeyMapToSlice(t any) (bindings []key.Binding) {\n\ttyp := reflect.TypeOf(t)\n\tif typ.Kind() != reflect.Struct {\n\t\treturn nil\n\t}\n\tfor i := range typ.NumField() {\n\t\tv := reflect.ValueOf(t).Field(i)\n\t\tbindings = append(bindings, v.Interface().(key.Binding))\n\t}\n\treturn\n}\n"], ["/opencode/main.go", "package main\n\nimport (\n\t\"github.com/opencode-ai/opencode/cmd\"\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n)\n\nfunc main() {\n\tdefer logging.RecoverPanic(\"main\", func() {\n\t\tlogging.ErrorPersist(\"Application terminated due to unhandled panic\")\n\t})\n\n\tcmd.Execute()\n}\n"], ["/opencode/internal/tui/theme/gruvbox.go", "package theme\n\nimport (\n\t\"github.com/charmbracelet/lipgloss\"\n)\n\n// Gruvbox color palette constants\nconst (\n\t// Dark theme colors\n\tgruvboxDarkBg0 = \"#282828\"\n\tgruvboxDarkBg0Soft = \"#32302f\"\n\tgruvboxDarkBg1 = \"#3c3836\"\n\tgruvboxDarkBg2 = \"#504945\"\n\tgruvboxDarkBg3 = \"#665c54\"\n\tgruvboxDarkBg4 = \"#7c6f64\"\n\tgruvboxDarkFg0 = \"#fbf1c7\"\n\tgruvboxDarkFg1 = \"#ebdbb2\"\n\tgruvboxDarkFg2 = \"#d5c4a1\"\n\tgruvboxDarkFg3 = \"#bdae93\"\n\tgruvboxDarkFg4 = \"#a89984\"\n\tgruvboxDarkGray = \"#928374\"\n\tgruvboxDarkRed = \"#cc241d\"\n\tgruvboxDarkRedBright = \"#fb4934\"\n\tgruvboxDarkGreen = \"#98971a\"\n\tgruvboxDarkGreenBright = \"#b8bb26\"\n\tgruvboxDarkYellow = \"#d79921\"\n\tgruvboxDarkYellowBright = \"#fabd2f\"\n\tgruvboxDarkBlue = \"#458588\"\n\tgruvboxDarkBlueBright = \"#83a598\"\n\tgruvboxDarkPurple = \"#b16286\"\n\tgruvboxDarkPurpleBright = \"#d3869b\"\n\tgruvboxDarkAqua = \"#689d6a\"\n\tgruvboxDarkAquaBright = \"#8ec07c\"\n\tgruvboxDarkOrange = \"#d65d0e\"\n\tgruvboxDarkOrangeBright = \"#fe8019\"\n\n\t// Light theme colors\n\tgruvboxLightBg0 = \"#fbf1c7\"\n\tgruvboxLightBg0Soft = \"#f2e5bc\"\n\tgruvboxLightBg1 = \"#ebdbb2\"\n\tgruvboxLightBg2 = \"#d5c4a1\"\n\tgruvboxLightBg3 = \"#bdae93\"\n\tgruvboxLightBg4 = \"#a89984\"\n\tgruvboxLightFg0 = \"#282828\"\n\tgruvboxLightFg1 = \"#3c3836\"\n\tgruvboxLightFg2 = \"#504945\"\n\tgruvboxLightFg3 = \"#665c54\"\n\tgruvboxLightFg4 = \"#7c6f64\"\n\tgruvboxLightGray = \"#928374\"\n\tgruvboxLightRed = \"#9d0006\"\n\tgruvboxLightRedBright = \"#cc241d\"\n\tgruvboxLightGreen = \"#79740e\"\n\tgruvboxLightGreenBright = \"#98971a\"\n\tgruvboxLightYellow = \"#b57614\"\n\tgruvboxLightYellowBright = \"#d79921\"\n\tgruvboxLightBlue = \"#076678\"\n\tgruvboxLightBlueBright = \"#458588\"\n\tgruvboxLightPurple = \"#8f3f71\"\n\tgruvboxLightPurpleBright = \"#b16286\"\n\tgruvboxLightAqua = \"#427b58\"\n\tgruvboxLightAquaBright = \"#689d6a\"\n\tgruvboxLightOrange = \"#af3a03\"\n\tgruvboxLightOrangeBright = \"#d65d0e\"\n)\n\n// GruvboxTheme implements the Theme interface with Gruvbox colors.\n// It provides both dark and light variants.\ntype GruvboxTheme struct {\n\tBaseTheme\n}\n\n// NewGruvboxTheme creates a new instance of the Gruvbox theme.\nfunc NewGruvboxTheme() *GruvboxTheme {\n\ttheme := &GruvboxTheme{}\n\n\t// Base colors\n\ttheme.PrimaryColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkBlueBright,\n\t\tLight: gruvboxLightBlueBright,\n\t}\n\ttheme.SecondaryColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkPurpleBright,\n\t\tLight: gruvboxLightPurpleBright,\n\t}\n\ttheme.AccentColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkOrangeBright,\n\t\tLight: gruvboxLightOrangeBright,\n\t}\n\n\t// Status colors\n\ttheme.ErrorColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkRedBright,\n\t\tLight: gruvboxLightRedBright,\n\t}\n\ttheme.WarningColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkYellowBright,\n\t\tLight: gruvboxLightYellowBright,\n\t}\n\ttheme.SuccessColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkGreenBright,\n\t\tLight: gruvboxLightGreenBright,\n\t}\n\ttheme.InfoColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkBlueBright,\n\t\tLight: gruvboxLightBlueBright,\n\t}\n\n\t// Text colors\n\ttheme.TextColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkFg1,\n\t\tLight: gruvboxLightFg1,\n\t}\n\ttheme.TextMutedColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkFg4,\n\t\tLight: gruvboxLightFg4,\n\t}\n\ttheme.TextEmphasizedColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkYellowBright,\n\t\tLight: gruvboxLightYellowBright,\n\t}\n\n\t// Background colors\n\ttheme.BackgroundColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkBg0,\n\t\tLight: gruvboxLightBg0,\n\t}\n\ttheme.BackgroundSecondaryColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkBg1,\n\t\tLight: gruvboxLightBg1,\n\t}\n\ttheme.BackgroundDarkerColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkBg0Soft,\n\t\tLight: gruvboxLightBg0Soft,\n\t}\n\n\t// Border colors\n\ttheme.BorderNormalColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkBg2,\n\t\tLight: gruvboxLightBg2,\n\t}\n\ttheme.BorderFocusedColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkBlueBright,\n\t\tLight: gruvboxLightBlueBright,\n\t}\n\ttheme.BorderDimColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkBg1,\n\t\tLight: gruvboxLightBg1,\n\t}\n\n\t// Diff view colors\n\ttheme.DiffAddedColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkGreenBright,\n\t\tLight: gruvboxLightGreenBright,\n\t}\n\ttheme.DiffRemovedColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkRedBright,\n\t\tLight: gruvboxLightRedBright,\n\t}\n\ttheme.DiffContextColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkFg4,\n\t\tLight: gruvboxLightFg4,\n\t}\n\ttheme.DiffHunkHeaderColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkFg3,\n\t\tLight: gruvboxLightFg3,\n\t}\n\ttheme.DiffHighlightAddedColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkGreenBright,\n\t\tLight: gruvboxLightGreenBright,\n\t}\n\ttheme.DiffHighlightRemovedColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkRedBright,\n\t\tLight: gruvboxLightRedBright,\n\t}\n\ttheme.DiffAddedBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#3C4C3C\", // Darker green background\n\t\tLight: \"#E8F5E9\", // Light green background\n\t}\n\ttheme.DiffRemovedBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#4C3C3C\", // Darker red background\n\t\tLight: \"#FFEBEE\", // Light red background\n\t}\n\ttheme.DiffContextBgColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkBg0,\n\t\tLight: gruvboxLightBg0,\n\t}\n\ttheme.DiffLineNumberColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkFg4,\n\t\tLight: gruvboxLightFg4,\n\t}\n\ttheme.DiffAddedLineNumberBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#32432F\", // Slightly darker green\n\t\tLight: \"#C8E6C9\", // Light green\n\t}\n\ttheme.DiffRemovedLineNumberBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#43322F\", // Slightly darker red\n\t\tLight: \"#FFCDD2\", // Light red\n\t}\n\n\t// Markdown colors\n\ttheme.MarkdownTextColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkFg1,\n\t\tLight: gruvboxLightFg1,\n\t}\n\ttheme.MarkdownHeadingColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkYellowBright,\n\t\tLight: gruvboxLightYellowBright,\n\t}\n\ttheme.MarkdownLinkColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkBlueBright,\n\t\tLight: gruvboxLightBlueBright,\n\t}\n\ttheme.MarkdownLinkTextColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkAquaBright,\n\t\tLight: gruvboxLightAquaBright,\n\t}\n\ttheme.MarkdownCodeColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkGreenBright,\n\t\tLight: gruvboxLightGreenBright,\n\t}\n\ttheme.MarkdownBlockQuoteColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkAquaBright,\n\t\tLight: gruvboxLightAquaBright,\n\t}\n\ttheme.MarkdownEmphColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkYellowBright,\n\t\tLight: gruvboxLightYellowBright,\n\t}\n\ttheme.MarkdownStrongColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkOrangeBright,\n\t\tLight: gruvboxLightOrangeBright,\n\t}\n\ttheme.MarkdownHorizontalRuleColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkBg3,\n\t\tLight: gruvboxLightBg3,\n\t}\n\ttheme.MarkdownListItemColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkBlueBright,\n\t\tLight: gruvboxLightBlueBright,\n\t}\n\ttheme.MarkdownListEnumerationColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkBlueBright,\n\t\tLight: gruvboxLightBlueBright,\n\t}\n\ttheme.MarkdownImageColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkPurpleBright,\n\t\tLight: gruvboxLightPurpleBright,\n\t}\n\ttheme.MarkdownImageTextColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkAquaBright,\n\t\tLight: gruvboxLightAquaBright,\n\t}\n\ttheme.MarkdownCodeBlockColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkFg1,\n\t\tLight: gruvboxLightFg1,\n\t}\n\n\t// Syntax highlighting colors\n\ttheme.SyntaxCommentColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkGray,\n\t\tLight: gruvboxLightGray,\n\t}\n\ttheme.SyntaxKeywordColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkRedBright,\n\t\tLight: gruvboxLightRedBright,\n\t}\n\ttheme.SyntaxFunctionColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkGreenBright,\n\t\tLight: gruvboxLightGreenBright,\n\t}\n\ttheme.SyntaxVariableColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkBlueBright,\n\t\tLight: gruvboxLightBlueBright,\n\t}\n\ttheme.SyntaxStringColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkYellowBright,\n\t\tLight: gruvboxLightYellowBright,\n\t}\n\ttheme.SyntaxNumberColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkPurpleBright,\n\t\tLight: gruvboxLightPurpleBright,\n\t}\n\ttheme.SyntaxTypeColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkYellow,\n\t\tLight: gruvboxLightYellow,\n\t}\n\ttheme.SyntaxOperatorColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkAquaBright,\n\t\tLight: gruvboxLightAquaBright,\n\t}\n\ttheme.SyntaxPunctuationColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkFg1,\n\t\tLight: gruvboxLightFg1,\n\t}\n\n\treturn theme\n}\n\nfunc init() {\n\t// Register the Gruvbox theme with the theme manager\n\tRegisterTheme(\"gruvbox\", NewGruvboxTheme())\n}"], ["/opencode/internal/tui/styles/markdown.go", "package styles\n\nimport (\n\t\"github.com/charmbracelet/glamour\"\n\t\"github.com/charmbracelet/glamour/ansi\"\n\t\"github.com/charmbracelet/lipgloss\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n)\n\nconst defaultMargin = 1\n\n// Helper functions for style pointers\nfunc boolPtr(b bool) *bool { return &b }\nfunc stringPtr(s string) *string { return &s }\nfunc uintPtr(u uint) *uint { return &u }\n\n// returns a glamour TermRenderer configured with the current theme\nfunc GetMarkdownRenderer(width int) *glamour.TermRenderer {\n\tr, _ := glamour.NewTermRenderer(\n\t\tglamour.WithStyles(generateMarkdownStyleConfig()),\n\t\tglamour.WithWordWrap(width),\n\t)\n\treturn r\n}\n\n// creates an ansi.StyleConfig for markdown rendering\n// using adaptive colors from the provided theme.\nfunc generateMarkdownStyleConfig() ansi.StyleConfig {\n\tt := theme.CurrentTheme()\n\n\treturn ansi.StyleConfig{\n\t\tDocument: ansi.StyleBlock{\n\t\t\tStylePrimitive: ansi.StylePrimitive{\n\t\t\t\tBlockPrefix: \"\",\n\t\t\t\tBlockSuffix: \"\",\n\t\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownText())),\n\t\t\t},\n\t\t\tMargin: uintPtr(defaultMargin),\n\t\t},\n\t\tBlockQuote: ansi.StyleBlock{\n\t\t\tStylePrimitive: ansi.StylePrimitive{\n\t\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownBlockQuote())),\n\t\t\t\tItalic: boolPtr(true),\n\t\t\t\tPrefix: \"┃ \",\n\t\t\t},\n\t\t\tIndent: uintPtr(1),\n\t\t\tIndentToken: stringPtr(BaseStyle().Render(\" \")),\n\t\t},\n\t\tList: ansi.StyleList{\n\t\t\tLevelIndent: defaultMargin,\n\t\t\tStyleBlock: ansi.StyleBlock{\n\t\t\t\tIndentToken: stringPtr(BaseStyle().Render(\" \")),\n\t\t\t\tStylePrimitive: ansi.StylePrimitive{\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownText())),\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\tHeading: ansi.StyleBlock{\n\t\t\tStylePrimitive: ansi.StylePrimitive{\n\t\t\t\tBlockSuffix: \"\\n\",\n\t\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownHeading())),\n\t\t\t\tBold: boolPtr(true),\n\t\t\t},\n\t\t},\n\t\tH1: ansi.StyleBlock{\n\t\t\tStylePrimitive: ansi.StylePrimitive{\n\t\t\t\tPrefix: \"# \",\n\t\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownHeading())),\n\t\t\t\tBold: boolPtr(true),\n\t\t\t},\n\t\t},\n\t\tH2: ansi.StyleBlock{\n\t\t\tStylePrimitive: ansi.StylePrimitive{\n\t\t\t\tPrefix: \"## \",\n\t\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownHeading())),\n\t\t\t\tBold: boolPtr(true),\n\t\t\t},\n\t\t},\n\t\tH3: ansi.StyleBlock{\n\t\t\tStylePrimitive: ansi.StylePrimitive{\n\t\t\t\tPrefix: \"### \",\n\t\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownHeading())),\n\t\t\t\tBold: boolPtr(true),\n\t\t\t},\n\t\t},\n\t\tH4: ansi.StyleBlock{\n\t\t\tStylePrimitive: ansi.StylePrimitive{\n\t\t\t\tPrefix: \"#### \",\n\t\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownHeading())),\n\t\t\t\tBold: boolPtr(true),\n\t\t\t},\n\t\t},\n\t\tH5: ansi.StyleBlock{\n\t\t\tStylePrimitive: ansi.StylePrimitive{\n\t\t\t\tPrefix: \"##### \",\n\t\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownHeading())),\n\t\t\t\tBold: boolPtr(true),\n\t\t\t},\n\t\t},\n\t\tH6: ansi.StyleBlock{\n\t\t\tStylePrimitive: ansi.StylePrimitive{\n\t\t\t\tPrefix: \"###### \",\n\t\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownHeading())),\n\t\t\t\tBold: boolPtr(true),\n\t\t\t},\n\t\t},\n\t\tStrikethrough: ansi.StylePrimitive{\n\t\t\tCrossedOut: boolPtr(true),\n\t\t\tColor: stringPtr(adaptiveColorToString(t.TextMuted())),\n\t\t},\n\t\tEmph: ansi.StylePrimitive{\n\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownEmph())),\n\t\t\tItalic: boolPtr(true),\n\t\t},\n\t\tStrong: ansi.StylePrimitive{\n\t\t\tBold: boolPtr(true),\n\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownStrong())),\n\t\t},\n\t\tHorizontalRule: ansi.StylePrimitive{\n\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownHorizontalRule())),\n\t\t\tFormat: \"\\n─────────────────────────────────────────\\n\",\n\t\t},\n\t\tItem: ansi.StylePrimitive{\n\t\t\tBlockPrefix: \"• \",\n\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownListItem())),\n\t\t},\n\t\tEnumeration: ansi.StylePrimitive{\n\t\t\tBlockPrefix: \". \",\n\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownListEnumeration())),\n\t\t},\n\t\tTask: ansi.StyleTask{\n\t\t\tStylePrimitive: ansi.StylePrimitive{},\n\t\t\tTicked: \"[✓] \",\n\t\t\tUnticked: \"[ ] \",\n\t\t},\n\t\tLink: ansi.StylePrimitive{\n\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownLink())),\n\t\t\tUnderline: boolPtr(true),\n\t\t},\n\t\tLinkText: ansi.StylePrimitive{\n\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownLinkText())),\n\t\t\tBold: boolPtr(true),\n\t\t},\n\t\tImage: ansi.StylePrimitive{\n\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownImage())),\n\t\t\tUnderline: boolPtr(true),\n\t\t\tFormat: \"🖼 {{.text}}\",\n\t\t},\n\t\tImageText: ansi.StylePrimitive{\n\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownImageText())),\n\t\t\tFormat: \"{{.text}}\",\n\t\t},\n\t\tCode: ansi.StyleBlock{\n\t\t\tStylePrimitive: ansi.StylePrimitive{\n\t\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownCode())),\n\t\t\t\tPrefix: \"\",\n\t\t\t\tSuffix: \"\",\n\t\t\t},\n\t\t},\n\t\tCodeBlock: ansi.StyleCodeBlock{\n\t\t\tStyleBlock: ansi.StyleBlock{\n\t\t\t\tStylePrimitive: ansi.StylePrimitive{\n\t\t\t\t\tPrefix: \" \",\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownCodeBlock())),\n\t\t\t\t},\n\t\t\t\tMargin: uintPtr(defaultMargin),\n\t\t\t},\n\t\t\tChroma: &ansi.Chroma{\n\t\t\t\tText: ansi.StylePrimitive{\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownText())),\n\t\t\t\t},\n\t\t\t\tError: ansi.StylePrimitive{\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.Error())),\n\t\t\t\t},\n\t\t\t\tComment: ansi.StylePrimitive{\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.SyntaxComment())),\n\t\t\t\t},\n\t\t\t\tCommentPreproc: ansi.StylePrimitive{\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.SyntaxKeyword())),\n\t\t\t\t},\n\t\t\t\tKeyword: ansi.StylePrimitive{\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.SyntaxKeyword())),\n\t\t\t\t},\n\t\t\t\tKeywordReserved: ansi.StylePrimitive{\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.SyntaxKeyword())),\n\t\t\t\t},\n\t\t\t\tKeywordNamespace: ansi.StylePrimitive{\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.SyntaxKeyword())),\n\t\t\t\t},\n\t\t\t\tKeywordType: ansi.StylePrimitive{\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.SyntaxType())),\n\t\t\t\t},\n\t\t\t\tOperator: ansi.StylePrimitive{\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.SyntaxOperator())),\n\t\t\t\t},\n\t\t\t\tPunctuation: ansi.StylePrimitive{\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.SyntaxPunctuation())),\n\t\t\t\t},\n\t\t\t\tName: ansi.StylePrimitive{\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.SyntaxVariable())),\n\t\t\t\t},\n\t\t\t\tNameBuiltin: ansi.StylePrimitive{\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.SyntaxVariable())),\n\t\t\t\t},\n\t\t\t\tNameTag: ansi.StylePrimitive{\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.SyntaxKeyword())),\n\t\t\t\t},\n\t\t\t\tNameAttribute: ansi.StylePrimitive{\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.SyntaxFunction())),\n\t\t\t\t},\n\t\t\t\tNameClass: ansi.StylePrimitive{\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.SyntaxType())),\n\t\t\t\t},\n\t\t\t\tNameConstant: ansi.StylePrimitive{\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.SyntaxVariable())),\n\t\t\t\t},\n\t\t\t\tNameDecorator: ansi.StylePrimitive{\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.SyntaxFunction())),\n\t\t\t\t},\n\t\t\t\tNameFunction: ansi.StylePrimitive{\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.SyntaxFunction())),\n\t\t\t\t},\n\t\t\t\tLiteralNumber: ansi.StylePrimitive{\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.SyntaxNumber())),\n\t\t\t\t},\n\t\t\t\tLiteralString: ansi.StylePrimitive{\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.SyntaxString())),\n\t\t\t\t},\n\t\t\t\tLiteralStringEscape: ansi.StylePrimitive{\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.SyntaxKeyword())),\n\t\t\t\t},\n\t\t\t\tGenericDeleted: ansi.StylePrimitive{\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.DiffRemoved())),\n\t\t\t\t},\n\t\t\t\tGenericEmph: ansi.StylePrimitive{\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownEmph())),\n\t\t\t\t\tItalic: boolPtr(true),\n\t\t\t\t},\n\t\t\t\tGenericInserted: ansi.StylePrimitive{\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.DiffAdded())),\n\t\t\t\t},\n\t\t\t\tGenericStrong: ansi.StylePrimitive{\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownStrong())),\n\t\t\t\t\tBold: boolPtr(true),\n\t\t\t\t},\n\t\t\t\tGenericSubheading: ansi.StylePrimitive{\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownHeading())),\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\tTable: ansi.StyleTable{\n\t\t\tStyleBlock: ansi.StyleBlock{\n\t\t\t\tStylePrimitive: ansi.StylePrimitive{\n\t\t\t\t\tBlockPrefix: \"\\n\",\n\t\t\t\t\tBlockSuffix: \"\\n\",\n\t\t\t\t},\n\t\t\t},\n\t\t\tCenterSeparator: stringPtr(\"┼\"),\n\t\t\tColumnSeparator: stringPtr(\"│\"),\n\t\t\tRowSeparator: stringPtr(\"─\"),\n\t\t},\n\t\tDefinitionDescription: ansi.StylePrimitive{\n\t\t\tBlockPrefix: \"\\n ❯ \",\n\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownLinkText())),\n\t\t},\n\t\tText: ansi.StylePrimitive{\n\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownText())),\n\t\t},\n\t\tParagraph: ansi.StyleBlock{\n\t\t\tStylePrimitive: ansi.StylePrimitive{\n\t\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownText())),\n\t\t\t},\n\t\t},\n\t}\n}\n\n// adaptiveColorToString converts a lipgloss.AdaptiveColor to the appropriate\n// hex color string based on the current terminal background\nfunc adaptiveColorToString(color lipgloss.AdaptiveColor) string {\n\tif lipgloss.HasDarkBackground() {\n\t\treturn color.Dark\n\t}\n\treturn color.Light\n}\n"], ["/opencode/internal/version/version.go", "package version\n\nimport \"runtime/debug\"\n\n// Build-time parameters set via -ldflags\nvar Version = \"unknown\"\n\n// A user may install pug using `go install github.com/opencode-ai/opencode@latest`.\n// without -ldflags, in which case the version above is unset. As a workaround\n// we use the embedded build version that *is* set when using `go install` (and\n// is only set for `go install` and not for `go build`).\nfunc init() {\n\tinfo, ok := debug.ReadBuildInfo()\n\tif !ok {\n\t\t// < go v1.18\n\t\treturn\n\t}\n\tmainVersion := info.Main.Version\n\tif mainVersion == \"\" || mainVersion == \"(devel)\" {\n\t\t// bin not built using `go install`\n\t\treturn\n\t}\n\t// bin built using `go install`\n\tVersion = mainVersion\n}\n"], ["/opencode/internal/tui/theme/dracula.go", "package theme\n\nimport (\n\t\"github.com/charmbracelet/lipgloss\"\n)\n\n// DraculaTheme implements the Theme interface with Dracula colors.\n// It provides both dark and light variants, though Dracula is primarily a dark theme.\ntype DraculaTheme struct {\n\tBaseTheme\n}\n\n// NewDraculaTheme creates a new instance of the Dracula theme.\nfunc NewDraculaTheme() *DraculaTheme {\n\t// Dracula color palette\n\t// Official colors from https://draculatheme.com/\n\tdarkBackground := \"#282a36\"\n\tdarkCurrentLine := \"#44475a\"\n\tdarkSelection := \"#44475a\"\n\tdarkForeground := \"#f8f8f2\"\n\tdarkComment := \"#6272a4\"\n\tdarkCyan := \"#8be9fd\"\n\tdarkGreen := \"#50fa7b\"\n\tdarkOrange := \"#ffb86c\"\n\tdarkPink := \"#ff79c6\"\n\tdarkPurple := \"#bd93f9\"\n\tdarkRed := \"#ff5555\"\n\tdarkYellow := \"#f1fa8c\"\n\tdarkBorder := \"#44475a\"\n\n\t// Light mode approximation (Dracula is primarily a dark theme)\n\tlightBackground := \"#f8f8f2\"\n\tlightCurrentLine := \"#e6e6e6\"\n\tlightSelection := \"#d8d8d8\"\n\tlightForeground := \"#282a36\"\n\tlightComment := \"#6272a4\"\n\tlightCyan := \"#0097a7\"\n\tlightGreen := \"#388e3c\"\n\tlightOrange := \"#f57c00\"\n\tlightPink := \"#d81b60\"\n\tlightPurple := \"#7e57c2\"\n\tlightRed := \"#e53935\"\n\tlightYellow := \"#fbc02d\"\n\tlightBorder := \"#d8d8d8\"\n\n\ttheme := &DraculaTheme{}\n\n\t// Base colors\n\ttheme.PrimaryColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPurple,\n\t\tLight: lightPurple,\n\t}\n\ttheme.SecondaryColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPink,\n\t\tLight: lightPink,\n\t}\n\ttheme.AccentColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\n\t// Status colors\n\ttheme.ErrorColor = lipgloss.AdaptiveColor{\n\t\tDark: darkRed,\n\t\tLight: lightRed,\n\t}\n\ttheme.WarningColor = lipgloss.AdaptiveColor{\n\t\tDark: darkOrange,\n\t\tLight: lightOrange,\n\t}\n\ttheme.SuccessColor = lipgloss.AdaptiveColor{\n\t\tDark: darkGreen,\n\t\tLight: lightGreen,\n\t}\n\ttheme.InfoColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\n\t// Text colors\n\ttheme.TextColor = lipgloss.AdaptiveColor{\n\t\tDark: darkForeground,\n\t\tLight: lightForeground,\n\t}\n\ttheme.TextMutedColor = lipgloss.AdaptiveColor{\n\t\tDark: darkComment,\n\t\tLight: lightComment,\n\t}\n\ttheme.TextEmphasizedColor = lipgloss.AdaptiveColor{\n\t\tDark: darkYellow,\n\t\tLight: lightYellow,\n\t}\n\n\t// Background colors\n\ttheme.BackgroundColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBackground,\n\t\tLight: lightBackground,\n\t}\n\ttheme.BackgroundSecondaryColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCurrentLine,\n\t\tLight: lightCurrentLine,\n\t}\n\ttheme.BackgroundDarkerColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#21222c\", // Slightly darker than background\n\t\tLight: \"#ffffff\", // Slightly lighter than background\n\t}\n\n\t// Border colors\n\ttheme.BorderNormalColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBorder,\n\t\tLight: lightBorder,\n\t}\n\ttheme.BorderFocusedColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPurple,\n\t\tLight: lightPurple,\n\t}\n\ttheme.BorderDimColor = lipgloss.AdaptiveColor{\n\t\tDark: darkSelection,\n\t\tLight: lightSelection,\n\t}\n\n\t// Diff view colors\n\ttheme.DiffAddedColor = lipgloss.AdaptiveColor{\n\t\tDark: darkGreen,\n\t\tLight: lightGreen,\n\t}\n\ttheme.DiffRemovedColor = lipgloss.AdaptiveColor{\n\t\tDark: darkRed,\n\t\tLight: lightRed,\n\t}\n\ttheme.DiffContextColor = lipgloss.AdaptiveColor{\n\t\tDark: darkComment,\n\t\tLight: lightComment,\n\t}\n\ttheme.DiffHunkHeaderColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPurple,\n\t\tLight: lightPurple,\n\t}\n\ttheme.DiffHighlightAddedColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#50fa7b\",\n\t\tLight: \"#a5d6a7\",\n\t}\n\ttheme.DiffHighlightRemovedColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#ff5555\",\n\t\tLight: \"#ef9a9a\",\n\t}\n\ttheme.DiffAddedBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#2c3b2c\",\n\t\tLight: \"#e8f5e9\",\n\t}\n\ttheme.DiffRemovedBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#3b2c2c\",\n\t\tLight: \"#ffebee\",\n\t}\n\ttheme.DiffContextBgColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBackground,\n\t\tLight: lightBackground,\n\t}\n\ttheme.DiffLineNumberColor = lipgloss.AdaptiveColor{\n\t\tDark: darkComment,\n\t\tLight: lightComment,\n\t}\n\ttheme.DiffAddedLineNumberBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#253025\",\n\t\tLight: \"#c8e6c9\",\n\t}\n\ttheme.DiffRemovedLineNumberBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#302525\",\n\t\tLight: \"#ffcdd2\",\n\t}\n\n\t// Markdown colors\n\ttheme.MarkdownTextColor = lipgloss.AdaptiveColor{\n\t\tDark: darkForeground,\n\t\tLight: lightForeground,\n\t}\n\ttheme.MarkdownHeadingColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPink,\n\t\tLight: lightPink,\n\t}\n\ttheme.MarkdownLinkColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPurple,\n\t\tLight: lightPurple,\n\t}\n\ttheme.MarkdownLinkTextColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.MarkdownCodeColor = lipgloss.AdaptiveColor{\n\t\tDark: darkGreen,\n\t\tLight: lightGreen,\n\t}\n\ttheme.MarkdownBlockQuoteColor = lipgloss.AdaptiveColor{\n\t\tDark: darkYellow,\n\t\tLight: lightYellow,\n\t}\n\ttheme.MarkdownEmphColor = lipgloss.AdaptiveColor{\n\t\tDark: darkYellow,\n\t\tLight: lightYellow,\n\t}\n\ttheme.MarkdownStrongColor = lipgloss.AdaptiveColor{\n\t\tDark: darkOrange,\n\t\tLight: lightOrange,\n\t}\n\ttheme.MarkdownHorizontalRuleColor = lipgloss.AdaptiveColor{\n\t\tDark: darkComment,\n\t\tLight: lightComment,\n\t}\n\ttheme.MarkdownListItemColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPurple,\n\t\tLight: lightPurple,\n\t}\n\ttheme.MarkdownListEnumerationColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.MarkdownImageColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPurple,\n\t\tLight: lightPurple,\n\t}\n\ttheme.MarkdownImageTextColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.MarkdownCodeBlockColor = lipgloss.AdaptiveColor{\n\t\tDark: darkForeground,\n\t\tLight: lightForeground,\n\t}\n\n\t// Syntax highlighting colors\n\ttheme.SyntaxCommentColor = lipgloss.AdaptiveColor{\n\t\tDark: darkComment,\n\t\tLight: lightComment,\n\t}\n\ttheme.SyntaxKeywordColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPink,\n\t\tLight: lightPink,\n\t}\n\ttheme.SyntaxFunctionColor = lipgloss.AdaptiveColor{\n\t\tDark: darkGreen,\n\t\tLight: lightGreen,\n\t}\n\ttheme.SyntaxVariableColor = lipgloss.AdaptiveColor{\n\t\tDark: darkOrange,\n\t\tLight: lightOrange,\n\t}\n\ttheme.SyntaxStringColor = lipgloss.AdaptiveColor{\n\t\tDark: darkYellow,\n\t\tLight: lightYellow,\n\t}\n\ttheme.SyntaxNumberColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPurple,\n\t\tLight: lightPurple,\n\t}\n\ttheme.SyntaxTypeColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.SyntaxOperatorColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPink,\n\t\tLight: lightPink,\n\t}\n\ttheme.SyntaxPunctuationColor = lipgloss.AdaptiveColor{\n\t\tDark: darkForeground,\n\t\tLight: lightForeground,\n\t}\n\n\treturn theme\n}\n\nfunc init() {\n\t// Register the Dracula theme with the theme manager\n\tRegisterTheme(\"dracula\", NewDraculaTheme())\n}"], ["/opencode/internal/tui/theme/monokai.go", "package theme\n\nimport (\n\t\"github.com/charmbracelet/lipgloss\"\n)\n\n// MonokaiProTheme implements the Theme interface with Monokai Pro colors.\n// It provides both dark and light variants.\ntype MonokaiProTheme struct {\n\tBaseTheme\n}\n\n// NewMonokaiProTheme creates a new instance of the Monokai Pro theme.\nfunc NewMonokaiProTheme() *MonokaiProTheme {\n\t// Monokai Pro color palette (dark mode)\n\tdarkBackground := \"#2d2a2e\"\n\tdarkCurrentLine := \"#403e41\"\n\tdarkSelection := \"#5b595c\"\n\tdarkForeground := \"#fcfcfa\"\n\tdarkComment := \"#727072\"\n\tdarkRed := \"#ff6188\"\n\tdarkOrange := \"#fc9867\"\n\tdarkYellow := \"#ffd866\"\n\tdarkGreen := \"#a9dc76\"\n\tdarkCyan := \"#78dce8\"\n\tdarkBlue := \"#ab9df2\"\n\tdarkPurple := \"#ab9df2\"\n\tdarkBorder := \"#403e41\"\n\n\t// Light mode colors (adapted from dark)\n\tlightBackground := \"#fafafa\"\n\tlightCurrentLine := \"#f0f0f0\"\n\tlightSelection := \"#e5e5e6\"\n\tlightForeground := \"#2d2a2e\"\n\tlightComment := \"#939293\"\n\tlightRed := \"#f92672\"\n\tlightOrange := \"#fd971f\"\n\tlightYellow := \"#e6db74\"\n\tlightGreen := \"#9bca65\"\n\tlightCyan := \"#66d9ef\"\n\tlightBlue := \"#7e75db\"\n\tlightPurple := \"#ae81ff\"\n\tlightBorder := \"#d3d3d3\"\n\n\ttheme := &MonokaiProTheme{}\n\n\t// Base colors\n\ttheme.PrimaryColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.SecondaryColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPurple,\n\t\tLight: lightPurple,\n\t}\n\ttheme.AccentColor = lipgloss.AdaptiveColor{\n\t\tDark: darkOrange,\n\t\tLight: lightOrange,\n\t}\n\n\t// Status colors\n\ttheme.ErrorColor = lipgloss.AdaptiveColor{\n\t\tDark: darkRed,\n\t\tLight: lightRed,\n\t}\n\ttheme.WarningColor = lipgloss.AdaptiveColor{\n\t\tDark: darkOrange,\n\t\tLight: lightOrange,\n\t}\n\ttheme.SuccessColor = lipgloss.AdaptiveColor{\n\t\tDark: darkGreen,\n\t\tLight: lightGreen,\n\t}\n\ttheme.InfoColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBlue,\n\t\tLight: lightBlue,\n\t}\n\n\t// Text colors\n\ttheme.TextColor = lipgloss.AdaptiveColor{\n\t\tDark: darkForeground,\n\t\tLight: lightForeground,\n\t}\n\ttheme.TextMutedColor = lipgloss.AdaptiveColor{\n\t\tDark: darkComment,\n\t\tLight: lightComment,\n\t}\n\ttheme.TextEmphasizedColor = lipgloss.AdaptiveColor{\n\t\tDark: darkYellow,\n\t\tLight: lightYellow,\n\t}\n\n\t// Background colors\n\ttheme.BackgroundColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBackground,\n\t\tLight: lightBackground,\n\t}\n\ttheme.BackgroundSecondaryColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCurrentLine,\n\t\tLight: lightCurrentLine,\n\t}\n\ttheme.BackgroundDarkerColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#221f22\", // Slightly darker than background\n\t\tLight: \"#ffffff\", // Slightly lighter than background\n\t}\n\n\t// Border colors\n\ttheme.BorderNormalColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBorder,\n\t\tLight: lightBorder,\n\t}\n\ttheme.BorderFocusedColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.BorderDimColor = lipgloss.AdaptiveColor{\n\t\tDark: darkSelection,\n\t\tLight: lightSelection,\n\t}\n\n\t// Diff view colors\n\ttheme.DiffAddedColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#a9dc76\",\n\t\tLight: \"#9bca65\",\n\t}\n\ttheme.DiffRemovedColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#ff6188\",\n\t\tLight: \"#f92672\",\n\t}\n\ttheme.DiffContextColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#a0a0a0\",\n\t\tLight: \"#757575\",\n\t}\n\ttheme.DiffHunkHeaderColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#a0a0a0\",\n\t\tLight: \"#757575\",\n\t}\n\ttheme.DiffHighlightAddedColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#c2e7a9\",\n\t\tLight: \"#c5e0b4\",\n\t}\n\ttheme.DiffHighlightRemovedColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#ff8ca6\",\n\t\tLight: \"#ffb3c8\",\n\t}\n\ttheme.DiffAddedBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#3a4a35\",\n\t\tLight: \"#e8f5e9\",\n\t}\n\ttheme.DiffRemovedBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#4a3439\",\n\t\tLight: \"#ffebee\",\n\t}\n\ttheme.DiffContextBgColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBackground,\n\t\tLight: lightBackground,\n\t}\n\ttheme.DiffLineNumberColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#888888\",\n\t\tLight: \"#9e9e9e\",\n\t}\n\ttheme.DiffAddedLineNumberBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#2d3a28\",\n\t\tLight: \"#c8e6c9\",\n\t}\n\ttheme.DiffRemovedLineNumberBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#3d2a2e\",\n\t\tLight: \"#ffcdd2\",\n\t}\n\n\t// Markdown colors\n\ttheme.MarkdownTextColor = lipgloss.AdaptiveColor{\n\t\tDark: darkForeground,\n\t\tLight: lightForeground,\n\t}\n\ttheme.MarkdownHeadingColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPurple,\n\t\tLight: lightPurple,\n\t}\n\ttheme.MarkdownLinkColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.MarkdownLinkTextColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBlue,\n\t\tLight: lightBlue,\n\t}\n\ttheme.MarkdownCodeColor = lipgloss.AdaptiveColor{\n\t\tDark: darkGreen,\n\t\tLight: lightGreen,\n\t}\n\ttheme.MarkdownBlockQuoteColor = lipgloss.AdaptiveColor{\n\t\tDark: darkYellow,\n\t\tLight: lightYellow,\n\t}\n\ttheme.MarkdownEmphColor = lipgloss.AdaptiveColor{\n\t\tDark: darkYellow,\n\t\tLight: lightYellow,\n\t}\n\ttheme.MarkdownStrongColor = lipgloss.AdaptiveColor{\n\t\tDark: darkOrange,\n\t\tLight: lightOrange,\n\t}\n\ttheme.MarkdownHorizontalRuleColor = lipgloss.AdaptiveColor{\n\t\tDark: darkComment,\n\t\tLight: lightComment,\n\t}\n\ttheme.MarkdownListItemColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.MarkdownListEnumerationColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBlue,\n\t\tLight: lightBlue,\n\t}\n\ttheme.MarkdownImageColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.MarkdownImageTextColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBlue,\n\t\tLight: lightBlue,\n\t}\n\ttheme.MarkdownCodeBlockColor = lipgloss.AdaptiveColor{\n\t\tDark: darkForeground,\n\t\tLight: lightForeground,\n\t}\n\n\t// Syntax highlighting colors\n\ttheme.SyntaxCommentColor = lipgloss.AdaptiveColor{\n\t\tDark: darkComment,\n\t\tLight: lightComment,\n\t}\n\ttheme.SyntaxKeywordColor = lipgloss.AdaptiveColor{\n\t\tDark: darkRed,\n\t\tLight: lightRed,\n\t}\n\ttheme.SyntaxFunctionColor = lipgloss.AdaptiveColor{\n\t\tDark: darkGreen,\n\t\tLight: lightGreen,\n\t}\n\ttheme.SyntaxVariableColor = lipgloss.AdaptiveColor{\n\t\tDark: darkForeground,\n\t\tLight: lightForeground,\n\t}\n\ttheme.SyntaxStringColor = lipgloss.AdaptiveColor{\n\t\tDark: darkYellow,\n\t\tLight: lightYellow,\n\t}\n\ttheme.SyntaxNumberColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPurple,\n\t\tLight: lightPurple,\n\t}\n\ttheme.SyntaxTypeColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBlue,\n\t\tLight: lightBlue,\n\t}\n\ttheme.SyntaxOperatorColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.SyntaxPunctuationColor = lipgloss.AdaptiveColor{\n\t\tDark: darkForeground,\n\t\tLight: lightForeground,\n\t}\n\n\treturn theme\n}\n\nfunc init() {\n\t// Register the Monokai Pro theme with the theme manager\n\tRegisterTheme(\"monokai\", NewMonokaiProTheme())\n}"], ["/opencode/internal/tui/theme/tokyonight.go", "package theme\n\nimport (\n\t\"github.com/charmbracelet/lipgloss\"\n)\n\n// TokyoNightTheme implements the Theme interface with Tokyo Night colors.\n// It provides both dark and light variants.\ntype TokyoNightTheme struct {\n\tBaseTheme\n}\n\n// NewTokyoNightTheme creates a new instance of the Tokyo Night theme.\nfunc NewTokyoNightTheme() *TokyoNightTheme {\n\t// Tokyo Night color palette\n\t// Dark mode colors\n\tdarkBackground := \"#222436\"\n\tdarkCurrentLine := \"#1e2030\"\n\tdarkSelection := \"#2f334d\"\n\tdarkForeground := \"#c8d3f5\"\n\tdarkComment := \"#636da6\"\n\tdarkRed := \"#ff757f\"\n\tdarkOrange := \"#ff966c\"\n\tdarkYellow := \"#ffc777\"\n\tdarkGreen := \"#c3e88d\"\n\tdarkCyan := \"#86e1fc\"\n\tdarkBlue := \"#82aaff\"\n\tdarkPurple := \"#c099ff\"\n\tdarkBorder := \"#3b4261\"\n\n\t// Light mode colors (Tokyo Night Day)\n\tlightBackground := \"#e1e2e7\"\n\tlightCurrentLine := \"#d5d6db\"\n\tlightSelection := \"#c8c9ce\"\n\tlightForeground := \"#3760bf\"\n\tlightComment := \"#848cb5\"\n\tlightRed := \"#f52a65\"\n\tlightOrange := \"#b15c00\"\n\tlightYellow := \"#8c6c3e\"\n\tlightGreen := \"#587539\"\n\tlightCyan := \"#007197\"\n\tlightBlue := \"#2e7de9\"\n\tlightPurple := \"#9854f1\"\n\tlightBorder := \"#a8aecb\"\n\n\ttheme := &TokyoNightTheme{}\n\n\t// Base colors\n\ttheme.PrimaryColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBlue,\n\t\tLight: lightBlue,\n\t}\n\ttheme.SecondaryColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPurple,\n\t\tLight: lightPurple,\n\t}\n\ttheme.AccentColor = lipgloss.AdaptiveColor{\n\t\tDark: darkOrange,\n\t\tLight: lightOrange,\n\t}\n\n\t// Status colors\n\ttheme.ErrorColor = lipgloss.AdaptiveColor{\n\t\tDark: darkRed,\n\t\tLight: lightRed,\n\t}\n\ttheme.WarningColor = lipgloss.AdaptiveColor{\n\t\tDark: darkOrange,\n\t\tLight: lightOrange,\n\t}\n\ttheme.SuccessColor = lipgloss.AdaptiveColor{\n\t\tDark: darkGreen,\n\t\tLight: lightGreen,\n\t}\n\ttheme.InfoColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBlue,\n\t\tLight: lightBlue,\n\t}\n\n\t// Text colors\n\ttheme.TextColor = lipgloss.AdaptiveColor{\n\t\tDark: darkForeground,\n\t\tLight: lightForeground,\n\t}\n\ttheme.TextMutedColor = lipgloss.AdaptiveColor{\n\t\tDark: darkComment,\n\t\tLight: lightComment,\n\t}\n\ttheme.TextEmphasizedColor = lipgloss.AdaptiveColor{\n\t\tDark: darkYellow,\n\t\tLight: lightYellow,\n\t}\n\n\t// Background colors\n\ttheme.BackgroundColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBackground,\n\t\tLight: lightBackground,\n\t}\n\ttheme.BackgroundSecondaryColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCurrentLine,\n\t\tLight: lightCurrentLine,\n\t}\n\ttheme.BackgroundDarkerColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#191B29\", // Darker background from palette\n\t\tLight: \"#f0f0f5\", // Slightly lighter than background\n\t}\n\n\t// Border colors\n\ttheme.BorderNormalColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBorder,\n\t\tLight: lightBorder,\n\t}\n\ttheme.BorderFocusedColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBlue,\n\t\tLight: lightBlue,\n\t}\n\ttheme.BorderDimColor = lipgloss.AdaptiveColor{\n\t\tDark: darkSelection,\n\t\tLight: lightSelection,\n\t}\n\n\t// Diff view colors\n\ttheme.DiffAddedColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#4fd6be\", // teal from palette\n\t\tLight: \"#1e725c\",\n\t}\n\ttheme.DiffRemovedColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#c53b53\", // red1 from palette\n\t\tLight: \"#c53b53\",\n\t}\n\ttheme.DiffContextColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#828bb8\", // fg_dark from palette\n\t\tLight: \"#7086b5\",\n\t}\n\ttheme.DiffHunkHeaderColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#828bb8\", // fg_dark from palette\n\t\tLight: \"#7086b5\",\n\t}\n\ttheme.DiffHighlightAddedColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#b8db87\", // git.add from palette\n\t\tLight: \"#4db380\",\n\t}\n\ttheme.DiffHighlightRemovedColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#e26a75\", // git.delete from palette\n\t\tLight: \"#f52a65\",\n\t}\n\ttheme.DiffAddedBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#20303b\",\n\t\tLight: \"#d5e5d5\",\n\t}\n\ttheme.DiffRemovedBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#37222c\",\n\t\tLight: \"#f7d8db\",\n\t}\n\ttheme.DiffContextBgColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBackground,\n\t\tLight: lightBackground,\n\t}\n\ttheme.DiffLineNumberColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#545c7e\", // dark3 from palette\n\t\tLight: \"#848cb5\",\n\t}\n\ttheme.DiffAddedLineNumberBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#1b2b34\",\n\t\tLight: \"#c5d5c5\",\n\t}\n\ttheme.DiffRemovedLineNumberBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#2d1f26\",\n\t\tLight: \"#e7c8cb\",\n\t}\n\n\t// Markdown colors\n\ttheme.MarkdownTextColor = lipgloss.AdaptiveColor{\n\t\tDark: darkForeground,\n\t\tLight: lightForeground,\n\t}\n\ttheme.MarkdownHeadingColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPurple,\n\t\tLight: lightPurple,\n\t}\n\ttheme.MarkdownLinkColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBlue,\n\t\tLight: lightBlue,\n\t}\n\ttheme.MarkdownLinkTextColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.MarkdownCodeColor = lipgloss.AdaptiveColor{\n\t\tDark: darkGreen,\n\t\tLight: lightGreen,\n\t}\n\ttheme.MarkdownBlockQuoteColor = lipgloss.AdaptiveColor{\n\t\tDark: darkYellow,\n\t\tLight: lightYellow,\n\t}\n\ttheme.MarkdownEmphColor = lipgloss.AdaptiveColor{\n\t\tDark: darkYellow,\n\t\tLight: lightYellow,\n\t}\n\ttheme.MarkdownStrongColor = lipgloss.AdaptiveColor{\n\t\tDark: darkOrange,\n\t\tLight: lightOrange,\n\t}\n\ttheme.MarkdownHorizontalRuleColor = lipgloss.AdaptiveColor{\n\t\tDark: darkComment,\n\t\tLight: lightComment,\n\t}\n\ttheme.MarkdownListItemColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBlue,\n\t\tLight: lightBlue,\n\t}\n\ttheme.MarkdownListEnumerationColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.MarkdownImageColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBlue,\n\t\tLight: lightBlue,\n\t}\n\ttheme.MarkdownImageTextColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.MarkdownCodeBlockColor = lipgloss.AdaptiveColor{\n\t\tDark: darkForeground,\n\t\tLight: lightForeground,\n\t}\n\n\t// Syntax highlighting colors\n\ttheme.SyntaxCommentColor = lipgloss.AdaptiveColor{\n\t\tDark: darkComment,\n\t\tLight: lightComment,\n\t}\n\ttheme.SyntaxKeywordColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPurple,\n\t\tLight: lightPurple,\n\t}\n\ttheme.SyntaxFunctionColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBlue,\n\t\tLight: lightBlue,\n\t}\n\ttheme.SyntaxVariableColor = lipgloss.AdaptiveColor{\n\t\tDark: darkRed,\n\t\tLight: lightRed,\n\t}\n\ttheme.SyntaxStringColor = lipgloss.AdaptiveColor{\n\t\tDark: darkGreen,\n\t\tLight: lightGreen,\n\t}\n\ttheme.SyntaxNumberColor = lipgloss.AdaptiveColor{\n\t\tDark: darkOrange,\n\t\tLight: lightOrange,\n\t}\n\ttheme.SyntaxTypeColor = lipgloss.AdaptiveColor{\n\t\tDark: darkYellow,\n\t\tLight: lightYellow,\n\t}\n\ttheme.SyntaxOperatorColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.SyntaxPunctuationColor = lipgloss.AdaptiveColor{\n\t\tDark: darkForeground,\n\t\tLight: lightForeground,\n\t}\n\n\treturn theme\n}\n\nfunc init() {\n\t// Register the Tokyo Night theme with the theme manager\n\tRegisterTheme(\"tokyonight\", NewTokyoNightTheme())\n}"], ["/opencode/internal/tui/util/util.go", "package util\n\nimport (\n\t\"time\"\n\n\ttea \"github.com/charmbracelet/bubbletea\"\n)\n\nfunc CmdHandler(msg tea.Msg) tea.Cmd {\n\treturn func() tea.Msg {\n\t\treturn msg\n\t}\n}\n\nfunc ReportError(err error) tea.Cmd {\n\treturn CmdHandler(InfoMsg{\n\t\tType: InfoTypeError,\n\t\tMsg: err.Error(),\n\t})\n}\n\ntype InfoType int\n\nconst (\n\tInfoTypeInfo InfoType = iota\n\tInfoTypeWarn\n\tInfoTypeError\n)\n\nfunc ReportInfo(info string) tea.Cmd {\n\treturn CmdHandler(InfoMsg{\n\t\tType: InfoTypeInfo,\n\t\tMsg: info,\n\t})\n}\n\nfunc ReportWarn(warn string) tea.Cmd {\n\treturn CmdHandler(InfoMsg{\n\t\tType: InfoTypeWarn,\n\t\tMsg: warn,\n\t})\n}\n\ntype (\n\tInfoMsg struct {\n\t\tType InfoType\n\t\tMsg string\n\t\tTTL time.Duration\n\t}\n\tClearStatusMsg struct{}\n)\n\nfunc Clamp(v, low, high int) int {\n\tif high < low {\n\t\tlow, high = high, low\n\t}\n\treturn min(high, max(low, v))\n}\n"], ["/opencode/internal/llm/agent/tools.go", "package agent\n\nimport (\n\t\"context\"\n\n\t\"github.com/opencode-ai/opencode/internal/history\"\n\t\"github.com/opencode-ai/opencode/internal/llm/tools\"\n\t\"github.com/opencode-ai/opencode/internal/lsp\"\n\t\"github.com/opencode-ai/opencode/internal/message\"\n\t\"github.com/opencode-ai/opencode/internal/permission\"\n\t\"github.com/opencode-ai/opencode/internal/session\"\n)\n\nfunc CoderAgentTools(\n\tpermissions permission.Service,\n\tsessions session.Service,\n\tmessages message.Service,\n\thistory history.Service,\n\tlspClients map[string]*lsp.Client,\n) []tools.BaseTool {\n\tctx := context.Background()\n\totherTools := GetMcpTools(ctx, permissions)\n\tif len(lspClients) > 0 {\n\t\totherTools = append(otherTools, tools.NewDiagnosticsTool(lspClients))\n\t}\n\treturn append(\n\t\t[]tools.BaseTool{\n\t\t\ttools.NewBashTool(permissions),\n\t\t\ttools.NewEditTool(lspClients, permissions, history),\n\t\t\ttools.NewFetchTool(permissions),\n\t\t\ttools.NewGlobTool(),\n\t\t\ttools.NewGrepTool(),\n\t\t\ttools.NewLsTool(),\n\t\t\ttools.NewSourcegraphTool(),\n\t\t\ttools.NewViewTool(lspClients),\n\t\t\ttools.NewPatchTool(lspClients, permissions, history),\n\t\t\ttools.NewWriteTool(lspClients, permissions, history),\n\t\t\tNewAgentTool(sessions, messages, lspClients),\n\t\t}, otherTools...,\n\t)\n}\n\nfunc TaskAgentTools(lspClients map[string]*lsp.Client) []tools.BaseTool {\n\treturn []tools.BaseTool{\n\t\ttools.NewGlobTool(),\n\t\ttools.NewGrepTool(),\n\t\ttools.NewLsTool(),\n\t\ttools.NewSourcegraphTool(),\n\t\ttools.NewViewTool(lspClients),\n\t}\n}\n"], ["/opencode/internal/tui/theme/tron.go", "package theme\n\nimport (\n\t\"github.com/charmbracelet/lipgloss\"\n)\n\n// TronTheme implements the Theme interface with Tron-inspired colors.\n// It provides both dark and light variants, though Tron is primarily a dark theme.\ntype TronTheme struct {\n\tBaseTheme\n}\n\n// NewTronTheme creates a new instance of the Tron theme.\nfunc NewTronTheme() *TronTheme {\n\t// Tron color palette\n\t// Inspired by the Tron movie's neon aesthetic\n\tdarkBackground := \"#0c141f\"\n\tdarkCurrentLine := \"#1a2633\"\n\tdarkSelection := \"#1a2633\"\n\tdarkForeground := \"#caf0ff\"\n\tdarkComment := \"#4d6b87\"\n\tdarkCyan := \"#00d9ff\"\n\tdarkBlue := \"#007fff\"\n\tdarkOrange := \"#ff9000\"\n\tdarkPink := \"#ff00a0\"\n\tdarkPurple := \"#b73fff\"\n\tdarkRed := \"#ff3333\"\n\tdarkYellow := \"#ffcc00\"\n\tdarkGreen := \"#00ff8f\"\n\tdarkBorder := \"#1a2633\"\n\n\t// Light mode approximation\n\tlightBackground := \"#f0f8ff\"\n\tlightCurrentLine := \"#e0f0ff\"\n\tlightSelection := \"#d0e8ff\"\n\tlightForeground := \"#0c141f\"\n\tlightComment := \"#4d6b87\"\n\tlightCyan := \"#0097b3\"\n\tlightBlue := \"#0066cc\"\n\tlightOrange := \"#cc7300\"\n\tlightPink := \"#cc0080\"\n\tlightPurple := \"#9932cc\"\n\tlightRed := \"#cc2929\"\n\tlightYellow := \"#cc9900\"\n\tlightGreen := \"#00cc72\"\n\tlightBorder := \"#d0e8ff\"\n\n\ttheme := &TronTheme{}\n\n\t// Base colors\n\ttheme.PrimaryColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.SecondaryColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBlue,\n\t\tLight: lightBlue,\n\t}\n\ttheme.AccentColor = lipgloss.AdaptiveColor{\n\t\tDark: darkOrange,\n\t\tLight: lightOrange,\n\t}\n\n\t// Status colors\n\ttheme.ErrorColor = lipgloss.AdaptiveColor{\n\t\tDark: darkRed,\n\t\tLight: lightRed,\n\t}\n\ttheme.WarningColor = lipgloss.AdaptiveColor{\n\t\tDark: darkOrange,\n\t\tLight: lightOrange,\n\t}\n\ttheme.SuccessColor = lipgloss.AdaptiveColor{\n\t\tDark: darkGreen,\n\t\tLight: lightGreen,\n\t}\n\ttheme.InfoColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\n\t// Text colors\n\ttheme.TextColor = lipgloss.AdaptiveColor{\n\t\tDark: darkForeground,\n\t\tLight: lightForeground,\n\t}\n\ttheme.TextMutedColor = lipgloss.AdaptiveColor{\n\t\tDark: darkComment,\n\t\tLight: lightComment,\n\t}\n\ttheme.TextEmphasizedColor = lipgloss.AdaptiveColor{\n\t\tDark: darkYellow,\n\t\tLight: lightYellow,\n\t}\n\n\t// Background colors\n\ttheme.BackgroundColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBackground,\n\t\tLight: lightBackground,\n\t}\n\ttheme.BackgroundSecondaryColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCurrentLine,\n\t\tLight: lightCurrentLine,\n\t}\n\ttheme.BackgroundDarkerColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#070d14\", // Slightly darker than background\n\t\tLight: \"#ffffff\", // Slightly lighter than background\n\t}\n\n\t// Border colors\n\ttheme.BorderNormalColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBorder,\n\t\tLight: lightBorder,\n\t}\n\ttheme.BorderFocusedColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.BorderDimColor = lipgloss.AdaptiveColor{\n\t\tDark: darkSelection,\n\t\tLight: lightSelection,\n\t}\n\n\t// Diff view colors\n\ttheme.DiffAddedColor = lipgloss.AdaptiveColor{\n\t\tDark: darkGreen,\n\t\tLight: lightGreen,\n\t}\n\ttheme.DiffRemovedColor = lipgloss.AdaptiveColor{\n\t\tDark: darkRed,\n\t\tLight: lightRed,\n\t}\n\ttheme.DiffContextColor = lipgloss.AdaptiveColor{\n\t\tDark: darkComment,\n\t\tLight: lightComment,\n\t}\n\ttheme.DiffHunkHeaderColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBlue,\n\t\tLight: lightBlue,\n\t}\n\ttheme.DiffHighlightAddedColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#00ff8f\",\n\t\tLight: \"#a5d6a7\",\n\t}\n\ttheme.DiffHighlightRemovedColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#ff3333\",\n\t\tLight: \"#ef9a9a\",\n\t}\n\ttheme.DiffAddedBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#0a2a1a\",\n\t\tLight: \"#e8f5e9\",\n\t}\n\ttheme.DiffRemovedBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#2a0a0a\",\n\t\tLight: \"#ffebee\",\n\t}\n\ttheme.DiffContextBgColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBackground,\n\t\tLight: lightBackground,\n\t}\n\ttheme.DiffLineNumberColor = lipgloss.AdaptiveColor{\n\t\tDark: darkComment,\n\t\tLight: lightComment,\n\t}\n\ttheme.DiffAddedLineNumberBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#082015\",\n\t\tLight: \"#c8e6c9\",\n\t}\n\ttheme.DiffRemovedLineNumberBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#200808\",\n\t\tLight: \"#ffcdd2\",\n\t}\n\n\t// Markdown colors\n\ttheme.MarkdownTextColor = lipgloss.AdaptiveColor{\n\t\tDark: darkForeground,\n\t\tLight: lightForeground,\n\t}\n\ttheme.MarkdownHeadingColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.MarkdownLinkColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBlue,\n\t\tLight: lightBlue,\n\t}\n\ttheme.MarkdownLinkTextColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.MarkdownCodeColor = lipgloss.AdaptiveColor{\n\t\tDark: darkGreen,\n\t\tLight: lightGreen,\n\t}\n\ttheme.MarkdownBlockQuoteColor = lipgloss.AdaptiveColor{\n\t\tDark: darkYellow,\n\t\tLight: lightYellow,\n\t}\n\ttheme.MarkdownEmphColor = lipgloss.AdaptiveColor{\n\t\tDark: darkYellow,\n\t\tLight: lightYellow,\n\t}\n\ttheme.MarkdownStrongColor = lipgloss.AdaptiveColor{\n\t\tDark: darkOrange,\n\t\tLight: lightOrange,\n\t}\n\ttheme.MarkdownHorizontalRuleColor = lipgloss.AdaptiveColor{\n\t\tDark: darkComment,\n\t\tLight: lightComment,\n\t}\n\ttheme.MarkdownListItemColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBlue,\n\t\tLight: lightBlue,\n\t}\n\ttheme.MarkdownListEnumerationColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.MarkdownImageColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBlue,\n\t\tLight: lightBlue,\n\t}\n\ttheme.MarkdownImageTextColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.MarkdownCodeBlockColor = lipgloss.AdaptiveColor{\n\t\tDark: darkForeground,\n\t\tLight: lightForeground,\n\t}\n\n\t// Syntax highlighting colors\n\ttheme.SyntaxCommentColor = lipgloss.AdaptiveColor{\n\t\tDark: darkComment,\n\t\tLight: lightComment,\n\t}\n\ttheme.SyntaxKeywordColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.SyntaxFunctionColor = lipgloss.AdaptiveColor{\n\t\tDark: darkGreen,\n\t\tLight: lightGreen,\n\t}\n\ttheme.SyntaxVariableColor = lipgloss.AdaptiveColor{\n\t\tDark: darkOrange,\n\t\tLight: lightOrange,\n\t}\n\ttheme.SyntaxStringColor = lipgloss.AdaptiveColor{\n\t\tDark: darkYellow,\n\t\tLight: lightYellow,\n\t}\n\ttheme.SyntaxNumberColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBlue,\n\t\tLight: lightBlue,\n\t}\n\ttheme.SyntaxTypeColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPurple,\n\t\tLight: lightPurple,\n\t}\n\ttheme.SyntaxOperatorColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPink,\n\t\tLight: lightPink,\n\t}\n\ttheme.SyntaxPunctuationColor = lipgloss.AdaptiveColor{\n\t\tDark: darkForeground,\n\t\tLight: lightForeground,\n\t}\n\n\treturn theme\n}\n\nfunc init() {\n\t// Register the Tron theme with the theme manager\n\tRegisterTheme(\"tron\", NewTronTheme())\n}"], ["/opencode/internal/tui/theme/onedark.go", "package theme\n\nimport (\n\t\"github.com/charmbracelet/lipgloss\"\n)\n\n// OneDarkTheme implements the Theme interface with Atom's One Dark colors.\n// It provides both dark and light variants.\ntype OneDarkTheme struct {\n\tBaseTheme\n}\n\n// NewOneDarkTheme creates a new instance of the One Dark theme.\nfunc NewOneDarkTheme() *OneDarkTheme {\n\t// One Dark color palette\n\t// Dark mode colors from Atom One Dark\n\tdarkBackground := \"#282c34\"\n\tdarkCurrentLine := \"#2c313c\"\n\tdarkSelection := \"#3e4451\"\n\tdarkForeground := \"#abb2bf\"\n\tdarkComment := \"#5c6370\"\n\tdarkRed := \"#e06c75\"\n\tdarkOrange := \"#d19a66\"\n\tdarkYellow := \"#e5c07b\"\n\tdarkGreen := \"#98c379\"\n\tdarkCyan := \"#56b6c2\"\n\tdarkBlue := \"#61afef\"\n\tdarkPurple := \"#c678dd\"\n\tdarkBorder := \"#3b4048\"\n\n\t// Light mode colors from Atom One Light\n\tlightBackground := \"#fafafa\"\n\tlightCurrentLine := \"#f0f0f0\"\n\tlightSelection := \"#e5e5e6\"\n\tlightForeground := \"#383a42\"\n\tlightComment := \"#a0a1a7\"\n\tlightRed := \"#e45649\"\n\tlightOrange := \"#da8548\"\n\tlightYellow := \"#c18401\"\n\tlightGreen := \"#50a14f\"\n\tlightCyan := \"#0184bc\"\n\tlightBlue := \"#4078f2\"\n\tlightPurple := \"#a626a4\"\n\tlightBorder := \"#d3d3d3\"\n\n\ttheme := &OneDarkTheme{}\n\n\t// Base colors\n\ttheme.PrimaryColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBlue,\n\t\tLight: lightBlue,\n\t}\n\ttheme.SecondaryColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPurple,\n\t\tLight: lightPurple,\n\t}\n\ttheme.AccentColor = lipgloss.AdaptiveColor{\n\t\tDark: darkOrange,\n\t\tLight: lightOrange,\n\t}\n\n\t// Status colors\n\ttheme.ErrorColor = lipgloss.AdaptiveColor{\n\t\tDark: darkRed,\n\t\tLight: lightRed,\n\t}\n\ttheme.WarningColor = lipgloss.AdaptiveColor{\n\t\tDark: darkOrange,\n\t\tLight: lightOrange,\n\t}\n\ttheme.SuccessColor = lipgloss.AdaptiveColor{\n\t\tDark: darkGreen,\n\t\tLight: lightGreen,\n\t}\n\ttheme.InfoColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBlue,\n\t\tLight: lightBlue,\n\t}\n\n\t// Text colors\n\ttheme.TextColor = lipgloss.AdaptiveColor{\n\t\tDark: darkForeground,\n\t\tLight: lightForeground,\n\t}\n\ttheme.TextMutedColor = lipgloss.AdaptiveColor{\n\t\tDark: darkComment,\n\t\tLight: lightComment,\n\t}\n\ttheme.TextEmphasizedColor = lipgloss.AdaptiveColor{\n\t\tDark: darkYellow,\n\t\tLight: lightYellow,\n\t}\n\n\t// Background colors\n\ttheme.BackgroundColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBackground,\n\t\tLight: lightBackground,\n\t}\n\ttheme.BackgroundSecondaryColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCurrentLine,\n\t\tLight: lightCurrentLine,\n\t}\n\ttheme.BackgroundDarkerColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#21252b\", // Slightly darker than background\n\t\tLight: \"#ffffff\", // Slightly lighter than background\n\t}\n\n\t// Border colors\n\ttheme.BorderNormalColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBorder,\n\t\tLight: lightBorder,\n\t}\n\ttheme.BorderFocusedColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBlue,\n\t\tLight: lightBlue,\n\t}\n\ttheme.BorderDimColor = lipgloss.AdaptiveColor{\n\t\tDark: darkSelection,\n\t\tLight: lightSelection,\n\t}\n\n\t// Diff view colors\n\ttheme.DiffAddedColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#478247\",\n\t\tLight: \"#2E7D32\",\n\t}\n\ttheme.DiffRemovedColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#7C4444\",\n\t\tLight: \"#C62828\",\n\t}\n\ttheme.DiffContextColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#a0a0a0\",\n\t\tLight: \"#757575\",\n\t}\n\ttheme.DiffHunkHeaderColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#a0a0a0\",\n\t\tLight: \"#757575\",\n\t}\n\ttheme.DiffHighlightAddedColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#DAFADA\",\n\t\tLight: \"#A5D6A7\",\n\t}\n\ttheme.DiffHighlightRemovedColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#FADADD\",\n\t\tLight: \"#EF9A9A\",\n\t}\n\ttheme.DiffAddedBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#303A30\",\n\t\tLight: \"#E8F5E9\",\n\t}\n\ttheme.DiffRemovedBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#3A3030\",\n\t\tLight: \"#FFEBEE\",\n\t}\n\ttheme.DiffContextBgColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBackground,\n\t\tLight: lightBackground,\n\t}\n\ttheme.DiffLineNumberColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#888888\",\n\t\tLight: \"#9E9E9E\",\n\t}\n\ttheme.DiffAddedLineNumberBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#293229\",\n\t\tLight: \"#C8E6C9\",\n\t}\n\ttheme.DiffRemovedLineNumberBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#332929\",\n\t\tLight: \"#FFCDD2\",\n\t}\n\n\t// Markdown colors\n\ttheme.MarkdownTextColor = lipgloss.AdaptiveColor{\n\t\tDark: darkForeground,\n\t\tLight: lightForeground,\n\t}\n\ttheme.MarkdownHeadingColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPurple,\n\t\tLight: lightPurple,\n\t}\n\ttheme.MarkdownLinkColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBlue,\n\t\tLight: lightBlue,\n\t}\n\ttheme.MarkdownLinkTextColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.MarkdownCodeColor = lipgloss.AdaptiveColor{\n\t\tDark: darkGreen,\n\t\tLight: lightGreen,\n\t}\n\ttheme.MarkdownBlockQuoteColor = lipgloss.AdaptiveColor{\n\t\tDark: darkYellow,\n\t\tLight: lightYellow,\n\t}\n\ttheme.MarkdownEmphColor = lipgloss.AdaptiveColor{\n\t\tDark: darkYellow,\n\t\tLight: lightYellow,\n\t}\n\ttheme.MarkdownStrongColor = lipgloss.AdaptiveColor{\n\t\tDark: darkOrange,\n\t\tLight: lightOrange,\n\t}\n\ttheme.MarkdownHorizontalRuleColor = lipgloss.AdaptiveColor{\n\t\tDark: darkComment,\n\t\tLight: lightComment,\n\t}\n\ttheme.MarkdownListItemColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBlue,\n\t\tLight: lightBlue,\n\t}\n\ttheme.MarkdownListEnumerationColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.MarkdownImageColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBlue,\n\t\tLight: lightBlue,\n\t}\n\ttheme.MarkdownImageTextColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.MarkdownCodeBlockColor = lipgloss.AdaptiveColor{\n\t\tDark: darkForeground,\n\t\tLight: lightForeground,\n\t}\n\n\t// Syntax highlighting colors\n\ttheme.SyntaxCommentColor = lipgloss.AdaptiveColor{\n\t\tDark: darkComment,\n\t\tLight: lightComment,\n\t}\n\ttheme.SyntaxKeywordColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPurple,\n\t\tLight: lightPurple,\n\t}\n\ttheme.SyntaxFunctionColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBlue,\n\t\tLight: lightBlue,\n\t}\n\ttheme.SyntaxVariableColor = lipgloss.AdaptiveColor{\n\t\tDark: darkRed,\n\t\tLight: lightRed,\n\t}\n\ttheme.SyntaxStringColor = lipgloss.AdaptiveColor{\n\t\tDark: darkGreen,\n\t\tLight: lightGreen,\n\t}\n\ttheme.SyntaxNumberColor = lipgloss.AdaptiveColor{\n\t\tDark: darkOrange,\n\t\tLight: lightOrange,\n\t}\n\ttheme.SyntaxTypeColor = lipgloss.AdaptiveColor{\n\t\tDark: darkYellow,\n\t\tLight: lightYellow,\n\t}\n\ttheme.SyntaxOperatorColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.SyntaxPunctuationColor = lipgloss.AdaptiveColor{\n\t\tDark: darkForeground,\n\t\tLight: lightForeground,\n\t}\n\n\treturn theme\n}\n\nfunc init() {\n\t// Register the One Dark theme with the theme manager\n\tRegisterTheme(\"onedark\", NewOneDarkTheme())\n}"], ["/opencode/internal/llm/models/copilot.go", "package models\n\nconst (\n\tProviderCopilot ModelProvider = \"copilot\"\n\n\t// GitHub Copilot models\n\tCopilotGTP35Turbo ModelID = \"copilot.gpt-3.5-turbo\"\n\tCopilotGPT4o ModelID = \"copilot.gpt-4o\"\n\tCopilotGPT4oMini ModelID = \"copilot.gpt-4o-mini\"\n\tCopilotGPT41 ModelID = \"copilot.gpt-4.1\"\n\tCopilotClaude35 ModelID = \"copilot.claude-3.5-sonnet\"\n\tCopilotClaude37 ModelID = \"copilot.claude-3.7-sonnet\"\n\tCopilotClaude4 ModelID = \"copilot.claude-sonnet-4\"\n\tCopilotO1 ModelID = \"copilot.o1\"\n\tCopilotO3Mini ModelID = \"copilot.o3-mini\"\n\tCopilotO4Mini ModelID = \"copilot.o4-mini\"\n\tCopilotGemini20 ModelID = \"copilot.gemini-2.0-flash\"\n\tCopilotGemini25 ModelID = \"copilot.gemini-2.5-pro\"\n\tCopilotGPT4 ModelID = \"copilot.gpt-4\"\n\tCopilotClaude37Thought ModelID = \"copilot.claude-3.7-sonnet-thought\"\n)\n\nvar CopilotAnthropicModels = []ModelID{\n\tCopilotClaude35,\n\tCopilotClaude37,\n\tCopilotClaude37Thought,\n\tCopilotClaude4,\n}\n\n// GitHub Copilot models available through GitHub's API\nvar CopilotModels = map[ModelID]Model{\n\tCopilotGTP35Turbo: {\n\t\tID: CopilotGTP35Turbo,\n\t\tName: \"GitHub Copilot GPT-3.5-turbo\",\n\t\tProvider: ProviderCopilot,\n\t\tAPIModel: \"gpt-3.5-turbo\",\n\t\tCostPer1MIn: 0.0, // Included in GitHub Copilot subscription\n\t\tCostPer1MInCached: 0.0,\n\t\tCostPer1MOutCached: 0.0,\n\t\tCostPer1MOut: 0.0,\n\t\tContextWindow: 16_384,\n\t\tDefaultMaxTokens: 4096,\n\t\tSupportsAttachments: true,\n\t},\n\tCopilotGPT4o: {\n\t\tID: CopilotGPT4o,\n\t\tName: \"GitHub Copilot GPT-4o\",\n\t\tProvider: ProviderCopilot,\n\t\tAPIModel: \"gpt-4o\",\n\t\tCostPer1MIn: 0.0, // Included in GitHub Copilot subscription\n\t\tCostPer1MInCached: 0.0,\n\t\tCostPer1MOutCached: 0.0,\n\t\tCostPer1MOut: 0.0,\n\t\tContextWindow: 128_000,\n\t\tDefaultMaxTokens: 16384,\n\t\tSupportsAttachments: true,\n\t},\n\tCopilotGPT4oMini: {\n\t\tID: CopilotGPT4oMini,\n\t\tName: \"GitHub Copilot GPT-4o Mini\",\n\t\tProvider: ProviderCopilot,\n\t\tAPIModel: \"gpt-4o-mini\",\n\t\tCostPer1MIn: 0.0, // Included in GitHub Copilot subscription\n\t\tCostPer1MInCached: 0.0,\n\t\tCostPer1MOutCached: 0.0,\n\t\tCostPer1MOut: 0.0,\n\t\tContextWindow: 128_000,\n\t\tDefaultMaxTokens: 4096,\n\t\tSupportsAttachments: true,\n\t},\n\tCopilotGPT41: {\n\t\tID: CopilotGPT41,\n\t\tName: \"GitHub Copilot GPT-4.1\",\n\t\tProvider: ProviderCopilot,\n\t\tAPIModel: \"gpt-4.1\",\n\t\tCostPer1MIn: 0.0, // Included in GitHub Copilot subscription\n\t\tCostPer1MInCached: 0.0,\n\t\tCostPer1MOutCached: 0.0,\n\t\tCostPer1MOut: 0.0,\n\t\tContextWindow: 128_000,\n\t\tDefaultMaxTokens: 16384,\n\t\tCanReason: true,\n\t\tSupportsAttachments: true,\n\t},\n\tCopilotClaude35: {\n\t\tID: CopilotClaude35,\n\t\tName: \"GitHub Copilot Claude 3.5 Sonnet\",\n\t\tProvider: ProviderCopilot,\n\t\tAPIModel: \"claude-3.5-sonnet\",\n\t\tCostPer1MIn: 0.0, // Included in GitHub Copilot subscription\n\t\tCostPer1MInCached: 0.0,\n\t\tCostPer1MOutCached: 0.0,\n\t\tCostPer1MOut: 0.0,\n\t\tContextWindow: 90_000,\n\t\tDefaultMaxTokens: 8192,\n\t\tSupportsAttachments: true,\n\t},\n\tCopilotClaude37: {\n\t\tID: CopilotClaude37,\n\t\tName: \"GitHub Copilot Claude 3.7 Sonnet\",\n\t\tProvider: ProviderCopilot,\n\t\tAPIModel: \"claude-3.7-sonnet\",\n\t\tCostPer1MIn: 0.0, // Included in GitHub Copilot subscription\n\t\tCostPer1MInCached: 0.0,\n\t\tCostPer1MOutCached: 0.0,\n\t\tCostPer1MOut: 0.0,\n\t\tContextWindow: 200_000,\n\t\tDefaultMaxTokens: 16384,\n\t\tSupportsAttachments: true,\n\t},\n\tCopilotClaude4: {\n\t\tID: CopilotClaude4,\n\t\tName: \"GitHub Copilot Claude Sonnet 4\",\n\t\tProvider: ProviderCopilot,\n\t\tAPIModel: \"claude-sonnet-4\",\n\t\tCostPer1MIn: 0.0, // Included in GitHub Copilot subscription\n\t\tCostPer1MInCached: 0.0,\n\t\tCostPer1MOutCached: 0.0,\n\t\tCostPer1MOut: 0.0,\n\t\tContextWindow: 128_000,\n\t\tDefaultMaxTokens: 16000,\n\t\tSupportsAttachments: true,\n\t},\n\tCopilotO1: {\n\t\tID: CopilotO1,\n\t\tName: \"GitHub Copilot o1\",\n\t\tProvider: ProviderCopilot,\n\t\tAPIModel: \"o1\",\n\t\tCostPer1MIn: 0.0, // Included in GitHub Copilot subscription\n\t\tCostPer1MInCached: 0.0,\n\t\tCostPer1MOutCached: 0.0,\n\t\tCostPer1MOut: 0.0,\n\t\tContextWindow: 200_000,\n\t\tDefaultMaxTokens: 100_000,\n\t\tCanReason: true,\n\t\tSupportsAttachments: false,\n\t},\n\tCopilotO3Mini: {\n\t\tID: CopilotO3Mini,\n\t\tName: \"GitHub Copilot o3-mini\",\n\t\tProvider: ProviderCopilot,\n\t\tAPIModel: \"o3-mini\",\n\t\tCostPer1MIn: 0.0, // Included in GitHub Copilot subscription\n\t\tCostPer1MInCached: 0.0,\n\t\tCostPer1MOutCached: 0.0,\n\t\tCostPer1MOut: 0.0,\n\t\tContextWindow: 200_000,\n\t\tDefaultMaxTokens: 100_000,\n\t\tCanReason: true,\n\t\tSupportsAttachments: false,\n\t},\n\tCopilotO4Mini: {\n\t\tID: CopilotO4Mini,\n\t\tName: \"GitHub Copilot o4-mini\",\n\t\tProvider: ProviderCopilot,\n\t\tAPIModel: \"o4-mini\",\n\t\tCostPer1MIn: 0.0, // Included in GitHub Copilot subscription\n\t\tCostPer1MInCached: 0.0,\n\t\tCostPer1MOutCached: 0.0,\n\t\tCostPer1MOut: 0.0,\n\t\tContextWindow: 128_000,\n\t\tDefaultMaxTokens: 16_384,\n\t\tCanReason: true,\n\t\tSupportsAttachments: true,\n\t},\n\tCopilotGemini20: {\n\t\tID: CopilotGemini20,\n\t\tName: \"GitHub Copilot Gemini 2.0 Flash\",\n\t\tProvider: ProviderCopilot,\n\t\tAPIModel: \"gemini-2.0-flash-001\",\n\t\tCostPer1MIn: 0.0, // Included in GitHub Copilot subscription\n\t\tCostPer1MInCached: 0.0,\n\t\tCostPer1MOutCached: 0.0,\n\t\tCostPer1MOut: 0.0,\n\t\tContextWindow: 1_000_000,\n\t\tDefaultMaxTokens: 8192,\n\t\tSupportsAttachments: true,\n\t},\n\tCopilotGemini25: {\n\t\tID: CopilotGemini25,\n\t\tName: \"GitHub Copilot Gemini 2.5 Pro\",\n\t\tProvider: ProviderCopilot,\n\t\tAPIModel: \"gemini-2.5-pro\",\n\t\tCostPer1MIn: 0.0, // Included in GitHub Copilot subscription\n\t\tCostPer1MInCached: 0.0,\n\t\tCostPer1MOutCached: 0.0,\n\t\tCostPer1MOut: 0.0,\n\t\tContextWindow: 128_000,\n\t\tDefaultMaxTokens: 64000,\n\t\tSupportsAttachments: true,\n\t},\n\tCopilotGPT4: {\n\t\tID: CopilotGPT4,\n\t\tName: \"GitHub Copilot GPT-4\",\n\t\tProvider: ProviderCopilot,\n\t\tAPIModel: \"gpt-4\",\n\t\tCostPer1MIn: 0.0, // Included in GitHub Copilot subscription\n\t\tCostPer1MInCached: 0.0,\n\t\tCostPer1MOutCached: 0.0,\n\t\tCostPer1MOut: 0.0,\n\t\tContextWindow: 32_768,\n\t\tDefaultMaxTokens: 4096,\n\t\tSupportsAttachments: true,\n\t},\n\tCopilotClaude37Thought: {\n\t\tID: CopilotClaude37Thought,\n\t\tName: \"GitHub Copilot Claude 3.7 Sonnet Thinking\",\n\t\tProvider: ProviderCopilot,\n\t\tAPIModel: \"claude-3.7-sonnet-thought\",\n\t\tCostPer1MIn: 0.0, // Included in GitHub Copilot subscription\n\t\tCostPer1MInCached: 0.0,\n\t\tCostPer1MOutCached: 0.0,\n\t\tCostPer1MOut: 0.0,\n\t\tContextWindow: 200_000,\n\t\tDefaultMaxTokens: 16384,\n\t\tCanReason: true,\n\t\tSupportsAttachments: true,\n\t},\n}\n"], ["/opencode/internal/lsp/language.go", "package lsp\n\nimport (\n\t\"path/filepath\"\n\t\"strings\"\n\n\t\"github.com/opencode-ai/opencode/internal/lsp/protocol\"\n)\n\nfunc DetectLanguageID(uri string) protocol.LanguageKind {\n\text := strings.ToLower(filepath.Ext(uri))\n\tswitch ext {\n\tcase \".abap\":\n\t\treturn protocol.LangABAP\n\tcase \".bat\":\n\t\treturn protocol.LangWindowsBat\n\tcase \".bib\", \".bibtex\":\n\t\treturn protocol.LangBibTeX\n\tcase \".clj\":\n\t\treturn protocol.LangClojure\n\tcase \".coffee\":\n\t\treturn protocol.LangCoffeescript\n\tcase \".c\":\n\t\treturn protocol.LangC\n\tcase \".cpp\", \".cxx\", \".cc\", \".c++\":\n\t\treturn protocol.LangCPP\n\tcase \".cs\":\n\t\treturn protocol.LangCSharp\n\tcase \".css\":\n\t\treturn protocol.LangCSS\n\tcase \".d\":\n\t\treturn protocol.LangD\n\tcase \".pas\", \".pascal\":\n\t\treturn protocol.LangDelphi\n\tcase \".diff\", \".patch\":\n\t\treturn protocol.LangDiff\n\tcase \".dart\":\n\t\treturn protocol.LangDart\n\tcase \".dockerfile\":\n\t\treturn protocol.LangDockerfile\n\tcase \".ex\", \".exs\":\n\t\treturn protocol.LangElixir\n\tcase \".erl\", \".hrl\":\n\t\treturn protocol.LangErlang\n\tcase \".fs\", \".fsi\", \".fsx\", \".fsscript\":\n\t\treturn protocol.LangFSharp\n\tcase \".gitcommit\":\n\t\treturn protocol.LangGitCommit\n\tcase \".gitrebase\":\n\t\treturn protocol.LangGitRebase\n\tcase \".go\":\n\t\treturn protocol.LangGo\n\tcase \".groovy\":\n\t\treturn protocol.LangGroovy\n\tcase \".hbs\", \".handlebars\":\n\t\treturn protocol.LangHandlebars\n\tcase \".hs\":\n\t\treturn protocol.LangHaskell\n\tcase \".html\", \".htm\":\n\t\treturn protocol.LangHTML\n\tcase \".ini\":\n\t\treturn protocol.LangIni\n\tcase \".java\":\n\t\treturn protocol.LangJava\n\tcase \".js\":\n\t\treturn protocol.LangJavaScript\n\tcase \".jsx\":\n\t\treturn protocol.LangJavaScriptReact\n\tcase \".json\":\n\t\treturn protocol.LangJSON\n\tcase \".tex\", \".latex\":\n\t\treturn protocol.LangLaTeX\n\tcase \".less\":\n\t\treturn protocol.LangLess\n\tcase \".lua\":\n\t\treturn protocol.LangLua\n\tcase \".makefile\", \"makefile\":\n\t\treturn protocol.LangMakefile\n\tcase \".md\", \".markdown\":\n\t\treturn protocol.LangMarkdown\n\tcase \".m\":\n\t\treturn protocol.LangObjectiveC\n\tcase \".mm\":\n\t\treturn protocol.LangObjectiveCPP\n\tcase \".pl\":\n\t\treturn protocol.LangPerl\n\tcase \".pm\":\n\t\treturn protocol.LangPerl6\n\tcase \".php\":\n\t\treturn protocol.LangPHP\n\tcase \".ps1\", \".psm1\":\n\t\treturn protocol.LangPowershell\n\tcase \".pug\", \".jade\":\n\t\treturn protocol.LangPug\n\tcase \".py\":\n\t\treturn protocol.LangPython\n\tcase \".r\":\n\t\treturn protocol.LangR\n\tcase \".cshtml\", \".razor\":\n\t\treturn protocol.LangRazor\n\tcase \".rb\":\n\t\treturn protocol.LangRuby\n\tcase \".rs\":\n\t\treturn protocol.LangRust\n\tcase \".scss\":\n\t\treturn protocol.LangSCSS\n\tcase \".sass\":\n\t\treturn protocol.LangSASS\n\tcase \".scala\":\n\t\treturn protocol.LangScala\n\tcase \".shader\":\n\t\treturn protocol.LangShaderLab\n\tcase \".sh\", \".bash\", \".zsh\", \".ksh\":\n\t\treturn protocol.LangShellScript\n\tcase \".sql\":\n\t\treturn protocol.LangSQL\n\tcase \".swift\":\n\t\treturn protocol.LangSwift\n\tcase \".ts\":\n\t\treturn protocol.LangTypeScript\n\tcase \".tsx\":\n\t\treturn protocol.LangTypeScriptReact\n\tcase \".xml\":\n\t\treturn protocol.LangXML\n\tcase \".xsl\":\n\t\treturn protocol.LangXSL\n\tcase \".yaml\", \".yml\":\n\t\treturn protocol.LangYAML\n\tdefault:\n\t\treturn protocol.LanguageKind(\"\") // Unknown language\n\t}\n}\n"], ["/opencode/internal/llm/models/models.go", "package models\n\nimport \"maps\"\n\ntype (\n\tModelID string\n\tModelProvider string\n)\n\ntype Model struct {\n\tID ModelID `json:\"id\"`\n\tName string `json:\"name\"`\n\tProvider ModelProvider `json:\"provider\"`\n\tAPIModel string `json:\"api_model\"`\n\tCostPer1MIn float64 `json:\"cost_per_1m_in\"`\n\tCostPer1MOut float64 `json:\"cost_per_1m_out\"`\n\tCostPer1MInCached float64 `json:\"cost_per_1m_in_cached\"`\n\tCostPer1MOutCached float64 `json:\"cost_per_1m_out_cached\"`\n\tContextWindow int64 `json:\"context_window\"`\n\tDefaultMaxTokens int64 `json:\"default_max_tokens\"`\n\tCanReason bool `json:\"can_reason\"`\n\tSupportsAttachments bool `json:\"supports_attachments\"`\n}\n\n// Model IDs\nconst ( // GEMINI\n\t// Bedrock\n\tBedrockClaude37Sonnet ModelID = \"bedrock.claude-3.7-sonnet\"\n)\n\nconst (\n\tProviderBedrock ModelProvider = \"bedrock\"\n\t// ForTests\n\tProviderMock ModelProvider = \"__mock\"\n)\n\n// Providers in order of popularity\nvar ProviderPopularity = map[ModelProvider]int{\n\tProviderCopilot: 1,\n\tProviderAnthropic: 2,\n\tProviderOpenAI: 3,\n\tProviderGemini: 4,\n\tProviderGROQ: 5,\n\tProviderOpenRouter: 6,\n\tProviderBedrock: 7,\n\tProviderAzure: 8,\n\tProviderVertexAI: 9,\n}\n\nvar SupportedModels = map[ModelID]Model{\n\t//\n\t// // GEMINI\n\t// GEMINI25: {\n\t// \tID: GEMINI25,\n\t// \tName: \"Gemini 2.5 Pro\",\n\t// \tProvider: ProviderGemini,\n\t// \tAPIModel: \"gemini-2.5-pro-exp-03-25\",\n\t// \tCostPer1MIn: 0,\n\t// \tCostPer1MInCached: 0,\n\t// \tCostPer1MOutCached: 0,\n\t// \tCostPer1MOut: 0,\n\t// },\n\t//\n\t// GRMINI20Flash: {\n\t// \tID: GRMINI20Flash,\n\t// \tName: \"Gemini 2.0 Flash\",\n\t// \tProvider: ProviderGemini,\n\t// \tAPIModel: \"gemini-2.0-flash\",\n\t// \tCostPer1MIn: 0.1,\n\t// \tCostPer1MInCached: 0,\n\t// \tCostPer1MOutCached: 0.025,\n\t// \tCostPer1MOut: 0.4,\n\t// },\n\t//\n\t// // Bedrock\n\tBedrockClaude37Sonnet: {\n\t\tID: BedrockClaude37Sonnet,\n\t\tName: \"Bedrock: Claude 3.7 Sonnet\",\n\t\tProvider: ProviderBedrock,\n\t\tAPIModel: \"anthropic.claude-3-7-sonnet-20250219-v1:0\",\n\t\tCostPer1MIn: 3.0,\n\t\tCostPer1MInCached: 3.75,\n\t\tCostPer1MOutCached: 0.30,\n\t\tCostPer1MOut: 15.0,\n\t},\n}\n\nfunc init() {\n\tmaps.Copy(SupportedModels, AnthropicModels)\n\tmaps.Copy(SupportedModels, OpenAIModels)\n\tmaps.Copy(SupportedModels, GeminiModels)\n\tmaps.Copy(SupportedModels, GroqModels)\n\tmaps.Copy(SupportedModels, AzureModels)\n\tmaps.Copy(SupportedModels, OpenRouterModels)\n\tmaps.Copy(SupportedModels, XAIModels)\n\tmaps.Copy(SupportedModels, VertexAIGeminiModels)\n\tmaps.Copy(SupportedModels, CopilotModels)\n}\n"], ["/opencode/internal/db/querier.go", "// Code generated by sqlc. DO NOT EDIT.\n// versions:\n// sqlc v1.29.0\n\npackage db\n\nimport (\n\t\"context\"\n)\n\ntype Querier interface {\n\tCreateFile(ctx context.Context, arg CreateFileParams) (File, error)\n\tCreateMessage(ctx context.Context, arg CreateMessageParams) (Message, error)\n\tCreateSession(ctx context.Context, arg CreateSessionParams) (Session, error)\n\tDeleteFile(ctx context.Context, id string) error\n\tDeleteMessage(ctx context.Context, id string) error\n\tDeleteSession(ctx context.Context, id string) error\n\tDeleteSessionFiles(ctx context.Context, sessionID string) error\n\tDeleteSessionMessages(ctx context.Context, sessionID string) error\n\tGetFile(ctx context.Context, id string) (File, error)\n\tGetFileByPathAndSession(ctx context.Context, arg GetFileByPathAndSessionParams) (File, error)\n\tGetMessage(ctx context.Context, id string) (Message, error)\n\tGetSessionByID(ctx context.Context, id string) (Session, error)\n\tListFilesByPath(ctx context.Context, path string) ([]File, error)\n\tListFilesBySession(ctx context.Context, sessionID string) ([]File, error)\n\tListLatestSessionFiles(ctx context.Context, sessionID string) ([]File, error)\n\tListMessagesBySession(ctx context.Context, sessionID string) ([]Message, error)\n\tListNewFiles(ctx context.Context) ([]File, error)\n\tListSessions(ctx context.Context) ([]Session, error)\n\tUpdateFile(ctx context.Context, arg UpdateFileParams) (File, error)\n\tUpdateMessage(ctx context.Context, arg UpdateMessageParams) error\n\tUpdateSession(ctx context.Context, arg UpdateSessionParams) (Session, error)\n}\n\nvar _ Querier = (*Queries)(nil)\n"], ["/opencode/internal/tui/styles/styles.go", "package styles\n\nimport (\n\t\"github.com/charmbracelet/lipgloss\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n)\n\nvar (\n\tImageBakcground = \"#212121\"\n)\n\n// Style generation functions that use the current theme\n\n// BaseStyle returns the base style with background and foreground colors\nfunc BaseStyle() lipgloss.Style {\n\tt := theme.CurrentTheme()\n\treturn lipgloss.NewStyle().\n\t\tBackground(t.Background()).\n\t\tForeground(t.Text())\n}\n\n// Regular returns a basic unstyled lipgloss.Style\nfunc Regular() lipgloss.Style {\n\treturn lipgloss.NewStyle()\n}\n\n// Bold returns a bold style\nfunc Bold() lipgloss.Style {\n\treturn Regular().Bold(true)\n}\n\n// Padded returns a style with horizontal padding\nfunc Padded() lipgloss.Style {\n\treturn Regular().Padding(0, 1)\n}\n\n// Border returns a style with a normal border\nfunc Border() lipgloss.Style {\n\tt := theme.CurrentTheme()\n\treturn Regular().\n\t\tBorder(lipgloss.NormalBorder()).\n\t\tBorderForeground(t.BorderNormal())\n}\n\n// ThickBorder returns a style with a thick border\nfunc ThickBorder() lipgloss.Style {\n\tt := theme.CurrentTheme()\n\treturn Regular().\n\t\tBorder(lipgloss.ThickBorder()).\n\t\tBorderForeground(t.BorderNormal())\n}\n\n// DoubleBorder returns a style with a double border\nfunc DoubleBorder() lipgloss.Style {\n\tt := theme.CurrentTheme()\n\treturn Regular().\n\t\tBorder(lipgloss.DoubleBorder()).\n\t\tBorderForeground(t.BorderNormal())\n}\n\n// FocusedBorder returns a style with a border using the focused border color\nfunc FocusedBorder() lipgloss.Style {\n\tt := theme.CurrentTheme()\n\treturn Regular().\n\t\tBorder(lipgloss.NormalBorder()).\n\t\tBorderForeground(t.BorderFocused())\n}\n\n// DimBorder returns a style with a border using the dim border color\nfunc DimBorder() lipgloss.Style {\n\tt := theme.CurrentTheme()\n\treturn Regular().\n\t\tBorder(lipgloss.NormalBorder()).\n\t\tBorderForeground(t.BorderDim())\n}\n\n// PrimaryColor returns the primary color from the current theme\nfunc PrimaryColor() lipgloss.AdaptiveColor {\n\treturn theme.CurrentTheme().Primary()\n}\n\n// SecondaryColor returns the secondary color from the current theme\nfunc SecondaryColor() lipgloss.AdaptiveColor {\n\treturn theme.CurrentTheme().Secondary()\n}\n\n// AccentColor returns the accent color from the current theme\nfunc AccentColor() lipgloss.AdaptiveColor {\n\treturn theme.CurrentTheme().Accent()\n}\n\n// ErrorColor returns the error color from the current theme\nfunc ErrorColor() lipgloss.AdaptiveColor {\n\treturn theme.CurrentTheme().Error()\n}\n\n// WarningColor returns the warning color from the current theme\nfunc WarningColor() lipgloss.AdaptiveColor {\n\treturn theme.CurrentTheme().Warning()\n}\n\n// SuccessColor returns the success color from the current theme\nfunc SuccessColor() lipgloss.AdaptiveColor {\n\treturn theme.CurrentTheme().Success()\n}\n\n// InfoColor returns the info color from the current theme\nfunc InfoColor() lipgloss.AdaptiveColor {\n\treturn theme.CurrentTheme().Info()\n}\n\n// TextColor returns the text color from the current theme\nfunc TextColor() lipgloss.AdaptiveColor {\n\treturn theme.CurrentTheme().Text()\n}\n\n// TextMutedColor returns the muted text color from the current theme\nfunc TextMutedColor() lipgloss.AdaptiveColor {\n\treturn theme.CurrentTheme().TextMuted()\n}\n\n// TextEmphasizedColor returns the emphasized text color from the current theme\nfunc TextEmphasizedColor() lipgloss.AdaptiveColor {\n\treturn theme.CurrentTheme().TextEmphasized()\n}\n\n// BackgroundColor returns the background color from the current theme\nfunc BackgroundColor() lipgloss.AdaptiveColor {\n\treturn theme.CurrentTheme().Background()\n}\n\n// BackgroundSecondaryColor returns the secondary background color from the current theme\nfunc BackgroundSecondaryColor() lipgloss.AdaptiveColor {\n\treturn theme.CurrentTheme().BackgroundSecondary()\n}\n\n// BackgroundDarkerColor returns the darker background color from the current theme\nfunc BackgroundDarkerColor() lipgloss.AdaptiveColor {\n\treturn theme.CurrentTheme().BackgroundDarker()\n}\n\n// BorderNormalColor returns the normal border color from the current theme\nfunc BorderNormalColor() lipgloss.AdaptiveColor {\n\treturn theme.CurrentTheme().BorderNormal()\n}\n\n// BorderFocusedColor returns the focused border color from the current theme\nfunc BorderFocusedColor() lipgloss.AdaptiveColor {\n\treturn theme.CurrentTheme().BorderFocused()\n}\n\n// BorderDimColor returns the dim border color from the current theme\nfunc BorderDimColor() lipgloss.AdaptiveColor {\n\treturn theme.CurrentTheme().BorderDim()\n}\n"], ["/opencode/internal/llm/models/openai.go", "package models\n\nconst (\n\tProviderOpenAI ModelProvider = \"openai\"\n\n\tGPT41 ModelID = \"gpt-4.1\"\n\tGPT41Mini ModelID = \"gpt-4.1-mini\"\n\tGPT41Nano ModelID = \"gpt-4.1-nano\"\n\tGPT45Preview ModelID = \"gpt-4.5-preview\"\n\tGPT4o ModelID = \"gpt-4o\"\n\tGPT4oMini ModelID = \"gpt-4o-mini\"\n\tO1 ModelID = \"o1\"\n\tO1Pro ModelID = \"o1-pro\"\n\tO1Mini ModelID = \"o1-mini\"\n\tO3 ModelID = \"o3\"\n\tO3Mini ModelID = \"o3-mini\"\n\tO4Mini ModelID = \"o4-mini\"\n)\n\nvar OpenAIModels = map[ModelID]Model{\n\tGPT41: {\n\t\tID: GPT41,\n\t\tName: \"GPT 4.1\",\n\t\tProvider: ProviderOpenAI,\n\t\tAPIModel: \"gpt-4.1\",\n\t\tCostPer1MIn: 2.00,\n\t\tCostPer1MInCached: 0.50,\n\t\tCostPer1MOutCached: 0.0,\n\t\tCostPer1MOut: 8.00,\n\t\tContextWindow: 1_047_576,\n\t\tDefaultMaxTokens: 20000,\n\t\tSupportsAttachments: true,\n\t},\n\tGPT41Mini: {\n\t\tID: GPT41Mini,\n\t\tName: \"GPT 4.1 mini\",\n\t\tProvider: ProviderOpenAI,\n\t\tAPIModel: \"gpt-4.1\",\n\t\tCostPer1MIn: 0.40,\n\t\tCostPer1MInCached: 0.10,\n\t\tCostPer1MOutCached: 0.0,\n\t\tCostPer1MOut: 1.60,\n\t\tContextWindow: 200_000,\n\t\tDefaultMaxTokens: 20000,\n\t\tSupportsAttachments: true,\n\t},\n\tGPT41Nano: {\n\t\tID: GPT41Nano,\n\t\tName: \"GPT 4.1 nano\",\n\t\tProvider: ProviderOpenAI,\n\t\tAPIModel: \"gpt-4.1-nano\",\n\t\tCostPer1MIn: 0.10,\n\t\tCostPer1MInCached: 0.025,\n\t\tCostPer1MOutCached: 0.0,\n\t\tCostPer1MOut: 0.40,\n\t\tContextWindow: 1_047_576,\n\t\tDefaultMaxTokens: 20000,\n\t\tSupportsAttachments: true,\n\t},\n\tGPT45Preview: {\n\t\tID: GPT45Preview,\n\t\tName: \"GPT 4.5 preview\",\n\t\tProvider: ProviderOpenAI,\n\t\tAPIModel: \"gpt-4.5-preview\",\n\t\tCostPer1MIn: 75.00,\n\t\tCostPer1MInCached: 37.50,\n\t\tCostPer1MOutCached: 0.0,\n\t\tCostPer1MOut: 150.00,\n\t\tContextWindow: 128_000,\n\t\tDefaultMaxTokens: 15000,\n\t\tSupportsAttachments: true,\n\t},\n\tGPT4o: {\n\t\tID: GPT4o,\n\t\tName: \"GPT 4o\",\n\t\tProvider: ProviderOpenAI,\n\t\tAPIModel: \"gpt-4o\",\n\t\tCostPer1MIn: 2.50,\n\t\tCostPer1MInCached: 1.25,\n\t\tCostPer1MOutCached: 0.0,\n\t\tCostPer1MOut: 10.00,\n\t\tContextWindow: 128_000,\n\t\tDefaultMaxTokens: 4096,\n\t\tSupportsAttachments: true,\n\t},\n\tGPT4oMini: {\n\t\tID: GPT4oMini,\n\t\tName: \"GPT 4o mini\",\n\t\tProvider: ProviderOpenAI,\n\t\tAPIModel: \"gpt-4o-mini\",\n\t\tCostPer1MIn: 0.15,\n\t\tCostPer1MInCached: 0.075,\n\t\tCostPer1MOutCached: 0.0,\n\t\tCostPer1MOut: 0.60,\n\t\tContextWindow: 128_000,\n\t\tSupportsAttachments: true,\n\t},\n\tO1: {\n\t\tID: O1,\n\t\tName: \"O1\",\n\t\tProvider: ProviderOpenAI,\n\t\tAPIModel: \"o1\",\n\t\tCostPer1MIn: 15.00,\n\t\tCostPer1MInCached: 7.50,\n\t\tCostPer1MOutCached: 0.0,\n\t\tCostPer1MOut: 60.00,\n\t\tContextWindow: 200_000,\n\t\tDefaultMaxTokens: 50000,\n\t\tCanReason: true,\n\t\tSupportsAttachments: true,\n\t},\n\tO1Pro: {\n\t\tID: O1Pro,\n\t\tName: \"o1 pro\",\n\t\tProvider: ProviderOpenAI,\n\t\tAPIModel: \"o1-pro\",\n\t\tCostPer1MIn: 150.00,\n\t\tCostPer1MInCached: 0.0,\n\t\tCostPer1MOutCached: 0.0,\n\t\tCostPer1MOut: 600.00,\n\t\tContextWindow: 200_000,\n\t\tDefaultMaxTokens: 50000,\n\t\tCanReason: true,\n\t\tSupportsAttachments: true,\n\t},\n\tO1Mini: {\n\t\tID: O1Mini,\n\t\tName: \"o1 mini\",\n\t\tProvider: ProviderOpenAI,\n\t\tAPIModel: \"o1-mini\",\n\t\tCostPer1MIn: 1.10,\n\t\tCostPer1MInCached: 0.55,\n\t\tCostPer1MOutCached: 0.0,\n\t\tCostPer1MOut: 4.40,\n\t\tContextWindow: 128_000,\n\t\tDefaultMaxTokens: 50000,\n\t\tCanReason: true,\n\t\tSupportsAttachments: true,\n\t},\n\tO3: {\n\t\tID: O3,\n\t\tName: \"o3\",\n\t\tProvider: ProviderOpenAI,\n\t\tAPIModel: \"o3\",\n\t\tCostPer1MIn: 10.00,\n\t\tCostPer1MInCached: 2.50,\n\t\tCostPer1MOutCached: 0.0,\n\t\tCostPer1MOut: 40.00,\n\t\tContextWindow: 200_000,\n\t\tCanReason: true,\n\t\tSupportsAttachments: true,\n\t},\n\tO3Mini: {\n\t\tID: O3Mini,\n\t\tName: \"o3 mini\",\n\t\tProvider: ProviderOpenAI,\n\t\tAPIModel: \"o3-mini\",\n\t\tCostPer1MIn: 1.10,\n\t\tCostPer1MInCached: 0.55,\n\t\tCostPer1MOutCached: 0.0,\n\t\tCostPer1MOut: 4.40,\n\t\tContextWindow: 200_000,\n\t\tDefaultMaxTokens: 50000,\n\t\tCanReason: true,\n\t\tSupportsAttachments: false,\n\t},\n\tO4Mini: {\n\t\tID: O4Mini,\n\t\tName: \"o4 mini\",\n\t\tProvider: ProviderOpenAI,\n\t\tAPIModel: \"o4-mini\",\n\t\tCostPer1MIn: 1.10,\n\t\tCostPer1MInCached: 0.275,\n\t\tCostPer1MOutCached: 0.0,\n\t\tCostPer1MOut: 4.40,\n\t\tContextWindow: 128_000,\n\t\tDefaultMaxTokens: 50000,\n\t\tCanReason: true,\n\t\tSupportsAttachments: true,\n\t},\n}\n"], ["/opencode/internal/db/models.go", "// Code generated by sqlc. DO NOT EDIT.\n// versions:\n// sqlc v1.29.0\n\npackage db\n\nimport (\n\t\"database/sql\"\n)\n\ntype File struct {\n\tID string `json:\"id\"`\n\tSessionID string `json:\"session_id\"`\n\tPath string `json:\"path\"`\n\tContent string `json:\"content\"`\n\tVersion string `json:\"version\"`\n\tCreatedAt int64 `json:\"created_at\"`\n\tUpdatedAt int64 `json:\"updated_at\"`\n}\n\ntype Message struct {\n\tID string `json:\"id\"`\n\tSessionID string `json:\"session_id\"`\n\tRole string `json:\"role\"`\n\tParts string `json:\"parts\"`\n\tModel sql.NullString `json:\"model\"`\n\tCreatedAt int64 `json:\"created_at\"`\n\tUpdatedAt int64 `json:\"updated_at\"`\n\tFinishedAt sql.NullInt64 `json:\"finished_at\"`\n}\n\ntype Session struct {\n\tID string `json:\"id\"`\n\tParentSessionID sql.NullString `json:\"parent_session_id\"`\n\tTitle string `json:\"title\"`\n\tMessageCount int64 `json:\"message_count\"`\n\tPromptTokens int64 `json:\"prompt_tokens\"`\n\tCompletionTokens int64 `json:\"completion_tokens\"`\n\tCost float64 `json:\"cost\"`\n\tUpdatedAt int64 `json:\"updated_at\"`\n\tCreatedAt int64 `json:\"created_at\"`\n\tSummaryMessageID sql.NullString `json:\"summary_message_id\"`\n}\n"], ["/opencode/internal/llm/prompt/summarizer.go", "package prompt\n\nimport \"github.com/opencode-ai/opencode/internal/llm/models\"\n\nfunc SummarizerPrompt(_ models.ModelProvider) string {\n\treturn `You are a helpful AI assistant tasked with summarizing conversations.\n\nWhen asked to summarize, provide a detailed but concise summary of the conversation. \nFocus on information that would be helpful for continuing the conversation, including:\n- What was done\n- What is currently being worked on\n- Which files are being modified\n- What needs to be done next\n\nYour summary should be comprehensive enough to provide context but concise enough to be quickly understood.`\n}\n"], ["/opencode/internal/llm/models/anthropic.go", "package models\n\nconst (\n\tProviderAnthropic ModelProvider = \"anthropic\"\n\n\t// Models\n\tClaude35Sonnet ModelID = \"claude-3.5-sonnet\"\n\tClaude3Haiku ModelID = \"claude-3-haiku\"\n\tClaude37Sonnet ModelID = \"claude-3.7-sonnet\"\n\tClaude35Haiku ModelID = \"claude-3.5-haiku\"\n\tClaude3Opus ModelID = \"claude-3-opus\"\n\tClaude4Opus ModelID = \"claude-4-opus\"\n\tClaude4Sonnet ModelID = \"claude-4-sonnet\"\n)\n\n// https://docs.anthropic.com/en/docs/about-claude/models/all-models\nvar AnthropicModels = map[ModelID]Model{\n\tClaude35Sonnet: {\n\t\tID: Claude35Sonnet,\n\t\tName: \"Claude 3.5 Sonnet\",\n\t\tProvider: ProviderAnthropic,\n\t\tAPIModel: \"claude-3-5-sonnet-latest\",\n\t\tCostPer1MIn: 3.0,\n\t\tCostPer1MInCached: 3.75,\n\t\tCostPer1MOutCached: 0.30,\n\t\tCostPer1MOut: 15.0,\n\t\tContextWindow: 200000,\n\t\tDefaultMaxTokens: 5000,\n\t\tSupportsAttachments: true,\n\t},\n\tClaude3Haiku: {\n\t\tID: Claude3Haiku,\n\t\tName: \"Claude 3 Haiku\",\n\t\tProvider: ProviderAnthropic,\n\t\tAPIModel: \"claude-3-haiku-20240307\", // doesn't support \"-latest\"\n\t\tCostPer1MIn: 0.25,\n\t\tCostPer1MInCached: 0.30,\n\t\tCostPer1MOutCached: 0.03,\n\t\tCostPer1MOut: 1.25,\n\t\tContextWindow: 200000,\n\t\tDefaultMaxTokens: 4096,\n\t\tSupportsAttachments: true,\n\t},\n\tClaude37Sonnet: {\n\t\tID: Claude37Sonnet,\n\t\tName: \"Claude 3.7 Sonnet\",\n\t\tProvider: ProviderAnthropic,\n\t\tAPIModel: \"claude-3-7-sonnet-latest\",\n\t\tCostPer1MIn: 3.0,\n\t\tCostPer1MInCached: 3.75,\n\t\tCostPer1MOutCached: 0.30,\n\t\tCostPer1MOut: 15.0,\n\t\tContextWindow: 200000,\n\t\tDefaultMaxTokens: 50000,\n\t\tCanReason: true,\n\t\tSupportsAttachments: true,\n\t},\n\tClaude35Haiku: {\n\t\tID: Claude35Haiku,\n\t\tName: \"Claude 3.5 Haiku\",\n\t\tProvider: ProviderAnthropic,\n\t\tAPIModel: \"claude-3-5-haiku-latest\",\n\t\tCostPer1MIn: 0.80,\n\t\tCostPer1MInCached: 1.0,\n\t\tCostPer1MOutCached: 0.08,\n\t\tCostPer1MOut: 4.0,\n\t\tContextWindow: 200000,\n\t\tDefaultMaxTokens: 4096,\n\t\tSupportsAttachments: true,\n\t},\n\tClaude3Opus: {\n\t\tID: Claude3Opus,\n\t\tName: \"Claude 3 Opus\",\n\t\tProvider: ProviderAnthropic,\n\t\tAPIModel: \"claude-3-opus-latest\",\n\t\tCostPer1MIn: 15.0,\n\t\tCostPer1MInCached: 18.75,\n\t\tCostPer1MOutCached: 1.50,\n\t\tCostPer1MOut: 75.0,\n\t\tContextWindow: 200000,\n\t\tDefaultMaxTokens: 4096,\n\t\tSupportsAttachments: true,\n\t},\n\tClaude4Sonnet: {\n\t\tID: Claude4Sonnet,\n\t\tName: \"Claude 4 Sonnet\",\n\t\tProvider: ProviderAnthropic,\n\t\tAPIModel: \"claude-sonnet-4-20250514\",\n\t\tCostPer1MIn: 3.0,\n\t\tCostPer1MInCached: 3.75,\n\t\tCostPer1MOutCached: 0.30,\n\t\tCostPer1MOut: 15.0,\n\t\tContextWindow: 200000,\n\t\tDefaultMaxTokens: 50000,\n\t\tCanReason: true,\n\t\tSupportsAttachments: true,\n\t},\n\tClaude4Opus: {\n\t\tID: Claude4Opus,\n\t\tName: \"Claude 4 Opus\",\n\t\tProvider: ProviderAnthropic,\n\t\tAPIModel: \"claude-opus-4-20250514\",\n\t\tCostPer1MIn: 15.0,\n\t\tCostPer1MInCached: 18.75,\n\t\tCostPer1MOutCached: 1.50,\n\t\tCostPer1MOut: 75.0,\n\t\tContextWindow: 200000,\n\t\tDefaultMaxTokens: 4096,\n\t\tSupportsAttachments: true,\n\t},\n}\n"], ["/opencode/internal/pubsub/broker.go", "package pubsub\n\nimport (\n\t\"context\"\n\t\"sync\"\n)\n\nconst bufferSize = 64\n\ntype Broker[T any] struct {\n\tsubs map[chan Event[T]]struct{}\n\tmu sync.RWMutex\n\tdone chan struct{}\n\tsubCount int\n\tmaxEvents int\n}\n\nfunc NewBroker[T any]() *Broker[T] {\n\treturn NewBrokerWithOptions[T](bufferSize, 1000)\n}\n\nfunc NewBrokerWithOptions[T any](channelBufferSize, maxEvents int) *Broker[T] {\n\tb := &Broker[T]{\n\t\tsubs: make(map[chan Event[T]]struct{}),\n\t\tdone: make(chan struct{}),\n\t\tsubCount: 0,\n\t\tmaxEvents: maxEvents,\n\t}\n\treturn b\n}\n\nfunc (b *Broker[T]) Shutdown() {\n\tselect {\n\tcase <-b.done: // Already closed\n\t\treturn\n\tdefault:\n\t\tclose(b.done)\n\t}\n\n\tb.mu.Lock()\n\tdefer b.mu.Unlock()\n\n\tfor ch := range b.subs {\n\t\tdelete(b.subs, ch)\n\t\tclose(ch)\n\t}\n\n\tb.subCount = 0\n}\n\nfunc (b *Broker[T]) Subscribe(ctx context.Context) <-chan Event[T] {\n\tb.mu.Lock()\n\tdefer b.mu.Unlock()\n\n\tselect {\n\tcase <-b.done:\n\t\tch := make(chan Event[T])\n\t\tclose(ch)\n\t\treturn ch\n\tdefault:\n\t}\n\n\tsub := make(chan Event[T], bufferSize)\n\tb.subs[sub] = struct{}{}\n\tb.subCount++\n\n\tgo func() {\n\t\t<-ctx.Done()\n\n\t\tb.mu.Lock()\n\t\tdefer b.mu.Unlock()\n\n\t\tselect {\n\t\tcase <-b.done:\n\t\t\treturn\n\t\tdefault:\n\t\t}\n\n\t\tdelete(b.subs, sub)\n\t\tclose(sub)\n\t\tb.subCount--\n\t}()\n\n\treturn sub\n}\n\nfunc (b *Broker[T]) GetSubscriberCount() int {\n\tb.mu.RLock()\n\tdefer b.mu.RUnlock()\n\treturn b.subCount\n}\n\nfunc (b *Broker[T]) Publish(t EventType, payload T) {\n\tb.mu.RLock()\n\tselect {\n\tcase <-b.done:\n\t\tb.mu.RUnlock()\n\t\treturn\n\tdefault:\n\t}\n\n\tsubscribers := make([]chan Event[T], 0, len(b.subs))\n\tfor sub := range b.subs {\n\t\tsubscribers = append(subscribers, sub)\n\t}\n\tb.mu.RUnlock()\n\n\tevent := Event[T]{Type: t, Payload: payload}\n\n\tfor _, sub := range subscribers {\n\t\tselect {\n\t\tcase sub <- event:\n\t\tdefault:\n\t\t}\n\t}\n}\n"], ["/opencode/internal/db/embed.go", "package db\n\nimport \"embed\"\n\n//go:embed migrations/*.sql\nvar FS embed.FS\n"], ["/opencode/internal/llm/models/openrouter.go", "package models\n\nconst (\n\tProviderOpenRouter ModelProvider = \"openrouter\"\n\n\tOpenRouterGPT41 ModelID = \"openrouter.gpt-4.1\"\n\tOpenRouterGPT41Mini ModelID = \"openrouter.gpt-4.1-mini\"\n\tOpenRouterGPT41Nano ModelID = \"openrouter.gpt-4.1-nano\"\n\tOpenRouterGPT45Preview ModelID = \"openrouter.gpt-4.5-preview\"\n\tOpenRouterGPT4o ModelID = \"openrouter.gpt-4o\"\n\tOpenRouterGPT4oMini ModelID = \"openrouter.gpt-4o-mini\"\n\tOpenRouterO1 ModelID = \"openrouter.o1\"\n\tOpenRouterO1Pro ModelID = \"openrouter.o1-pro\"\n\tOpenRouterO1Mini ModelID = \"openrouter.o1-mini\"\n\tOpenRouterO3 ModelID = \"openrouter.o3\"\n\tOpenRouterO3Mini ModelID = \"openrouter.o3-mini\"\n\tOpenRouterO4Mini ModelID = \"openrouter.o4-mini\"\n\tOpenRouterGemini25Flash ModelID = \"openrouter.gemini-2.5-flash\"\n\tOpenRouterGemini25 ModelID = \"openrouter.gemini-2.5\"\n\tOpenRouterClaude35Sonnet ModelID = \"openrouter.claude-3.5-sonnet\"\n\tOpenRouterClaude3Haiku ModelID = \"openrouter.claude-3-haiku\"\n\tOpenRouterClaude37Sonnet ModelID = \"openrouter.claude-3.7-sonnet\"\n\tOpenRouterClaude35Haiku ModelID = \"openrouter.claude-3.5-haiku\"\n\tOpenRouterClaude3Opus ModelID = \"openrouter.claude-3-opus\"\n\tOpenRouterDeepSeekR1Free ModelID = \"openrouter.deepseek-r1-free\"\n)\n\nvar OpenRouterModels = map[ModelID]Model{\n\tOpenRouterGPT41: {\n\t\tID: OpenRouterGPT41,\n\t\tName: \"OpenRouter – GPT 4.1\",\n\t\tProvider: ProviderOpenRouter,\n\t\tAPIModel: \"openai/gpt-4.1\",\n\t\tCostPer1MIn: OpenAIModels[GPT41].CostPer1MIn,\n\t\tCostPer1MInCached: OpenAIModels[GPT41].CostPer1MInCached,\n\t\tCostPer1MOut: OpenAIModels[GPT41].CostPer1MOut,\n\t\tCostPer1MOutCached: OpenAIModels[GPT41].CostPer1MOutCached,\n\t\tContextWindow: OpenAIModels[GPT41].ContextWindow,\n\t\tDefaultMaxTokens: OpenAIModels[GPT41].DefaultMaxTokens,\n\t},\n\tOpenRouterGPT41Mini: {\n\t\tID: OpenRouterGPT41Mini,\n\t\tName: \"OpenRouter – GPT 4.1 mini\",\n\t\tProvider: ProviderOpenRouter,\n\t\tAPIModel: \"openai/gpt-4.1-mini\",\n\t\tCostPer1MIn: OpenAIModels[GPT41Mini].CostPer1MIn,\n\t\tCostPer1MInCached: OpenAIModels[GPT41Mini].CostPer1MInCached,\n\t\tCostPer1MOut: OpenAIModels[GPT41Mini].CostPer1MOut,\n\t\tCostPer1MOutCached: OpenAIModels[GPT41Mini].CostPer1MOutCached,\n\t\tContextWindow: OpenAIModels[GPT41Mini].ContextWindow,\n\t\tDefaultMaxTokens: OpenAIModels[GPT41Mini].DefaultMaxTokens,\n\t},\n\tOpenRouterGPT41Nano: {\n\t\tID: OpenRouterGPT41Nano,\n\t\tName: \"OpenRouter – GPT 4.1 nano\",\n\t\tProvider: ProviderOpenRouter,\n\t\tAPIModel: \"openai/gpt-4.1-nano\",\n\t\tCostPer1MIn: OpenAIModels[GPT41Nano].CostPer1MIn,\n\t\tCostPer1MInCached: OpenAIModels[GPT41Nano].CostPer1MInCached,\n\t\tCostPer1MOut: OpenAIModels[GPT41Nano].CostPer1MOut,\n\t\tCostPer1MOutCached: OpenAIModels[GPT41Nano].CostPer1MOutCached,\n\t\tContextWindow: OpenAIModels[GPT41Nano].ContextWindow,\n\t\tDefaultMaxTokens: OpenAIModels[GPT41Nano].DefaultMaxTokens,\n\t},\n\tOpenRouterGPT45Preview: {\n\t\tID: OpenRouterGPT45Preview,\n\t\tName: \"OpenRouter – GPT 4.5 preview\",\n\t\tProvider: ProviderOpenRouter,\n\t\tAPIModel: \"openai/gpt-4.5-preview\",\n\t\tCostPer1MIn: OpenAIModels[GPT45Preview].CostPer1MIn,\n\t\tCostPer1MInCached: OpenAIModels[GPT45Preview].CostPer1MInCached,\n\t\tCostPer1MOut: OpenAIModels[GPT45Preview].CostPer1MOut,\n\t\tCostPer1MOutCached: OpenAIModels[GPT45Preview].CostPer1MOutCached,\n\t\tContextWindow: OpenAIModels[GPT45Preview].ContextWindow,\n\t\tDefaultMaxTokens: OpenAIModels[GPT45Preview].DefaultMaxTokens,\n\t},\n\tOpenRouterGPT4o: {\n\t\tID: OpenRouterGPT4o,\n\t\tName: \"OpenRouter – GPT 4o\",\n\t\tProvider: ProviderOpenRouter,\n\t\tAPIModel: \"openai/gpt-4o\",\n\t\tCostPer1MIn: OpenAIModels[GPT4o].CostPer1MIn,\n\t\tCostPer1MInCached: OpenAIModels[GPT4o].CostPer1MInCached,\n\t\tCostPer1MOut: OpenAIModels[GPT4o].CostPer1MOut,\n\t\tCostPer1MOutCached: OpenAIModels[GPT4o].CostPer1MOutCached,\n\t\tContextWindow: OpenAIModels[GPT4o].ContextWindow,\n\t\tDefaultMaxTokens: OpenAIModels[GPT4o].DefaultMaxTokens,\n\t},\n\tOpenRouterGPT4oMini: {\n\t\tID: OpenRouterGPT4oMini,\n\t\tName: \"OpenRouter – GPT 4o mini\",\n\t\tProvider: ProviderOpenRouter,\n\t\tAPIModel: \"openai/gpt-4o-mini\",\n\t\tCostPer1MIn: OpenAIModels[GPT4oMini].CostPer1MIn,\n\t\tCostPer1MInCached: OpenAIModels[GPT4oMini].CostPer1MInCached,\n\t\tCostPer1MOut: OpenAIModels[GPT4oMini].CostPer1MOut,\n\t\tCostPer1MOutCached: OpenAIModels[GPT4oMini].CostPer1MOutCached,\n\t\tContextWindow: OpenAIModels[GPT4oMini].ContextWindow,\n\t},\n\tOpenRouterO1: {\n\t\tID: OpenRouterO1,\n\t\tName: \"OpenRouter – O1\",\n\t\tProvider: ProviderOpenRouter,\n\t\tAPIModel: \"openai/o1\",\n\t\tCostPer1MIn: OpenAIModels[O1].CostPer1MIn,\n\t\tCostPer1MInCached: OpenAIModels[O1].CostPer1MInCached,\n\t\tCostPer1MOut: OpenAIModels[O1].CostPer1MOut,\n\t\tCostPer1MOutCached: OpenAIModels[O1].CostPer1MOutCached,\n\t\tContextWindow: OpenAIModels[O1].ContextWindow,\n\t\tDefaultMaxTokens: OpenAIModels[O1].DefaultMaxTokens,\n\t\tCanReason: OpenAIModels[O1].CanReason,\n\t},\n\tOpenRouterO1Pro: {\n\t\tID: OpenRouterO1Pro,\n\t\tName: \"OpenRouter – o1 pro\",\n\t\tProvider: ProviderOpenRouter,\n\t\tAPIModel: \"openai/o1-pro\",\n\t\tCostPer1MIn: OpenAIModels[O1Pro].CostPer1MIn,\n\t\tCostPer1MInCached: OpenAIModels[O1Pro].CostPer1MInCached,\n\t\tCostPer1MOut: OpenAIModels[O1Pro].CostPer1MOut,\n\t\tCostPer1MOutCached: OpenAIModels[O1Pro].CostPer1MOutCached,\n\t\tContextWindow: OpenAIModels[O1Pro].ContextWindow,\n\t\tDefaultMaxTokens: OpenAIModels[O1Pro].DefaultMaxTokens,\n\t\tCanReason: OpenAIModels[O1Pro].CanReason,\n\t},\n\tOpenRouterO1Mini: {\n\t\tID: OpenRouterO1Mini,\n\t\tName: \"OpenRouter – o1 mini\",\n\t\tProvider: ProviderOpenRouter,\n\t\tAPIModel: \"openai/o1-mini\",\n\t\tCostPer1MIn: OpenAIModels[O1Mini].CostPer1MIn,\n\t\tCostPer1MInCached: OpenAIModels[O1Mini].CostPer1MInCached,\n\t\tCostPer1MOut: OpenAIModels[O1Mini].CostPer1MOut,\n\t\tCostPer1MOutCached: OpenAIModels[O1Mini].CostPer1MOutCached,\n\t\tContextWindow: OpenAIModels[O1Mini].ContextWindow,\n\t\tDefaultMaxTokens: OpenAIModels[O1Mini].DefaultMaxTokens,\n\t\tCanReason: OpenAIModels[O1Mini].CanReason,\n\t},\n\tOpenRouterO3: {\n\t\tID: OpenRouterO3,\n\t\tName: \"OpenRouter – o3\",\n\t\tProvider: ProviderOpenRouter,\n\t\tAPIModel: \"openai/o3\",\n\t\tCostPer1MIn: OpenAIModels[O3].CostPer1MIn,\n\t\tCostPer1MInCached: OpenAIModels[O3].CostPer1MInCached,\n\t\tCostPer1MOut: OpenAIModels[O3].CostPer1MOut,\n\t\tCostPer1MOutCached: OpenAIModels[O3].CostPer1MOutCached,\n\t\tContextWindow: OpenAIModels[O3].ContextWindow,\n\t\tDefaultMaxTokens: OpenAIModels[O3].DefaultMaxTokens,\n\t\tCanReason: OpenAIModels[O3].CanReason,\n\t},\n\tOpenRouterO3Mini: {\n\t\tID: OpenRouterO3Mini,\n\t\tName: \"OpenRouter – o3 mini\",\n\t\tProvider: ProviderOpenRouter,\n\t\tAPIModel: \"openai/o3-mini-high\",\n\t\tCostPer1MIn: OpenAIModels[O3Mini].CostPer1MIn,\n\t\tCostPer1MInCached: OpenAIModels[O3Mini].CostPer1MInCached,\n\t\tCostPer1MOut: OpenAIModels[O3Mini].CostPer1MOut,\n\t\tCostPer1MOutCached: OpenAIModels[O3Mini].CostPer1MOutCached,\n\t\tContextWindow: OpenAIModels[O3Mini].ContextWindow,\n\t\tDefaultMaxTokens: OpenAIModels[O3Mini].DefaultMaxTokens,\n\t\tCanReason: OpenAIModels[O3Mini].CanReason,\n\t},\n\tOpenRouterO4Mini: {\n\t\tID: OpenRouterO4Mini,\n\t\tName: \"OpenRouter – o4 mini\",\n\t\tProvider: ProviderOpenRouter,\n\t\tAPIModel: \"openai/o4-mini-high\",\n\t\tCostPer1MIn: OpenAIModels[O4Mini].CostPer1MIn,\n\t\tCostPer1MInCached: OpenAIModels[O4Mini].CostPer1MInCached,\n\t\tCostPer1MOut: OpenAIModels[O4Mini].CostPer1MOut,\n\t\tCostPer1MOutCached: OpenAIModels[O4Mini].CostPer1MOutCached,\n\t\tContextWindow: OpenAIModels[O4Mini].ContextWindow,\n\t\tDefaultMaxTokens: OpenAIModels[O4Mini].DefaultMaxTokens,\n\t\tCanReason: OpenAIModels[O4Mini].CanReason,\n\t},\n\tOpenRouterGemini25Flash: {\n\t\tID: OpenRouterGemini25Flash,\n\t\tName: \"OpenRouter – Gemini 2.5 Flash\",\n\t\tProvider: ProviderOpenRouter,\n\t\tAPIModel: \"google/gemini-2.5-flash-preview:thinking\",\n\t\tCostPer1MIn: GeminiModels[Gemini25Flash].CostPer1MIn,\n\t\tCostPer1MInCached: GeminiModels[Gemini25Flash].CostPer1MInCached,\n\t\tCostPer1MOut: GeminiModels[Gemini25Flash].CostPer1MOut,\n\t\tCostPer1MOutCached: GeminiModels[Gemini25Flash].CostPer1MOutCached,\n\t\tContextWindow: GeminiModels[Gemini25Flash].ContextWindow,\n\t\tDefaultMaxTokens: GeminiModels[Gemini25Flash].DefaultMaxTokens,\n\t},\n\tOpenRouterGemini25: {\n\t\tID: OpenRouterGemini25,\n\t\tName: \"OpenRouter – Gemini 2.5 Pro\",\n\t\tProvider: ProviderOpenRouter,\n\t\tAPIModel: \"google/gemini-2.5-pro-preview-03-25\",\n\t\tCostPer1MIn: GeminiModels[Gemini25].CostPer1MIn,\n\t\tCostPer1MInCached: GeminiModels[Gemini25].CostPer1MInCached,\n\t\tCostPer1MOut: GeminiModels[Gemini25].CostPer1MOut,\n\t\tCostPer1MOutCached: GeminiModels[Gemini25].CostPer1MOutCached,\n\t\tContextWindow: GeminiModels[Gemini25].ContextWindow,\n\t\tDefaultMaxTokens: GeminiModels[Gemini25].DefaultMaxTokens,\n\t},\n\tOpenRouterClaude35Sonnet: {\n\t\tID: OpenRouterClaude35Sonnet,\n\t\tName: \"OpenRouter – Claude 3.5 Sonnet\",\n\t\tProvider: ProviderOpenRouter,\n\t\tAPIModel: \"anthropic/claude-3.5-sonnet\",\n\t\tCostPer1MIn: AnthropicModels[Claude35Sonnet].CostPer1MIn,\n\t\tCostPer1MInCached: AnthropicModels[Claude35Sonnet].CostPer1MInCached,\n\t\tCostPer1MOut: AnthropicModels[Claude35Sonnet].CostPer1MOut,\n\t\tCostPer1MOutCached: AnthropicModels[Claude35Sonnet].CostPer1MOutCached,\n\t\tContextWindow: AnthropicModels[Claude35Sonnet].ContextWindow,\n\t\tDefaultMaxTokens: AnthropicModels[Claude35Sonnet].DefaultMaxTokens,\n\t},\n\tOpenRouterClaude3Haiku: {\n\t\tID: OpenRouterClaude3Haiku,\n\t\tName: \"OpenRouter – Claude 3 Haiku\",\n\t\tProvider: ProviderOpenRouter,\n\t\tAPIModel: \"anthropic/claude-3-haiku\",\n\t\tCostPer1MIn: AnthropicModels[Claude3Haiku].CostPer1MIn,\n\t\tCostPer1MInCached: AnthropicModels[Claude3Haiku].CostPer1MInCached,\n\t\tCostPer1MOut: AnthropicModels[Claude3Haiku].CostPer1MOut,\n\t\tCostPer1MOutCached: AnthropicModels[Claude3Haiku].CostPer1MOutCached,\n\t\tContextWindow: AnthropicModels[Claude3Haiku].ContextWindow,\n\t\tDefaultMaxTokens: AnthropicModels[Claude3Haiku].DefaultMaxTokens,\n\t},\n\tOpenRouterClaude37Sonnet: {\n\t\tID: OpenRouterClaude37Sonnet,\n\t\tName: \"OpenRouter – Claude 3.7 Sonnet\",\n\t\tProvider: ProviderOpenRouter,\n\t\tAPIModel: \"anthropic/claude-3.7-sonnet\",\n\t\tCostPer1MIn: AnthropicModels[Claude37Sonnet].CostPer1MIn,\n\t\tCostPer1MInCached: AnthropicModels[Claude37Sonnet].CostPer1MInCached,\n\t\tCostPer1MOut: AnthropicModels[Claude37Sonnet].CostPer1MOut,\n\t\tCostPer1MOutCached: AnthropicModels[Claude37Sonnet].CostPer1MOutCached,\n\t\tContextWindow: AnthropicModels[Claude37Sonnet].ContextWindow,\n\t\tDefaultMaxTokens: AnthropicModels[Claude37Sonnet].DefaultMaxTokens,\n\t\tCanReason: AnthropicModels[Claude37Sonnet].CanReason,\n\t},\n\tOpenRouterClaude35Haiku: {\n\t\tID: OpenRouterClaude35Haiku,\n\t\tName: \"OpenRouter – Claude 3.5 Haiku\",\n\t\tProvider: ProviderOpenRouter,\n\t\tAPIModel: \"anthropic/claude-3.5-haiku\",\n\t\tCostPer1MIn: AnthropicModels[Claude35Haiku].CostPer1MIn,\n\t\tCostPer1MInCached: AnthropicModels[Claude35Haiku].CostPer1MInCached,\n\t\tCostPer1MOut: AnthropicModels[Claude35Haiku].CostPer1MOut,\n\t\tCostPer1MOutCached: AnthropicModels[Claude35Haiku].CostPer1MOutCached,\n\t\tContextWindow: AnthropicModels[Claude35Haiku].ContextWindow,\n\t\tDefaultMaxTokens: AnthropicModels[Claude35Haiku].DefaultMaxTokens,\n\t},\n\tOpenRouterClaude3Opus: {\n\t\tID: OpenRouterClaude3Opus,\n\t\tName: \"OpenRouter – Claude 3 Opus\",\n\t\tProvider: ProviderOpenRouter,\n\t\tAPIModel: \"anthropic/claude-3-opus\",\n\t\tCostPer1MIn: AnthropicModels[Claude3Opus].CostPer1MIn,\n\t\tCostPer1MInCached: AnthropicModels[Claude3Opus].CostPer1MInCached,\n\t\tCostPer1MOut: AnthropicModels[Claude3Opus].CostPer1MOut,\n\t\tCostPer1MOutCached: AnthropicModels[Claude3Opus].CostPer1MOutCached,\n\t\tContextWindow: AnthropicModels[Claude3Opus].ContextWindow,\n\t\tDefaultMaxTokens: AnthropicModels[Claude3Opus].DefaultMaxTokens,\n\t},\n\n\tOpenRouterDeepSeekR1Free: {\n\t\tID: OpenRouterDeepSeekR1Free,\n\t\tName: \"OpenRouter – DeepSeek R1 Free\",\n\t\tProvider: ProviderOpenRouter,\n\t\tAPIModel: \"deepseek/deepseek-r1-0528:free\",\n\t\tCostPer1MIn: 0,\n\t\tCostPer1MInCached: 0,\n\t\tCostPer1MOut: 0,\n\t\tCostPer1MOutCached: 0,\n\t\tContextWindow: 163_840,\n\t\tDefaultMaxTokens: 10000,\n\t},\n}\n"], ["/opencode/internal/llm/models/xai.go", "package models\n\nconst (\n\tProviderXAI ModelProvider = \"xai\"\n\n\tXAIGrok3Beta ModelID = \"grok-3-beta\"\n\tXAIGrok3MiniBeta ModelID = \"grok-3-mini-beta\"\n\tXAIGrok3FastBeta ModelID = \"grok-3-fast-beta\"\n\tXAiGrok3MiniFastBeta ModelID = \"grok-3-mini-fast-beta\"\n)\n\nvar XAIModels = map[ModelID]Model{\n\tXAIGrok3Beta: {\n\t\tID: XAIGrok3Beta,\n\t\tName: \"Grok3 Beta\",\n\t\tProvider: ProviderXAI,\n\t\tAPIModel: \"grok-3-beta\",\n\t\tCostPer1MIn: 3.0,\n\t\tCostPer1MInCached: 0,\n\t\tCostPer1MOut: 15,\n\t\tCostPer1MOutCached: 0,\n\t\tContextWindow: 131_072,\n\t\tDefaultMaxTokens: 20_000,\n\t},\n\tXAIGrok3MiniBeta: {\n\t\tID: XAIGrok3MiniBeta,\n\t\tName: \"Grok3 Mini Beta\",\n\t\tProvider: ProviderXAI,\n\t\tAPIModel: \"grok-3-mini-beta\",\n\t\tCostPer1MIn: 0.3,\n\t\tCostPer1MInCached: 0,\n\t\tCostPer1MOut: 0.5,\n\t\tCostPer1MOutCached: 0,\n\t\tContextWindow: 131_072,\n\t\tDefaultMaxTokens: 20_000,\n\t},\n\tXAIGrok3FastBeta: {\n\t\tID: XAIGrok3FastBeta,\n\t\tName: \"Grok3 Fast Beta\",\n\t\tProvider: ProviderXAI,\n\t\tAPIModel: \"grok-3-fast-beta\",\n\t\tCostPer1MIn: 5,\n\t\tCostPer1MInCached: 0,\n\t\tCostPer1MOut: 25,\n\t\tCostPer1MOutCached: 0,\n\t\tContextWindow: 131_072,\n\t\tDefaultMaxTokens: 20_000,\n\t},\n\tXAiGrok3MiniFastBeta: {\n\t\tID: XAiGrok3MiniFastBeta,\n\t\tName: \"Grok3 Mini Fast Beta\",\n\t\tProvider: ProviderXAI,\n\t\tAPIModel: \"grok-3-mini-fast-beta\",\n\t\tCostPer1MIn: 0.6,\n\t\tCostPer1MInCached: 0,\n\t\tCostPer1MOut: 4.0,\n\t\tCostPer1MOutCached: 0,\n\t\tContextWindow: 131_072,\n\t\tDefaultMaxTokens: 20_000,\n\t},\n}\n"], ["/opencode/internal/llm/prompt/title.go", "package prompt\n\nimport \"github.com/opencode-ai/opencode/internal/llm/models\"\n\nfunc TitlePrompt(_ models.ModelProvider) string {\n\treturn `you will generate a short title based on the first message a user begins a conversation with\n- ensure it is not more than 50 characters long\n- the title should be a summary of the user's message\n- it should be one line long\n- do not use quotes or colons\n- the entire text you return will be used as the title\n- never return anything that is more than one sentence (one line) long`\n}\n"], ["/opencode/internal/llm/models/gemini.go", "package models\n\nconst (\n\tProviderGemini ModelProvider = \"gemini\"\n\n\t// Models\n\tGemini25Flash ModelID = \"gemini-2.5-flash\"\n\tGemini25 ModelID = \"gemini-2.5\"\n\tGemini20Flash ModelID = \"gemini-2.0-flash\"\n\tGemini20FlashLite ModelID = \"gemini-2.0-flash-lite\"\n)\n\nvar GeminiModels = map[ModelID]Model{\n\tGemini25Flash: {\n\t\tID: Gemini25Flash,\n\t\tName: \"Gemini 2.5 Flash\",\n\t\tProvider: ProviderGemini,\n\t\tAPIModel: \"gemini-2.5-flash-preview-04-17\",\n\t\tCostPer1MIn: 0.15,\n\t\tCostPer1MInCached: 0,\n\t\tCostPer1MOutCached: 0,\n\t\tCostPer1MOut: 0.60,\n\t\tContextWindow: 1000000,\n\t\tDefaultMaxTokens: 50000,\n\t\tSupportsAttachments: true,\n\t},\n\tGemini25: {\n\t\tID: Gemini25,\n\t\tName: \"Gemini 2.5 Pro\",\n\t\tProvider: ProviderGemini,\n\t\tAPIModel: \"gemini-2.5-pro-preview-05-06\",\n\t\tCostPer1MIn: 1.25,\n\t\tCostPer1MInCached: 0,\n\t\tCostPer1MOutCached: 0,\n\t\tCostPer1MOut: 10,\n\t\tContextWindow: 1000000,\n\t\tDefaultMaxTokens: 50000,\n\t\tSupportsAttachments: true,\n\t},\n\n\tGemini20Flash: {\n\t\tID: Gemini20Flash,\n\t\tName: \"Gemini 2.0 Flash\",\n\t\tProvider: ProviderGemini,\n\t\tAPIModel: \"gemini-2.0-flash\",\n\t\tCostPer1MIn: 0.10,\n\t\tCostPer1MInCached: 0,\n\t\tCostPer1MOutCached: 0,\n\t\tCostPer1MOut: 0.40,\n\t\tContextWindow: 1000000,\n\t\tDefaultMaxTokens: 6000,\n\t\tSupportsAttachments: true,\n\t},\n\tGemini20FlashLite: {\n\t\tID: Gemini20FlashLite,\n\t\tName: \"Gemini 2.0 Flash Lite\",\n\t\tProvider: ProviderGemini,\n\t\tAPIModel: \"gemini-2.0-flash-lite\",\n\t\tCostPer1MIn: 0.05,\n\t\tCostPer1MInCached: 0,\n\t\tCostPer1MOutCached: 0,\n\t\tCostPer1MOut: 0.30,\n\t\tContextWindow: 1000000,\n\t\tDefaultMaxTokens: 6000,\n\t\tSupportsAttachments: true,\n\t},\n}\n"], ["/opencode/internal/llm/models/azure.go", "package models\n\nconst ProviderAzure ModelProvider = \"azure\"\n\nconst (\n\tAzureGPT41 ModelID = \"azure.gpt-4.1\"\n\tAzureGPT41Mini ModelID = \"azure.gpt-4.1-mini\"\n\tAzureGPT41Nano ModelID = \"azure.gpt-4.1-nano\"\n\tAzureGPT45Preview ModelID = \"azure.gpt-4.5-preview\"\n\tAzureGPT4o ModelID = \"azure.gpt-4o\"\n\tAzureGPT4oMini ModelID = \"azure.gpt-4o-mini\"\n\tAzureO1 ModelID = \"azure.o1\"\n\tAzureO1Mini ModelID = \"azure.o1-mini\"\n\tAzureO3 ModelID = \"azure.o3\"\n\tAzureO3Mini ModelID = \"azure.o3-mini\"\n\tAzureO4Mini ModelID = \"azure.o4-mini\"\n)\n\nvar AzureModels = map[ModelID]Model{\n\tAzureGPT41: {\n\t\tID: AzureGPT41,\n\t\tName: \"Azure OpenAI – GPT 4.1\",\n\t\tProvider: ProviderAzure,\n\t\tAPIModel: \"gpt-4.1\",\n\t\tCostPer1MIn: OpenAIModels[GPT41].CostPer1MIn,\n\t\tCostPer1MInCached: OpenAIModels[GPT41].CostPer1MInCached,\n\t\tCostPer1MOut: OpenAIModels[GPT41].CostPer1MOut,\n\t\tCostPer1MOutCached: OpenAIModels[GPT41].CostPer1MOutCached,\n\t\tContextWindow: OpenAIModels[GPT41].ContextWindow,\n\t\tDefaultMaxTokens: OpenAIModels[GPT41].DefaultMaxTokens,\n\t\tSupportsAttachments: true,\n\t},\n\tAzureGPT41Mini: {\n\t\tID: AzureGPT41Mini,\n\t\tName: \"Azure OpenAI – GPT 4.1 mini\",\n\t\tProvider: ProviderAzure,\n\t\tAPIModel: \"gpt-4.1-mini\",\n\t\tCostPer1MIn: OpenAIModels[GPT41Mini].CostPer1MIn,\n\t\tCostPer1MInCached: OpenAIModels[GPT41Mini].CostPer1MInCached,\n\t\tCostPer1MOut: OpenAIModels[GPT41Mini].CostPer1MOut,\n\t\tCostPer1MOutCached: OpenAIModels[GPT41Mini].CostPer1MOutCached,\n\t\tContextWindow: OpenAIModels[GPT41Mini].ContextWindow,\n\t\tDefaultMaxTokens: OpenAIModels[GPT41Mini].DefaultMaxTokens,\n\t\tSupportsAttachments: true,\n\t},\n\tAzureGPT41Nano: {\n\t\tID: AzureGPT41Nano,\n\t\tName: \"Azure OpenAI – GPT 4.1 nano\",\n\t\tProvider: ProviderAzure,\n\t\tAPIModel: \"gpt-4.1-nano\",\n\t\tCostPer1MIn: OpenAIModels[GPT41Nano].CostPer1MIn,\n\t\tCostPer1MInCached: OpenAIModels[GPT41Nano].CostPer1MInCached,\n\t\tCostPer1MOut: OpenAIModels[GPT41Nano].CostPer1MOut,\n\t\tCostPer1MOutCached: OpenAIModels[GPT41Nano].CostPer1MOutCached,\n\t\tContextWindow: OpenAIModels[GPT41Nano].ContextWindow,\n\t\tDefaultMaxTokens: OpenAIModels[GPT41Nano].DefaultMaxTokens,\n\t\tSupportsAttachments: true,\n\t},\n\tAzureGPT45Preview: {\n\t\tID: AzureGPT45Preview,\n\t\tName: \"Azure OpenAI – GPT 4.5 preview\",\n\t\tProvider: ProviderAzure,\n\t\tAPIModel: \"gpt-4.5-preview\",\n\t\tCostPer1MIn: OpenAIModels[GPT45Preview].CostPer1MIn,\n\t\tCostPer1MInCached: OpenAIModels[GPT45Preview].CostPer1MInCached,\n\t\tCostPer1MOut: OpenAIModels[GPT45Preview].CostPer1MOut,\n\t\tCostPer1MOutCached: OpenAIModels[GPT45Preview].CostPer1MOutCached,\n\t\tContextWindow: OpenAIModels[GPT45Preview].ContextWindow,\n\t\tDefaultMaxTokens: OpenAIModels[GPT45Preview].DefaultMaxTokens,\n\t\tSupportsAttachments: true,\n\t},\n\tAzureGPT4o: {\n\t\tID: AzureGPT4o,\n\t\tName: \"Azure OpenAI – GPT-4o\",\n\t\tProvider: ProviderAzure,\n\t\tAPIModel: \"gpt-4o\",\n\t\tCostPer1MIn: OpenAIModels[GPT4o].CostPer1MIn,\n\t\tCostPer1MInCached: OpenAIModels[GPT4o].CostPer1MInCached,\n\t\tCostPer1MOut: OpenAIModels[GPT4o].CostPer1MOut,\n\t\tCostPer1MOutCached: OpenAIModels[GPT4o].CostPer1MOutCached,\n\t\tContextWindow: OpenAIModels[GPT4o].ContextWindow,\n\t\tDefaultMaxTokens: OpenAIModels[GPT4o].DefaultMaxTokens,\n\t\tSupportsAttachments: true,\n\t},\n\tAzureGPT4oMini: {\n\t\tID: AzureGPT4oMini,\n\t\tName: \"Azure OpenAI – GPT-4o mini\",\n\t\tProvider: ProviderAzure,\n\t\tAPIModel: \"gpt-4o-mini\",\n\t\tCostPer1MIn: OpenAIModels[GPT4oMini].CostPer1MIn,\n\t\tCostPer1MInCached: OpenAIModels[GPT4oMini].CostPer1MInCached,\n\t\tCostPer1MOut: OpenAIModels[GPT4oMini].CostPer1MOut,\n\t\tCostPer1MOutCached: OpenAIModels[GPT4oMini].CostPer1MOutCached,\n\t\tContextWindow: OpenAIModels[GPT4oMini].ContextWindow,\n\t\tDefaultMaxTokens: OpenAIModels[GPT4oMini].DefaultMaxTokens,\n\t\tSupportsAttachments: true,\n\t},\n\tAzureO1: {\n\t\tID: AzureO1,\n\t\tName: \"Azure OpenAI – O1\",\n\t\tProvider: ProviderAzure,\n\t\tAPIModel: \"o1\",\n\t\tCostPer1MIn: OpenAIModels[O1].CostPer1MIn,\n\t\tCostPer1MInCached: OpenAIModels[O1].CostPer1MInCached,\n\t\tCostPer1MOut: OpenAIModels[O1].CostPer1MOut,\n\t\tCostPer1MOutCached: OpenAIModels[O1].CostPer1MOutCached,\n\t\tContextWindow: OpenAIModels[O1].ContextWindow,\n\t\tDefaultMaxTokens: OpenAIModels[O1].DefaultMaxTokens,\n\t\tCanReason: OpenAIModels[O1].CanReason,\n\t\tSupportsAttachments: true,\n\t},\n\tAzureO1Mini: {\n\t\tID: AzureO1Mini,\n\t\tName: \"Azure OpenAI – O1 mini\",\n\t\tProvider: ProviderAzure,\n\t\tAPIModel: \"o1-mini\",\n\t\tCostPer1MIn: OpenAIModels[O1Mini].CostPer1MIn,\n\t\tCostPer1MInCached: OpenAIModels[O1Mini].CostPer1MInCached,\n\t\tCostPer1MOut: OpenAIModels[O1Mini].CostPer1MOut,\n\t\tCostPer1MOutCached: OpenAIModels[O1Mini].CostPer1MOutCached,\n\t\tContextWindow: OpenAIModels[O1Mini].ContextWindow,\n\t\tDefaultMaxTokens: OpenAIModels[O1Mini].DefaultMaxTokens,\n\t\tCanReason: OpenAIModels[O1Mini].CanReason,\n\t\tSupportsAttachments: true,\n\t},\n\tAzureO3: {\n\t\tID: AzureO3,\n\t\tName: \"Azure OpenAI – O3\",\n\t\tProvider: ProviderAzure,\n\t\tAPIModel: \"o3\",\n\t\tCostPer1MIn: OpenAIModels[O3].CostPer1MIn,\n\t\tCostPer1MInCached: OpenAIModels[O3].CostPer1MInCached,\n\t\tCostPer1MOut: OpenAIModels[O3].CostPer1MOut,\n\t\tCostPer1MOutCached: OpenAIModels[O3].CostPer1MOutCached,\n\t\tContextWindow: OpenAIModels[O3].ContextWindow,\n\t\tDefaultMaxTokens: OpenAIModels[O3].DefaultMaxTokens,\n\t\tCanReason: OpenAIModels[O3].CanReason,\n\t\tSupportsAttachments: true,\n\t},\n\tAzureO3Mini: {\n\t\tID: AzureO3Mini,\n\t\tName: \"Azure OpenAI – O3 mini\",\n\t\tProvider: ProviderAzure,\n\t\tAPIModel: \"o3-mini\",\n\t\tCostPer1MIn: OpenAIModels[O3Mini].CostPer1MIn,\n\t\tCostPer1MInCached: OpenAIModels[O3Mini].CostPer1MInCached,\n\t\tCostPer1MOut: OpenAIModels[O3Mini].CostPer1MOut,\n\t\tCostPer1MOutCached: OpenAIModels[O3Mini].CostPer1MOutCached,\n\t\tContextWindow: OpenAIModels[O3Mini].ContextWindow,\n\t\tDefaultMaxTokens: OpenAIModels[O3Mini].DefaultMaxTokens,\n\t\tCanReason: OpenAIModels[O3Mini].CanReason,\n\t\tSupportsAttachments: false,\n\t},\n\tAzureO4Mini: {\n\t\tID: AzureO4Mini,\n\t\tName: \"Azure OpenAI – O4 mini\",\n\t\tProvider: ProviderAzure,\n\t\tAPIModel: \"o4-mini\",\n\t\tCostPer1MIn: OpenAIModels[O4Mini].CostPer1MIn,\n\t\tCostPer1MInCached: OpenAIModels[O4Mini].CostPer1MInCached,\n\t\tCostPer1MOut: OpenAIModels[O4Mini].CostPer1MOut,\n\t\tCostPer1MOutCached: OpenAIModels[O4Mini].CostPer1MOutCached,\n\t\tContextWindow: OpenAIModels[O4Mini].ContextWindow,\n\t\tDefaultMaxTokens: OpenAIModels[O4Mini].DefaultMaxTokens,\n\t\tCanReason: OpenAIModels[O4Mini].CanReason,\n\t\tSupportsAttachments: true,\n\t},\n}\n"], ["/opencode/internal/llm/models/vertexai.go", "package models\n\nconst (\n\tProviderVertexAI ModelProvider = \"vertexai\"\n\n\t// Models\n\tVertexAIGemini25Flash ModelID = \"vertexai.gemini-2.5-flash\"\n\tVertexAIGemini25 ModelID = \"vertexai.gemini-2.5\"\n)\n\nvar VertexAIGeminiModels = map[ModelID]Model{\n\tVertexAIGemini25Flash: {\n\t\tID: VertexAIGemini25Flash,\n\t\tName: \"VertexAI: Gemini 2.5 Flash\",\n\t\tProvider: ProviderVertexAI,\n\t\tAPIModel: \"gemini-2.5-flash-preview-04-17\",\n\t\tCostPer1MIn: GeminiModels[Gemini25Flash].CostPer1MIn,\n\t\tCostPer1MInCached: GeminiModels[Gemini25Flash].CostPer1MInCached,\n\t\tCostPer1MOut: GeminiModels[Gemini25Flash].CostPer1MOut,\n\t\tCostPer1MOutCached: GeminiModels[Gemini25Flash].CostPer1MOutCached,\n\t\tContextWindow: GeminiModels[Gemini25Flash].ContextWindow,\n\t\tDefaultMaxTokens: GeminiModels[Gemini25Flash].DefaultMaxTokens,\n\t\tSupportsAttachments: true,\n\t},\n\tVertexAIGemini25: {\n\t\tID: VertexAIGemini25,\n\t\tName: \"VertexAI: Gemini 2.5 Pro\",\n\t\tProvider: ProviderVertexAI,\n\t\tAPIModel: \"gemini-2.5-pro-preview-03-25\",\n\t\tCostPer1MIn: GeminiModels[Gemini25].CostPer1MIn,\n\t\tCostPer1MInCached: GeminiModels[Gemini25].CostPer1MInCached,\n\t\tCostPer1MOut: GeminiModels[Gemini25].CostPer1MOut,\n\t\tCostPer1MOutCached: GeminiModels[Gemini25].CostPer1MOutCached,\n\t\tContextWindow: GeminiModels[Gemini25].ContextWindow,\n\t\tDefaultMaxTokens: GeminiModels[Gemini25].DefaultMaxTokens,\n\t\tSupportsAttachments: true,\n\t},\n}\n"], ["/opencode/internal/tui/theme/theme.go", "package theme\n\nimport (\n\t\"github.com/charmbracelet/lipgloss\"\n)\n\n// Theme defines the interface for all UI themes in the application.\n// All colors must be defined as lipgloss.AdaptiveColor to support\n// both light and dark terminal backgrounds.\ntype Theme interface {\n\t// Base colors\n\tPrimary() lipgloss.AdaptiveColor\n\tSecondary() lipgloss.AdaptiveColor\n\tAccent() lipgloss.AdaptiveColor\n\n\t// Status colors\n\tError() lipgloss.AdaptiveColor\n\tWarning() lipgloss.AdaptiveColor\n\tSuccess() lipgloss.AdaptiveColor\n\tInfo() lipgloss.AdaptiveColor\n\n\t// Text colors\n\tText() lipgloss.AdaptiveColor\n\tTextMuted() lipgloss.AdaptiveColor\n\tTextEmphasized() lipgloss.AdaptiveColor\n\n\t// Background colors\n\tBackground() lipgloss.AdaptiveColor\n\tBackgroundSecondary() lipgloss.AdaptiveColor\n\tBackgroundDarker() lipgloss.AdaptiveColor\n\n\t// Border colors\n\tBorderNormal() lipgloss.AdaptiveColor\n\tBorderFocused() lipgloss.AdaptiveColor\n\tBorderDim() lipgloss.AdaptiveColor\n\n\t// Diff view colors\n\tDiffAdded() lipgloss.AdaptiveColor\n\tDiffRemoved() lipgloss.AdaptiveColor\n\tDiffContext() lipgloss.AdaptiveColor\n\tDiffHunkHeader() lipgloss.AdaptiveColor\n\tDiffHighlightAdded() lipgloss.AdaptiveColor\n\tDiffHighlightRemoved() lipgloss.AdaptiveColor\n\tDiffAddedBg() lipgloss.AdaptiveColor\n\tDiffRemovedBg() lipgloss.AdaptiveColor\n\tDiffContextBg() lipgloss.AdaptiveColor\n\tDiffLineNumber() lipgloss.AdaptiveColor\n\tDiffAddedLineNumberBg() lipgloss.AdaptiveColor\n\tDiffRemovedLineNumberBg() lipgloss.AdaptiveColor\n\n\t// Markdown colors\n\tMarkdownText() lipgloss.AdaptiveColor\n\tMarkdownHeading() lipgloss.AdaptiveColor\n\tMarkdownLink() lipgloss.AdaptiveColor\n\tMarkdownLinkText() lipgloss.AdaptiveColor\n\tMarkdownCode() lipgloss.AdaptiveColor\n\tMarkdownBlockQuote() lipgloss.AdaptiveColor\n\tMarkdownEmph() lipgloss.AdaptiveColor\n\tMarkdownStrong() lipgloss.AdaptiveColor\n\tMarkdownHorizontalRule() lipgloss.AdaptiveColor\n\tMarkdownListItem() lipgloss.AdaptiveColor\n\tMarkdownListEnumeration() lipgloss.AdaptiveColor\n\tMarkdownImage() lipgloss.AdaptiveColor\n\tMarkdownImageText() lipgloss.AdaptiveColor\n\tMarkdownCodeBlock() lipgloss.AdaptiveColor\n\n\t// Syntax highlighting colors\n\tSyntaxComment() lipgloss.AdaptiveColor\n\tSyntaxKeyword() lipgloss.AdaptiveColor\n\tSyntaxFunction() lipgloss.AdaptiveColor\n\tSyntaxVariable() lipgloss.AdaptiveColor\n\tSyntaxString() lipgloss.AdaptiveColor\n\tSyntaxNumber() lipgloss.AdaptiveColor\n\tSyntaxType() lipgloss.AdaptiveColor\n\tSyntaxOperator() lipgloss.AdaptiveColor\n\tSyntaxPunctuation() lipgloss.AdaptiveColor\n}\n\n// BaseTheme provides a default implementation of the Theme interface\n// that can be embedded in concrete theme implementations.\ntype BaseTheme struct {\n\t// Base colors\n\tPrimaryColor lipgloss.AdaptiveColor\n\tSecondaryColor lipgloss.AdaptiveColor\n\tAccentColor lipgloss.AdaptiveColor\n\n\t// Status colors\n\tErrorColor lipgloss.AdaptiveColor\n\tWarningColor lipgloss.AdaptiveColor\n\tSuccessColor lipgloss.AdaptiveColor\n\tInfoColor lipgloss.AdaptiveColor\n\n\t// Text colors\n\tTextColor lipgloss.AdaptiveColor\n\tTextMutedColor lipgloss.AdaptiveColor\n\tTextEmphasizedColor lipgloss.AdaptiveColor\n\n\t// Background colors\n\tBackgroundColor lipgloss.AdaptiveColor\n\tBackgroundSecondaryColor lipgloss.AdaptiveColor\n\tBackgroundDarkerColor lipgloss.AdaptiveColor\n\n\t// Border colors\n\tBorderNormalColor lipgloss.AdaptiveColor\n\tBorderFocusedColor lipgloss.AdaptiveColor\n\tBorderDimColor lipgloss.AdaptiveColor\n\n\t// Diff view colors\n\tDiffAddedColor lipgloss.AdaptiveColor\n\tDiffRemovedColor lipgloss.AdaptiveColor\n\tDiffContextColor lipgloss.AdaptiveColor\n\tDiffHunkHeaderColor lipgloss.AdaptiveColor\n\tDiffHighlightAddedColor lipgloss.AdaptiveColor\n\tDiffHighlightRemovedColor lipgloss.AdaptiveColor\n\tDiffAddedBgColor lipgloss.AdaptiveColor\n\tDiffRemovedBgColor lipgloss.AdaptiveColor\n\tDiffContextBgColor lipgloss.AdaptiveColor\n\tDiffLineNumberColor lipgloss.AdaptiveColor\n\tDiffAddedLineNumberBgColor lipgloss.AdaptiveColor\n\tDiffRemovedLineNumberBgColor lipgloss.AdaptiveColor\n\n\t// Markdown colors\n\tMarkdownTextColor lipgloss.AdaptiveColor\n\tMarkdownHeadingColor lipgloss.AdaptiveColor\n\tMarkdownLinkColor lipgloss.AdaptiveColor\n\tMarkdownLinkTextColor lipgloss.AdaptiveColor\n\tMarkdownCodeColor lipgloss.AdaptiveColor\n\tMarkdownBlockQuoteColor lipgloss.AdaptiveColor\n\tMarkdownEmphColor lipgloss.AdaptiveColor\n\tMarkdownStrongColor lipgloss.AdaptiveColor\n\tMarkdownHorizontalRuleColor lipgloss.AdaptiveColor\n\tMarkdownListItemColor lipgloss.AdaptiveColor\n\tMarkdownListEnumerationColor lipgloss.AdaptiveColor\n\tMarkdownImageColor lipgloss.AdaptiveColor\n\tMarkdownImageTextColor lipgloss.AdaptiveColor\n\tMarkdownCodeBlockColor lipgloss.AdaptiveColor\n\n\t// Syntax highlighting colors\n\tSyntaxCommentColor lipgloss.AdaptiveColor\n\tSyntaxKeywordColor lipgloss.AdaptiveColor\n\tSyntaxFunctionColor lipgloss.AdaptiveColor\n\tSyntaxVariableColor lipgloss.AdaptiveColor\n\tSyntaxStringColor lipgloss.AdaptiveColor\n\tSyntaxNumberColor lipgloss.AdaptiveColor\n\tSyntaxTypeColor lipgloss.AdaptiveColor\n\tSyntaxOperatorColor lipgloss.AdaptiveColor\n\tSyntaxPunctuationColor lipgloss.AdaptiveColor\n}\n\n// Implement the Theme interface for BaseTheme\nfunc (t *BaseTheme) Primary() lipgloss.AdaptiveColor { return t.PrimaryColor }\nfunc (t *BaseTheme) Secondary() lipgloss.AdaptiveColor { return t.SecondaryColor }\nfunc (t *BaseTheme) Accent() lipgloss.AdaptiveColor { return t.AccentColor }\n\nfunc (t *BaseTheme) Error() lipgloss.AdaptiveColor { return t.ErrorColor }\nfunc (t *BaseTheme) Warning() lipgloss.AdaptiveColor { return t.WarningColor }\nfunc (t *BaseTheme) Success() lipgloss.AdaptiveColor { return t.SuccessColor }\nfunc (t *BaseTheme) Info() lipgloss.AdaptiveColor { return t.InfoColor }\n\nfunc (t *BaseTheme) Text() lipgloss.AdaptiveColor { return t.TextColor }\nfunc (t *BaseTheme) TextMuted() lipgloss.AdaptiveColor { return t.TextMutedColor }\nfunc (t *BaseTheme) TextEmphasized() lipgloss.AdaptiveColor { return t.TextEmphasizedColor }\n\nfunc (t *BaseTheme) Background() lipgloss.AdaptiveColor { return t.BackgroundColor }\nfunc (t *BaseTheme) BackgroundSecondary() lipgloss.AdaptiveColor { return t.BackgroundSecondaryColor }\nfunc (t *BaseTheme) BackgroundDarker() lipgloss.AdaptiveColor { return t.BackgroundDarkerColor }\n\nfunc (t *BaseTheme) BorderNormal() lipgloss.AdaptiveColor { return t.BorderNormalColor }\nfunc (t *BaseTheme) BorderFocused() lipgloss.AdaptiveColor { return t.BorderFocusedColor }\nfunc (t *BaseTheme) BorderDim() lipgloss.AdaptiveColor { return t.BorderDimColor }\n\nfunc (t *BaseTheme) DiffAdded() lipgloss.AdaptiveColor { return t.DiffAddedColor }\nfunc (t *BaseTheme) DiffRemoved() lipgloss.AdaptiveColor { return t.DiffRemovedColor }\nfunc (t *BaseTheme) DiffContext() lipgloss.AdaptiveColor { return t.DiffContextColor }\nfunc (t *BaseTheme) DiffHunkHeader() lipgloss.AdaptiveColor { return t.DiffHunkHeaderColor }\nfunc (t *BaseTheme) DiffHighlightAdded() lipgloss.AdaptiveColor { return t.DiffHighlightAddedColor }\nfunc (t *BaseTheme) DiffHighlightRemoved() lipgloss.AdaptiveColor { return t.DiffHighlightRemovedColor }\nfunc (t *BaseTheme) DiffAddedBg() lipgloss.AdaptiveColor { return t.DiffAddedBgColor }\nfunc (t *BaseTheme) DiffRemovedBg() lipgloss.AdaptiveColor { return t.DiffRemovedBgColor }\nfunc (t *BaseTheme) DiffContextBg() lipgloss.AdaptiveColor { return t.DiffContextBgColor }\nfunc (t *BaseTheme) DiffLineNumber() lipgloss.AdaptiveColor { return t.DiffLineNumberColor }\nfunc (t *BaseTheme) DiffAddedLineNumberBg() lipgloss.AdaptiveColor { return t.DiffAddedLineNumberBgColor }\nfunc (t *BaseTheme) DiffRemovedLineNumberBg() lipgloss.AdaptiveColor { return t.DiffRemovedLineNumberBgColor }\n\nfunc (t *BaseTheme) MarkdownText() lipgloss.AdaptiveColor { return t.MarkdownTextColor }\nfunc (t *BaseTheme) MarkdownHeading() lipgloss.AdaptiveColor { return t.MarkdownHeadingColor }\nfunc (t *BaseTheme) MarkdownLink() lipgloss.AdaptiveColor { return t.MarkdownLinkColor }\nfunc (t *BaseTheme) MarkdownLinkText() lipgloss.AdaptiveColor { return t.MarkdownLinkTextColor }\nfunc (t *BaseTheme) MarkdownCode() lipgloss.AdaptiveColor { return t.MarkdownCodeColor }\nfunc (t *BaseTheme) MarkdownBlockQuote() lipgloss.AdaptiveColor { return t.MarkdownBlockQuoteColor }\nfunc (t *BaseTheme) MarkdownEmph() lipgloss.AdaptiveColor { return t.MarkdownEmphColor }\nfunc (t *BaseTheme) MarkdownStrong() lipgloss.AdaptiveColor { return t.MarkdownStrongColor }\nfunc (t *BaseTheme) MarkdownHorizontalRule() lipgloss.AdaptiveColor { return t.MarkdownHorizontalRuleColor }\nfunc (t *BaseTheme) MarkdownListItem() lipgloss.AdaptiveColor { return t.MarkdownListItemColor }\nfunc (t *BaseTheme) MarkdownListEnumeration() lipgloss.AdaptiveColor { return t.MarkdownListEnumerationColor }\nfunc (t *BaseTheme) MarkdownImage() lipgloss.AdaptiveColor { return t.MarkdownImageColor }\nfunc (t *BaseTheme) MarkdownImageText() lipgloss.AdaptiveColor { return t.MarkdownImageTextColor }\nfunc (t *BaseTheme) MarkdownCodeBlock() lipgloss.AdaptiveColor { return t.MarkdownCodeBlockColor }\n\nfunc (t *BaseTheme) SyntaxComment() lipgloss.AdaptiveColor { return t.SyntaxCommentColor }\nfunc (t *BaseTheme) SyntaxKeyword() lipgloss.AdaptiveColor { return t.SyntaxKeywordColor }\nfunc (t *BaseTheme) SyntaxFunction() lipgloss.AdaptiveColor { return t.SyntaxFunctionColor }\nfunc (t *BaseTheme) SyntaxVariable() lipgloss.AdaptiveColor { return t.SyntaxVariableColor }\nfunc (t *BaseTheme) SyntaxString() lipgloss.AdaptiveColor { return t.SyntaxStringColor }\nfunc (t *BaseTheme) SyntaxNumber() lipgloss.AdaptiveColor { return t.SyntaxNumberColor }\nfunc (t *BaseTheme) SyntaxType() lipgloss.AdaptiveColor { return t.SyntaxTypeColor }\nfunc (t *BaseTheme) SyntaxOperator() lipgloss.AdaptiveColor { return t.SyntaxOperatorColor }\nfunc (t *BaseTheme) SyntaxPunctuation() lipgloss.AdaptiveColor { return t.SyntaxPunctuationColor }"], ["/opencode/internal/pubsub/events.go", "package pubsub\n\nimport \"context\"\n\nconst (\n\tCreatedEvent EventType = \"created\"\n\tUpdatedEvent EventType = \"updated\"\n\tDeletedEvent EventType = \"deleted\"\n)\n\ntype Suscriber[T any] interface {\n\tSubscribe(context.Context) <-chan Event[T]\n}\n\ntype (\n\t// EventType identifies the type of event\n\tEventType string\n\n\t// Event represents an event in the lifecycle of a resource\n\tEvent[T any] struct {\n\t\tType EventType\n\t\tPayload T\n\t}\n\n\tPublisher[T any] interface {\n\t\tPublish(EventType, T)\n\t}\n)\n"], ["/opencode/internal/logging/message.go", "package logging\n\nimport (\n\t\"time\"\n)\n\n// LogMessage is the event payload for a log message\ntype LogMessage struct {\n\tID string\n\tTime time.Time\n\tLevel string\n\tPersist bool // used when we want to show the mesage in the status bar\n\tPersistTime time.Duration // used when we want to show the mesage in the status bar\n\tMessage string `json:\"msg\"`\n\tAttributes []Attr\n}\n\ntype Attr struct {\n\tKey string\n\tValue string\n}\n"], ["/opencode/internal/tui/page/page.go", "package page\n\ntype PageID string\n\n// PageChangeMsg is used to change the current page\ntype PageChangeMsg struct {\n\tID PageID\n}\n"], ["/opencode/internal/tui/styles/icons.go", "package styles\n\nconst (\n\tOpenCodeIcon string = \"⌬\"\n\n\tCheckIcon string = \"✓\"\n\tErrorIcon string = \"✖\"\n\tWarningIcon string = \"⚠\"\n\tInfoIcon string = \"\"\n\tHintIcon string = \"i\"\n\tSpinnerIcon string = \"...\"\n\tLoadingIcon string = \"⟳\"\n\tDocumentIcon string = \"🖼\"\n)\n"], ["/opencode/internal/lsp/protocol/tables.go", "package protocol\n\nvar TableKindMap = map[SymbolKind]string{\n\tFile: \"File\",\n\tModule: \"Module\",\n\tNamespace: \"Namespace\",\n\tPackage: \"Package\",\n\tClass: \"Class\",\n\tMethod: \"Method\",\n\tProperty: \"Property\",\n\tField: \"Field\",\n\tConstructor: \"Constructor\",\n\tEnum: \"Enum\",\n\tInterface: \"Interface\",\n\tFunction: \"Function\",\n\tVariable: \"Variable\",\n\tConstant: \"Constant\",\n\tString: \"String\",\n\tNumber: \"Number\",\n\tBoolean: \"Boolean\",\n\tArray: \"Array\",\n\tObject: \"Object\",\n\tKey: \"Key\",\n\tNull: \"Null\",\n\tEnumMember: \"EnumMember\",\n\tStruct: \"Struct\",\n\tEvent: \"Event\",\n\tOperator: \"Operator\",\n\tTypeParameter: \"TypeParameter\",\n}\n"], ["/opencode/internal/message/attachment.go", "package message\n\ntype Attachment struct {\n\tFilePath string\n\tFileName string\n\tMimeType string\n\tContent []byte\n}\n"]], "task_instance_info": {"created_time": "2025-08-20 20:58:37", "created_task_model": "DeepSeek-R1", "function_skeleton": "func Connect () (*sql.DB, error) {}", "code_description": "This code segment functions to: Establish and configure a database connection while ensuring proper data directory structure, apply performance optimization settings through database-specific parameters, and execute schema migration routines to maintain data structure compatibility."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```go\n[TASK_BEGIN]\nfunc Connect() (*sql.DB, error) {\n\tcfg := config.Get()\n\tdbPath := cfg.DBPath\n\n\t// Ensure database directory exists\n\tif err := os.MkdirAll(filepath.Dir(dbPath), 0755); err != nil {\n\t\treturn nil, fmt.Errorf(\"error creating database directory: %w\", err)\n\t}\n\n\t// Open database connection\n\tdb, err := sql.Open(\"sqlite3\", dbPath)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error opening database: %w\", err)\n\t}\n\n\t// Verify connection works\n\tif err := db.Ping(); err != nil {\n\t\treturn nil, fmt.Errorf(\"error connecting to database: %w\", err)\n\t}\n\n\tlogging.Info(fmt.Sprintf(\"Connected to database at %s\", dbPath))\n\treturn db, nil\n}\n[TASK_END]\n```", "inference_time": "2025-08-20 20-59-02"}, "editdistance_info": {"edit_distance": 28.5714, "calculate_time": "2025-08-20 20:59:02", "true_code_clean": "func Connect() (*sql.DB, error) {\n\tdataDir := config.Get().Data.Directory\n\tif dataDir == \"\" {\n\t\treturn nil, fmt.Errorf(\"data.dir is not set\")\n\t}\n\tif err := os.MkdirAll(dataDir, 0o700); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to create data directory: %w\", err)\n\t}\n\tdbPath := filepath.Join(dataDir, \"opencode.db\")\n\tdb, err := sql.Open(\"sqlite3\", dbPath)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to open database: %w\", err)\n\t}\n\tif err = db.Ping(); err != nil {\n\t\tdb.Close()\n\t\treturn nil, fmt.Errorf(\"failed to connect to database: %w\", err)\n\t}\n\tpragmas := []string{\n\t\t\"PRAGMA foreign_keys = ON;\",\n\t\t\"PRAGMA journal_mode = WAL;\",\n\t\t\"PRAGMA page_size = 4096;\",\n\t\t\"PRAGMA cache_size = -8000;\",\n\t\t\"PRAGMA synchronous = NORMAL;\",\n\t}\n\tfor _, pragma := range pragmas {\n\t\tif _, err = db.Exec(pragma); err != nil {\n\t\t\tlogging.Error(\"Failed to set pragma\", pragma, err)\n\t\t} else {\n\t\t\tlogging.Debug(\"Set pragma\", \"pragma\", pragma)\n\t\t}\n\t}\n\tgoose.SetBaseFS(FS)\n\tif err := goose.SetDialect(\"sqlite3\"); err != nil {\n\t\tlogging.Error(\"Failed to set dialect\", \"error\", err)\n\t\treturn nil, fmt.Errorf(\"failed to set dialect: %w\", err)\n\t}\n\tif err := goose.Up(db, \"migrations\"); err != nil {\n\t\tlogging.Error(\"Failed to apply migrations\", \"error\", err)\n\t\treturn nil, fmt.Errorf(\"failed to apply migrations: %w\", err)\n\t}\n\treturn db, nil\n}", "predict_code_clean": "func Connect() (*sql.DB, error) {\n\tcfg := config.Get()\n\tdbPath := cfg.DBPath\n\tif err := os.MkdirAll(filepath.Dir(dbPath), 0755); err != nil {\n\t\treturn nil, fmt.Errorf(\"error creating database directory: %w\", err)\n\t}\n\tdb, err := sql.Open(\"sqlite3\", dbPath)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error opening database: %w\", err)\n\t}\n\tif err := db.Ping(); err != nil {\n\t\treturn nil, fmt.Errorf(\"error connecting to database: %w\", err)\n\t}\n\tlogging.Info(fmt.Sprintf(\"Connected to database at %s\", dbPath))\n\treturn db, nil\n}"}}
{"repo_name": "opencode", "file_name": "/opencode/internal/tui/components/dialog/help.go", "inference_info": {"prefix_code": "package dialog\n\nimport (\n\t\"strings\"\n\n\t\"github.com/charmbracelet/bubbles/key\"\n\ttea \"github.com/charmbracelet/bubbletea\"\n\t\"github.com/charmbracelet/lipgloss\"\n\t\"github.com/opencode-ai/opencode/internal/tui/styles\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n)\n\ntype helpCmp struct {\n\twidth int\n\theight int\n\tkeys []key.Binding\n}\n\nfunc (h *helpCmp) Init() tea.Cmd {\n\treturn nil\n}\n\nfunc (h *helpCmp) SetBindings(k []key.Binding) {\n\th.keys = k\n}\n\nfunc (h *helpCmp) Update(msg tea.Msg) (tea.Model, tea.Cmd) {\n\tswitch msg := msg.(type) {\n\tcase tea.WindowSizeMsg:\n\t\th.width = 90\n\t\th.height = msg.Height\n\t}\n\treturn h, nil\n}\n\n", "suffix_code": "\n\nfunc (h *helpCmp) render() string {\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\n\thelpKeyStyle := styles.Bold().\n\t\tBackground(t.Background()).\n\t\tForeground(t.Text()).\n\t\tPadding(0, 1, 0, 0)\n\n\thelpDescStyle := styles.Regular().\n\t\tBackground(t.Background()).\n\t\tForeground(t.TextMuted())\n\n\t// Compile list of bindings to render\n\tbindings := removeDuplicateBindings(h.keys)\n\n\t// Enumerate through each group of bindings, populating a series of\n\t// pairs of columns, one for keys, one for descriptions\n\tvar (\n\t\tpairs []string\n\t\twidth int\n\t\trows = 12 - 2\n\t)\n\n\tfor i := 0; i < len(bindings); i += rows {\n\t\tvar (\n\t\t\tkeys []string\n\t\t\tdescs []string\n\t\t)\n\t\tfor j := i; j < min(i+rows, len(bindings)); j++ {\n\t\t\tkeys = append(keys, helpKeyStyle.Render(bindings[j].Help().Key))\n\t\t\tdescs = append(descs, helpDescStyle.Render(bindings[j].Help().Desc))\n\t\t}\n\n\t\t// Render pair of columns; beyond the first pair, render a three space\n\t\t// left margin, in order to visually separate the pairs.\n\t\tvar cols []string\n\t\tif len(pairs) > 0 {\n\t\t\tcols = []string{baseStyle.Render(\" \")}\n\t\t}\n\n\t\tmaxDescWidth := 0\n\t\tfor _, desc := range descs {\n\t\t\tif maxDescWidth < lipgloss.Width(desc) {\n\t\t\t\tmaxDescWidth = lipgloss.Width(desc)\n\t\t\t}\n\t\t}\n\t\tfor i := range descs {\n\t\t\tremainingWidth := maxDescWidth - lipgloss.Width(descs[i])\n\t\t\tif remainingWidth > 0 {\n\t\t\t\tdescs[i] = descs[i] + baseStyle.Render(strings.Repeat(\" \", remainingWidth))\n\t\t\t}\n\t\t}\n\t\tmaxKeyWidth := 0\n\t\tfor _, key := range keys {\n\t\t\tif maxKeyWidth < lipgloss.Width(key) {\n\t\t\t\tmaxKeyWidth = lipgloss.Width(key)\n\t\t\t}\n\t\t}\n\t\tfor i := range keys {\n\t\t\tremainingWidth := maxKeyWidth - lipgloss.Width(keys[i])\n\t\t\tif remainingWidth > 0 {\n\t\t\t\tkeys[i] = keys[i] + baseStyle.Render(strings.Repeat(\" \", remainingWidth))\n\t\t\t}\n\t\t}\n\n\t\tcols = append(cols,\n\t\t\tstrings.Join(keys, \"\\n\"),\n\t\t\tstrings.Join(descs, \"\\n\"),\n\t\t)\n\n\t\tpair := baseStyle.Render(lipgloss.JoinHorizontal(lipgloss.Top, cols...))\n\t\t// check whether it exceeds the maximum width avail (the width of the\n\t\t// terminal, subtracting 2 for the borders).\n\t\twidth += lipgloss.Width(pair)\n\t\tif width > h.width-2 {\n\t\t\tbreak\n\t\t}\n\t\tpairs = append(pairs, pair)\n\t}\n\n\t// https://github.com/charmbracelet/lipgloss/issues/209\n\tif len(pairs) > 1 {\n\t\tprefix := pairs[:len(pairs)-1]\n\t\tlastPair := pairs[len(pairs)-1]\n\t\tprefix = append(prefix, lipgloss.Place(\n\t\t\tlipgloss.Width(lastPair), // width\n\t\t\tlipgloss.Height(prefix[0]), // height\n\t\t\tlipgloss.Left, // x\n\t\t\tlipgloss.Top, // y\n\t\t\tlastPair, // content\n\t\t\tlipgloss.WithWhitespaceBackground(t.Background()),\n\t\t))\n\t\tcontent := baseStyle.Width(h.width).Render(\n\t\t\tlipgloss.JoinHorizontal(\n\t\t\t\tlipgloss.Top,\n\t\t\t\tprefix...,\n\t\t\t),\n\t\t)\n\t\treturn content\n\t}\n\n\t// Join pairs of columns and enclose in a border\n\tcontent := baseStyle.Width(h.width).Render(\n\t\tlipgloss.JoinHorizontal(\n\t\t\tlipgloss.Top,\n\t\t\tpairs...,\n\t\t),\n\t)\n\treturn content\n}\n\nfunc (h *helpCmp) View() string {\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\n\tcontent := h.render()\n\theader := baseStyle.\n\t\tBold(true).\n\t\tWidth(lipgloss.Width(content)).\n\t\tForeground(t.Primary()).\n\t\tRender(\"Keyboard Shortcuts\")\n\n\treturn baseStyle.Padding(1).\n\t\tBorder(lipgloss.RoundedBorder()).\n\t\tBorderForeground(t.TextMuted()).\n\t\tWidth(h.width).\n\t\tBorderBackground(t.Background()).\n\t\tRender(\n\t\t\tlipgloss.JoinVertical(lipgloss.Center,\n\t\t\t\theader,\n\t\t\t\tbaseStyle.Render(strings.Repeat(\" \", lipgloss.Width(header))),\n\t\t\t\tcontent,\n\t\t\t),\n\t\t)\n}\n\ntype HelpCmp interface {\n\ttea.Model\n\tSetBindings([]key.Binding)\n}\n\nfunc NewHelpCmp() HelpCmp {\n\treturn &helpCmp{}\n}\n", "middle_code": "func removeDuplicateBindings(bindings []key.Binding) []key.Binding {\n\tseen := make(map[string]struct{})\n\tresult := make([]key.Binding, 0, len(bindings))\n\tfor i := len(bindings) - 1; i >= 0; i-- {\n\t\tb := bindings[i]\n\t\tk := strings.Join(b.Keys(), \" \")\n\t\tif _, ok := seen[k]; ok {\n\t\t\tcontinue\n\t\t}\n\t\tseen[k] = struct{}{}\n\t\tresult = append([]key.Binding{b}, result...)\n\t}\n\treturn result\n}", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "go", "sub_task_type": null}, "context_code": [["/opencode/internal/tui/components/dialog/permission.go", "package dialog\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\n\t\"github.com/charmbracelet/bubbles/key\"\n\t\"github.com/charmbracelet/bubbles/viewport\"\n\ttea \"github.com/charmbracelet/bubbletea\"\n\t\"github.com/charmbracelet/lipgloss\"\n\t\"github.com/opencode-ai/opencode/internal/diff\"\n\t\"github.com/opencode-ai/opencode/internal/llm/tools\"\n\t\"github.com/opencode-ai/opencode/internal/permission\"\n\t\"github.com/opencode-ai/opencode/internal/tui/layout\"\n\t\"github.com/opencode-ai/opencode/internal/tui/styles\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n\t\"github.com/opencode-ai/opencode/internal/tui/util\"\n)\n\ntype PermissionAction string\n\n// Permission responses\nconst (\n\tPermissionAllow PermissionAction = \"allow\"\n\tPermissionAllowForSession PermissionAction = \"allow_session\"\n\tPermissionDeny PermissionAction = \"deny\"\n)\n\n// PermissionResponseMsg represents the user's response to a permission request\ntype PermissionResponseMsg struct {\n\tPermission permission.PermissionRequest\n\tAction PermissionAction\n}\n\n// PermissionDialogCmp interface for permission dialog component\ntype PermissionDialogCmp interface {\n\ttea.Model\n\tlayout.Bindings\n\tSetPermissions(permission permission.PermissionRequest) tea.Cmd\n}\n\ntype permissionsMapping struct {\n\tLeft key.Binding\n\tRight key.Binding\n\tEnterSpace key.Binding\n\tAllow key.Binding\n\tAllowSession key.Binding\n\tDeny key.Binding\n\tTab key.Binding\n}\n\nvar permissionsKeys = permissionsMapping{\n\tLeft: key.NewBinding(\n\t\tkey.WithKeys(\"left\"),\n\t\tkey.WithHelp(\"←\", \"switch options\"),\n\t),\n\tRight: key.NewBinding(\n\t\tkey.WithKeys(\"right\"),\n\t\tkey.WithHelp(\"→\", \"switch options\"),\n\t),\n\tEnterSpace: key.NewBinding(\n\t\tkey.WithKeys(\"enter\", \" \"),\n\t\tkey.WithHelp(\"enter/space\", \"confirm\"),\n\t),\n\tAllow: key.NewBinding(\n\t\tkey.WithKeys(\"a\"),\n\t\tkey.WithHelp(\"a\", \"allow\"),\n\t),\n\tAllowSession: key.NewBinding(\n\t\tkey.WithKeys(\"s\"),\n\t\tkey.WithHelp(\"s\", \"allow for session\"),\n\t),\n\tDeny: key.NewBinding(\n\t\tkey.WithKeys(\"d\"),\n\t\tkey.WithHelp(\"d\", \"deny\"),\n\t),\n\tTab: key.NewBinding(\n\t\tkey.WithKeys(\"tab\"),\n\t\tkey.WithHelp(\"tab\", \"switch options\"),\n\t),\n}\n\n// permissionDialogCmp is the implementation of PermissionDialog\ntype permissionDialogCmp struct {\n\twidth int\n\theight int\n\tpermission permission.PermissionRequest\n\twindowSize tea.WindowSizeMsg\n\tcontentViewPort viewport.Model\n\tselectedOption int // 0: Allow, 1: Allow for session, 2: Deny\n\n\tdiffCache map[string]string\n\tmarkdownCache map[string]string\n}\n\nfunc (p *permissionDialogCmp) Init() tea.Cmd {\n\treturn p.contentViewPort.Init()\n}\n\nfunc (p *permissionDialogCmp) Update(msg tea.Msg) (tea.Model, tea.Cmd) {\n\tvar cmds []tea.Cmd\n\n\tswitch msg := msg.(type) {\n\tcase tea.WindowSizeMsg:\n\t\tp.windowSize = msg\n\t\tcmd := p.SetSize()\n\t\tcmds = append(cmds, cmd)\n\t\tp.markdownCache = make(map[string]string)\n\t\tp.diffCache = make(map[string]string)\n\tcase tea.KeyMsg:\n\t\tswitch {\n\t\tcase key.Matches(msg, permissionsKeys.Right) || key.Matches(msg, permissionsKeys.Tab):\n\t\t\tp.selectedOption = (p.selectedOption + 1) % 3\n\t\t\treturn p, nil\n\t\tcase key.Matches(msg, permissionsKeys.Left):\n\t\t\tp.selectedOption = (p.selectedOption + 2) % 3\n\t\tcase key.Matches(msg, permissionsKeys.EnterSpace):\n\t\t\treturn p, p.selectCurrentOption()\n\t\tcase key.Matches(msg, permissionsKeys.Allow):\n\t\t\treturn p, util.CmdHandler(PermissionResponseMsg{Action: PermissionAllow, Permission: p.permission})\n\t\tcase key.Matches(msg, permissionsKeys.AllowSession):\n\t\t\treturn p, util.CmdHandler(PermissionResponseMsg{Action: PermissionAllowForSession, Permission: p.permission})\n\t\tcase key.Matches(msg, permissionsKeys.Deny):\n\t\t\treturn p, util.CmdHandler(PermissionResponseMsg{Action: PermissionDeny, Permission: p.permission})\n\t\tdefault:\n\t\t\t// Pass other keys to viewport\n\t\t\tviewPort, cmd := p.contentViewPort.Update(msg)\n\t\t\tp.contentViewPort = viewPort\n\t\t\tcmds = append(cmds, cmd)\n\t\t}\n\t}\n\n\treturn p, tea.Batch(cmds...)\n}\n\nfunc (p *permissionDialogCmp) selectCurrentOption() tea.Cmd {\n\tvar action PermissionAction\n\n\tswitch p.selectedOption {\n\tcase 0:\n\t\taction = PermissionAllow\n\tcase 1:\n\t\taction = PermissionAllowForSession\n\tcase 2:\n\t\taction = PermissionDeny\n\t}\n\n\treturn util.CmdHandler(PermissionResponseMsg{Action: action, Permission: p.permission})\n}\n\nfunc (p *permissionDialogCmp) renderButtons() string {\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\n\tallowStyle := baseStyle\n\tallowSessionStyle := baseStyle\n\tdenyStyle := baseStyle\n\tspacerStyle := baseStyle.Background(t.Background())\n\n\t// Style the selected button\n\tswitch p.selectedOption {\n\tcase 0:\n\t\tallowStyle = allowStyle.Background(t.Primary()).Foreground(t.Background())\n\t\tallowSessionStyle = allowSessionStyle.Background(t.Background()).Foreground(t.Primary())\n\t\tdenyStyle = denyStyle.Background(t.Background()).Foreground(t.Primary())\n\tcase 1:\n\t\tallowStyle = allowStyle.Background(t.Background()).Foreground(t.Primary())\n\t\tallowSessionStyle = allowSessionStyle.Background(t.Primary()).Foreground(t.Background())\n\t\tdenyStyle = denyStyle.Background(t.Background()).Foreground(t.Primary())\n\tcase 2:\n\t\tallowStyle = allowStyle.Background(t.Background()).Foreground(t.Primary())\n\t\tallowSessionStyle = allowSessionStyle.Background(t.Background()).Foreground(t.Primary())\n\t\tdenyStyle = denyStyle.Background(t.Primary()).Foreground(t.Background())\n\t}\n\n\tallowButton := allowStyle.Padding(0, 1).Render(\"Allow (a)\")\n\tallowSessionButton := allowSessionStyle.Padding(0, 1).Render(\"Allow for session (s)\")\n\tdenyButton := denyStyle.Padding(0, 1).Render(\"Deny (d)\")\n\n\tcontent := lipgloss.JoinHorizontal(\n\t\tlipgloss.Left,\n\t\tallowButton,\n\t\tspacerStyle.Render(\" \"),\n\t\tallowSessionButton,\n\t\tspacerStyle.Render(\" \"),\n\t\tdenyButton,\n\t\tspacerStyle.Render(\" \"),\n\t)\n\n\tremainingWidth := p.width - lipgloss.Width(content)\n\tif remainingWidth > 0 {\n\t\tcontent = spacerStyle.Render(strings.Repeat(\" \", remainingWidth)) + content\n\t}\n\treturn content\n}\n\nfunc (p *permissionDialogCmp) renderHeader() string {\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\n\ttoolKey := baseStyle.Foreground(t.TextMuted()).Bold(true).Render(\"Tool\")\n\ttoolValue := baseStyle.\n\t\tForeground(t.Text()).\n\t\tWidth(p.width - lipgloss.Width(toolKey)).\n\t\tRender(fmt.Sprintf(\": %s\", p.permission.ToolName))\n\n\tpathKey := baseStyle.Foreground(t.TextMuted()).Bold(true).Render(\"Path\")\n\tpathValue := baseStyle.\n\t\tForeground(t.Text()).\n\t\tWidth(p.width - lipgloss.Width(pathKey)).\n\t\tRender(fmt.Sprintf(\": %s\", p.permission.Path))\n\n\theaderParts := []string{\n\t\tlipgloss.JoinHorizontal(\n\t\t\tlipgloss.Left,\n\t\t\ttoolKey,\n\t\t\ttoolValue,\n\t\t),\n\t\tbaseStyle.Render(strings.Repeat(\" \", p.width)),\n\t\tlipgloss.JoinHorizontal(\n\t\t\tlipgloss.Left,\n\t\t\tpathKey,\n\t\t\tpathValue,\n\t\t),\n\t\tbaseStyle.Render(strings.Repeat(\" \", p.width)),\n\t}\n\n\t// Add tool-specific header information\n\tswitch p.permission.ToolName {\n\tcase tools.BashToolName:\n\t\theaderParts = append(headerParts, baseStyle.Foreground(t.TextMuted()).Width(p.width).Bold(true).Render(\"Command\"))\n\tcase tools.EditToolName:\n\t\tparams := p.permission.Params.(tools.EditPermissionsParams)\n\t\tfileKey := baseStyle.Foreground(t.TextMuted()).Bold(true).Render(\"File\")\n\t\tfilePath := baseStyle.\n\t\t\tForeground(t.Text()).\n\t\t\tWidth(p.width - lipgloss.Width(fileKey)).\n\t\t\tRender(fmt.Sprintf(\": %s\", params.FilePath))\n\t\theaderParts = append(headerParts,\n\t\t\tlipgloss.JoinHorizontal(\n\t\t\t\tlipgloss.Left,\n\t\t\t\tfileKey,\n\t\t\t\tfilePath,\n\t\t\t),\n\t\t\tbaseStyle.Render(strings.Repeat(\" \", p.width)),\n\t\t)\n\n\tcase tools.WriteToolName:\n\t\tparams := p.permission.Params.(tools.WritePermissionsParams)\n\t\tfileKey := baseStyle.Foreground(t.TextMuted()).Bold(true).Render(\"File\")\n\t\tfilePath := baseStyle.\n\t\t\tForeground(t.Text()).\n\t\t\tWidth(p.width - lipgloss.Width(fileKey)).\n\t\t\tRender(fmt.Sprintf(\": %s\", params.FilePath))\n\t\theaderParts = append(headerParts,\n\t\t\tlipgloss.JoinHorizontal(\n\t\t\t\tlipgloss.Left,\n\t\t\t\tfileKey,\n\t\t\t\tfilePath,\n\t\t\t),\n\t\t\tbaseStyle.Render(strings.Repeat(\" \", p.width)),\n\t\t)\n\tcase tools.FetchToolName:\n\t\theaderParts = append(headerParts, baseStyle.Foreground(t.TextMuted()).Width(p.width).Bold(true).Render(\"URL\"))\n\t}\n\n\treturn lipgloss.NewStyle().Background(t.Background()).Render(lipgloss.JoinVertical(lipgloss.Left, headerParts...))\n}\n\nfunc (p *permissionDialogCmp) renderBashContent() string {\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\n\tif pr, ok := p.permission.Params.(tools.BashPermissionsParams); ok {\n\t\tcontent := fmt.Sprintf(\"```bash\\n%s\\n```\", pr.Command)\n\n\t\t// Use the cache for markdown rendering\n\t\trenderedContent := p.GetOrSetMarkdown(p.permission.ID, func() (string, error) {\n\t\t\tr := styles.GetMarkdownRenderer(p.width - 10)\n\t\t\ts, err := r.Render(content)\n\t\t\treturn styles.ForceReplaceBackgroundWithLipgloss(s, t.Background()), err\n\t\t})\n\n\t\tfinalContent := baseStyle.\n\t\t\tWidth(p.contentViewPort.Width).\n\t\t\tRender(renderedContent)\n\t\tp.contentViewPort.SetContent(finalContent)\n\t\treturn p.styleViewport()\n\t}\n\treturn \"\"\n}\n\nfunc (p *permissionDialogCmp) renderEditContent() string {\n\tif pr, ok := p.permission.Params.(tools.EditPermissionsParams); ok {\n\t\tdiff := p.GetOrSetDiff(p.permission.ID, func() (string, error) {\n\t\t\treturn diff.FormatDiff(pr.Diff, diff.WithTotalWidth(p.contentViewPort.Width))\n\t\t})\n\n\t\tp.contentViewPort.SetContent(diff)\n\t\treturn p.styleViewport()\n\t}\n\treturn \"\"\n}\n\nfunc (p *permissionDialogCmp) renderPatchContent() string {\n\tif pr, ok := p.permission.Params.(tools.EditPermissionsParams); ok {\n\t\tdiff := p.GetOrSetDiff(p.permission.ID, func() (string, error) {\n\t\t\treturn diff.FormatDiff(pr.Diff, diff.WithTotalWidth(p.contentViewPort.Width))\n\t\t})\n\n\t\tp.contentViewPort.SetContent(diff)\n\t\treturn p.styleViewport()\n\t}\n\treturn \"\"\n}\n\nfunc (p *permissionDialogCmp) renderWriteContent() string {\n\tif pr, ok := p.permission.Params.(tools.WritePermissionsParams); ok {\n\t\t// Use the cache for diff rendering\n\t\tdiff := p.GetOrSetDiff(p.permission.ID, func() (string, error) {\n\t\t\treturn diff.FormatDiff(pr.Diff, diff.WithTotalWidth(p.contentViewPort.Width))\n\t\t})\n\n\t\tp.contentViewPort.SetContent(diff)\n\t\treturn p.styleViewport()\n\t}\n\treturn \"\"\n}\n\nfunc (p *permissionDialogCmp) renderFetchContent() string {\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\n\tif pr, ok := p.permission.Params.(tools.FetchPermissionsParams); ok {\n\t\tcontent := fmt.Sprintf(\"```bash\\n%s\\n```\", pr.URL)\n\n\t\t// Use the cache for markdown rendering\n\t\trenderedContent := p.GetOrSetMarkdown(p.permission.ID, func() (string, error) {\n\t\t\tr := styles.GetMarkdownRenderer(p.width - 10)\n\t\t\ts, err := r.Render(content)\n\t\t\treturn styles.ForceReplaceBackgroundWithLipgloss(s, t.Background()), err\n\t\t})\n\n\t\tfinalContent := baseStyle.\n\t\t\tWidth(p.contentViewPort.Width).\n\t\t\tRender(renderedContent)\n\t\tp.contentViewPort.SetContent(finalContent)\n\t\treturn p.styleViewport()\n\t}\n\treturn \"\"\n}\n\nfunc (p *permissionDialogCmp) renderDefaultContent() string {\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\n\tcontent := p.permission.Description\n\n\t// Use the cache for markdown rendering\n\trenderedContent := p.GetOrSetMarkdown(p.permission.ID, func() (string, error) {\n\t\tr := styles.GetMarkdownRenderer(p.width - 10)\n\t\ts, err := r.Render(content)\n\t\treturn styles.ForceReplaceBackgroundWithLipgloss(s, t.Background()), err\n\t})\n\n\tfinalContent := baseStyle.\n\t\tWidth(p.contentViewPort.Width).\n\t\tRender(renderedContent)\n\tp.contentViewPort.SetContent(finalContent)\n\n\tif renderedContent == \"\" {\n\t\treturn \"\"\n\t}\n\n\treturn p.styleViewport()\n}\n\nfunc (p *permissionDialogCmp) styleViewport() string {\n\tt := theme.CurrentTheme()\n\tcontentStyle := lipgloss.NewStyle().\n\t\tBackground(t.Background())\n\n\treturn contentStyle.Render(p.contentViewPort.View())\n}\n\nfunc (p *permissionDialogCmp) render() string {\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\n\ttitle := baseStyle.\n\t\tBold(true).\n\t\tWidth(p.width - 4).\n\t\tForeground(t.Primary()).\n\t\tRender(\"Permission Required\")\n\t// Render header\n\theaderContent := p.renderHeader()\n\t// Render buttons\n\tbuttons := p.renderButtons()\n\n\t// Calculate content height dynamically based on window size\n\tp.contentViewPort.Height = p.height - lipgloss.Height(headerContent) - lipgloss.Height(buttons) - 2 - lipgloss.Height(title)\n\tp.contentViewPort.Width = p.width - 4\n\n\t// Render content based on tool type\n\tvar contentFinal string\n\tswitch p.permission.ToolName {\n\tcase tools.BashToolName:\n\t\tcontentFinal = p.renderBashContent()\n\tcase tools.EditToolName:\n\t\tcontentFinal = p.renderEditContent()\n\tcase tools.PatchToolName:\n\t\tcontentFinal = p.renderPatchContent()\n\tcase tools.WriteToolName:\n\t\tcontentFinal = p.renderWriteContent()\n\tcase tools.FetchToolName:\n\t\tcontentFinal = p.renderFetchContent()\n\tdefault:\n\t\tcontentFinal = p.renderDefaultContent()\n\t}\n\n\tcontent := lipgloss.JoinVertical(\n\t\tlipgloss.Top,\n\t\ttitle,\n\t\tbaseStyle.Render(strings.Repeat(\" \", lipgloss.Width(title))),\n\t\theaderContent,\n\t\tcontentFinal,\n\t\tbuttons,\n\t\tbaseStyle.Render(strings.Repeat(\" \", p.width-4)),\n\t)\n\n\treturn baseStyle.\n\t\tPadding(1, 0, 0, 1).\n\t\tBorder(lipgloss.RoundedBorder()).\n\t\tBorderBackground(t.Background()).\n\t\tBorderForeground(t.TextMuted()).\n\t\tWidth(p.width).\n\t\tHeight(p.height).\n\t\tRender(\n\t\t\tcontent,\n\t\t)\n}\n\nfunc (p *permissionDialogCmp) View() string {\n\treturn p.render()\n}\n\nfunc (p *permissionDialogCmp) BindingKeys() []key.Binding {\n\treturn layout.KeyMapToSlice(permissionsKeys)\n}\n\nfunc (p *permissionDialogCmp) SetSize() tea.Cmd {\n\tif p.permission.ID == \"\" {\n\t\treturn nil\n\t}\n\tswitch p.permission.ToolName {\n\tcase tools.BashToolName:\n\t\tp.width = int(float64(p.windowSize.Width) * 0.4)\n\t\tp.height = int(float64(p.windowSize.Height) * 0.3)\n\tcase tools.EditToolName:\n\t\tp.width = int(float64(p.windowSize.Width) * 0.8)\n\t\tp.height = int(float64(p.windowSize.Height) * 0.8)\n\tcase tools.WriteToolName:\n\t\tp.width = int(float64(p.windowSize.Width) * 0.8)\n\t\tp.height = int(float64(p.windowSize.Height) * 0.8)\n\tcase tools.FetchToolName:\n\t\tp.width = int(float64(p.windowSize.Width) * 0.4)\n\t\tp.height = int(float64(p.windowSize.Height) * 0.3)\n\tdefault:\n\t\tp.width = int(float64(p.windowSize.Width) * 0.7)\n\t\tp.height = int(float64(p.windowSize.Height) * 0.5)\n\t}\n\treturn nil\n}\n\nfunc (p *permissionDialogCmp) SetPermissions(permission permission.PermissionRequest) tea.Cmd {\n\tp.permission = permission\n\treturn p.SetSize()\n}\n\n// Helper to get or set cached diff content\nfunc (c *permissionDialogCmp) GetOrSetDiff(key string, generator func() (string, error)) string {\n\tif cached, ok := c.diffCache[key]; ok {\n\t\treturn cached\n\t}\n\n\tcontent, err := generator()\n\tif err != nil {\n\t\treturn fmt.Sprintf(\"Error formatting diff: %v\", err)\n\t}\n\n\tc.diffCache[key] = content\n\n\treturn content\n}\n\n// Helper to get or set cached markdown content\nfunc (c *permissionDialogCmp) GetOrSetMarkdown(key string, generator func() (string, error)) string {\n\tif cached, ok := c.markdownCache[key]; ok {\n\t\treturn cached\n\t}\n\n\tcontent, err := generator()\n\tif err != nil {\n\t\treturn fmt.Sprintf(\"Error rendering markdown: %v\", err)\n\t}\n\n\tc.markdownCache[key] = content\n\n\treturn content\n}\n\nfunc NewPermissionDialogCmp() PermissionDialogCmp {\n\t// Create viewport for content\n\tcontentViewport := viewport.New(0, 0)\n\n\treturn &permissionDialogCmp{\n\t\tcontentViewPort: contentViewport,\n\t\tselectedOption: 0, // Default to \"Allow\"\n\t\tdiffCache: make(map[string]string),\n\t\tmarkdownCache: make(map[string]string),\n\t}\n}\n"], ["/opencode/internal/tui/components/dialog/arguments.go", "package dialog\n\nimport (\n\t\"fmt\"\n\t\"github.com/charmbracelet/bubbles/key\"\n\t\"github.com/charmbracelet/bubbles/textinput\"\n\ttea \"github.com/charmbracelet/bubbletea\"\n\t\"github.com/charmbracelet/lipgloss\"\n\n\t\"github.com/opencode-ai/opencode/internal/tui/styles\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n\t\"github.com/opencode-ai/opencode/internal/tui/util\"\n)\n\ntype argumentsDialogKeyMap struct {\n\tEnter key.Binding\n\tEscape key.Binding\n}\n\n// ShortHelp implements key.Map.\nfunc (k argumentsDialogKeyMap) ShortHelp() []key.Binding {\n\treturn []key.Binding{\n\t\tkey.NewBinding(\n\t\t\tkey.WithKeys(\"enter\"),\n\t\t\tkey.WithHelp(\"enter\", \"confirm\"),\n\t\t),\n\t\tkey.NewBinding(\n\t\t\tkey.WithKeys(\"esc\"),\n\t\t\tkey.WithHelp(\"esc\", \"cancel\"),\n\t\t),\n\t}\n}\n\n// FullHelp implements key.Map.\nfunc (k argumentsDialogKeyMap) FullHelp() [][]key.Binding {\n\treturn [][]key.Binding{k.ShortHelp()}\n}\n\n// ShowMultiArgumentsDialogMsg is a message that is sent to show the multi-arguments dialog.\ntype ShowMultiArgumentsDialogMsg struct {\n\tCommandID string\n\tContent string\n\tArgNames []string\n}\n\n// CloseMultiArgumentsDialogMsg is a message that is sent when the multi-arguments dialog is closed.\ntype CloseMultiArgumentsDialogMsg struct {\n\tSubmit bool\n\tCommandID string\n\tContent string\n\tArgs map[string]string\n}\n\n// MultiArgumentsDialogCmp is a component that asks the user for multiple command arguments.\ntype MultiArgumentsDialogCmp struct {\n\twidth, height int\n\tinputs []textinput.Model\n\tfocusIndex int\n\tkeys argumentsDialogKeyMap\n\tcommandID string\n\tcontent string\n\targNames []string\n}\n\n// NewMultiArgumentsDialogCmp creates a new MultiArgumentsDialogCmp.\nfunc NewMultiArgumentsDialogCmp(commandID, content string, argNames []string) MultiArgumentsDialogCmp {\n\tt := theme.CurrentTheme()\n\tinputs := make([]textinput.Model, len(argNames))\n\n\tfor i, name := range argNames {\n\t\tti := textinput.New()\n\t\tti.Placeholder = fmt.Sprintf(\"Enter value for %s...\", name)\n\t\tti.Width = 40\n\t\tti.Prompt = \"\"\n\t\tti.PlaceholderStyle = ti.PlaceholderStyle.Background(t.Background())\n\t\tti.PromptStyle = ti.PromptStyle.Background(t.Background())\n\t\tti.TextStyle = ti.TextStyle.Background(t.Background())\n\t\t\n\t\t// Only focus the first input initially\n\t\tif i == 0 {\n\t\t\tti.Focus()\n\t\t\tti.PromptStyle = ti.PromptStyle.Foreground(t.Primary())\n\t\t\tti.TextStyle = ti.TextStyle.Foreground(t.Primary())\n\t\t} else {\n\t\t\tti.Blur()\n\t\t}\n\n\t\tinputs[i] = ti\n\t}\n\n\treturn MultiArgumentsDialogCmp{\n\t\tinputs: inputs,\n\t\tkeys: argumentsDialogKeyMap{},\n\t\tcommandID: commandID,\n\t\tcontent: content,\n\t\targNames: argNames,\n\t\tfocusIndex: 0,\n\t}\n}\n\n// Init implements tea.Model.\nfunc (m MultiArgumentsDialogCmp) Init() tea.Cmd {\n\t// Make sure only the first input is focused\n\tfor i := range m.inputs {\n\t\tif i == 0 {\n\t\t\tm.inputs[i].Focus()\n\t\t} else {\n\t\t\tm.inputs[i].Blur()\n\t\t}\n\t}\n\t\n\treturn textinput.Blink\n}\n\n// Update implements tea.Model.\nfunc (m MultiArgumentsDialogCmp) Update(msg tea.Msg) (tea.Model, tea.Cmd) {\n\tvar cmds []tea.Cmd\n\tt := theme.CurrentTheme()\n\n\tswitch msg := msg.(type) {\n\tcase tea.KeyMsg:\n\t\tswitch {\n\t\tcase key.Matches(msg, key.NewBinding(key.WithKeys(\"esc\"))):\n\t\t\treturn m, util.CmdHandler(CloseMultiArgumentsDialogMsg{\n\t\t\t\tSubmit: false,\n\t\t\t\tCommandID: m.commandID,\n\t\t\t\tContent: m.content,\n\t\t\t\tArgs: nil,\n\t\t\t})\n\t\tcase key.Matches(msg, key.NewBinding(key.WithKeys(\"enter\"))):\n\t\t\t// If we're on the last input, submit the form\n\t\t\tif m.focusIndex == len(m.inputs)-1 {\n\t\t\t\targs := make(map[string]string)\n\t\t\t\tfor i, name := range m.argNames {\n\t\t\t\t\targs[name] = m.inputs[i].Value()\n\t\t\t\t}\n\t\t\t\treturn m, util.CmdHandler(CloseMultiArgumentsDialogMsg{\n\t\t\t\t\tSubmit: true,\n\t\t\t\t\tCommandID: m.commandID,\n\t\t\t\t\tContent: m.content,\n\t\t\t\t\tArgs: args,\n\t\t\t\t})\n\t\t\t}\n\t\t\t// Otherwise, move to the next input\n\t\t\tm.inputs[m.focusIndex].Blur()\n\t\t\tm.focusIndex++\n\t\t\tm.inputs[m.focusIndex].Focus()\n\t\t\tm.inputs[m.focusIndex].PromptStyle = m.inputs[m.focusIndex].PromptStyle.Foreground(t.Primary())\n\t\t\tm.inputs[m.focusIndex].TextStyle = m.inputs[m.focusIndex].TextStyle.Foreground(t.Primary())\n\t\tcase key.Matches(msg, key.NewBinding(key.WithKeys(\"tab\"))):\n\t\t\t// Move to the next input\n\t\t\tm.inputs[m.focusIndex].Blur()\n\t\t\tm.focusIndex = (m.focusIndex + 1) % len(m.inputs)\n\t\t\tm.inputs[m.focusIndex].Focus()\n\t\t\tm.inputs[m.focusIndex].PromptStyle = m.inputs[m.focusIndex].PromptStyle.Foreground(t.Primary())\n\t\t\tm.inputs[m.focusIndex].TextStyle = m.inputs[m.focusIndex].TextStyle.Foreground(t.Primary())\n\t\tcase key.Matches(msg, key.NewBinding(key.WithKeys(\"shift+tab\"))):\n\t\t\t// Move to the previous input\n\t\t\tm.inputs[m.focusIndex].Blur()\n\t\t\tm.focusIndex = (m.focusIndex - 1 + len(m.inputs)) % len(m.inputs)\n\t\t\tm.inputs[m.focusIndex].Focus()\n\t\t\tm.inputs[m.focusIndex].PromptStyle = m.inputs[m.focusIndex].PromptStyle.Foreground(t.Primary())\n\t\t\tm.inputs[m.focusIndex].TextStyle = m.inputs[m.focusIndex].TextStyle.Foreground(t.Primary())\n\t\t}\n\tcase tea.WindowSizeMsg:\n\t\tm.width = msg.Width\n\t\tm.height = msg.Height\n\t}\n\n\t// Update the focused input\n\tvar cmd tea.Cmd\n\tm.inputs[m.focusIndex], cmd = m.inputs[m.focusIndex].Update(msg)\n\tcmds = append(cmds, cmd)\n\n\treturn m, tea.Batch(cmds...)\n}\n\n// View implements tea.Model.\nfunc (m MultiArgumentsDialogCmp) View() string {\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\n\t// Calculate width needed for content\n\tmaxWidth := 60 // Width for explanation text\n\n\ttitle := lipgloss.NewStyle().\n\t\tForeground(t.Primary()).\n\t\tBold(true).\n\t\tWidth(maxWidth).\n\t\tPadding(0, 1).\n\t\tBackground(t.Background()).\n\t\tRender(\"Command Arguments\")\n\n\texplanation := lipgloss.NewStyle().\n\t\tForeground(t.Text()).\n\t\tWidth(maxWidth).\n\t\tPadding(0, 1).\n\t\tBackground(t.Background()).\n\t\tRender(\"This command requires multiple arguments. Please enter values for each:\")\n\n\t// Create input fields for each argument\n\tinputFields := make([]string, len(m.inputs))\n\tfor i, input := range m.inputs {\n\t\t// Highlight the label of the focused input\n\t\tlabelStyle := lipgloss.NewStyle().\n\t\t\tWidth(maxWidth).\n\t\t\tPadding(1, 1, 0, 1).\n\t\t\tBackground(t.Background())\n\t\t\t\n\t\tif i == m.focusIndex {\n\t\t\tlabelStyle = labelStyle.Foreground(t.Primary()).Bold(true)\n\t\t} else {\n\t\t\tlabelStyle = labelStyle.Foreground(t.TextMuted())\n\t\t}\n\t\t\n\t\tlabel := labelStyle.Render(m.argNames[i] + \":\")\n\n\t\tfield := lipgloss.NewStyle().\n\t\t\tForeground(t.Text()).\n\t\t\tWidth(maxWidth).\n\t\t\tPadding(0, 1).\n\t\t\tBackground(t.Background()).\n\t\t\tRender(input.View())\n\n\t\tinputFields[i] = lipgloss.JoinVertical(lipgloss.Left, label, field)\n\t}\n\n\tmaxWidth = min(maxWidth, m.width-10)\n\n\t// Join all elements vertically\n\telements := []string{title, explanation}\n\telements = append(elements, inputFields...)\n\n\tcontent := lipgloss.JoinVertical(\n\t\tlipgloss.Left,\n\t\telements...,\n\t)\n\n\treturn baseStyle.Padding(1, 2).\n\t\tBorder(lipgloss.RoundedBorder()).\n\t\tBorderBackground(t.Background()).\n\t\tBorderForeground(t.TextMuted()).\n\t\tBackground(t.Background()).\n\t\tWidth(lipgloss.Width(content) + 4).\n\t\tRender(content)\n}\n\n// SetSize sets the size of the component.\nfunc (m *MultiArgumentsDialogCmp) SetSize(width, height int) {\n\tm.width = width\n\tm.height = height\n}\n\n// Bindings implements layout.Bindings.\nfunc (m MultiArgumentsDialogCmp) Bindings() []key.Binding {\n\treturn m.keys.ShortHelp()\n}"], ["/opencode/internal/tui/components/dialog/session.go", "package dialog\n\nimport (\n\t\"github.com/charmbracelet/bubbles/key\"\n\ttea \"github.com/charmbracelet/bubbletea\"\n\t\"github.com/charmbracelet/lipgloss\"\n\t\"github.com/opencode-ai/opencode/internal/session\"\n\t\"github.com/opencode-ai/opencode/internal/tui/layout\"\n\t\"github.com/opencode-ai/opencode/internal/tui/styles\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n\t\"github.com/opencode-ai/opencode/internal/tui/util\"\n)\n\n// SessionSelectedMsg is sent when a session is selected\ntype SessionSelectedMsg struct {\n\tSession session.Session\n}\n\n// CloseSessionDialogMsg is sent when the session dialog is closed\ntype CloseSessionDialogMsg struct{}\n\n// SessionDialog interface for the session switching dialog\ntype SessionDialog interface {\n\ttea.Model\n\tlayout.Bindings\n\tSetSessions(sessions []session.Session)\n\tSetSelectedSession(sessionID string)\n}\n\ntype sessionDialogCmp struct {\n\tsessions []session.Session\n\tselectedIdx int\n\twidth int\n\theight int\n\tselectedSessionID string\n}\n\ntype sessionKeyMap struct {\n\tUp key.Binding\n\tDown key.Binding\n\tEnter key.Binding\n\tEscape key.Binding\n\tJ key.Binding\n\tK key.Binding\n}\n\nvar sessionKeys = sessionKeyMap{\n\tUp: key.NewBinding(\n\t\tkey.WithKeys(\"up\"),\n\t\tkey.WithHelp(\"↑\", \"previous session\"),\n\t),\n\tDown: key.NewBinding(\n\t\tkey.WithKeys(\"down\"),\n\t\tkey.WithHelp(\"↓\", \"next session\"),\n\t),\n\tEnter: key.NewBinding(\n\t\tkey.WithKeys(\"enter\"),\n\t\tkey.WithHelp(\"enter\", \"select session\"),\n\t),\n\tEscape: key.NewBinding(\n\t\tkey.WithKeys(\"esc\"),\n\t\tkey.WithHelp(\"esc\", \"close\"),\n\t),\n\tJ: key.NewBinding(\n\t\tkey.WithKeys(\"j\"),\n\t\tkey.WithHelp(\"j\", \"next session\"),\n\t),\n\tK: key.NewBinding(\n\t\tkey.WithKeys(\"k\"),\n\t\tkey.WithHelp(\"k\", \"previous session\"),\n\t),\n}\n\nfunc (s *sessionDialogCmp) Init() tea.Cmd {\n\treturn nil\n}\n\nfunc (s *sessionDialogCmp) Update(msg tea.Msg) (tea.Model, tea.Cmd) {\n\tswitch msg := msg.(type) {\n\tcase tea.KeyMsg:\n\t\tswitch {\n\t\tcase key.Matches(msg, sessionKeys.Up) || key.Matches(msg, sessionKeys.K):\n\t\t\tif s.selectedIdx > 0 {\n\t\t\t\ts.selectedIdx--\n\t\t\t}\n\t\t\treturn s, nil\n\t\tcase key.Matches(msg, sessionKeys.Down) || key.Matches(msg, sessionKeys.J):\n\t\t\tif s.selectedIdx < len(s.sessions)-1 {\n\t\t\t\ts.selectedIdx++\n\t\t\t}\n\t\t\treturn s, nil\n\t\tcase key.Matches(msg, sessionKeys.Enter):\n\t\t\tif len(s.sessions) > 0 {\n\t\t\t\treturn s, util.CmdHandler(SessionSelectedMsg{\n\t\t\t\t\tSession: s.sessions[s.selectedIdx],\n\t\t\t\t})\n\t\t\t}\n\t\tcase key.Matches(msg, sessionKeys.Escape):\n\t\t\treturn s, util.CmdHandler(CloseSessionDialogMsg{})\n\t\t}\n\tcase tea.WindowSizeMsg:\n\t\ts.width = msg.Width\n\t\ts.height = msg.Height\n\t}\n\treturn s, nil\n}\n\nfunc (s *sessionDialogCmp) View() string {\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\t\n\tif len(s.sessions) == 0 {\n\t\treturn baseStyle.Padding(1, 2).\n\t\t\tBorder(lipgloss.RoundedBorder()).\n\t\t\tBorderBackground(t.Background()).\n\t\t\tBorderForeground(t.TextMuted()).\n\t\t\tWidth(40).\n\t\t\tRender(\"No sessions available\")\n\t}\n\n\t// Calculate max width needed for session titles\n\tmaxWidth := 40 // Minimum width\n\tfor _, sess := range s.sessions {\n\t\tif len(sess.Title) > maxWidth-4 { // Account for padding\n\t\t\tmaxWidth = len(sess.Title) + 4\n\t\t}\n\t}\n\n\tmaxWidth = max(30, min(maxWidth, s.width-15)) // Limit width to avoid overflow\n\n\t// Limit height to avoid taking up too much screen space\n\tmaxVisibleSessions := min(10, len(s.sessions))\n\n\t// Build the session list\n\tsessionItems := make([]string, 0, maxVisibleSessions)\n\tstartIdx := 0\n\n\t// If we have more sessions than can be displayed, adjust the start index\n\tif len(s.sessions) > maxVisibleSessions {\n\t\t// Center the selected item when possible\n\t\thalfVisible := maxVisibleSessions / 2\n\t\tif s.selectedIdx >= halfVisible && s.selectedIdx < len(s.sessions)-halfVisible {\n\t\t\tstartIdx = s.selectedIdx - halfVisible\n\t\t} else if s.selectedIdx >= len(s.sessions)-halfVisible {\n\t\t\tstartIdx = len(s.sessions) - maxVisibleSessions\n\t\t}\n\t}\n\n\tendIdx := min(startIdx+maxVisibleSessions, len(s.sessions))\n\n\tfor i := startIdx; i < endIdx; i++ {\n\t\tsess := s.sessions[i]\n\t\titemStyle := baseStyle.Width(maxWidth)\n\n\t\tif i == s.selectedIdx {\n\t\t\titemStyle = itemStyle.\n\t\t\t\tBackground(t.Primary()).\n\t\t\t\tForeground(t.Background()).\n\t\t\t\tBold(true)\n\t\t}\n\n\t\tsessionItems = append(sessionItems, itemStyle.Padding(0, 1).Render(sess.Title))\n\t}\n\n\ttitle := baseStyle.\n\t\tForeground(t.Primary()).\n\t\tBold(true).\n\t\tWidth(maxWidth).\n\t\tPadding(0, 1).\n\t\tRender(\"Switch Session\")\n\n\tcontent := lipgloss.JoinVertical(\n\t\tlipgloss.Left,\n\t\ttitle,\n\t\tbaseStyle.Width(maxWidth).Render(\"\"),\n\t\tbaseStyle.Width(maxWidth).Render(lipgloss.JoinVertical(lipgloss.Left, sessionItems...)),\n\t\tbaseStyle.Width(maxWidth).Render(\"\"),\n\t)\n\n\treturn baseStyle.Padding(1, 2).\n\t\tBorder(lipgloss.RoundedBorder()).\n\t\tBorderBackground(t.Background()).\n\t\tBorderForeground(t.TextMuted()).\n\t\tWidth(lipgloss.Width(content) + 4).\n\t\tRender(content)\n}\n\nfunc (s *sessionDialogCmp) BindingKeys() []key.Binding {\n\treturn layout.KeyMapToSlice(sessionKeys)\n}\n\nfunc (s *sessionDialogCmp) SetSessions(sessions []session.Session) {\n\ts.sessions = sessions\n\n\t// If we have a selected session ID, find its index\n\tif s.selectedSessionID != \"\" {\n\t\tfor i, sess := range sessions {\n\t\t\tif sess.ID == s.selectedSessionID {\n\t\t\t\ts.selectedIdx = i\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\n\t// Default to first session if selected not found\n\ts.selectedIdx = 0\n}\n\nfunc (s *sessionDialogCmp) SetSelectedSession(sessionID string) {\n\ts.selectedSessionID = sessionID\n\n\t// Update the selected index if sessions are already loaded\n\tif len(s.sessions) > 0 {\n\t\tfor i, sess := range s.sessions {\n\t\t\tif sess.ID == sessionID {\n\t\t\t\ts.selectedIdx = i\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}\n\n// NewSessionDialogCmp creates a new session switching dialog\nfunc NewSessionDialogCmp() SessionDialog {\n\treturn &sessionDialogCmp{\n\t\tsessions: []session.Session{},\n\t\tselectedIdx: 0,\n\t\tselectedSessionID: \"\",\n\t}\n}\n"], ["/opencode/internal/tui/components/chat/editor.go", "package chat\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"os/exec\"\n\t\"slices\"\n\t\"strings\"\n\t\"unicode\"\n\n\t\"github.com/charmbracelet/bubbles/key\"\n\t\"github.com/charmbracelet/bubbles/textarea\"\n\ttea \"github.com/charmbracelet/bubbletea\"\n\t\"github.com/charmbracelet/lipgloss\"\n\t\"github.com/opencode-ai/opencode/internal/app\"\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n\t\"github.com/opencode-ai/opencode/internal/message\"\n\t\"github.com/opencode-ai/opencode/internal/session\"\n\t\"github.com/opencode-ai/opencode/internal/tui/components/dialog\"\n\t\"github.com/opencode-ai/opencode/internal/tui/layout\"\n\t\"github.com/opencode-ai/opencode/internal/tui/styles\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n\t\"github.com/opencode-ai/opencode/internal/tui/util\"\n)\n\ntype editorCmp struct {\n\twidth int\n\theight int\n\tapp *app.App\n\tsession session.Session\n\ttextarea textarea.Model\n\tattachments []message.Attachment\n\tdeleteMode bool\n}\n\ntype EditorKeyMaps struct {\n\tSend key.Binding\n\tOpenEditor key.Binding\n}\n\ntype bluredEditorKeyMaps struct {\n\tSend key.Binding\n\tFocus key.Binding\n\tOpenEditor key.Binding\n}\ntype DeleteAttachmentKeyMaps struct {\n\tAttachmentDeleteMode key.Binding\n\tEscape key.Binding\n\tDeleteAllAttachments key.Binding\n}\n\nvar editorMaps = EditorKeyMaps{\n\tSend: key.NewBinding(\n\t\tkey.WithKeys(\"enter\", \"ctrl+s\"),\n\t\tkey.WithHelp(\"enter\", \"send message\"),\n\t),\n\tOpenEditor: key.NewBinding(\n\t\tkey.WithKeys(\"ctrl+e\"),\n\t\tkey.WithHelp(\"ctrl+e\", \"open editor\"),\n\t),\n}\n\nvar DeleteKeyMaps = DeleteAttachmentKeyMaps{\n\tAttachmentDeleteMode: key.NewBinding(\n\t\tkey.WithKeys(\"ctrl+r\"),\n\t\tkey.WithHelp(\"ctrl+r+{i}\", \"delete attachment at index i\"),\n\t),\n\tEscape: key.NewBinding(\n\t\tkey.WithKeys(\"esc\"),\n\t\tkey.WithHelp(\"esc\", \"cancel delete mode\"),\n\t),\n\tDeleteAllAttachments: key.NewBinding(\n\t\tkey.WithKeys(\"r\"),\n\t\tkey.WithHelp(\"ctrl+r+r\", \"delete all attchments\"),\n\t),\n}\n\nconst (\n\tmaxAttachments = 5\n)\n\nfunc (m *editorCmp) openEditor() tea.Cmd {\n\teditor := os.Getenv(\"EDITOR\")\n\tif editor == \"\" {\n\t\teditor = \"nvim\"\n\t}\n\n\ttmpfile, err := os.CreateTemp(\"\", \"msg_*.md\")\n\tif err != nil {\n\t\treturn util.ReportError(err)\n\t}\n\ttmpfile.Close()\n\tc := exec.Command(editor, tmpfile.Name()) //nolint:gosec\n\tc.Stdin = os.Stdin\n\tc.Stdout = os.Stdout\n\tc.Stderr = os.Stderr\n\treturn tea.ExecProcess(c, func(err error) tea.Msg {\n\t\tif err != nil {\n\t\t\treturn util.ReportError(err)\n\t\t}\n\t\tcontent, err := os.ReadFile(tmpfile.Name())\n\t\tif err != nil {\n\t\t\treturn util.ReportError(err)\n\t\t}\n\t\tif len(content) == 0 {\n\t\t\treturn util.ReportWarn(\"Message is empty\")\n\t\t}\n\t\tos.Remove(tmpfile.Name())\n\t\tattachments := m.attachments\n\t\tm.attachments = nil\n\t\treturn SendMsg{\n\t\t\tText: string(content),\n\t\t\tAttachments: attachments,\n\t\t}\n\t})\n}\n\nfunc (m *editorCmp) Init() tea.Cmd {\n\treturn textarea.Blink\n}\n\nfunc (m *editorCmp) send() tea.Cmd {\n\tif m.app.CoderAgent.IsSessionBusy(m.session.ID) {\n\t\treturn util.ReportWarn(\"Agent is working, please wait...\")\n\t}\n\n\tvalue := m.textarea.Value()\n\tm.textarea.Reset()\n\tattachments := m.attachments\n\n\tm.attachments = nil\n\tif value == \"\" {\n\t\treturn nil\n\t}\n\treturn tea.Batch(\n\t\tutil.CmdHandler(SendMsg{\n\t\t\tText: value,\n\t\t\tAttachments: attachments,\n\t\t}),\n\t)\n}\n\nfunc (m *editorCmp) Update(msg tea.Msg) (tea.Model, tea.Cmd) {\n\tvar cmd tea.Cmd\n\tswitch msg := msg.(type) {\n\tcase dialog.ThemeChangedMsg:\n\t\tm.textarea = CreateTextArea(&m.textarea)\n\tcase dialog.CompletionSelectedMsg:\n\t\texistingValue := m.textarea.Value()\n\t\tmodifiedValue := strings.Replace(existingValue, msg.SearchString, msg.CompletionValue, 1)\n\n\t\tm.textarea.SetValue(modifiedValue)\n\t\treturn m, nil\n\tcase SessionSelectedMsg:\n\t\tif msg.ID != m.session.ID {\n\t\t\tm.session = msg\n\t\t}\n\t\treturn m, nil\n\tcase dialog.AttachmentAddedMsg:\n\t\tif len(m.attachments) >= maxAttachments {\n\t\t\tlogging.ErrorPersist(fmt.Sprintf(\"cannot add more than %d images\", maxAttachments))\n\t\t\treturn m, cmd\n\t\t}\n\t\tm.attachments = append(m.attachments, msg.Attachment)\n\tcase tea.KeyMsg:\n\t\tif key.Matches(msg, DeleteKeyMaps.AttachmentDeleteMode) {\n\t\t\tm.deleteMode = true\n\t\t\treturn m, nil\n\t\t}\n\t\tif key.Matches(msg, DeleteKeyMaps.DeleteAllAttachments) && m.deleteMode {\n\t\t\tm.deleteMode = false\n\t\t\tm.attachments = nil\n\t\t\treturn m, nil\n\t\t}\n\t\tif m.deleteMode && len(msg.Runes) > 0 && unicode.IsDigit(msg.Runes[0]) {\n\t\t\tnum := int(msg.Runes[0] - '0')\n\t\t\tm.deleteMode = false\n\t\t\tif num < 10 && len(m.attachments) > num {\n\t\t\t\tif num == 0 {\n\t\t\t\t\tm.attachments = m.attachments[num+1:]\n\t\t\t\t} else {\n\t\t\t\t\tm.attachments = slices.Delete(m.attachments, num, num+1)\n\t\t\t\t}\n\t\t\t\treturn m, nil\n\t\t\t}\n\t\t}\n\t\tif key.Matches(msg, messageKeys.PageUp) || key.Matches(msg, messageKeys.PageDown) ||\n\t\t\tkey.Matches(msg, messageKeys.HalfPageUp) || key.Matches(msg, messageKeys.HalfPageDown) {\n\t\t\treturn m, nil\n\t\t}\n\t\tif key.Matches(msg, editorMaps.OpenEditor) {\n\t\t\tif m.app.CoderAgent.IsSessionBusy(m.session.ID) {\n\t\t\t\treturn m, util.ReportWarn(\"Agent is working, please wait...\")\n\t\t\t}\n\t\t\treturn m, m.openEditor()\n\t\t}\n\t\tif key.Matches(msg, DeleteKeyMaps.Escape) {\n\t\t\tm.deleteMode = false\n\t\t\treturn m, nil\n\t\t}\n\t\t// Hanlde Enter key\n\t\tif m.textarea.Focused() && key.Matches(msg, editorMaps.Send) {\n\t\t\tvalue := m.textarea.Value()\n\t\t\tif len(value) > 0 && value[len(value)-1] == '\\\\' {\n\t\t\t\t// If the last character is a backslash, remove it and add a newline\n\t\t\t\tm.textarea.SetValue(value[:len(value)-1] + \"\\n\")\n\t\t\t\treturn m, nil\n\t\t\t} else {\n\t\t\t\t// Otherwise, send the message\n\t\t\t\treturn m, m.send()\n\t\t\t}\n\t\t}\n\n\t}\n\tm.textarea, cmd = m.textarea.Update(msg)\n\treturn m, cmd\n}\n\nfunc (m *editorCmp) View() string {\n\tt := theme.CurrentTheme()\n\n\t// Style the prompt with theme colors\n\tstyle := lipgloss.NewStyle().\n\t\tPadding(0, 0, 0, 1).\n\t\tBold(true).\n\t\tForeground(t.Primary())\n\n\tif len(m.attachments) == 0 {\n\t\treturn lipgloss.JoinHorizontal(lipgloss.Top, style.Render(\">\"), m.textarea.View())\n\t}\n\tm.textarea.SetHeight(m.height - 1)\n\treturn lipgloss.JoinVertical(lipgloss.Top,\n\t\tm.attachmentsContent(),\n\t\tlipgloss.JoinHorizontal(lipgloss.Top, style.Render(\">\"),\n\t\t\tm.textarea.View()),\n\t)\n}\n\nfunc (m *editorCmp) SetSize(width, height int) tea.Cmd {\n\tm.width = width\n\tm.height = height\n\tm.textarea.SetWidth(width - 3) // account for the prompt and padding right\n\tm.textarea.SetHeight(height)\n\tm.textarea.SetWidth(width)\n\treturn nil\n}\n\nfunc (m *editorCmp) GetSize() (int, int) {\n\treturn m.textarea.Width(), m.textarea.Height()\n}\n\nfunc (m *editorCmp) attachmentsContent() string {\n\tvar styledAttachments []string\n\tt := theme.CurrentTheme()\n\tattachmentStyles := styles.BaseStyle().\n\t\tMarginLeft(1).\n\t\tBackground(t.TextMuted()).\n\t\tForeground(t.Text())\n\tfor i, attachment := range m.attachments {\n\t\tvar filename string\n\t\tif len(attachment.FileName) > 10 {\n\t\t\tfilename = fmt.Sprintf(\" %s %s...\", styles.DocumentIcon, attachment.FileName[0:7])\n\t\t} else {\n\t\t\tfilename = fmt.Sprintf(\" %s %s\", styles.DocumentIcon, attachment.FileName)\n\t\t}\n\t\tif m.deleteMode {\n\t\t\tfilename = fmt.Sprintf(\"%d%s\", i, filename)\n\t\t}\n\t\tstyledAttachments = append(styledAttachments, attachmentStyles.Render(filename))\n\t}\n\tcontent := lipgloss.JoinHorizontal(lipgloss.Left, styledAttachments...)\n\treturn content\n}\n\nfunc (m *editorCmp) BindingKeys() []key.Binding {\n\tbindings := []key.Binding{}\n\tbindings = append(bindings, layout.KeyMapToSlice(editorMaps)...)\n\tbindings = append(bindings, layout.KeyMapToSlice(DeleteKeyMaps)...)\n\treturn bindings\n}\n\nfunc CreateTextArea(existing *textarea.Model) textarea.Model {\n\tt := theme.CurrentTheme()\n\tbgColor := t.Background()\n\ttextColor := t.Text()\n\ttextMutedColor := t.TextMuted()\n\n\tta := textarea.New()\n\tta.BlurredStyle.Base = styles.BaseStyle().Background(bgColor).Foreground(textColor)\n\tta.BlurredStyle.CursorLine = styles.BaseStyle().Background(bgColor)\n\tta.BlurredStyle.Placeholder = styles.BaseStyle().Background(bgColor).Foreground(textMutedColor)\n\tta.BlurredStyle.Text = styles.BaseStyle().Background(bgColor).Foreground(textColor)\n\tta.FocusedStyle.Base = styles.BaseStyle().Background(bgColor).Foreground(textColor)\n\tta.FocusedStyle.CursorLine = styles.BaseStyle().Background(bgColor)\n\tta.FocusedStyle.Placeholder = styles.BaseStyle().Background(bgColor).Foreground(textMutedColor)\n\tta.FocusedStyle.Text = styles.BaseStyle().Background(bgColor).Foreground(textColor)\n\n\tta.Prompt = \" \"\n\tta.ShowLineNumbers = false\n\tta.CharLimit = -1\n\n\tif existing != nil {\n\t\tta.SetValue(existing.Value())\n\t\tta.SetWidth(existing.Width())\n\t\tta.SetHeight(existing.Height())\n\t}\n\n\tta.Focus()\n\treturn ta\n}\n\nfunc NewEditorCmp(app *app.App) tea.Model {\n\tta := CreateTextArea(nil)\n\treturn &editorCmp{\n\t\tapp: app,\n\t\ttextarea: ta,\n\t}\n}\n"], ["/opencode/internal/tui/components/chat/message.go", "package chat\n\nimport (\n\t\"context\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"path/filepath\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/charmbracelet/lipgloss\"\n\t\"github.com/charmbracelet/x/ansi\"\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/diff\"\n\t\"github.com/opencode-ai/opencode/internal/llm/agent\"\n\t\"github.com/opencode-ai/opencode/internal/llm/models\"\n\t\"github.com/opencode-ai/opencode/internal/llm/tools\"\n\t\"github.com/opencode-ai/opencode/internal/message\"\n\t\"github.com/opencode-ai/opencode/internal/tui/styles\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n)\n\ntype uiMessageType int\n\nconst (\n\tuserMessageType uiMessageType = iota\n\tassistantMessageType\n\ttoolMessageType\n\n\tmaxResultHeight = 10\n)\n\ntype uiMessage struct {\n\tID string\n\tmessageType uiMessageType\n\tposition int\n\theight int\n\tcontent string\n}\n\nfunc toMarkdown(content string, focused bool, width int) string {\n\tr := styles.GetMarkdownRenderer(width)\n\trendered, _ := r.Render(content)\n\treturn rendered\n}\n\nfunc renderMessage(msg string, isUser bool, isFocused bool, width int, info ...string) string {\n\tt := theme.CurrentTheme()\n\n\tstyle := styles.BaseStyle().\n\t\tWidth(width - 1).\n\t\tBorderLeft(true).\n\t\tForeground(t.TextMuted()).\n\t\tBorderForeground(t.Primary()).\n\t\tBorderStyle(lipgloss.ThickBorder())\n\n\tif isUser {\n\t\tstyle = style.BorderForeground(t.Secondary())\n\t}\n\n\t// Apply markdown formatting and handle background color\n\tparts := []string{\n\t\tstyles.ForceReplaceBackgroundWithLipgloss(toMarkdown(msg, isFocused, width), t.Background()),\n\t}\n\n\t// Remove newline at the end\n\tparts[0] = strings.TrimSuffix(parts[0], \"\\n\")\n\tif len(info) > 0 {\n\t\tparts = append(parts, info...)\n\t}\n\n\trendered := style.Render(\n\t\tlipgloss.JoinVertical(\n\t\t\tlipgloss.Left,\n\t\t\tparts...,\n\t\t),\n\t)\n\n\treturn rendered\n}\n\nfunc renderUserMessage(msg message.Message, isFocused bool, width int, position int) uiMessage {\n\tvar styledAttachments []string\n\tt := theme.CurrentTheme()\n\tattachmentStyles := styles.BaseStyle().\n\t\tMarginLeft(1).\n\t\tBackground(t.TextMuted()).\n\t\tForeground(t.Text())\n\tfor _, attachment := range msg.BinaryContent() {\n\t\tfile := filepath.Base(attachment.Path)\n\t\tvar filename string\n\t\tif len(file) > 10 {\n\t\t\tfilename = fmt.Sprintf(\" %s %s...\", styles.DocumentIcon, file[0:7])\n\t\t} else {\n\t\t\tfilename = fmt.Sprintf(\" %s %s\", styles.DocumentIcon, file)\n\t\t}\n\t\tstyledAttachments = append(styledAttachments, attachmentStyles.Render(filename))\n\t}\n\tcontent := \"\"\n\tif len(styledAttachments) > 0 {\n\t\tattachmentContent := styles.BaseStyle().Width(width).Render(lipgloss.JoinHorizontal(lipgloss.Left, styledAttachments...))\n\t\tcontent = renderMessage(msg.Content().String(), true, isFocused, width, attachmentContent)\n\t} else {\n\t\tcontent = renderMessage(msg.Content().String(), true, isFocused, width)\n\t}\n\tuserMsg := uiMessage{\n\t\tID: msg.ID,\n\t\tmessageType: userMessageType,\n\t\tposition: position,\n\t\theight: lipgloss.Height(content),\n\t\tcontent: content,\n\t}\n\treturn userMsg\n}\n\n// Returns multiple uiMessages because of the tool calls\nfunc renderAssistantMessage(\n\tmsg message.Message,\n\tmsgIndex int,\n\tallMessages []message.Message, // we need this to get tool results and the user message\n\tmessagesService message.Service, // We need this to get the task tool messages\n\tfocusedUIMessageId string,\n\tisSummary bool,\n\twidth int,\n\tposition int,\n) []uiMessage {\n\tmessages := []uiMessage{}\n\tcontent := msg.Content().String()\n\tthinking := msg.IsThinking()\n\tthinkingContent := msg.ReasoningContent().Thinking\n\tfinished := msg.IsFinished()\n\tfinishData := msg.FinishPart()\n\tinfo := []string{}\n\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\n\t// Add finish info if available\n\tif finished {\n\t\tswitch finishData.Reason {\n\t\tcase message.FinishReasonEndTurn:\n\t\t\ttook := formatTimestampDiff(msg.CreatedAt, finishData.Time)\n\t\t\tinfo = append(info, baseStyle.\n\t\t\t\tWidth(width-1).\n\t\t\t\tForeground(t.TextMuted()).\n\t\t\t\tRender(fmt.Sprintf(\" %s (%s)\", models.SupportedModels[msg.Model].Name, took)),\n\t\t\t)\n\t\tcase message.FinishReasonCanceled:\n\t\t\tinfo = append(info, baseStyle.\n\t\t\t\tWidth(width-1).\n\t\t\t\tForeground(t.TextMuted()).\n\t\t\t\tRender(fmt.Sprintf(\" %s (%s)\", models.SupportedModels[msg.Model].Name, \"canceled\")),\n\t\t\t)\n\t\tcase message.FinishReasonError:\n\t\t\tinfo = append(info, baseStyle.\n\t\t\t\tWidth(width-1).\n\t\t\t\tForeground(t.TextMuted()).\n\t\t\t\tRender(fmt.Sprintf(\" %s (%s)\", models.SupportedModels[msg.Model].Name, \"error\")),\n\t\t\t)\n\t\tcase message.FinishReasonPermissionDenied:\n\t\t\tinfo = append(info, baseStyle.\n\t\t\t\tWidth(width-1).\n\t\t\t\tForeground(t.TextMuted()).\n\t\t\t\tRender(fmt.Sprintf(\" %s (%s)\", models.SupportedModels[msg.Model].Name, \"permission denied\")),\n\t\t\t)\n\t\t}\n\t}\n\tif content != \"\" || (finished && finishData.Reason == message.FinishReasonEndTurn) {\n\t\tif content == \"\" {\n\t\t\tcontent = \"*Finished without output*\"\n\t\t}\n\t\tif isSummary {\n\t\t\tinfo = append(info, baseStyle.Width(width-1).Foreground(t.TextMuted()).Render(\" (summary)\"))\n\t\t}\n\n\t\tcontent = renderMessage(content, false, true, width, info...)\n\t\tmessages = append(messages, uiMessage{\n\t\t\tID: msg.ID,\n\t\t\tmessageType: assistantMessageType,\n\t\t\tposition: position,\n\t\t\theight: lipgloss.Height(content),\n\t\t\tcontent: content,\n\t\t})\n\t\tposition += messages[0].height\n\t\tposition++ // for the space\n\t} else if thinking && thinkingContent != \"\" {\n\t\t// Render the thinking content\n\t\tcontent = renderMessage(thinkingContent, false, msg.ID == focusedUIMessageId, width)\n\t}\n\n\tfor i, toolCall := range msg.ToolCalls() {\n\t\ttoolCallContent := renderToolMessage(\n\t\t\ttoolCall,\n\t\t\tallMessages,\n\t\t\tmessagesService,\n\t\t\tfocusedUIMessageId,\n\t\t\tfalse,\n\t\t\twidth,\n\t\t\ti+1,\n\t\t)\n\t\tmessages = append(messages, toolCallContent)\n\t\tposition += toolCallContent.height\n\t\tposition++ // for the space\n\t}\n\treturn messages\n}\n\nfunc findToolResponse(toolCallID string, futureMessages []message.Message) *message.ToolResult {\n\tfor _, msg := range futureMessages {\n\t\tfor _, result := range msg.ToolResults() {\n\t\t\tif result.ToolCallID == toolCallID {\n\t\t\t\treturn &result\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc toolName(name string) string {\n\tswitch name {\n\tcase agent.AgentToolName:\n\t\treturn \"Task\"\n\tcase tools.BashToolName:\n\t\treturn \"Bash\"\n\tcase tools.EditToolName:\n\t\treturn \"Edit\"\n\tcase tools.FetchToolName:\n\t\treturn \"Fetch\"\n\tcase tools.GlobToolName:\n\t\treturn \"Glob\"\n\tcase tools.GrepToolName:\n\t\treturn \"Grep\"\n\tcase tools.LSToolName:\n\t\treturn \"List\"\n\tcase tools.SourcegraphToolName:\n\t\treturn \"Sourcegraph\"\n\tcase tools.ViewToolName:\n\t\treturn \"View\"\n\tcase tools.WriteToolName:\n\t\treturn \"Write\"\n\tcase tools.PatchToolName:\n\t\treturn \"Patch\"\n\t}\n\treturn name\n}\n\nfunc getToolAction(name string) string {\n\tswitch name {\n\tcase agent.AgentToolName:\n\t\treturn \"Preparing prompt...\"\n\tcase tools.BashToolName:\n\t\treturn \"Building command...\"\n\tcase tools.EditToolName:\n\t\treturn \"Preparing edit...\"\n\tcase tools.FetchToolName:\n\t\treturn \"Writing fetch...\"\n\tcase tools.GlobToolName:\n\t\treturn \"Finding files...\"\n\tcase tools.GrepToolName:\n\t\treturn \"Searching content...\"\n\tcase tools.LSToolName:\n\t\treturn \"Listing directory...\"\n\tcase tools.SourcegraphToolName:\n\t\treturn \"Searching code...\"\n\tcase tools.ViewToolName:\n\t\treturn \"Reading file...\"\n\tcase tools.WriteToolName:\n\t\treturn \"Preparing write...\"\n\tcase tools.PatchToolName:\n\t\treturn \"Preparing patch...\"\n\t}\n\treturn \"Working...\"\n}\n\n// renders params, params[0] (params[1]=params[2] ....)\nfunc renderParams(paramsWidth int, params ...string) string {\n\tif len(params) == 0 {\n\t\treturn \"\"\n\t}\n\tmainParam := params[0]\n\tif len(mainParam) > paramsWidth {\n\t\tmainParam = mainParam[:paramsWidth-3] + \"...\"\n\t}\n\n\tif len(params) == 1 {\n\t\treturn mainParam\n\t}\n\totherParams := params[1:]\n\t// create pairs of key/value\n\t// if odd number of params, the last one is a key without value\n\tif len(otherParams)%2 != 0 {\n\t\totherParams = append(otherParams, \"\")\n\t}\n\tparts := make([]string, 0, len(otherParams)/2)\n\tfor i := 0; i < len(otherParams); i += 2 {\n\t\tkey := otherParams[i]\n\t\tvalue := otherParams[i+1]\n\t\tif value == \"\" {\n\t\t\tcontinue\n\t\t}\n\t\tparts = append(parts, fmt.Sprintf(\"%s=%s\", key, value))\n\t}\n\n\tpartsRendered := strings.Join(parts, \", \")\n\tremainingWidth := paramsWidth - lipgloss.Width(partsRendered) - 5 // for the space\n\tif remainingWidth < 30 {\n\t\t// No space for the params, just show the main\n\t\treturn mainParam\n\t}\n\n\tif len(parts) > 0 {\n\t\tmainParam = fmt.Sprintf(\"%s (%s)\", mainParam, strings.Join(parts, \", \"))\n\t}\n\n\treturn ansi.Truncate(mainParam, paramsWidth, \"...\")\n}\n\nfunc removeWorkingDirPrefix(path string) string {\n\twd := config.WorkingDirectory()\n\tif strings.HasPrefix(path, wd) {\n\t\tpath = strings.TrimPrefix(path, wd)\n\t}\n\tif strings.HasPrefix(path, \"/\") {\n\t\tpath = strings.TrimPrefix(path, \"/\")\n\t}\n\tif strings.HasPrefix(path, \"./\") {\n\t\tpath = strings.TrimPrefix(path, \"./\")\n\t}\n\tif strings.HasPrefix(path, \"../\") {\n\t\tpath = strings.TrimPrefix(path, \"../\")\n\t}\n\treturn path\n}\n\nfunc renderToolParams(paramWidth int, toolCall message.ToolCall) string {\n\tparams := \"\"\n\tswitch toolCall.Name {\n\tcase agent.AgentToolName:\n\t\tvar params agent.AgentParams\n\t\tjson.Unmarshal([]byte(toolCall.Input), ¶ms)\n\t\tprompt := strings.ReplaceAll(params.Prompt, \"\\n\", \" \")\n\t\treturn renderParams(paramWidth, prompt)\n\tcase tools.BashToolName:\n\t\tvar params tools.BashParams\n\t\tjson.Unmarshal([]byte(toolCall.Input), ¶ms)\n\t\tcommand := strings.ReplaceAll(params.Command, \"\\n\", \" \")\n\t\treturn renderParams(paramWidth, command)\n\tcase tools.EditToolName:\n\t\tvar params tools.EditParams\n\t\tjson.Unmarshal([]byte(toolCall.Input), ¶ms)\n\t\tfilePath := removeWorkingDirPrefix(params.FilePath)\n\t\treturn renderParams(paramWidth, filePath)\n\tcase tools.FetchToolName:\n\t\tvar params tools.FetchParams\n\t\tjson.Unmarshal([]byte(toolCall.Input), ¶ms)\n\t\turl := params.URL\n\t\ttoolParams := []string{\n\t\t\turl,\n\t\t}\n\t\tif params.Format != \"\" {\n\t\t\ttoolParams = append(toolParams, \"format\", params.Format)\n\t\t}\n\t\tif params.Timeout != 0 {\n\t\t\ttoolParams = append(toolParams, \"timeout\", (time.Duration(params.Timeout) * time.Second).String())\n\t\t}\n\t\treturn renderParams(paramWidth, toolParams...)\n\tcase tools.GlobToolName:\n\t\tvar params tools.GlobParams\n\t\tjson.Unmarshal([]byte(toolCall.Input), ¶ms)\n\t\tpattern := params.Pattern\n\t\ttoolParams := []string{\n\t\t\tpattern,\n\t\t}\n\t\tif params.Path != \"\" {\n\t\t\ttoolParams = append(toolParams, \"path\", params.Path)\n\t\t}\n\t\treturn renderParams(paramWidth, toolParams...)\n\tcase tools.GrepToolName:\n\t\tvar params tools.GrepParams\n\t\tjson.Unmarshal([]byte(toolCall.Input), ¶ms)\n\t\tpattern := params.Pattern\n\t\ttoolParams := []string{\n\t\t\tpattern,\n\t\t}\n\t\tif params.Path != \"\" {\n\t\t\ttoolParams = append(toolParams, \"path\", params.Path)\n\t\t}\n\t\tif params.Include != \"\" {\n\t\t\ttoolParams = append(toolParams, \"include\", params.Include)\n\t\t}\n\t\tif params.LiteralText {\n\t\t\ttoolParams = append(toolParams, \"literal\", \"true\")\n\t\t}\n\t\treturn renderParams(paramWidth, toolParams...)\n\tcase tools.LSToolName:\n\t\tvar params tools.LSParams\n\t\tjson.Unmarshal([]byte(toolCall.Input), ¶ms)\n\t\tpath := params.Path\n\t\tif path == \"\" {\n\t\t\tpath = \".\"\n\t\t}\n\t\treturn renderParams(paramWidth, path)\n\tcase tools.SourcegraphToolName:\n\t\tvar params tools.SourcegraphParams\n\t\tjson.Unmarshal([]byte(toolCall.Input), ¶ms)\n\t\treturn renderParams(paramWidth, params.Query)\n\tcase tools.ViewToolName:\n\t\tvar params tools.ViewParams\n\t\tjson.Unmarshal([]byte(toolCall.Input), ¶ms)\n\t\tfilePath := removeWorkingDirPrefix(params.FilePath)\n\t\ttoolParams := []string{\n\t\t\tfilePath,\n\t\t}\n\t\tif params.Limit != 0 {\n\t\t\ttoolParams = append(toolParams, \"limit\", fmt.Sprintf(\"%d\", params.Limit))\n\t\t}\n\t\tif params.Offset != 0 {\n\t\t\ttoolParams = append(toolParams, \"offset\", fmt.Sprintf(\"%d\", params.Offset))\n\t\t}\n\t\treturn renderParams(paramWidth, toolParams...)\n\tcase tools.WriteToolName:\n\t\tvar params tools.WriteParams\n\t\tjson.Unmarshal([]byte(toolCall.Input), ¶ms)\n\t\tfilePath := removeWorkingDirPrefix(params.FilePath)\n\t\treturn renderParams(paramWidth, filePath)\n\tdefault:\n\t\tinput := strings.ReplaceAll(toolCall.Input, \"\\n\", \" \")\n\t\tparams = renderParams(paramWidth, input)\n\t}\n\treturn params\n}\n\nfunc truncateHeight(content string, height int) string {\n\tlines := strings.Split(content, \"\\n\")\n\tif len(lines) > height {\n\t\treturn strings.Join(lines[:height], \"\\n\")\n\t}\n\treturn content\n}\n\nfunc renderToolResponse(toolCall message.ToolCall, response message.ToolResult, width int) string {\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\n\tif response.IsError {\n\t\terrContent := fmt.Sprintf(\"Error: %s\", strings.ReplaceAll(response.Content, \"\\n\", \" \"))\n\t\terrContent = ansi.Truncate(errContent, width-1, \"...\")\n\t\treturn baseStyle.\n\t\t\tWidth(width).\n\t\t\tForeground(t.Error()).\n\t\t\tRender(errContent)\n\t}\n\n\tresultContent := truncateHeight(response.Content, maxResultHeight)\n\tswitch toolCall.Name {\n\tcase agent.AgentToolName:\n\t\treturn styles.ForceReplaceBackgroundWithLipgloss(\n\t\t\ttoMarkdown(resultContent, false, width),\n\t\t\tt.Background(),\n\t\t)\n\tcase tools.BashToolName:\n\t\tresultContent = fmt.Sprintf(\"```bash\\n%s\\n```\", resultContent)\n\t\treturn styles.ForceReplaceBackgroundWithLipgloss(\n\t\t\ttoMarkdown(resultContent, true, width),\n\t\t\tt.Background(),\n\t\t)\n\tcase tools.EditToolName:\n\t\tmetadata := tools.EditResponseMetadata{}\n\t\tjson.Unmarshal([]byte(response.Metadata), &metadata)\n\t\ttruncDiff := truncateHeight(metadata.Diff, maxResultHeight)\n\t\tformattedDiff, _ := diff.FormatDiff(truncDiff, diff.WithTotalWidth(width))\n\t\treturn formattedDiff\n\tcase tools.FetchToolName:\n\t\tvar params tools.FetchParams\n\t\tjson.Unmarshal([]byte(toolCall.Input), ¶ms)\n\t\tmdFormat := \"markdown\"\n\t\tswitch params.Format {\n\t\tcase \"text\":\n\t\t\tmdFormat = \"text\"\n\t\tcase \"html\":\n\t\t\tmdFormat = \"html\"\n\t\t}\n\t\tresultContent = fmt.Sprintf(\"```%s\\n%s\\n```\", mdFormat, resultContent)\n\t\treturn styles.ForceReplaceBackgroundWithLipgloss(\n\t\t\ttoMarkdown(resultContent, true, width),\n\t\t\tt.Background(),\n\t\t)\n\tcase tools.GlobToolName:\n\t\treturn baseStyle.Width(width).Foreground(t.TextMuted()).Render(resultContent)\n\tcase tools.GrepToolName:\n\t\treturn baseStyle.Width(width).Foreground(t.TextMuted()).Render(resultContent)\n\tcase tools.LSToolName:\n\t\treturn baseStyle.Width(width).Foreground(t.TextMuted()).Render(resultContent)\n\tcase tools.SourcegraphToolName:\n\t\treturn baseStyle.Width(width).Foreground(t.TextMuted()).Render(resultContent)\n\tcase tools.ViewToolName:\n\t\tmetadata := tools.ViewResponseMetadata{}\n\t\tjson.Unmarshal([]byte(response.Metadata), &metadata)\n\t\text := filepath.Ext(metadata.FilePath)\n\t\tif ext == \"\" {\n\t\t\text = \"\"\n\t\t} else {\n\t\t\text = strings.ToLower(ext[1:])\n\t\t}\n\t\tresultContent = fmt.Sprintf(\"```%s\\n%s\\n```\", ext, truncateHeight(metadata.Content, maxResultHeight))\n\t\treturn styles.ForceReplaceBackgroundWithLipgloss(\n\t\t\ttoMarkdown(resultContent, true, width),\n\t\t\tt.Background(),\n\t\t)\n\tcase tools.WriteToolName:\n\t\tparams := tools.WriteParams{}\n\t\tjson.Unmarshal([]byte(toolCall.Input), ¶ms)\n\t\tmetadata := tools.WriteResponseMetadata{}\n\t\tjson.Unmarshal([]byte(response.Metadata), &metadata)\n\t\text := filepath.Ext(params.FilePath)\n\t\tif ext == \"\" {\n\t\t\text = \"\"\n\t\t} else {\n\t\t\text = strings.ToLower(ext[1:])\n\t\t}\n\t\tresultContent = fmt.Sprintf(\"```%s\\n%s\\n```\", ext, truncateHeight(params.Content, maxResultHeight))\n\t\treturn styles.ForceReplaceBackgroundWithLipgloss(\n\t\t\ttoMarkdown(resultContent, true, width),\n\t\t\tt.Background(),\n\t\t)\n\tdefault:\n\t\tresultContent = fmt.Sprintf(\"```text\\n%s\\n```\", resultContent)\n\t\treturn styles.ForceReplaceBackgroundWithLipgloss(\n\t\t\ttoMarkdown(resultContent, true, width),\n\t\t\tt.Background(),\n\t\t)\n\t}\n}\n\nfunc renderToolMessage(\n\ttoolCall message.ToolCall,\n\tallMessages []message.Message,\n\tmessagesService message.Service,\n\tfocusedUIMessageId string,\n\tnested bool,\n\twidth int,\n\tposition int,\n) uiMessage {\n\tif nested {\n\t\twidth = width - 3\n\t}\n\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\n\tstyle := baseStyle.\n\t\tWidth(width - 1).\n\t\tBorderLeft(true).\n\t\tBorderStyle(lipgloss.ThickBorder()).\n\t\tPaddingLeft(1).\n\t\tBorderForeground(t.TextMuted())\n\n\tresponse := findToolResponse(toolCall.ID, allMessages)\n\ttoolNameText := baseStyle.Foreground(t.TextMuted()).\n\t\tRender(fmt.Sprintf(\"%s: \", toolName(toolCall.Name)))\n\n\tif !toolCall.Finished {\n\t\t// Get a brief description of what the tool is doing\n\t\ttoolAction := getToolAction(toolCall.Name)\n\n\t\tprogressText := baseStyle.\n\t\t\tWidth(width - 2 - lipgloss.Width(toolNameText)).\n\t\t\tForeground(t.TextMuted()).\n\t\t\tRender(fmt.Sprintf(\"%s\", toolAction))\n\n\t\tcontent := style.Render(lipgloss.JoinHorizontal(lipgloss.Left, toolNameText, progressText))\n\t\ttoolMsg := uiMessage{\n\t\t\tmessageType: toolMessageType,\n\t\t\tposition: position,\n\t\t\theight: lipgloss.Height(content),\n\t\t\tcontent: content,\n\t\t}\n\t\treturn toolMsg\n\t}\n\n\tparams := renderToolParams(width-2-lipgloss.Width(toolNameText), toolCall)\n\tresponseContent := \"\"\n\tif response != nil {\n\t\tresponseContent = renderToolResponse(toolCall, *response, width-2)\n\t\tresponseContent = strings.TrimSuffix(responseContent, \"\\n\")\n\t} else {\n\t\tresponseContent = baseStyle.\n\t\t\tItalic(true).\n\t\t\tWidth(width - 2).\n\t\t\tForeground(t.TextMuted()).\n\t\t\tRender(\"Waiting for response...\")\n\t}\n\n\tparts := []string{}\n\tif !nested {\n\t\tformattedParams := baseStyle.\n\t\t\tWidth(width - 2 - lipgloss.Width(toolNameText)).\n\t\t\tForeground(t.TextMuted()).\n\t\t\tRender(params)\n\n\t\tparts = append(parts, lipgloss.JoinHorizontal(lipgloss.Left, toolNameText, formattedParams))\n\t} else {\n\t\tprefix := baseStyle.\n\t\t\tForeground(t.TextMuted()).\n\t\t\tRender(\" └ \")\n\t\tformattedParams := baseStyle.\n\t\t\tWidth(width - 2 - lipgloss.Width(toolNameText)).\n\t\t\tForeground(t.TextMuted()).\n\t\t\tRender(params)\n\t\tparts = append(parts, lipgloss.JoinHorizontal(lipgloss.Left, prefix, toolNameText, formattedParams))\n\t}\n\n\tif toolCall.Name == agent.AgentToolName {\n\t\ttaskMessages, _ := messagesService.List(context.Background(), toolCall.ID)\n\t\ttoolCalls := []message.ToolCall{}\n\t\tfor _, v := range taskMessages {\n\t\t\ttoolCalls = append(toolCalls, v.ToolCalls()...)\n\t\t}\n\t\tfor _, call := range toolCalls {\n\t\t\trendered := renderToolMessage(call, []message.Message{}, messagesService, focusedUIMessageId, true, width, 0)\n\t\t\tparts = append(parts, rendered.content)\n\t\t}\n\t}\n\tif responseContent != \"\" && !nested {\n\t\tparts = append(parts, responseContent)\n\t}\n\n\tcontent := style.Render(\n\t\tlipgloss.JoinVertical(\n\t\t\tlipgloss.Left,\n\t\t\tparts...,\n\t\t),\n\t)\n\tif nested {\n\t\tcontent = lipgloss.JoinVertical(\n\t\t\tlipgloss.Left,\n\t\t\tparts...,\n\t\t)\n\t}\n\ttoolMsg := uiMessage{\n\t\tmessageType: toolMessageType,\n\t\tposition: position,\n\t\theight: lipgloss.Height(content),\n\t\tcontent: content,\n\t}\n\treturn toolMsg\n}\n\n// Helper function to format the time difference between two Unix timestamps\nfunc formatTimestampDiff(start, end int64) string {\n\tdiffSeconds := float64(end-start) / 1000.0 // Convert to seconds\n\tif diffSeconds < 1 {\n\t\treturn fmt.Sprintf(\"%dms\", int(diffSeconds*1000))\n\t}\n\tif diffSeconds < 60 {\n\t\treturn fmt.Sprintf(\"%.1fs\", diffSeconds)\n\t}\n\treturn fmt.Sprintf(\"%.1fm\", diffSeconds/60)\n}\n"], ["/opencode/internal/tui/components/dialog/theme.go", "package dialog\n\nimport (\n\t\"github.com/charmbracelet/bubbles/key\"\n\ttea \"github.com/charmbracelet/bubbletea\"\n\t\"github.com/charmbracelet/lipgloss\"\n\t\"github.com/opencode-ai/opencode/internal/tui/layout\"\n\t\"github.com/opencode-ai/opencode/internal/tui/styles\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n\t\"github.com/opencode-ai/opencode/internal/tui/util\"\n)\n\n// ThemeChangedMsg is sent when the theme is changed\ntype ThemeChangedMsg struct {\n\tThemeName string\n}\n\n// CloseThemeDialogMsg is sent when the theme dialog is closed\ntype CloseThemeDialogMsg struct{}\n\n// ThemeDialog interface for the theme switching dialog\ntype ThemeDialog interface {\n\ttea.Model\n\tlayout.Bindings\n}\n\ntype themeDialogCmp struct {\n\tthemes []string\n\tselectedIdx int\n\twidth int\n\theight int\n\tcurrentTheme string\n}\n\ntype themeKeyMap struct {\n\tUp key.Binding\n\tDown key.Binding\n\tEnter key.Binding\n\tEscape key.Binding\n\tJ key.Binding\n\tK key.Binding\n}\n\nvar themeKeys = themeKeyMap{\n\tUp: key.NewBinding(\n\t\tkey.WithKeys(\"up\"),\n\t\tkey.WithHelp(\"↑\", \"previous theme\"),\n\t),\n\tDown: key.NewBinding(\n\t\tkey.WithKeys(\"down\"),\n\t\tkey.WithHelp(\"↓\", \"next theme\"),\n\t),\n\tEnter: key.NewBinding(\n\t\tkey.WithKeys(\"enter\"),\n\t\tkey.WithHelp(\"enter\", \"select theme\"),\n\t),\n\tEscape: key.NewBinding(\n\t\tkey.WithKeys(\"esc\"),\n\t\tkey.WithHelp(\"esc\", \"close\"),\n\t),\n\tJ: key.NewBinding(\n\t\tkey.WithKeys(\"j\"),\n\t\tkey.WithHelp(\"j\", \"next theme\"),\n\t),\n\tK: key.NewBinding(\n\t\tkey.WithKeys(\"k\"),\n\t\tkey.WithHelp(\"k\", \"previous theme\"),\n\t),\n}\n\nfunc (t *themeDialogCmp) Init() tea.Cmd {\n\t// Load available themes and update selectedIdx based on current theme\n\tt.themes = theme.AvailableThemes()\n\tt.currentTheme = theme.CurrentThemeName()\n\n\t// Find the current theme in the list\n\tfor i, name := range t.themes {\n\t\tif name == t.currentTheme {\n\t\t\tt.selectedIdx = i\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc (t *themeDialogCmp) Update(msg tea.Msg) (tea.Model, tea.Cmd) {\n\tswitch msg := msg.(type) {\n\tcase tea.KeyMsg:\n\t\tswitch {\n\t\tcase key.Matches(msg, themeKeys.Up) || key.Matches(msg, themeKeys.K):\n\t\t\tif t.selectedIdx > 0 {\n\t\t\t\tt.selectedIdx--\n\t\t\t}\n\t\t\treturn t, nil\n\t\tcase key.Matches(msg, themeKeys.Down) || key.Matches(msg, themeKeys.J):\n\t\t\tif t.selectedIdx < len(t.themes)-1 {\n\t\t\t\tt.selectedIdx++\n\t\t\t}\n\t\t\treturn t, nil\n\t\tcase key.Matches(msg, themeKeys.Enter):\n\t\t\tif len(t.themes) > 0 {\n\t\t\t\tpreviousTheme := theme.CurrentThemeName()\n\t\t\t\tselectedTheme := t.themes[t.selectedIdx]\n\t\t\t\tif previousTheme == selectedTheme {\n\t\t\t\t\treturn t, util.CmdHandler(CloseThemeDialogMsg{})\n\t\t\t\t}\n\t\t\t\tif err := theme.SetTheme(selectedTheme); err != nil {\n\t\t\t\t\treturn t, util.ReportError(err)\n\t\t\t\t}\n\t\t\t\treturn t, util.CmdHandler(ThemeChangedMsg{\n\t\t\t\t\tThemeName: selectedTheme,\n\t\t\t\t})\n\t\t\t}\n\t\tcase key.Matches(msg, themeKeys.Escape):\n\t\t\treturn t, util.CmdHandler(CloseThemeDialogMsg{})\n\t\t}\n\tcase tea.WindowSizeMsg:\n\t\tt.width = msg.Width\n\t\tt.height = msg.Height\n\t}\n\treturn t, nil\n}\n\nfunc (t *themeDialogCmp) View() string {\n\tcurrentTheme := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\n\tif len(t.themes) == 0 {\n\t\treturn baseStyle.Padding(1, 2).\n\t\t\tBorder(lipgloss.RoundedBorder()).\n\t\t\tBorderBackground(currentTheme.Background()).\n\t\t\tBorderForeground(currentTheme.TextMuted()).\n\t\t\tWidth(40).\n\t\t\tRender(\"No themes available\")\n\t}\n\n\t// Calculate max width needed for theme names\n\tmaxWidth := 40 // Minimum width\n\tfor _, themeName := range t.themes {\n\t\tif len(themeName) > maxWidth-4 { // Account for padding\n\t\t\tmaxWidth = len(themeName) + 4\n\t\t}\n\t}\n\n\tmaxWidth = max(30, min(maxWidth, t.width-15)) // Limit width to avoid overflow\n\n\t// Build the theme list\n\tthemeItems := make([]string, 0, len(t.themes))\n\tfor i, themeName := range t.themes {\n\t\titemStyle := baseStyle.Width(maxWidth)\n\n\t\tif i == t.selectedIdx {\n\t\t\titemStyle = itemStyle.\n\t\t\t\tBackground(currentTheme.Primary()).\n\t\t\t\tForeground(currentTheme.Background()).\n\t\t\t\tBold(true)\n\t\t}\n\n\t\tthemeItems = append(themeItems, itemStyle.Padding(0, 1).Render(themeName))\n\t}\n\n\ttitle := baseStyle.\n\t\tForeground(currentTheme.Primary()).\n\t\tBold(true).\n\t\tWidth(maxWidth).\n\t\tPadding(0, 1).\n\t\tRender(\"Select Theme\")\n\n\tcontent := lipgloss.JoinVertical(\n\t\tlipgloss.Left,\n\t\ttitle,\n\t\tbaseStyle.Width(maxWidth).Render(\"\"),\n\t\tbaseStyle.Width(maxWidth).Render(lipgloss.JoinVertical(lipgloss.Left, themeItems...)),\n\t\tbaseStyle.Width(maxWidth).Render(\"\"),\n\t)\n\n\treturn baseStyle.Padding(1, 2).\n\t\tBorder(lipgloss.RoundedBorder()).\n\t\tBorderBackground(currentTheme.Background()).\n\t\tBorderForeground(currentTheme.TextMuted()).\n\t\tWidth(lipgloss.Width(content) + 4).\n\t\tRender(content)\n}\n\nfunc (t *themeDialogCmp) BindingKeys() []key.Binding {\n\treturn layout.KeyMapToSlice(themeKeys)\n}\n\n// NewThemeDialogCmp creates a new theme switching dialog\nfunc NewThemeDialogCmp() ThemeDialog {\n\treturn &themeDialogCmp{\n\t\tthemes: []string{},\n\t\tselectedIdx: 0,\n\t\tcurrentTheme: \"\",\n\t}\n}\n\n"], ["/opencode/internal/tui/components/dialog/init.go", "package dialog\n\nimport (\n\t\"github.com/charmbracelet/bubbles/key\"\n\ttea \"github.com/charmbracelet/bubbletea\"\n\t\"github.com/charmbracelet/lipgloss\"\n\n\t\"github.com/opencode-ai/opencode/internal/tui/styles\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n\t\"github.com/opencode-ai/opencode/internal/tui/util\"\n)\n\n// InitDialogCmp is a component that asks the user if they want to initialize the project.\ntype InitDialogCmp struct {\n\twidth, height int\n\tselected int\n\tkeys initDialogKeyMap\n}\n\n// NewInitDialogCmp creates a new InitDialogCmp.\nfunc NewInitDialogCmp() InitDialogCmp {\n\treturn InitDialogCmp{\n\t\tselected: 0,\n\t\tkeys: initDialogKeyMap{},\n\t}\n}\n\ntype initDialogKeyMap struct {\n\tTab key.Binding\n\tLeft key.Binding\n\tRight key.Binding\n\tEnter key.Binding\n\tEscape key.Binding\n\tY key.Binding\n\tN key.Binding\n}\n\n// ShortHelp implements key.Map.\nfunc (k initDialogKeyMap) ShortHelp() []key.Binding {\n\treturn []key.Binding{\n\t\tkey.NewBinding(\n\t\t\tkey.WithKeys(\"tab\", \"left\", \"right\"),\n\t\t\tkey.WithHelp(\"tab/←/→\", \"toggle selection\"),\n\t\t),\n\t\tkey.NewBinding(\n\t\t\tkey.WithKeys(\"enter\"),\n\t\t\tkey.WithHelp(\"enter\", \"confirm\"),\n\t\t),\n\t\tkey.NewBinding(\n\t\t\tkey.WithKeys(\"esc\", \"q\"),\n\t\t\tkey.WithHelp(\"esc/q\", \"cancel\"),\n\t\t),\n\t\tkey.NewBinding(\n\t\t\tkey.WithKeys(\"y\", \"n\"),\n\t\t\tkey.WithHelp(\"y/n\", \"yes/no\"),\n\t\t),\n\t}\n}\n\n// FullHelp implements key.Map.\nfunc (k initDialogKeyMap) FullHelp() [][]key.Binding {\n\treturn [][]key.Binding{k.ShortHelp()}\n}\n\n// Init implements tea.Model.\nfunc (m InitDialogCmp) Init() tea.Cmd {\n\treturn nil\n}\n\n// Update implements tea.Model.\nfunc (m InitDialogCmp) Update(msg tea.Msg) (tea.Model, tea.Cmd) {\n\tswitch msg := msg.(type) {\n\tcase tea.KeyMsg:\n\t\tswitch {\n\t\tcase key.Matches(msg, key.NewBinding(key.WithKeys(\"esc\"))):\n\t\t\treturn m, util.CmdHandler(CloseInitDialogMsg{Initialize: false})\n\t\tcase key.Matches(msg, key.NewBinding(key.WithKeys(\"tab\", \"left\", \"right\", \"h\", \"l\"))):\n\t\t\tm.selected = (m.selected + 1) % 2\n\t\t\treturn m, nil\n\t\tcase key.Matches(msg, key.NewBinding(key.WithKeys(\"enter\"))):\n\t\t\treturn m, util.CmdHandler(CloseInitDialogMsg{Initialize: m.selected == 0})\n\t\tcase key.Matches(msg, key.NewBinding(key.WithKeys(\"y\"))):\n\t\t\treturn m, util.CmdHandler(CloseInitDialogMsg{Initialize: true})\n\t\tcase key.Matches(msg, key.NewBinding(key.WithKeys(\"n\"))):\n\t\t\treturn m, util.CmdHandler(CloseInitDialogMsg{Initialize: false})\n\t\t}\n\tcase tea.WindowSizeMsg:\n\t\tm.width = msg.Width\n\t\tm.height = msg.Height\n\t}\n\treturn m, nil\n}\n\n// View implements tea.Model.\nfunc (m InitDialogCmp) View() string {\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\t\n\t// Calculate width needed for content\n\tmaxWidth := 60 // Width for explanation text\n\n\ttitle := baseStyle.\n\t\tForeground(t.Primary()).\n\t\tBold(true).\n\t\tWidth(maxWidth).\n\t\tPadding(0, 1).\n\t\tRender(\"Initialize Project\")\n\n\texplanation := baseStyle.\n\t\tForeground(t.Text()).\n\t\tWidth(maxWidth).\n\t\tPadding(0, 1).\n\t\tRender(\"Initialization generates a new OpenCode.md file that contains information about your codebase, this file serves as memory for each project, you can freely add to it to help the agents be better at their job.\")\n\n\tquestion := baseStyle.\n\t\tForeground(t.Text()).\n\t\tWidth(maxWidth).\n\t\tPadding(1, 1).\n\t\tRender(\"Would you like to initialize this project?\")\n\n\tmaxWidth = min(maxWidth, m.width-10)\n\tyesStyle := baseStyle\n\tnoStyle := baseStyle\n\n\tif m.selected == 0 {\n\t\tyesStyle = yesStyle.\n\t\t\tBackground(t.Primary()).\n\t\t\tForeground(t.Background()).\n\t\t\tBold(true)\n\t\tnoStyle = noStyle.\n\t\t\tBackground(t.Background()).\n\t\t\tForeground(t.Primary())\n\t} else {\n\t\tnoStyle = noStyle.\n\t\t\tBackground(t.Primary()).\n\t\t\tForeground(t.Background()).\n\t\t\tBold(true)\n\t\tyesStyle = yesStyle.\n\t\t\tBackground(t.Background()).\n\t\t\tForeground(t.Primary())\n\t}\n\n\tyes := yesStyle.Padding(0, 3).Render(\"Yes\")\n\tno := noStyle.Padding(0, 3).Render(\"No\")\n\n\tbuttons := lipgloss.JoinHorizontal(lipgloss.Center, yes, baseStyle.Render(\" \"), no)\n\tbuttons = baseStyle.\n\t\tWidth(maxWidth).\n\t\tPadding(1, 0).\n\t\tRender(buttons)\n\n\tcontent := lipgloss.JoinVertical(\n\t\tlipgloss.Left,\n\t\ttitle,\n\t\tbaseStyle.Width(maxWidth).Render(\"\"),\n\t\texplanation,\n\t\tquestion,\n\t\tbuttons,\n\t\tbaseStyle.Width(maxWidth).Render(\"\"),\n\t)\n\n\treturn baseStyle.Padding(1, 2).\n\t\tBorder(lipgloss.RoundedBorder()).\n\t\tBorderBackground(t.Background()).\n\t\tBorderForeground(t.TextMuted()).\n\t\tWidth(lipgloss.Width(content) + 4).\n\t\tRender(content)\n}\n\n// SetSize sets the size of the component.\nfunc (m *InitDialogCmp) SetSize(width, height int) {\n\tm.width = width\n\tm.height = height\n}\n\n// Bindings implements layout.Bindings.\nfunc (m InitDialogCmp) Bindings() []key.Binding {\n\treturn m.keys.ShortHelp()\n}\n\n// CloseInitDialogMsg is a message that is sent when the init dialog is closed.\ntype CloseInitDialogMsg struct {\n\tInitialize bool\n}\n\n// ShowInitDialogMsg is a message that is sent to show the init dialog.\ntype ShowInitDialogMsg struct {\n\tShow bool\n}\n"], ["/opencode/internal/tui/components/dialog/models.go", "package dialog\n\nimport (\n\t\"fmt\"\n\t\"slices\"\n\t\"strings\"\n\n\t\"github.com/charmbracelet/bubbles/key\"\n\ttea \"github.com/charmbracelet/bubbletea\"\n\t\"github.com/charmbracelet/lipgloss\"\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/llm/models\"\n\t\"github.com/opencode-ai/opencode/internal/tui/layout\"\n\t\"github.com/opencode-ai/opencode/internal/tui/styles\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n\t\"github.com/opencode-ai/opencode/internal/tui/util\"\n)\n\nconst (\n\tnumVisibleModels = 10\n\tmaxDialogWidth = 40\n)\n\n// ModelSelectedMsg is sent when a model is selected\ntype ModelSelectedMsg struct {\n\tModel models.Model\n}\n\n// CloseModelDialogMsg is sent when a model is selected\ntype CloseModelDialogMsg struct{}\n\n// ModelDialog interface for the model selection dialog\ntype ModelDialog interface {\n\ttea.Model\n\tlayout.Bindings\n}\n\ntype modelDialogCmp struct {\n\tmodels []models.Model\n\tprovider models.ModelProvider\n\tavailableProviders []models.ModelProvider\n\n\tselectedIdx int\n\twidth int\n\theight int\n\tscrollOffset int\n\thScrollOffset int\n\thScrollPossible bool\n}\n\ntype modelKeyMap struct {\n\tUp key.Binding\n\tDown key.Binding\n\tLeft key.Binding\n\tRight key.Binding\n\tEnter key.Binding\n\tEscape key.Binding\n\tJ key.Binding\n\tK key.Binding\n\tH key.Binding\n\tL key.Binding\n}\n\nvar modelKeys = modelKeyMap{\n\tUp: key.NewBinding(\n\t\tkey.WithKeys(\"up\"),\n\t\tkey.WithHelp(\"↑\", \"previous model\"),\n\t),\n\tDown: key.NewBinding(\n\t\tkey.WithKeys(\"down\"),\n\t\tkey.WithHelp(\"↓\", \"next model\"),\n\t),\n\tLeft: key.NewBinding(\n\t\tkey.WithKeys(\"left\"),\n\t\tkey.WithHelp(\"←\", \"scroll left\"),\n\t),\n\tRight: key.NewBinding(\n\t\tkey.WithKeys(\"right\"),\n\t\tkey.WithHelp(\"→\", \"scroll right\"),\n\t),\n\tEnter: key.NewBinding(\n\t\tkey.WithKeys(\"enter\"),\n\t\tkey.WithHelp(\"enter\", \"select model\"),\n\t),\n\tEscape: key.NewBinding(\n\t\tkey.WithKeys(\"esc\"),\n\t\tkey.WithHelp(\"esc\", \"close\"),\n\t),\n\tJ: key.NewBinding(\n\t\tkey.WithKeys(\"j\"),\n\t\tkey.WithHelp(\"j\", \"next model\"),\n\t),\n\tK: key.NewBinding(\n\t\tkey.WithKeys(\"k\"),\n\t\tkey.WithHelp(\"k\", \"previous model\"),\n\t),\n\tH: key.NewBinding(\n\t\tkey.WithKeys(\"h\"),\n\t\tkey.WithHelp(\"h\", \"scroll left\"),\n\t),\n\tL: key.NewBinding(\n\t\tkey.WithKeys(\"l\"),\n\t\tkey.WithHelp(\"l\", \"scroll right\"),\n\t),\n}\n\nfunc (m *modelDialogCmp) Init() tea.Cmd {\n\tm.setupModels()\n\treturn nil\n}\n\nfunc (m *modelDialogCmp) Update(msg tea.Msg) (tea.Model, tea.Cmd) {\n\tswitch msg := msg.(type) {\n\tcase tea.KeyMsg:\n\t\tswitch {\n\t\tcase key.Matches(msg, modelKeys.Up) || key.Matches(msg, modelKeys.K):\n\t\t\tm.moveSelectionUp()\n\t\tcase key.Matches(msg, modelKeys.Down) || key.Matches(msg, modelKeys.J):\n\t\t\tm.moveSelectionDown()\n\t\tcase key.Matches(msg, modelKeys.Left) || key.Matches(msg, modelKeys.H):\n\t\t\tif m.hScrollPossible {\n\t\t\t\tm.switchProvider(-1)\n\t\t\t}\n\t\tcase key.Matches(msg, modelKeys.Right) || key.Matches(msg, modelKeys.L):\n\t\t\tif m.hScrollPossible {\n\t\t\t\tm.switchProvider(1)\n\t\t\t}\n\t\tcase key.Matches(msg, modelKeys.Enter):\n\t\t\tutil.ReportInfo(fmt.Sprintf(\"selected model: %s\", m.models[m.selectedIdx].Name))\n\t\t\treturn m, util.CmdHandler(ModelSelectedMsg{Model: m.models[m.selectedIdx]})\n\t\tcase key.Matches(msg, modelKeys.Escape):\n\t\t\treturn m, util.CmdHandler(CloseModelDialogMsg{})\n\t\t}\n\tcase tea.WindowSizeMsg:\n\t\tm.width = msg.Width\n\t\tm.height = msg.Height\n\t}\n\n\treturn m, nil\n}\n\n// moveSelectionUp moves the selection up or wraps to bottom\nfunc (m *modelDialogCmp) moveSelectionUp() {\n\tif m.selectedIdx > 0 {\n\t\tm.selectedIdx--\n\t} else {\n\t\tm.selectedIdx = len(m.models) - 1\n\t\tm.scrollOffset = max(0, len(m.models)-numVisibleModels)\n\t}\n\n\t// Keep selection visible\n\tif m.selectedIdx < m.scrollOffset {\n\t\tm.scrollOffset = m.selectedIdx\n\t}\n}\n\n// moveSelectionDown moves the selection down or wraps to top\nfunc (m *modelDialogCmp) moveSelectionDown() {\n\tif m.selectedIdx < len(m.models)-1 {\n\t\tm.selectedIdx++\n\t} else {\n\t\tm.selectedIdx = 0\n\t\tm.scrollOffset = 0\n\t}\n\n\t// Keep selection visible\n\tif m.selectedIdx >= m.scrollOffset+numVisibleModels {\n\t\tm.scrollOffset = m.selectedIdx - (numVisibleModels - 1)\n\t}\n}\n\nfunc (m *modelDialogCmp) switchProvider(offset int) {\n\tnewOffset := m.hScrollOffset + offset\n\n\t// Ensure we stay within bounds\n\tif newOffset < 0 {\n\t\tnewOffset = len(m.availableProviders) - 1\n\t}\n\tif newOffset >= len(m.availableProviders) {\n\t\tnewOffset = 0\n\t}\n\n\tm.hScrollOffset = newOffset\n\tm.provider = m.availableProviders[m.hScrollOffset]\n\tm.setupModelsForProvider(m.provider)\n}\n\nfunc (m *modelDialogCmp) View() string {\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\n\t// Capitalize first letter of provider name\n\tproviderName := strings.ToUpper(string(m.provider)[:1]) + string(m.provider[1:])\n\ttitle := baseStyle.\n\t\tForeground(t.Primary()).\n\t\tBold(true).\n\t\tWidth(maxDialogWidth).\n\t\tPadding(0, 0, 1).\n\t\tRender(fmt.Sprintf(\"Select %s Model\", providerName))\n\n\t// Render visible models\n\tendIdx := min(m.scrollOffset+numVisibleModels, len(m.models))\n\tmodelItems := make([]string, 0, endIdx-m.scrollOffset)\n\n\tfor i := m.scrollOffset; i < endIdx; i++ {\n\t\titemStyle := baseStyle.Width(maxDialogWidth)\n\t\tif i == m.selectedIdx {\n\t\t\titemStyle = itemStyle.Background(t.Primary()).\n\t\t\t\tForeground(t.Background()).Bold(true)\n\t\t}\n\t\tmodelItems = append(modelItems, itemStyle.Render(m.models[i].Name))\n\t}\n\n\tscrollIndicator := m.getScrollIndicators(maxDialogWidth)\n\n\tcontent := lipgloss.JoinVertical(\n\t\tlipgloss.Left,\n\t\ttitle,\n\t\tbaseStyle.Width(maxDialogWidth).Render(lipgloss.JoinVertical(lipgloss.Left, modelItems...)),\n\t\tscrollIndicator,\n\t)\n\n\treturn baseStyle.Padding(1, 2).\n\t\tBorder(lipgloss.RoundedBorder()).\n\t\tBorderBackground(t.Background()).\n\t\tBorderForeground(t.TextMuted()).\n\t\tWidth(lipgloss.Width(content) + 4).\n\t\tRender(content)\n}\n\nfunc (m *modelDialogCmp) getScrollIndicators(maxWidth int) string {\n\tvar indicator string\n\n\tif len(m.models) > numVisibleModels {\n\t\tif m.scrollOffset > 0 {\n\t\t\tindicator += \"↑ \"\n\t\t}\n\t\tif m.scrollOffset+numVisibleModels < len(m.models) {\n\t\t\tindicator += \"↓ \"\n\t\t}\n\t}\n\n\tif m.hScrollPossible {\n\t\tif m.hScrollOffset > 0 {\n\t\t\tindicator = \"← \" + indicator\n\t\t}\n\t\tif m.hScrollOffset < len(m.availableProviders)-1 {\n\t\t\tindicator += \"→\"\n\t\t}\n\t}\n\n\tif indicator == \"\" {\n\t\treturn \"\"\n\t}\n\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\n\treturn baseStyle.\n\t\tForeground(t.Primary()).\n\t\tWidth(maxWidth).\n\t\tAlign(lipgloss.Right).\n\t\tBold(true).\n\t\tRender(indicator)\n}\n\nfunc (m *modelDialogCmp) BindingKeys() []key.Binding {\n\treturn layout.KeyMapToSlice(modelKeys)\n}\n\nfunc (m *modelDialogCmp) setupModels() {\n\tcfg := config.Get()\n\tmodelInfo := GetSelectedModel(cfg)\n\tm.availableProviders = getEnabledProviders(cfg)\n\tm.hScrollPossible = len(m.availableProviders) > 1\n\n\tm.provider = modelInfo.Provider\n\tm.hScrollOffset = findProviderIndex(m.availableProviders, m.provider)\n\n\tm.setupModelsForProvider(m.provider)\n}\n\nfunc GetSelectedModel(cfg *config.Config) models.Model {\n\n\tagentCfg := cfg.Agents[config.AgentCoder]\n\tselectedModelId := agentCfg.Model\n\treturn models.SupportedModels[selectedModelId]\n}\n\nfunc getEnabledProviders(cfg *config.Config) []models.ModelProvider {\n\tvar providers []models.ModelProvider\n\tfor providerId, provider := range cfg.Providers {\n\t\tif !provider.Disabled {\n\t\t\tproviders = append(providers, providerId)\n\t\t}\n\t}\n\n\t// Sort by provider popularity\n\tslices.SortFunc(providers, func(a, b models.ModelProvider) int {\n\t\trA := models.ProviderPopularity[a]\n\t\trB := models.ProviderPopularity[b]\n\n\t\t// models not included in popularity ranking default to last\n\t\tif rA == 0 {\n\t\t\trA = 999\n\t\t}\n\t\tif rB == 0 {\n\t\t\trB = 999\n\t\t}\n\t\treturn rA - rB\n\t})\n\treturn providers\n}\n\n// findProviderIndex returns the index of the provider in the list, or -1 if not found\nfunc findProviderIndex(providers []models.ModelProvider, provider models.ModelProvider) int {\n\tfor i, p := range providers {\n\t\tif p == provider {\n\t\t\treturn i\n\t\t}\n\t}\n\treturn -1\n}\n\nfunc (m *modelDialogCmp) setupModelsForProvider(provider models.ModelProvider) {\n\tcfg := config.Get()\n\tagentCfg := cfg.Agents[config.AgentCoder]\n\tselectedModelId := agentCfg.Model\n\n\tm.provider = provider\n\tm.models = getModelsForProvider(provider)\n\tm.selectedIdx = 0\n\tm.scrollOffset = 0\n\n\t// Try to select the current model if it belongs to this provider\n\tif provider == models.SupportedModels[selectedModelId].Provider {\n\t\tfor i, model := range m.models {\n\t\t\tif model.ID == selectedModelId {\n\t\t\t\tm.selectedIdx = i\n\t\t\t\t// Adjust scroll position to keep selected model visible\n\t\t\t\tif m.selectedIdx >= numVisibleModels {\n\t\t\t\t\tm.scrollOffset = m.selectedIdx - (numVisibleModels - 1)\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc getModelsForProvider(provider models.ModelProvider) []models.Model {\n\tvar providerModels []models.Model\n\tfor _, model := range models.SupportedModels {\n\t\tif model.Provider == provider {\n\t\t\tproviderModels = append(providerModels, model)\n\t\t}\n\t}\n\n\t// reverse alphabetical order (if llm naming was consistent latest would appear first)\n\tslices.SortFunc(providerModels, func(a, b models.Model) int {\n\t\tif a.Name > b.Name {\n\t\t\treturn -1\n\t\t} else if a.Name < b.Name {\n\t\t\treturn 1\n\t\t}\n\t\treturn 0\n\t})\n\n\treturn providerModels\n}\n\nfunc NewModelDialogCmp() ModelDialog {\n\treturn &modelDialogCmp{}\n}\n"], ["/opencode/internal/tui/components/chat/list.go", "package chat\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"math\"\n\n\t\"github.com/charmbracelet/bubbles/key\"\n\t\"github.com/charmbracelet/bubbles/spinner\"\n\t\"github.com/charmbracelet/bubbles/viewport\"\n\ttea \"github.com/charmbracelet/bubbletea\"\n\t\"github.com/charmbracelet/lipgloss\"\n\t\"github.com/opencode-ai/opencode/internal/app\"\n\t\"github.com/opencode-ai/opencode/internal/message\"\n\t\"github.com/opencode-ai/opencode/internal/pubsub\"\n\t\"github.com/opencode-ai/opencode/internal/session\"\n\t\"github.com/opencode-ai/opencode/internal/tui/components/dialog\"\n\t\"github.com/opencode-ai/opencode/internal/tui/styles\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n\t\"github.com/opencode-ai/opencode/internal/tui/util\"\n)\n\ntype cacheItem struct {\n\twidth int\n\tcontent []uiMessage\n}\ntype messagesCmp struct {\n\tapp *app.App\n\twidth, height int\n\tviewport viewport.Model\n\tsession session.Session\n\tmessages []message.Message\n\tuiMessages []uiMessage\n\tcurrentMsgID string\n\tcachedContent map[string]cacheItem\n\tspinner spinner.Model\n\trendering bool\n\tattachments viewport.Model\n}\ntype renderFinishedMsg struct{}\n\ntype MessageKeys struct {\n\tPageDown key.Binding\n\tPageUp key.Binding\n\tHalfPageUp key.Binding\n\tHalfPageDown key.Binding\n}\n\nvar messageKeys = MessageKeys{\n\tPageDown: key.NewBinding(\n\t\tkey.WithKeys(\"pgdown\"),\n\t\tkey.WithHelp(\"f/pgdn\", \"page down\"),\n\t),\n\tPageUp: key.NewBinding(\n\t\tkey.WithKeys(\"pgup\"),\n\t\tkey.WithHelp(\"b/pgup\", \"page up\"),\n\t),\n\tHalfPageUp: key.NewBinding(\n\t\tkey.WithKeys(\"ctrl+u\"),\n\t\tkey.WithHelp(\"ctrl+u\", \"½ page up\"),\n\t),\n\tHalfPageDown: key.NewBinding(\n\t\tkey.WithKeys(\"ctrl+d\", \"ctrl+d\"),\n\t\tkey.WithHelp(\"ctrl+d\", \"½ page down\"),\n\t),\n}\n\nfunc (m *messagesCmp) Init() tea.Cmd {\n\treturn tea.Batch(m.viewport.Init(), m.spinner.Tick)\n}\n\nfunc (m *messagesCmp) Update(msg tea.Msg) (tea.Model, tea.Cmd) {\n\tvar cmds []tea.Cmd\n\tswitch msg := msg.(type) {\n\tcase dialog.ThemeChangedMsg:\n\t\tm.rerender()\n\t\treturn m, nil\n\tcase SessionSelectedMsg:\n\t\tif msg.ID != m.session.ID {\n\t\t\tcmd := m.SetSession(msg)\n\t\t\treturn m, cmd\n\t\t}\n\t\treturn m, nil\n\tcase SessionClearedMsg:\n\t\tm.session = session.Session{}\n\t\tm.messages = make([]message.Message, 0)\n\t\tm.currentMsgID = \"\"\n\t\tm.rendering = false\n\t\treturn m, nil\n\n\tcase tea.KeyMsg:\n\t\tif key.Matches(msg, messageKeys.PageUp) || key.Matches(msg, messageKeys.PageDown) ||\n\t\t\tkey.Matches(msg, messageKeys.HalfPageUp) || key.Matches(msg, messageKeys.HalfPageDown) {\n\t\t\tu, cmd := m.viewport.Update(msg)\n\t\t\tm.viewport = u\n\t\t\tcmds = append(cmds, cmd)\n\t\t}\n\n\tcase renderFinishedMsg:\n\t\tm.rendering = false\n\t\tm.viewport.GotoBottom()\n\tcase pubsub.Event[session.Session]:\n\t\tif msg.Type == pubsub.UpdatedEvent && msg.Payload.ID == m.session.ID {\n\t\t\tm.session = msg.Payload\n\t\t\tif m.session.SummaryMessageID == m.currentMsgID {\n\t\t\t\tdelete(m.cachedContent, m.currentMsgID)\n\t\t\t\tm.renderView()\n\t\t\t}\n\t\t}\n\tcase pubsub.Event[message.Message]:\n\t\tneedsRerender := false\n\t\tif msg.Type == pubsub.CreatedEvent {\n\t\t\tif msg.Payload.SessionID == m.session.ID {\n\n\t\t\t\tmessageExists := false\n\t\t\t\tfor _, v := range m.messages {\n\t\t\t\t\tif v.ID == msg.Payload.ID {\n\t\t\t\t\t\tmessageExists = true\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif !messageExists {\n\t\t\t\t\tif len(m.messages) > 0 {\n\t\t\t\t\t\tlastMsgID := m.messages[len(m.messages)-1].ID\n\t\t\t\t\t\tdelete(m.cachedContent, lastMsgID)\n\t\t\t\t\t}\n\n\t\t\t\t\tm.messages = append(m.messages, msg.Payload)\n\t\t\t\t\tdelete(m.cachedContent, m.currentMsgID)\n\t\t\t\t\tm.currentMsgID = msg.Payload.ID\n\t\t\t\t\tneedsRerender = true\n\t\t\t\t}\n\t\t\t}\n\t\t\t// There are tool calls from the child task\n\t\t\tfor _, v := range m.messages {\n\t\t\t\tfor _, c := range v.ToolCalls() {\n\t\t\t\t\tif c.ID == msg.Payload.SessionID {\n\t\t\t\t\t\tdelete(m.cachedContent, v.ID)\n\t\t\t\t\t\tneedsRerender = true\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t} else if msg.Type == pubsub.UpdatedEvent && msg.Payload.SessionID == m.session.ID {\n\t\t\tfor i, v := range m.messages {\n\t\t\t\tif v.ID == msg.Payload.ID {\n\t\t\t\t\tm.messages[i] = msg.Payload\n\t\t\t\t\tdelete(m.cachedContent, msg.Payload.ID)\n\t\t\t\t\tneedsRerender = true\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif needsRerender {\n\t\t\tm.renderView()\n\t\t\tif len(m.messages) > 0 {\n\t\t\t\tif (msg.Type == pubsub.CreatedEvent) ||\n\t\t\t\t\t(msg.Type == pubsub.UpdatedEvent && msg.Payload.ID == m.messages[len(m.messages)-1].ID) {\n\t\t\t\t\tm.viewport.GotoBottom()\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tspinner, cmd := m.spinner.Update(msg)\n\tm.spinner = spinner\n\tcmds = append(cmds, cmd)\n\treturn m, tea.Batch(cmds...)\n}\n\nfunc (m *messagesCmp) IsAgentWorking() bool {\n\treturn m.app.CoderAgent.IsSessionBusy(m.session.ID)\n}\n\nfunc formatTimeDifference(unixTime1, unixTime2 int64) string {\n\tdiffSeconds := float64(math.Abs(float64(unixTime2 - unixTime1)))\n\n\tif diffSeconds < 60 {\n\t\treturn fmt.Sprintf(\"%.1fs\", diffSeconds)\n\t}\n\n\tminutes := int(diffSeconds / 60)\n\tseconds := int(diffSeconds) % 60\n\treturn fmt.Sprintf(\"%dm%ds\", minutes, seconds)\n}\n\nfunc (m *messagesCmp) renderView() {\n\tm.uiMessages = make([]uiMessage, 0)\n\tpos := 0\n\tbaseStyle := styles.BaseStyle()\n\n\tif m.width == 0 {\n\t\treturn\n\t}\n\tfor inx, msg := range m.messages {\n\t\tswitch msg.Role {\n\t\tcase message.User:\n\t\t\tif cache, ok := m.cachedContent[msg.ID]; ok && cache.width == m.width {\n\t\t\t\tm.uiMessages = append(m.uiMessages, cache.content...)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tuserMsg := renderUserMessage(\n\t\t\t\tmsg,\n\t\t\t\tmsg.ID == m.currentMsgID,\n\t\t\t\tm.width,\n\t\t\t\tpos,\n\t\t\t)\n\t\t\tm.uiMessages = append(m.uiMessages, userMsg)\n\t\t\tm.cachedContent[msg.ID] = cacheItem{\n\t\t\t\twidth: m.width,\n\t\t\t\tcontent: []uiMessage{userMsg},\n\t\t\t}\n\t\t\tpos += userMsg.height + 1 // + 1 for spacing\n\t\tcase message.Assistant:\n\t\t\tif cache, ok := m.cachedContent[msg.ID]; ok && cache.width == m.width {\n\t\t\t\tm.uiMessages = append(m.uiMessages, cache.content...)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tisSummary := m.session.SummaryMessageID == msg.ID\n\n\t\t\tassistantMessages := renderAssistantMessage(\n\t\t\t\tmsg,\n\t\t\t\tinx,\n\t\t\t\tm.messages,\n\t\t\t\tm.app.Messages,\n\t\t\t\tm.currentMsgID,\n\t\t\t\tisSummary,\n\t\t\t\tm.width,\n\t\t\t\tpos,\n\t\t\t)\n\t\t\tfor _, msg := range assistantMessages {\n\t\t\t\tm.uiMessages = append(m.uiMessages, msg)\n\t\t\t\tpos += msg.height + 1 // + 1 for spacing\n\t\t\t}\n\t\t\tm.cachedContent[msg.ID] = cacheItem{\n\t\t\t\twidth: m.width,\n\t\t\t\tcontent: assistantMessages,\n\t\t\t}\n\t\t}\n\t}\n\n\tmessages := make([]string, 0)\n\tfor _, v := range m.uiMessages {\n\t\tmessages = append(messages, lipgloss.JoinVertical(lipgloss.Left, v.content),\n\t\t\tbaseStyle.\n\t\t\t\tWidth(m.width).\n\t\t\t\tRender(\n\t\t\t\t\t\"\",\n\t\t\t\t),\n\t\t)\n\t}\n\n\tm.viewport.SetContent(\n\t\tbaseStyle.\n\t\t\tWidth(m.width).\n\t\t\tRender(\n\t\t\t\tlipgloss.JoinVertical(\n\t\t\t\t\tlipgloss.Top,\n\t\t\t\t\tmessages...,\n\t\t\t\t),\n\t\t\t),\n\t)\n}\n\nfunc (m *messagesCmp) View() string {\n\tbaseStyle := styles.BaseStyle()\n\n\tif m.rendering {\n\t\treturn baseStyle.\n\t\t\tWidth(m.width).\n\t\t\tRender(\n\t\t\t\tlipgloss.JoinVertical(\n\t\t\t\t\tlipgloss.Top,\n\t\t\t\t\t\"Loading...\",\n\t\t\t\t\tm.working(),\n\t\t\t\t\tm.help(),\n\t\t\t\t),\n\t\t\t)\n\t}\n\tif len(m.messages) == 0 {\n\t\tcontent := baseStyle.\n\t\t\tWidth(m.width).\n\t\t\tHeight(m.height - 1).\n\t\t\tRender(\n\t\t\t\tm.initialScreen(),\n\t\t\t)\n\n\t\treturn baseStyle.\n\t\t\tWidth(m.width).\n\t\t\tRender(\n\t\t\t\tlipgloss.JoinVertical(\n\t\t\t\t\tlipgloss.Top,\n\t\t\t\t\tcontent,\n\t\t\t\t\t\"\",\n\t\t\t\t\tm.help(),\n\t\t\t\t),\n\t\t\t)\n\t}\n\n\treturn baseStyle.\n\t\tWidth(m.width).\n\t\tRender(\n\t\t\tlipgloss.JoinVertical(\n\t\t\t\tlipgloss.Top,\n\t\t\t\tm.viewport.View(),\n\t\t\t\tm.working(),\n\t\t\t\tm.help(),\n\t\t\t),\n\t\t)\n}\n\nfunc hasToolsWithoutResponse(messages []message.Message) bool {\n\ttoolCalls := make([]message.ToolCall, 0)\n\ttoolResults := make([]message.ToolResult, 0)\n\tfor _, m := range messages {\n\t\ttoolCalls = append(toolCalls, m.ToolCalls()...)\n\t\ttoolResults = append(toolResults, m.ToolResults()...)\n\t}\n\n\tfor _, v := range toolCalls {\n\t\tfound := false\n\t\tfor _, r := range toolResults {\n\t\t\tif v.ID == r.ToolCallID {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif !found && v.Finished {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc hasUnfinishedToolCalls(messages []message.Message) bool {\n\ttoolCalls := make([]message.ToolCall, 0)\n\tfor _, m := range messages {\n\t\ttoolCalls = append(toolCalls, m.ToolCalls()...)\n\t}\n\tfor _, v := range toolCalls {\n\t\tif !v.Finished {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc (m *messagesCmp) working() string {\n\ttext := \"\"\n\tif m.IsAgentWorking() && len(m.messages) > 0 {\n\t\tt := theme.CurrentTheme()\n\t\tbaseStyle := styles.BaseStyle()\n\n\t\ttask := \"Thinking...\"\n\t\tlastMessage := m.messages[len(m.messages)-1]\n\t\tif hasToolsWithoutResponse(m.messages) {\n\t\t\ttask = \"Waiting for tool response...\"\n\t\t} else if hasUnfinishedToolCalls(m.messages) {\n\t\t\ttask = \"Building tool call...\"\n\t\t} else if !lastMessage.IsFinished() {\n\t\t\ttask = \"Generating...\"\n\t\t}\n\t\tif task != \"\" {\n\t\t\ttext += baseStyle.\n\t\t\t\tWidth(m.width).\n\t\t\t\tForeground(t.Primary()).\n\t\t\t\tBold(true).\n\t\t\t\tRender(fmt.Sprintf(\"%s %s \", m.spinner.View(), task))\n\t\t}\n\t}\n\treturn text\n}\n\nfunc (m *messagesCmp) help() string {\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\n\ttext := \"\"\n\n\tif m.app.CoderAgent.IsBusy() {\n\t\ttext += lipgloss.JoinHorizontal(\n\t\t\tlipgloss.Left,\n\t\t\tbaseStyle.Foreground(t.TextMuted()).Bold(true).Render(\"press \"),\n\t\t\tbaseStyle.Foreground(t.Text()).Bold(true).Render(\"esc\"),\n\t\t\tbaseStyle.Foreground(t.TextMuted()).Bold(true).Render(\" to exit cancel\"),\n\t\t)\n\t} else {\n\t\ttext += lipgloss.JoinHorizontal(\n\t\t\tlipgloss.Left,\n\t\t\tbaseStyle.Foreground(t.TextMuted()).Bold(true).Render(\"press \"),\n\t\t\tbaseStyle.Foreground(t.Text()).Bold(true).Render(\"enter\"),\n\t\t\tbaseStyle.Foreground(t.TextMuted()).Bold(true).Render(\" to send the message,\"),\n\t\t\tbaseStyle.Foreground(t.TextMuted()).Bold(true).Render(\" write\"),\n\t\t\tbaseStyle.Foreground(t.Text()).Bold(true).Render(\" \\\\\"),\n\t\t\tbaseStyle.Foreground(t.TextMuted()).Bold(true).Render(\" and enter to add a new line\"),\n\t\t)\n\t}\n\treturn baseStyle.\n\t\tWidth(m.width).\n\t\tRender(text)\n}\n\nfunc (m *messagesCmp) initialScreen() string {\n\tbaseStyle := styles.BaseStyle()\n\n\treturn baseStyle.Width(m.width).Render(\n\t\tlipgloss.JoinVertical(\n\t\t\tlipgloss.Top,\n\t\t\theader(m.width),\n\t\t\t\"\",\n\t\t\tlspsConfigured(m.width),\n\t\t),\n\t)\n}\n\nfunc (m *messagesCmp) rerender() {\n\tfor _, msg := range m.messages {\n\t\tdelete(m.cachedContent, msg.ID)\n\t}\n\tm.renderView()\n}\n\nfunc (m *messagesCmp) SetSize(width, height int) tea.Cmd {\n\tif m.width == width && m.height == height {\n\t\treturn nil\n\t}\n\tm.width = width\n\tm.height = height\n\tm.viewport.Width = width\n\tm.viewport.Height = height - 2\n\tm.attachments.Width = width + 40\n\tm.attachments.Height = 3\n\tm.rerender()\n\treturn nil\n}\n\nfunc (m *messagesCmp) GetSize() (int, int) {\n\treturn m.width, m.height\n}\n\nfunc (m *messagesCmp) SetSession(session session.Session) tea.Cmd {\n\tif m.session.ID == session.ID {\n\t\treturn nil\n\t}\n\tm.session = session\n\tmessages, err := m.app.Messages.List(context.Background(), session.ID)\n\tif err != nil {\n\t\treturn util.ReportError(err)\n\t}\n\tm.messages = messages\n\tif len(m.messages) > 0 {\n\t\tm.currentMsgID = m.messages[len(m.messages)-1].ID\n\t}\n\tdelete(m.cachedContent, m.currentMsgID)\n\tm.rendering = true\n\treturn func() tea.Msg {\n\t\tm.renderView()\n\t\treturn renderFinishedMsg{}\n\t}\n}\n\nfunc (m *messagesCmp) BindingKeys() []key.Binding {\n\treturn []key.Binding{\n\t\tm.viewport.KeyMap.PageDown,\n\t\tm.viewport.KeyMap.PageUp,\n\t\tm.viewport.KeyMap.HalfPageUp,\n\t\tm.viewport.KeyMap.HalfPageDown,\n\t}\n}\n\nfunc NewMessagesCmp(app *app.App) tea.Model {\n\ts := spinner.New()\n\ts.Spinner = spinner.Pulse\n\tvp := viewport.New(0, 0)\n\tattachmets := viewport.New(0, 0)\n\tvp.KeyMap.PageUp = messageKeys.PageUp\n\tvp.KeyMap.PageDown = messageKeys.PageDown\n\tvp.KeyMap.HalfPageUp = messageKeys.HalfPageUp\n\tvp.KeyMap.HalfPageDown = messageKeys.HalfPageDown\n\treturn &messagesCmp{\n\t\tapp: app,\n\t\tcachedContent: make(map[string]cacheItem),\n\t\tviewport: vp,\n\t\tspinner: s,\n\t\tattachments: attachmets,\n\t}\n}\n"], ["/opencode/internal/tui/components/dialog/filepicker.go", "package dialog\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"sort\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/charmbracelet/bubbles/key\"\n\t\"github.com/charmbracelet/bubbles/textinput\"\n\t\"github.com/charmbracelet/bubbles/viewport\"\n\ttea \"github.com/charmbracelet/bubbletea\"\n\t\"github.com/charmbracelet/lipgloss\"\n\t\"github.com/opencode-ai/opencode/internal/app\"\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n\t\"github.com/opencode-ai/opencode/internal/message\"\n\t\"github.com/opencode-ai/opencode/internal/tui/image\"\n\t\"github.com/opencode-ai/opencode/internal/tui/styles\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n\t\"github.com/opencode-ai/opencode/internal/tui/util\"\n)\n\nconst (\n\tmaxAttachmentSize = int64(5 * 1024 * 1024) // 5MB\n\tdownArrow = \"down\"\n\tupArrow = \"up\"\n)\n\ntype FilePrickerKeyMap struct {\n\tEnter key.Binding\n\tDown key.Binding\n\tUp key.Binding\n\tForward key.Binding\n\tBackward key.Binding\n\tOpenFilePicker key.Binding\n\tEsc key.Binding\n\tInsertCWD key.Binding\n}\n\nvar filePickerKeyMap = FilePrickerKeyMap{\n\tEnter: key.NewBinding(\n\t\tkey.WithKeys(\"enter\"),\n\t\tkey.WithHelp(\"enter\", \"select file/enter directory\"),\n\t),\n\tDown: key.NewBinding(\n\t\tkey.WithKeys(\"j\", downArrow),\n\t\tkey.WithHelp(\"↓/j\", \"down\"),\n\t),\n\tUp: key.NewBinding(\n\t\tkey.WithKeys(\"k\", upArrow),\n\t\tkey.WithHelp(\"↑/k\", \"up\"),\n\t),\n\tForward: key.NewBinding(\n\t\tkey.WithKeys(\"l\"),\n\t\tkey.WithHelp(\"l\", \"enter directory\"),\n\t),\n\tBackward: key.NewBinding(\n\t\tkey.WithKeys(\"h\", \"backspace\"),\n\t\tkey.WithHelp(\"h/backspace\", \"go back\"),\n\t),\n\tOpenFilePicker: key.NewBinding(\n\t\tkey.WithKeys(\"ctrl+f\"),\n\t\tkey.WithHelp(\"ctrl+f\", \"open file picker\"),\n\t),\n\tEsc: key.NewBinding(\n\t\tkey.WithKeys(\"esc\"),\n\t\tkey.WithHelp(\"esc\", \"close/exit\"),\n\t),\n\tInsertCWD: key.NewBinding(\n\t\tkey.WithKeys(\"i\"),\n\t\tkey.WithHelp(\"i\", \"manual path input\"),\n\t),\n}\n\ntype filepickerCmp struct {\n\tbasePath string\n\twidth int\n\theight int\n\tcursor int\n\terr error\n\tcursorChain stack\n\tviewport viewport.Model\n\tdirs []os.DirEntry\n\tcwdDetails *DirNode\n\tselectedFile string\n\tcwd textinput.Model\n\tShowFilePicker bool\n\tapp *app.App\n}\n\ntype DirNode struct {\n\tparent *DirNode\n\tchild *DirNode\n\tdirectory string\n}\ntype stack []int\n\nfunc (s stack) Push(v int) stack {\n\treturn append(s, v)\n}\n\nfunc (s stack) Pop() (stack, int) {\n\tl := len(s)\n\treturn s[:l-1], s[l-1]\n}\n\ntype AttachmentAddedMsg struct {\n\tAttachment message.Attachment\n}\n\nfunc (f *filepickerCmp) Init() tea.Cmd {\n\treturn nil\n}\n\nfunc (f *filepickerCmp) Update(msg tea.Msg) (tea.Model, tea.Cmd) {\n\tvar cmd tea.Cmd\n\tswitch msg := msg.(type) {\n\tcase tea.WindowSizeMsg:\n\t\tf.width = 60\n\t\tf.height = 20\n\t\tf.viewport.Width = 80\n\t\tf.viewport.Height = 22\n\t\tf.cursor = 0\n\t\tf.getCurrentFileBelowCursor()\n\tcase tea.KeyMsg:\n\t\tif f.cwd.Focused() {\n\t\t\tf.cwd, cmd = f.cwd.Update(msg)\n\t\t}\n\t\tswitch {\n\t\tcase key.Matches(msg, filePickerKeyMap.InsertCWD):\n\t\t\tf.cwd.Focus()\n\t\t\treturn f, cmd\n\t\tcase key.Matches(msg, filePickerKeyMap.Esc):\n\t\t\tif f.cwd.Focused() {\n\t\t\t\tf.cwd.Blur()\n\t\t\t}\n\t\tcase key.Matches(msg, filePickerKeyMap.Down):\n\t\t\tif !f.cwd.Focused() || msg.String() == downArrow {\n\t\t\t\tif f.cursor < len(f.dirs)-1 {\n\t\t\t\t\tf.cursor++\n\t\t\t\t\tf.getCurrentFileBelowCursor()\n\t\t\t\t}\n\t\t\t}\n\t\tcase key.Matches(msg, filePickerKeyMap.Up):\n\t\t\tif !f.cwd.Focused() || msg.String() == upArrow {\n\t\t\t\tif f.cursor > 0 {\n\t\t\t\t\tf.cursor--\n\t\t\t\t\tf.getCurrentFileBelowCursor()\n\t\t\t\t}\n\t\t\t}\n\t\tcase key.Matches(msg, filePickerKeyMap.Enter):\n\t\t\tvar path string\n\t\t\tvar isPathDir bool\n\t\t\tif f.cwd.Focused() {\n\t\t\t\tpath = f.cwd.Value()\n\t\t\t\tfileInfo, err := os.Stat(path)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlogging.ErrorPersist(\"Invalid path\")\n\t\t\t\t\treturn f, cmd\n\t\t\t\t}\n\t\t\t\tisPathDir = fileInfo.IsDir()\n\t\t\t} else {\n\t\t\t\tpath = filepath.Join(f.cwdDetails.directory, \"/\", f.dirs[f.cursor].Name())\n\t\t\t\tisPathDir = f.dirs[f.cursor].IsDir()\n\t\t\t}\n\t\t\tif isPathDir {\n\t\t\t\tnewWorkingDir := DirNode{parent: f.cwdDetails, directory: path}\n\t\t\t\tf.cwdDetails.child = &newWorkingDir\n\t\t\t\tf.cwdDetails = f.cwdDetails.child\n\t\t\t\tf.cursorChain = f.cursorChain.Push(f.cursor)\n\t\t\t\tf.dirs = readDir(f.cwdDetails.directory, false)\n\t\t\t\tf.cursor = 0\n\t\t\t\tf.cwd.SetValue(f.cwdDetails.directory)\n\t\t\t\tf.getCurrentFileBelowCursor()\n\t\t\t} else {\n\t\t\t\tf.selectedFile = path\n\t\t\t\treturn f.addAttachmentToMessage()\n\t\t\t}\n\t\tcase key.Matches(msg, filePickerKeyMap.Esc):\n\t\t\tif !f.cwd.Focused() {\n\t\t\t\tf.cursorChain = make(stack, 0)\n\t\t\t\tf.cursor = 0\n\t\t\t} else {\n\t\t\t\tf.cwd.Blur()\n\t\t\t}\n\t\tcase key.Matches(msg, filePickerKeyMap.Forward):\n\t\t\tif !f.cwd.Focused() {\n\t\t\t\tif f.dirs[f.cursor].IsDir() {\n\t\t\t\t\tpath := filepath.Join(f.cwdDetails.directory, \"/\", f.dirs[f.cursor].Name())\n\t\t\t\t\tnewWorkingDir := DirNode{parent: f.cwdDetails, directory: path}\n\t\t\t\t\tf.cwdDetails.child = &newWorkingDir\n\t\t\t\t\tf.cwdDetails = f.cwdDetails.child\n\t\t\t\t\tf.cursorChain = f.cursorChain.Push(f.cursor)\n\t\t\t\t\tf.dirs = readDir(f.cwdDetails.directory, false)\n\t\t\t\t\tf.cursor = 0\n\t\t\t\t\tf.cwd.SetValue(f.cwdDetails.directory)\n\t\t\t\t\tf.getCurrentFileBelowCursor()\n\t\t\t\t}\n\t\t\t}\n\t\tcase key.Matches(msg, filePickerKeyMap.Backward):\n\t\t\tif !f.cwd.Focused() {\n\t\t\t\tif len(f.cursorChain) != 0 && f.cwdDetails.parent != nil {\n\t\t\t\t\tf.cursorChain, f.cursor = f.cursorChain.Pop()\n\t\t\t\t\tf.cwdDetails = f.cwdDetails.parent\n\t\t\t\t\tf.cwdDetails.child = nil\n\t\t\t\t\tf.dirs = readDir(f.cwdDetails.directory, false)\n\t\t\t\t\tf.cwd.SetValue(f.cwdDetails.directory)\n\t\t\t\t\tf.getCurrentFileBelowCursor()\n\t\t\t\t}\n\t\t\t}\n\t\tcase key.Matches(msg, filePickerKeyMap.OpenFilePicker):\n\t\t\tf.dirs = readDir(f.cwdDetails.directory, false)\n\t\t\tf.cursor = 0\n\t\t\tf.getCurrentFileBelowCursor()\n\t\t}\n\t}\n\treturn f, cmd\n}\n\nfunc (f *filepickerCmp) addAttachmentToMessage() (tea.Model, tea.Cmd) {\n\tmodeInfo := GetSelectedModel(config.Get())\n\tif !modeInfo.SupportsAttachments {\n\t\tlogging.ErrorPersist(fmt.Sprintf(\"Model %s doesn't support attachments\", modeInfo.Name))\n\t\treturn f, nil\n\t}\n\n\tselectedFilePath := f.selectedFile\n\tif !isExtSupported(selectedFilePath) {\n\t\tlogging.ErrorPersist(\"Unsupported file\")\n\t\treturn f, nil\n\t}\n\n\tisFileLarge, err := image.ValidateFileSize(selectedFilePath, maxAttachmentSize)\n\tif err != nil {\n\t\tlogging.ErrorPersist(\"unable to read the image\")\n\t\treturn f, nil\n\t}\n\tif isFileLarge {\n\t\tlogging.ErrorPersist(\"file too large, max 5MB\")\n\t\treturn f, nil\n\t}\n\n\tcontent, err := os.ReadFile(selectedFilePath)\n\tif err != nil {\n\t\tlogging.ErrorPersist(\"Unable read selected file\")\n\t\treturn f, nil\n\t}\n\n\tmimeBufferSize := min(512, len(content))\n\tmimeType := http.DetectContentType(content[:mimeBufferSize])\n\tfileName := filepath.Base(selectedFilePath)\n\tattachment := message.Attachment{FilePath: selectedFilePath, FileName: fileName, MimeType: mimeType, Content: content}\n\tf.selectedFile = \"\"\n\treturn f, util.CmdHandler(AttachmentAddedMsg{attachment})\n}\n\nfunc (f *filepickerCmp) View() string {\n\tt := theme.CurrentTheme()\n\tconst maxVisibleDirs = 20\n\tconst maxWidth = 80\n\n\tadjustedWidth := maxWidth\n\tfor _, file := range f.dirs {\n\t\tif len(file.Name()) > adjustedWidth-4 { // Account for padding\n\t\t\tadjustedWidth = len(file.Name()) + 4\n\t\t}\n\t}\n\tadjustedWidth = max(30, min(adjustedWidth, f.width-15)) + 1\n\n\tfiles := make([]string, 0, maxVisibleDirs)\n\tstartIdx := 0\n\n\tif len(f.dirs) > maxVisibleDirs {\n\t\thalfVisible := maxVisibleDirs / 2\n\t\tif f.cursor >= halfVisible && f.cursor < len(f.dirs)-halfVisible {\n\t\t\tstartIdx = f.cursor - halfVisible\n\t\t} else if f.cursor >= len(f.dirs)-halfVisible {\n\t\t\tstartIdx = len(f.dirs) - maxVisibleDirs\n\t\t}\n\t}\n\n\tendIdx := min(startIdx+maxVisibleDirs, len(f.dirs))\n\n\tfor i := startIdx; i < endIdx; i++ {\n\t\tfile := f.dirs[i]\n\t\titemStyle := styles.BaseStyle().Width(adjustedWidth)\n\n\t\tif i == f.cursor {\n\t\t\titemStyle = itemStyle.\n\t\t\t\tBackground(t.Primary()).\n\t\t\t\tForeground(t.Background()).\n\t\t\t\tBold(true)\n\t\t}\n\t\tfilename := file.Name()\n\n\t\tif len(filename) > adjustedWidth-4 {\n\t\t\tfilename = filename[:adjustedWidth-7] + \"...\"\n\t\t}\n\t\tif file.IsDir() {\n\t\t\tfilename = filename + \"/\"\n\t\t}\n\t\t// No need to reassign filename if it's not changing\n\n\t\tfiles = append(files, itemStyle.Padding(0, 1).Render(filename))\n\t}\n\n\t// Pad to always show exactly 21 lines\n\tfor len(files) < maxVisibleDirs {\n\t\tfiles = append(files, styles.BaseStyle().Width(adjustedWidth).Render(\"\"))\n\t}\n\n\tcurrentPath := styles.BaseStyle().\n\t\tHeight(1).\n\t\tWidth(adjustedWidth).\n\t\tRender(f.cwd.View())\n\n\tviewportstyle := lipgloss.NewStyle().\n\t\tWidth(f.viewport.Width).\n\t\tBackground(t.Background()).\n\t\tBorder(lipgloss.RoundedBorder()).\n\t\tBorderForeground(t.TextMuted()).\n\t\tBorderBackground(t.Background()).\n\t\tPadding(2).\n\t\tRender(f.viewport.View())\n\tvar insertExitText string\n\tif f.IsCWDFocused() {\n\t\tinsertExitText = \"Press esc to exit typing path\"\n\t} else {\n\t\tinsertExitText = \"Press i to start typing path\"\n\t}\n\n\tcontent := lipgloss.JoinVertical(\n\t\tlipgloss.Left,\n\t\tcurrentPath,\n\t\tstyles.BaseStyle().Width(adjustedWidth).Render(\"\"),\n\t\tstyles.BaseStyle().Width(adjustedWidth).Render(lipgloss.JoinVertical(lipgloss.Left, files...)),\n\t\tstyles.BaseStyle().Width(adjustedWidth).Render(\"\"),\n\t\tstyles.BaseStyle().Foreground(t.TextMuted()).Width(adjustedWidth).Render(insertExitText),\n\t)\n\n\tf.cwd.SetValue(f.cwd.Value())\n\tcontentStyle := styles.BaseStyle().Padding(1, 2).\n\t\tBorder(lipgloss.RoundedBorder()).\n\t\tBorderBackground(t.Background()).\n\t\tBorderForeground(t.TextMuted()).\n\t\tWidth(lipgloss.Width(content) + 4)\n\n\treturn lipgloss.JoinHorizontal(lipgloss.Center, contentStyle.Render(content), viewportstyle)\n}\n\ntype FilepickerCmp interface {\n\ttea.Model\n\tToggleFilepicker(showFilepicker bool)\n\tIsCWDFocused() bool\n}\n\nfunc (f *filepickerCmp) ToggleFilepicker(showFilepicker bool) {\n\tf.ShowFilePicker = showFilepicker\n}\n\nfunc (f *filepickerCmp) IsCWDFocused() bool {\n\treturn f.cwd.Focused()\n}\n\nfunc NewFilepickerCmp(app *app.App) FilepickerCmp {\n\thomepath, err := os.UserHomeDir()\n\tif err != nil {\n\t\tlogging.Error(\"error loading user files\")\n\t\treturn nil\n\t}\n\tbaseDir := DirNode{parent: nil, directory: homepath}\n\tdirs := readDir(homepath, false)\n\tviewport := viewport.New(0, 0)\n\tcurrentDirectory := textinput.New()\n\tcurrentDirectory.CharLimit = 200\n\tcurrentDirectory.Width = 44\n\tcurrentDirectory.Cursor.Blink = true\n\tcurrentDirectory.SetValue(baseDir.directory)\n\treturn &filepickerCmp{cwdDetails: &baseDir, dirs: dirs, cursorChain: make(stack, 0), viewport: viewport, cwd: currentDirectory, app: app}\n}\n\nfunc (f *filepickerCmp) getCurrentFileBelowCursor() {\n\tif len(f.dirs) == 0 || f.cursor < 0 || f.cursor >= len(f.dirs) {\n\t\tlogging.Error(fmt.Sprintf(\"Invalid cursor position. Dirs length: %d, Cursor: %d\", len(f.dirs), f.cursor))\n\t\tf.viewport.SetContent(\"Preview unavailable\")\n\t\treturn\n\t}\n\n\tdir := f.dirs[f.cursor]\n\tfilename := dir.Name()\n\tif !dir.IsDir() && isExtSupported(filename) {\n\t\tfullPath := f.cwdDetails.directory + \"/\" + dir.Name()\n\n\t\tgo func() {\n\t\t\timageString, err := image.ImagePreview(f.viewport.Width-4, fullPath)\n\t\t\tif err != nil {\n\t\t\t\tlogging.Error(err.Error())\n\t\t\t\tf.viewport.SetContent(\"Preview unavailable\")\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tf.viewport.SetContent(imageString)\n\t\t}()\n\t} else {\n\t\tf.viewport.SetContent(\"Preview unavailable\")\n\t}\n}\n\nfunc readDir(path string, showHidden bool) []os.DirEntry {\n\tlogging.Info(fmt.Sprintf(\"Reading directory: %s\", path))\n\n\tentriesChan := make(chan []os.DirEntry, 1)\n\terrChan := make(chan error, 1)\n\n\tgo func() {\n\t\tdirEntries, err := os.ReadDir(path)\n\t\tif err != nil {\n\t\t\tlogging.ErrorPersist(err.Error())\n\t\t\terrChan <- err\n\t\t\treturn\n\t\t}\n\t\tentriesChan <- dirEntries\n\t}()\n\n\tselect {\n\tcase dirEntries := <-entriesChan:\n\t\tsort.Slice(dirEntries, func(i, j int) bool {\n\t\t\tif dirEntries[i].IsDir() == dirEntries[j].IsDir() {\n\t\t\t\treturn dirEntries[i].Name() < dirEntries[j].Name()\n\t\t\t}\n\t\t\treturn dirEntries[i].IsDir()\n\t\t})\n\n\t\tif showHidden {\n\t\t\treturn dirEntries\n\t\t}\n\n\t\tvar sanitizedDirEntries []os.DirEntry\n\t\tfor _, dirEntry := range dirEntries {\n\t\t\tisHidden, _ := IsHidden(dirEntry.Name())\n\t\t\tif !isHidden {\n\t\t\t\tif dirEntry.IsDir() || isExtSupported(dirEntry.Name()) {\n\t\t\t\t\tsanitizedDirEntries = append(sanitizedDirEntries, dirEntry)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn sanitizedDirEntries\n\n\tcase err := <-errChan:\n\t\tlogging.ErrorPersist(fmt.Sprintf(\"Error reading directory %s\", path), err)\n\t\treturn []os.DirEntry{}\n\n\tcase <-time.After(5 * time.Second):\n\t\tlogging.ErrorPersist(fmt.Sprintf(\"Timeout reading directory %s\", path), nil)\n\t\treturn []os.DirEntry{}\n\t}\n}\n\nfunc IsHidden(file string) (bool, error) {\n\treturn strings.HasPrefix(file, \".\"), nil\n}\n\nfunc isExtSupported(path string) bool {\n\text := strings.ToLower(filepath.Ext(path))\n\treturn (ext == \".jpg\" || ext == \".jpeg\" || ext == \".webp\" || ext == \".png\")\n}\n"], ["/opencode/internal/tui/components/dialog/commands.go", "package dialog\n\nimport (\n\t\"github.com/charmbracelet/bubbles/key\"\n\ttea \"github.com/charmbracelet/bubbletea\"\n\t\"github.com/charmbracelet/lipgloss\"\n\tutilComponents \"github.com/opencode-ai/opencode/internal/tui/components/util\"\n\t\"github.com/opencode-ai/opencode/internal/tui/layout\"\n\t\"github.com/opencode-ai/opencode/internal/tui/styles\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n\t\"github.com/opencode-ai/opencode/internal/tui/util\"\n)\n\n// Command represents a command that can be executed\ntype Command struct {\n\tID string\n\tTitle string\n\tDescription string\n\tHandler func(cmd Command) tea.Cmd\n}\n\nfunc (ci Command) Render(selected bool, width int) string {\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\n\tdescStyle := baseStyle.Width(width).Foreground(t.TextMuted())\n\titemStyle := baseStyle.Width(width).\n\t\tForeground(t.Text()).\n\t\tBackground(t.Background())\n\n\tif selected {\n\t\titemStyle = itemStyle.\n\t\t\tBackground(t.Primary()).\n\t\t\tForeground(t.Background()).\n\t\t\tBold(true)\n\t\tdescStyle = descStyle.\n\t\t\tBackground(t.Primary()).\n\t\t\tForeground(t.Background())\n\t}\n\n\ttitle := itemStyle.Padding(0, 1).Render(ci.Title)\n\tif ci.Description != \"\" {\n\t\tdescription := descStyle.Padding(0, 1).Render(ci.Description)\n\t\treturn lipgloss.JoinVertical(lipgloss.Left, title, description)\n\t}\n\treturn title\n}\n\n// CommandSelectedMsg is sent when a command is selected\ntype CommandSelectedMsg struct {\n\tCommand Command\n}\n\n// CloseCommandDialogMsg is sent when the command dialog is closed\ntype CloseCommandDialogMsg struct{}\n\n// CommandDialog interface for the command selection dialog\ntype CommandDialog interface {\n\ttea.Model\n\tlayout.Bindings\n\tSetCommands(commands []Command)\n}\n\ntype commandDialogCmp struct {\n\tlistView utilComponents.SimpleList[Command]\n\twidth int\n\theight int\n}\n\ntype commandKeyMap struct {\n\tEnter key.Binding\n\tEscape key.Binding\n}\n\nvar commandKeys = commandKeyMap{\n\tEnter: key.NewBinding(\n\t\tkey.WithKeys(\"enter\"),\n\t\tkey.WithHelp(\"enter\", \"select command\"),\n\t),\n\tEscape: key.NewBinding(\n\t\tkey.WithKeys(\"esc\"),\n\t\tkey.WithHelp(\"esc\", \"close\"),\n\t),\n}\n\nfunc (c *commandDialogCmp) Init() tea.Cmd {\n\treturn c.listView.Init()\n}\n\nfunc (c *commandDialogCmp) Update(msg tea.Msg) (tea.Model, tea.Cmd) {\n\tvar cmds []tea.Cmd\n\tswitch msg := msg.(type) {\n\tcase tea.KeyMsg:\n\t\tswitch {\n\t\tcase key.Matches(msg, commandKeys.Enter):\n\t\t\tselectedItem, idx := c.listView.GetSelectedItem()\n\t\t\tif idx != -1 {\n\t\t\t\treturn c, util.CmdHandler(CommandSelectedMsg{\n\t\t\t\t\tCommand: selectedItem,\n\t\t\t\t})\n\t\t\t}\n\t\tcase key.Matches(msg, commandKeys.Escape):\n\t\t\treturn c, util.CmdHandler(CloseCommandDialogMsg{})\n\t\t}\n\tcase tea.WindowSizeMsg:\n\t\tc.width = msg.Width\n\t\tc.height = msg.Height\n\t}\n\n\tu, cmd := c.listView.Update(msg)\n\tc.listView = u.(utilComponents.SimpleList[Command])\n\tcmds = append(cmds, cmd)\n\n\treturn c, tea.Batch(cmds...)\n}\n\nfunc (c *commandDialogCmp) View() string {\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\n\tmaxWidth := 40\n\n\tcommands := c.listView.GetItems()\n\n\tfor _, cmd := range commands {\n\t\tif len(cmd.Title) > maxWidth-4 {\n\t\t\tmaxWidth = len(cmd.Title) + 4\n\t\t}\n\t\tif cmd.Description != \"\" {\n\t\t\tif len(cmd.Description) > maxWidth-4 {\n\t\t\t\tmaxWidth = len(cmd.Description) + 4\n\t\t\t}\n\t\t}\n\t}\n\n\tc.listView.SetMaxWidth(maxWidth)\n\n\ttitle := baseStyle.\n\t\tForeground(t.Primary()).\n\t\tBold(true).\n\t\tWidth(maxWidth).\n\t\tPadding(0, 1).\n\t\tRender(\"Commands\")\n\n\tcontent := lipgloss.JoinVertical(\n\t\tlipgloss.Left,\n\t\ttitle,\n\t\tbaseStyle.Width(maxWidth).Render(\"\"),\n\t\tbaseStyle.Width(maxWidth).Render(c.listView.View()),\n\t\tbaseStyle.Width(maxWidth).Render(\"\"),\n\t)\n\n\treturn baseStyle.Padding(1, 2).\n\t\tBorder(lipgloss.RoundedBorder()).\n\t\tBorderBackground(t.Background()).\n\t\tBorderForeground(t.TextMuted()).\n\t\tWidth(lipgloss.Width(content) + 4).\n\t\tRender(content)\n}\n\nfunc (c *commandDialogCmp) BindingKeys() []key.Binding {\n\treturn layout.KeyMapToSlice(commandKeys)\n}\n\nfunc (c *commandDialogCmp) SetCommands(commands []Command) {\n\tc.listView.SetItems(commands)\n}\n\n// NewCommandDialogCmp creates a new command selection dialog\nfunc NewCommandDialogCmp() CommandDialog {\n\tlistView := utilComponents.NewSimpleList[Command](\n\t\t[]Command{},\n\t\t10,\n\t\t\"No commands available\",\n\t\ttrue,\n\t)\n\treturn &commandDialogCmp{\n\t\tlistView: listView,\n\t}\n}\n"], ["/opencode/internal/diff/diff.go", "package diff\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\"\n\t\"regexp\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"github.com/alecthomas/chroma/v2\"\n\t\"github.com/alecthomas/chroma/v2/formatters\"\n\t\"github.com/alecthomas/chroma/v2/lexers\"\n\t\"github.com/alecthomas/chroma/v2/styles\"\n\t\"github.com/aymanbagabas/go-udiff\"\n\t\"github.com/charmbracelet/lipgloss\"\n\t\"github.com/charmbracelet/x/ansi\"\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n\t\"github.com/sergi/go-diff/diffmatchpatch\"\n)\n\n// -------------------------------------------------------------------------\n// Core Types\n// -------------------------------------------------------------------------\n\n// LineType represents the kind of line in a diff.\ntype LineType int\n\nconst (\n\tLineContext LineType = iota // Line exists in both files\n\tLineAdded // Line added in the new file\n\tLineRemoved // Line removed from the old file\n)\n\n// Segment represents a portion of a line for intra-line highlighting\ntype Segment struct {\n\tStart int\n\tEnd int\n\tType LineType\n\tText string\n}\n\n// DiffLine represents a single line in a diff\ntype DiffLine struct {\n\tOldLineNo int // Line number in old file (0 for added lines)\n\tNewLineNo int // Line number in new file (0 for removed lines)\n\tKind LineType // Type of line (added, removed, context)\n\tContent string // Content of the line\n\tSegments []Segment // Segments for intraline highlighting\n}\n\n// Hunk represents a section of changes in a diff\ntype Hunk struct {\n\tHeader string\n\tLines []DiffLine\n}\n\n// DiffResult contains the parsed result of a diff\ntype DiffResult struct {\n\tOldFile string\n\tNewFile string\n\tHunks []Hunk\n}\n\n// linePair represents a pair of lines for side-by-side display\ntype linePair struct {\n\tleft *DiffLine\n\tright *DiffLine\n}\n\n// -------------------------------------------------------------------------\n// Parse Configuration\n// -------------------------------------------------------------------------\n\n// ParseConfig configures the behavior of diff parsing\ntype ParseConfig struct {\n\tContextSize int // Number of context lines to include\n}\n\n// ParseOption modifies a ParseConfig\ntype ParseOption func(*ParseConfig)\n\n// WithContextSize sets the number of context lines to include\nfunc WithContextSize(size int) ParseOption {\n\treturn func(p *ParseConfig) {\n\t\tif size >= 0 {\n\t\t\tp.ContextSize = size\n\t\t}\n\t}\n}\n\n// -------------------------------------------------------------------------\n// Side-by-Side Configuration\n// -------------------------------------------------------------------------\n\n// SideBySideConfig configures the rendering of side-by-side diffs\ntype SideBySideConfig struct {\n\tTotalWidth int\n}\n\n// SideBySideOption modifies a SideBySideConfig\ntype SideBySideOption func(*SideBySideConfig)\n\n// NewSideBySideConfig creates a SideBySideConfig with default values\nfunc NewSideBySideConfig(opts ...SideBySideOption) SideBySideConfig {\n\tconfig := SideBySideConfig{\n\t\tTotalWidth: 160, // Default width for side-by-side view\n\t}\n\n\tfor _, opt := range opts {\n\t\topt(&config)\n\t}\n\n\treturn config\n}\n\n// WithTotalWidth sets the total width for side-by-side view\nfunc WithTotalWidth(width int) SideBySideOption {\n\treturn func(s *SideBySideConfig) {\n\t\tif width > 0 {\n\t\t\ts.TotalWidth = width\n\t\t}\n\t}\n}\n\n// -------------------------------------------------------------------------\n// Diff Parsing\n// -------------------------------------------------------------------------\n\n// ParseUnifiedDiff parses a unified diff format string into structured data\nfunc ParseUnifiedDiff(diff string) (DiffResult, error) {\n\tvar result DiffResult\n\tvar currentHunk *Hunk\n\n\thunkHeaderRe := regexp.MustCompile(`^@@ -(\\d+),?(\\d*) \\+(\\d+),?(\\d*) @@`)\n\tlines := strings.Split(diff, \"\\n\")\n\n\tvar oldLine, newLine int\n\tinFileHeader := true\n\n\tfor _, line := range lines {\n\t\t// Parse file headers\n\t\tif inFileHeader {\n\t\t\tif strings.HasPrefix(line, \"--- a/\") {\n\t\t\t\tresult.OldFile = strings.TrimPrefix(line, \"--- a/\")\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif strings.HasPrefix(line, \"+++ b/\") {\n\t\t\t\tresult.NewFile = strings.TrimPrefix(line, \"+++ b/\")\n\t\t\t\tinFileHeader = false\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\n\t\t// Parse hunk headers\n\t\tif matches := hunkHeaderRe.FindStringSubmatch(line); matches != nil {\n\t\t\tif currentHunk != nil {\n\t\t\t\tresult.Hunks = append(result.Hunks, *currentHunk)\n\t\t\t}\n\t\t\tcurrentHunk = &Hunk{\n\t\t\t\tHeader: line,\n\t\t\t\tLines: []DiffLine{},\n\t\t\t}\n\n\t\t\toldStart, _ := strconv.Atoi(matches[1])\n\t\t\tnewStart, _ := strconv.Atoi(matches[3])\n\t\t\toldLine = oldStart\n\t\t\tnewLine = newStart\n\t\t\tcontinue\n\t\t}\n\n\t\t// Ignore \"No newline at end of file\" markers\n\t\tif strings.HasPrefix(line, \"\\\\ No newline at end of file\") {\n\t\t\tcontinue\n\t\t}\n\n\t\tif currentHunk == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\t// Process the line based on its prefix\n\t\tif len(line) > 0 {\n\t\t\tswitch line[0] {\n\t\t\tcase '+':\n\t\t\t\tcurrentHunk.Lines = append(currentHunk.Lines, DiffLine{\n\t\t\t\t\tOldLineNo: 0,\n\t\t\t\t\tNewLineNo: newLine,\n\t\t\t\t\tKind: LineAdded,\n\t\t\t\t\tContent: line[1:],\n\t\t\t\t})\n\t\t\t\tnewLine++\n\t\t\tcase '-':\n\t\t\t\tcurrentHunk.Lines = append(currentHunk.Lines, DiffLine{\n\t\t\t\t\tOldLineNo: oldLine,\n\t\t\t\t\tNewLineNo: 0,\n\t\t\t\t\tKind: LineRemoved,\n\t\t\t\t\tContent: line[1:],\n\t\t\t\t})\n\t\t\t\toldLine++\n\t\t\tdefault:\n\t\t\t\tcurrentHunk.Lines = append(currentHunk.Lines, DiffLine{\n\t\t\t\t\tOldLineNo: oldLine,\n\t\t\t\t\tNewLineNo: newLine,\n\t\t\t\t\tKind: LineContext,\n\t\t\t\t\tContent: line,\n\t\t\t\t})\n\t\t\t\toldLine++\n\t\t\t\tnewLine++\n\t\t\t}\n\t\t} else {\n\t\t\t// Handle empty lines\n\t\t\tcurrentHunk.Lines = append(currentHunk.Lines, DiffLine{\n\t\t\t\tOldLineNo: oldLine,\n\t\t\t\tNewLineNo: newLine,\n\t\t\t\tKind: LineContext,\n\t\t\t\tContent: \"\",\n\t\t\t})\n\t\t\toldLine++\n\t\t\tnewLine++\n\t\t}\n\t}\n\n\t// Add the last hunk if there is one\n\tif currentHunk != nil {\n\t\tresult.Hunks = append(result.Hunks, *currentHunk)\n\t}\n\n\treturn result, nil\n}\n\n// HighlightIntralineChanges updates lines in a hunk to show character-level differences\nfunc HighlightIntralineChanges(h *Hunk) {\n\tvar updated []DiffLine\n\tdmp := diffmatchpatch.New()\n\n\tfor i := 0; i < len(h.Lines); i++ {\n\t\t// Look for removed line followed by added line\n\t\tif i+1 < len(h.Lines) &&\n\t\t\th.Lines[i].Kind == LineRemoved &&\n\t\t\th.Lines[i+1].Kind == LineAdded {\n\n\t\t\toldLine := h.Lines[i]\n\t\t\tnewLine := h.Lines[i+1]\n\n\t\t\t// Find character-level differences\n\t\t\tpatches := dmp.DiffMain(oldLine.Content, newLine.Content, false)\n\t\t\tpatches = dmp.DiffCleanupSemantic(patches)\n\t\t\tpatches = dmp.DiffCleanupMerge(patches)\n\t\t\tpatches = dmp.DiffCleanupEfficiency(patches)\n\n\t\t\tsegments := make([]Segment, 0)\n\n\t\t\tremoveStart := 0\n\t\t\taddStart := 0\n\t\t\tfor _, patch := range patches {\n\t\t\t\tswitch patch.Type {\n\t\t\t\tcase diffmatchpatch.DiffDelete:\n\t\t\t\t\tsegments = append(segments, Segment{\n\t\t\t\t\t\tStart: removeStart,\n\t\t\t\t\t\tEnd: removeStart + len(patch.Text),\n\t\t\t\t\t\tType: LineRemoved,\n\t\t\t\t\t\tText: patch.Text,\n\t\t\t\t\t})\n\t\t\t\t\tremoveStart += len(patch.Text)\n\t\t\t\tcase diffmatchpatch.DiffInsert:\n\t\t\t\t\tsegments = append(segments, Segment{\n\t\t\t\t\t\tStart: addStart,\n\t\t\t\t\t\tEnd: addStart + len(patch.Text),\n\t\t\t\t\t\tType: LineAdded,\n\t\t\t\t\t\tText: patch.Text,\n\t\t\t\t\t})\n\t\t\t\t\taddStart += len(patch.Text)\n\t\t\t\tdefault:\n\t\t\t\t\t// Context text, no highlighting needed\n\t\t\t\t\tremoveStart += len(patch.Text)\n\t\t\t\t\taddStart += len(patch.Text)\n\t\t\t\t}\n\t\t\t}\n\t\t\toldLine.Segments = segments\n\t\t\tnewLine.Segments = segments\n\n\t\t\tupdated = append(updated, oldLine, newLine)\n\t\t\ti++ // Skip the next line as we've already processed it\n\t\t} else {\n\t\t\tupdated = append(updated, h.Lines[i])\n\t\t}\n\t}\n\n\th.Lines = updated\n}\n\n// pairLines converts a flat list of diff lines to pairs for side-by-side display\nfunc pairLines(lines []DiffLine) []linePair {\n\tvar pairs []linePair\n\ti := 0\n\n\tfor i < len(lines) {\n\t\tswitch lines[i].Kind {\n\t\tcase LineRemoved:\n\t\t\t// Check if the next line is an addition, if so pair them\n\t\t\tif i+1 < len(lines) && lines[i+1].Kind == LineAdded {\n\t\t\t\tpairs = append(pairs, linePair{left: &lines[i], right: &lines[i+1]})\n\t\t\t\ti += 2\n\t\t\t} else {\n\t\t\t\tpairs = append(pairs, linePair{left: &lines[i], right: nil})\n\t\t\t\ti++\n\t\t\t}\n\t\tcase LineAdded:\n\t\t\tpairs = append(pairs, linePair{left: nil, right: &lines[i]})\n\t\t\ti++\n\t\tcase LineContext:\n\t\t\tpairs = append(pairs, linePair{left: &lines[i], right: &lines[i]})\n\t\t\ti++\n\t\t}\n\t}\n\n\treturn pairs\n}\n\n// -------------------------------------------------------------------------\n// Syntax Highlighting\n// -------------------------------------------------------------------------\n\n// SyntaxHighlight applies syntax highlighting to text based on file extension\nfunc SyntaxHighlight(w io.Writer, source, fileName, formatter string, bg lipgloss.TerminalColor) error {\n\tt := theme.CurrentTheme()\n\n\t// Determine the language lexer to use\n\tl := lexers.Match(fileName)\n\tif l == nil {\n\t\tl = lexers.Analyse(source)\n\t}\n\tif l == nil {\n\t\tl = lexers.Fallback\n\t}\n\tl = chroma.Coalesce(l)\n\n\t// Get the formatter\n\tf := formatters.Get(formatter)\n\tif f == nil {\n\t\tf = formatters.Fallback\n\t}\n\n\t// Dynamic theme based on current theme values\n\tsyntaxThemeXml := fmt.Sprintf(`\n\t\n`,\n\t\tgetColor(t.Background()), // Background\n\t\tgetColor(t.Text()), // Text\n\t\tgetColor(t.Text()), // Other\n\t\tgetColor(t.Error()), // Error\n\n\t\tgetColor(t.SyntaxKeyword()), // Keyword\n\t\tgetColor(t.SyntaxKeyword()), // KeywordConstant\n\t\tgetColor(t.SyntaxKeyword()), // KeywordDeclaration\n\t\tgetColor(t.SyntaxKeyword()), // KeywordNamespace\n\t\tgetColor(t.SyntaxKeyword()), // KeywordPseudo\n\t\tgetColor(t.SyntaxKeyword()), // KeywordReserved\n\t\tgetColor(t.SyntaxType()), // KeywordType\n\n\t\tgetColor(t.Text()), // Name\n\t\tgetColor(t.SyntaxVariable()), // NameAttribute\n\t\tgetColor(t.SyntaxType()), // NameBuiltin\n\t\tgetColor(t.SyntaxVariable()), // NameBuiltinPseudo\n\t\tgetColor(t.SyntaxType()), // NameClass\n\t\tgetColor(t.SyntaxVariable()), // NameConstant\n\t\tgetColor(t.SyntaxFunction()), // NameDecorator\n\t\tgetColor(t.SyntaxVariable()), // NameEntity\n\t\tgetColor(t.SyntaxType()), // NameException\n\t\tgetColor(t.SyntaxFunction()), // NameFunction\n\t\tgetColor(t.Text()), // NameLabel\n\t\tgetColor(t.SyntaxType()), // NameNamespace\n\t\tgetColor(t.SyntaxVariable()), // NameOther\n\t\tgetColor(t.SyntaxKeyword()), // NameTag\n\t\tgetColor(t.SyntaxVariable()), // NameVariable\n\t\tgetColor(t.SyntaxVariable()), // NameVariableClass\n\t\tgetColor(t.SyntaxVariable()), // NameVariableGlobal\n\t\tgetColor(t.SyntaxVariable()), // NameVariableInstance\n\n\t\tgetColor(t.SyntaxString()), // Literal\n\t\tgetColor(t.SyntaxString()), // LiteralDate\n\t\tgetColor(t.SyntaxString()), // LiteralString\n\t\tgetColor(t.SyntaxString()), // LiteralStringBacktick\n\t\tgetColor(t.SyntaxString()), // LiteralStringChar\n\t\tgetColor(t.SyntaxString()), // LiteralStringDoc\n\t\tgetColor(t.SyntaxString()), // LiteralStringDouble\n\t\tgetColor(t.SyntaxString()), // LiteralStringEscape\n\t\tgetColor(t.SyntaxString()), // LiteralStringHeredoc\n\t\tgetColor(t.SyntaxString()), // LiteralStringInterpol\n\t\tgetColor(t.SyntaxString()), // LiteralStringOther\n\t\tgetColor(t.SyntaxString()), // LiteralStringRegex\n\t\tgetColor(t.SyntaxString()), // LiteralStringSingle\n\t\tgetColor(t.SyntaxString()), // LiteralStringSymbol\n\n\t\tgetColor(t.SyntaxNumber()), // LiteralNumber\n\t\tgetColor(t.SyntaxNumber()), // LiteralNumberBin\n\t\tgetColor(t.SyntaxNumber()), // LiteralNumberFloat\n\t\tgetColor(t.SyntaxNumber()), // LiteralNumberHex\n\t\tgetColor(t.SyntaxNumber()), // LiteralNumberInteger\n\t\tgetColor(t.SyntaxNumber()), // LiteralNumberIntegerLong\n\t\tgetColor(t.SyntaxNumber()), // LiteralNumberOct\n\n\t\tgetColor(t.SyntaxOperator()), // Operator\n\t\tgetColor(t.SyntaxKeyword()), // OperatorWord\n\t\tgetColor(t.SyntaxPunctuation()), // Punctuation\n\n\t\tgetColor(t.SyntaxComment()), // Comment\n\t\tgetColor(t.SyntaxComment()), // CommentHashbang\n\t\tgetColor(t.SyntaxComment()), // CommentMultiline\n\t\tgetColor(t.SyntaxComment()), // CommentSingle\n\t\tgetColor(t.SyntaxComment()), // CommentSpecial\n\t\tgetColor(t.SyntaxKeyword()), // CommentPreproc\n\n\t\tgetColor(t.Text()), // Generic\n\t\tgetColor(t.Error()), // GenericDeleted\n\t\tgetColor(t.Text()), // GenericEmph\n\t\tgetColor(t.Error()), // GenericError\n\t\tgetColor(t.Text()), // GenericHeading\n\t\tgetColor(t.Success()), // GenericInserted\n\t\tgetColor(t.TextMuted()), // GenericOutput\n\t\tgetColor(t.Text()), // GenericPrompt\n\t\tgetColor(t.Text()), // GenericStrong\n\t\tgetColor(t.Text()), // GenericSubheading\n\t\tgetColor(t.Error()), // GenericTraceback\n\t\tgetColor(t.Text()), // TextWhitespace\n\t)\n\n\tr := strings.NewReader(syntaxThemeXml)\n\tstyle := chroma.MustNewXMLStyle(r)\n\n\t// Modify the style to use the provided background\n\ts, err := style.Builder().Transform(\n\t\tfunc(t chroma.StyleEntry) chroma.StyleEntry {\n\t\t\tr, g, b, _ := bg.RGBA()\n\t\t\tt.Background = chroma.NewColour(uint8(r>>8), uint8(g>>8), uint8(b>>8))\n\t\t\treturn t\n\t\t},\n\t).Build()\n\tif err != nil {\n\t\ts = styles.Fallback\n\t}\n\n\t// Tokenize and format\n\tit, err := l.Tokenise(nil, source)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn f.Format(w, s, it)\n}\n\n// getColor returns the appropriate hex color string based on terminal background\nfunc getColor(adaptiveColor lipgloss.AdaptiveColor) string {\n\tif lipgloss.HasDarkBackground() {\n\t\treturn adaptiveColor.Dark\n\t}\n\treturn adaptiveColor.Light\n}\n\n// highlightLine applies syntax highlighting to a single line\nfunc highlightLine(fileName string, line string, bg lipgloss.TerminalColor) string {\n\tvar buf bytes.Buffer\n\terr := SyntaxHighlight(&buf, line, fileName, \"terminal16m\", bg)\n\tif err != nil {\n\t\treturn line\n\t}\n\treturn buf.String()\n}\n\n// createStyles generates the lipgloss styles needed for rendering diffs\nfunc createStyles(t theme.Theme) (removedLineStyle, addedLineStyle, contextLineStyle, lineNumberStyle lipgloss.Style) {\n\tremovedLineStyle = lipgloss.NewStyle().Background(t.DiffRemovedBg())\n\taddedLineStyle = lipgloss.NewStyle().Background(t.DiffAddedBg())\n\tcontextLineStyle = lipgloss.NewStyle().Background(t.DiffContextBg())\n\tlineNumberStyle = lipgloss.NewStyle().Foreground(t.DiffLineNumber())\n\n\treturn\n}\n\n// -------------------------------------------------------------------------\n// Rendering Functions\n// -------------------------------------------------------------------------\n\nfunc lipglossToHex(color lipgloss.Color) string {\n\tr, g, b, a := color.RGBA()\n\n\t// Scale uint32 values (0-65535) to uint8 (0-255).\n\tr8 := uint8(r >> 8)\n\tg8 := uint8(g >> 8)\n\tb8 := uint8(b >> 8)\n\ta8 := uint8(a >> 8)\n\n\treturn fmt.Sprintf(\"#%02x%02x%02x%02x\", r8, g8, b8, a8)\n}\n\n// applyHighlighting applies intra-line highlighting to a piece of text\nfunc applyHighlighting(content string, segments []Segment, segmentType LineType, highlightBg lipgloss.AdaptiveColor) string {\n\t// Find all ANSI sequences in the content\n\tansiRegex := regexp.MustCompile(`\\x1b(?:[@-Z\\\\-_]|\\[[0-9?]*(?:;[0-9?]*)*[@-~])`)\n\tansiMatches := ansiRegex.FindAllStringIndex(content, -1)\n\n\t// Build a mapping of visible character positions to their actual indices\n\tvisibleIdx := 0\n\tansiSequences := make(map[int]string)\n\tlastAnsiSeq := \"\\x1b[0m\" // Default reset sequence\n\n\tfor i := 0; i < len(content); {\n\t\tisAnsi := false\n\t\tfor _, match := range ansiMatches {\n\t\t\tif match[0] == i {\n\t\t\t\tansiSequences[visibleIdx] = content[match[0]:match[1]]\n\t\t\t\tlastAnsiSeq = content[match[0]:match[1]]\n\t\t\t\ti = match[1]\n\t\t\t\tisAnsi = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif isAnsi {\n\t\t\tcontinue\n\t\t}\n\n\t\t// For non-ANSI positions, store the last ANSI sequence\n\t\tif _, exists := ansiSequences[visibleIdx]; !exists {\n\t\t\tansiSequences[visibleIdx] = lastAnsiSeq\n\t\t}\n\t\tvisibleIdx++\n\t\ti++\n\t}\n\n\t// Apply highlighting\n\tvar sb strings.Builder\n\tinSelection := false\n\tcurrentPos := 0\n\n\t// Get the appropriate color based on terminal background\n\tbgColor := lipgloss.Color(getColor(highlightBg))\n\tfgColor := lipgloss.Color(getColor(theme.CurrentTheme().Background()))\n\n\tfor i := 0; i < len(content); {\n\t\t// Check if we're at an ANSI sequence\n\t\tisAnsi := false\n\t\tfor _, match := range ansiMatches {\n\t\t\tif match[0] == i {\n\t\t\t\tsb.WriteString(content[match[0]:match[1]]) // Preserve ANSI sequence\n\t\t\t\ti = match[1]\n\t\t\t\tisAnsi = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif isAnsi {\n\t\t\tcontinue\n\t\t}\n\n\t\t// Check for segment boundaries\n\t\tfor _, seg := range segments {\n\t\t\tif seg.Type == segmentType {\n\t\t\t\tif currentPos == seg.Start {\n\t\t\t\t\tinSelection = true\n\t\t\t\t}\n\t\t\t\tif currentPos == seg.End {\n\t\t\t\t\tinSelection = false\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Get current character\n\t\tchar := string(content[i])\n\n\t\tif inSelection {\n\t\t\t// Get the current styling\n\t\t\tcurrentStyle := ansiSequences[currentPos]\n\n\t\t\t// Apply foreground and background highlight\n\t\t\tsb.WriteString(\"\\x1b[38;2;\")\n\t\t\tr, g, b, _ := fgColor.RGBA()\n\t\t\tsb.WriteString(fmt.Sprintf(\"%d;%d;%dm\", r>>8, g>>8, b>>8))\n\t\t\tsb.WriteString(\"\\x1b[48;2;\")\n\t\t\tr, g, b, _ = bgColor.RGBA()\n\t\t\tsb.WriteString(fmt.Sprintf(\"%d;%d;%dm\", r>>8, g>>8, b>>8))\n\t\t\tsb.WriteString(char)\n\t\t\t// Reset foreground and background\n\t\t\tsb.WriteString(\"\\x1b[39m\")\n\n\t\t\t// Reapply the original ANSI sequence\n\t\t\tsb.WriteString(currentStyle)\n\t\t} else {\n\t\t\t// Not in selection, just copy the character\n\t\t\tsb.WriteString(char)\n\t\t}\n\n\t\tcurrentPos++\n\t\ti++\n\t}\n\n\treturn sb.String()\n}\n\n// renderLeftColumn formats the left side of a side-by-side diff\nfunc renderLeftColumn(fileName string, dl *DiffLine, colWidth int) string {\n\tt := theme.CurrentTheme()\n\n\tif dl == nil {\n\t\tcontextLineStyle := lipgloss.NewStyle().Background(t.DiffContextBg())\n\t\treturn contextLineStyle.Width(colWidth).Render(\"\")\n\t}\n\n\tremovedLineStyle, _, contextLineStyle, lineNumberStyle := createStyles(t)\n\n\t// Determine line style based on line type\n\tvar marker string\n\tvar bgStyle lipgloss.Style\n\tswitch dl.Kind {\n\tcase LineRemoved:\n\t\tmarker = removedLineStyle.Foreground(t.DiffRemoved()).Render(\"-\")\n\t\tbgStyle = removedLineStyle\n\t\tlineNumberStyle = lineNumberStyle.Foreground(t.DiffRemoved()).Background(t.DiffRemovedLineNumberBg())\n\tcase LineAdded:\n\t\tmarker = \"?\"\n\t\tbgStyle = contextLineStyle\n\tcase LineContext:\n\t\tmarker = contextLineStyle.Render(\" \")\n\t\tbgStyle = contextLineStyle\n\t}\n\n\t// Format line number\n\tlineNum := \"\"\n\tif dl.OldLineNo > 0 {\n\t\tlineNum = fmt.Sprintf(\"%6d\", dl.OldLineNo)\n\t}\n\n\t// Create the line prefix\n\tprefix := lineNumberStyle.Render(lineNum + \" \" + marker)\n\n\t// Apply syntax highlighting\n\tcontent := highlightLine(fileName, dl.Content, bgStyle.GetBackground())\n\n\t// Apply intra-line highlighting for removed lines\n\tif dl.Kind == LineRemoved && len(dl.Segments) > 0 {\n\t\tcontent = applyHighlighting(content, dl.Segments, LineRemoved, t.DiffHighlightRemoved())\n\t}\n\n\t// Add a padding space for removed lines\n\tif dl.Kind == LineRemoved {\n\t\tcontent = bgStyle.Render(\" \") + content\n\t}\n\n\t// Create the final line and truncate if needed\n\tlineText := prefix + content\n\treturn bgStyle.MaxHeight(1).Width(colWidth).Render(\n\t\tansi.Truncate(\n\t\t\tlineText,\n\t\t\tcolWidth,\n\t\t\tlipgloss.NewStyle().Background(bgStyle.GetBackground()).Foreground(t.TextMuted()).Render(\"...\"),\n\t\t),\n\t)\n}\n\n// renderRightColumn formats the right side of a side-by-side diff\nfunc renderRightColumn(fileName string, dl *DiffLine, colWidth int) string {\n\tt := theme.CurrentTheme()\n\n\tif dl == nil {\n\t\tcontextLineStyle := lipgloss.NewStyle().Background(t.DiffContextBg())\n\t\treturn contextLineStyle.Width(colWidth).Render(\"\")\n\t}\n\n\t_, addedLineStyle, contextLineStyle, lineNumberStyle := createStyles(t)\n\n\t// Determine line style based on line type\n\tvar marker string\n\tvar bgStyle lipgloss.Style\n\tswitch dl.Kind {\n\tcase LineAdded:\n\t\tmarker = addedLineStyle.Foreground(t.DiffAdded()).Render(\"+\")\n\t\tbgStyle = addedLineStyle\n\t\tlineNumberStyle = lineNumberStyle.Foreground(t.DiffAdded()).Background(t.DiffAddedLineNumberBg())\n\tcase LineRemoved:\n\t\tmarker = \"?\"\n\t\tbgStyle = contextLineStyle\n\tcase LineContext:\n\t\tmarker = contextLineStyle.Render(\" \")\n\t\tbgStyle = contextLineStyle\n\t}\n\n\t// Format line number\n\tlineNum := \"\"\n\tif dl.NewLineNo > 0 {\n\t\tlineNum = fmt.Sprintf(\"%6d\", dl.NewLineNo)\n\t}\n\n\t// Create the line prefix\n\tprefix := lineNumberStyle.Render(lineNum + \" \" + marker)\n\n\t// Apply syntax highlighting\n\tcontent := highlightLine(fileName, dl.Content, bgStyle.GetBackground())\n\n\t// Apply intra-line highlighting for added lines\n\tif dl.Kind == LineAdded && len(dl.Segments) > 0 {\n\t\tcontent = applyHighlighting(content, dl.Segments, LineAdded, t.DiffHighlightAdded())\n\t}\n\n\t// Add a padding space for added lines\n\tif dl.Kind == LineAdded {\n\t\tcontent = bgStyle.Render(\" \") + content\n\t}\n\n\t// Create the final line and truncate if needed\n\tlineText := prefix + content\n\treturn bgStyle.MaxHeight(1).Width(colWidth).Render(\n\t\tansi.Truncate(\n\t\t\tlineText,\n\t\t\tcolWidth,\n\t\t\tlipgloss.NewStyle().Background(bgStyle.GetBackground()).Foreground(t.TextMuted()).Render(\"...\"),\n\t\t),\n\t)\n}\n\n// -------------------------------------------------------------------------\n// Public API\n// -------------------------------------------------------------------------\n\n// RenderSideBySideHunk formats a hunk for side-by-side display\nfunc RenderSideBySideHunk(fileName string, h Hunk, opts ...SideBySideOption) string {\n\t// Apply options to create the configuration\n\tconfig := NewSideBySideConfig(opts...)\n\n\t// Make a copy of the hunk so we don't modify the original\n\thunkCopy := Hunk{Lines: make([]DiffLine, len(h.Lines))}\n\tcopy(hunkCopy.Lines, h.Lines)\n\n\t// Highlight changes within lines\n\tHighlightIntralineChanges(&hunkCopy)\n\n\t// Pair lines for side-by-side display\n\tpairs := pairLines(hunkCopy.Lines)\n\n\t// Calculate column width\n\tcolWidth := config.TotalWidth / 2\n\n\tleftWidth := colWidth\n\trightWidth := config.TotalWidth - colWidth\n\tvar sb strings.Builder\n\tfor _, p := range pairs {\n\t\tleftStr := renderLeftColumn(fileName, p.left, leftWidth)\n\t\trightStr := renderRightColumn(fileName, p.right, rightWidth)\n\t\tsb.WriteString(leftStr + rightStr + \"\\n\")\n\t}\n\n\treturn sb.String()\n}\n\n// FormatDiff creates a side-by-side formatted view of a diff\nfunc FormatDiff(diffText string, opts ...SideBySideOption) (string, error) {\n\tdiffResult, err := ParseUnifiedDiff(diffText)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tvar sb strings.Builder\n\tfor _, h := range diffResult.Hunks {\n\t\tsb.WriteString(RenderSideBySideHunk(diffResult.OldFile, h, opts...))\n\t}\n\n\treturn sb.String(), nil\n}\n\n// GenerateDiff creates a unified diff from two file contents\nfunc GenerateDiff(beforeContent, afterContent, fileName string) (string, int, int) {\n\t// remove the cwd prefix and ensure consistent path format\n\t// this prevents issues with absolute paths in different environments\n\tcwd := config.WorkingDirectory()\n\tfileName = strings.TrimPrefix(fileName, cwd)\n\tfileName = strings.TrimPrefix(fileName, \"/\")\n\n\tvar (\n\t\tunified = udiff.Unified(\"a/\"+fileName, \"b/\"+fileName, beforeContent, afterContent)\n\t\tadditions = 0\n\t\tremovals = 0\n\t)\n\n\tlines := strings.SplitSeq(unified, \"\\n\")\n\tfor line := range lines {\n\t\tif strings.HasPrefix(line, \"+\") && !strings.HasPrefix(line, \"+++\") {\n\t\t\tadditions++\n\t\t} else if strings.HasPrefix(line, \"-\") && !strings.HasPrefix(line, \"---\") {\n\t\t\tremovals++\n\t\t}\n\t}\n\n\treturn unified, additions, removals\n}\n"], ["/opencode/internal/tui/components/chat/sidebar.go", "package chat\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"sort\"\n\t\"strings\"\n\n\ttea \"github.com/charmbracelet/bubbletea\"\n\t\"github.com/charmbracelet/lipgloss\"\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/diff\"\n\t\"github.com/opencode-ai/opencode/internal/history\"\n\t\"github.com/opencode-ai/opencode/internal/pubsub\"\n\t\"github.com/opencode-ai/opencode/internal/session\"\n\t\"github.com/opencode-ai/opencode/internal/tui/styles\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n)\n\ntype sidebarCmp struct {\n\twidth, height int\n\tsession session.Session\n\thistory history.Service\n\tmodFiles map[string]struct {\n\t\tadditions int\n\t\tremovals int\n\t}\n}\n\nfunc (m *sidebarCmp) Init() tea.Cmd {\n\tif m.history != nil {\n\t\tctx := context.Background()\n\t\t// Subscribe to file events\n\t\tfilesCh := m.history.Subscribe(ctx)\n\n\t\t// Initialize the modified files map\n\t\tm.modFiles = make(map[string]struct {\n\t\t\tadditions int\n\t\t\tremovals int\n\t\t})\n\n\t\t// Load initial files and calculate diffs\n\t\tm.loadModifiedFiles(ctx)\n\n\t\t// Return a command that will send file events to the Update method\n\t\treturn func() tea.Msg {\n\t\t\treturn <-filesCh\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (m *sidebarCmp) Update(msg tea.Msg) (tea.Model, tea.Cmd) {\n\tswitch msg := msg.(type) {\n\tcase SessionSelectedMsg:\n\t\tif msg.ID != m.session.ID {\n\t\t\tm.session = msg\n\t\t\tctx := context.Background()\n\t\t\tm.loadModifiedFiles(ctx)\n\t\t}\n\tcase pubsub.Event[session.Session]:\n\t\tif msg.Type == pubsub.UpdatedEvent {\n\t\t\tif m.session.ID == msg.Payload.ID {\n\t\t\t\tm.session = msg.Payload\n\t\t\t}\n\t\t}\n\tcase pubsub.Event[history.File]:\n\t\tif msg.Payload.SessionID == m.session.ID {\n\t\t\t// Process the individual file change instead of reloading all files\n\t\t\tctx := context.Background()\n\t\t\tm.processFileChanges(ctx, msg.Payload)\n\n\t\t\t// Return a command to continue receiving events\n\t\t\treturn m, func() tea.Msg {\n\t\t\t\tctx := context.Background()\n\t\t\t\tfilesCh := m.history.Subscribe(ctx)\n\t\t\t\treturn <-filesCh\n\t\t\t}\n\t\t}\n\t}\n\treturn m, nil\n}\n\nfunc (m *sidebarCmp) View() string {\n\tbaseStyle := styles.BaseStyle()\n\n\treturn baseStyle.\n\t\tWidth(m.width).\n\t\tPaddingLeft(4).\n\t\tPaddingRight(2).\n\t\tHeight(m.height - 1).\n\t\tRender(\n\t\t\tlipgloss.JoinVertical(\n\t\t\t\tlipgloss.Top,\n\t\t\t\theader(m.width),\n\t\t\t\t\" \",\n\t\t\t\tm.sessionSection(),\n\t\t\t\t\" \",\n\t\t\t\tlspsConfigured(m.width),\n\t\t\t\t\" \",\n\t\t\t\tm.modifiedFiles(),\n\t\t\t),\n\t\t)\n}\n\nfunc (m *sidebarCmp) sessionSection() string {\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\n\tsessionKey := baseStyle.\n\t\tForeground(t.Primary()).\n\t\tBold(true).\n\t\tRender(\"Session\")\n\n\tsessionValue := baseStyle.\n\t\tForeground(t.Text()).\n\t\tWidth(m.width - lipgloss.Width(sessionKey)).\n\t\tRender(fmt.Sprintf(\": %s\", m.session.Title))\n\n\treturn lipgloss.JoinHorizontal(\n\t\tlipgloss.Left,\n\t\tsessionKey,\n\t\tsessionValue,\n\t)\n}\n\nfunc (m *sidebarCmp) modifiedFile(filePath string, additions, removals int) string {\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\n\tstats := \"\"\n\tif additions > 0 && removals > 0 {\n\t\tadditionsStr := baseStyle.\n\t\t\tForeground(t.Success()).\n\t\t\tPaddingLeft(1).\n\t\t\tRender(fmt.Sprintf(\"+%d\", additions))\n\n\t\tremovalsStr := baseStyle.\n\t\t\tForeground(t.Error()).\n\t\t\tPaddingLeft(1).\n\t\t\tRender(fmt.Sprintf(\"-%d\", removals))\n\n\t\tcontent := lipgloss.JoinHorizontal(lipgloss.Left, additionsStr, removalsStr)\n\t\tstats = baseStyle.Width(lipgloss.Width(content)).Render(content)\n\t} else if additions > 0 {\n\t\tadditionsStr := fmt.Sprintf(\" %s\", baseStyle.\n\t\t\tPaddingLeft(1).\n\t\t\tForeground(t.Success()).\n\t\t\tRender(fmt.Sprintf(\"+%d\", additions)))\n\t\tstats = baseStyle.Width(lipgloss.Width(additionsStr)).Render(additionsStr)\n\t} else if removals > 0 {\n\t\tremovalsStr := fmt.Sprintf(\" %s\", baseStyle.\n\t\t\tPaddingLeft(1).\n\t\t\tForeground(t.Error()).\n\t\t\tRender(fmt.Sprintf(\"-%d\", removals)))\n\t\tstats = baseStyle.Width(lipgloss.Width(removalsStr)).Render(removalsStr)\n\t}\n\n\tfilePathStr := baseStyle.Render(filePath)\n\n\treturn baseStyle.\n\t\tWidth(m.width).\n\t\tRender(\n\t\t\tlipgloss.JoinHorizontal(\n\t\t\t\tlipgloss.Left,\n\t\t\t\tfilePathStr,\n\t\t\t\tstats,\n\t\t\t),\n\t\t)\n}\n\nfunc (m *sidebarCmp) modifiedFiles() string {\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\n\tmodifiedFiles := baseStyle.\n\t\tWidth(m.width).\n\t\tForeground(t.Primary()).\n\t\tBold(true).\n\t\tRender(\"Modified Files:\")\n\n\t// If no modified files, show a placeholder message\n\tif m.modFiles == nil || len(m.modFiles) == 0 {\n\t\tmessage := \"No modified files\"\n\t\tremainingWidth := m.width - lipgloss.Width(message)\n\t\tif remainingWidth > 0 {\n\t\t\tmessage += strings.Repeat(\" \", remainingWidth)\n\t\t}\n\t\treturn baseStyle.\n\t\t\tWidth(m.width).\n\t\t\tRender(\n\t\t\t\tlipgloss.JoinVertical(\n\t\t\t\t\tlipgloss.Top,\n\t\t\t\t\tmodifiedFiles,\n\t\t\t\t\tbaseStyle.Foreground(t.TextMuted()).Render(message),\n\t\t\t\t),\n\t\t\t)\n\t}\n\n\t// Sort file paths alphabetically for consistent ordering\n\tvar paths []string\n\tfor path := range m.modFiles {\n\t\tpaths = append(paths, path)\n\t}\n\tsort.Strings(paths)\n\n\t// Create views for each file in sorted order\n\tvar fileViews []string\n\tfor _, path := range paths {\n\t\tstats := m.modFiles[path]\n\t\tfileViews = append(fileViews, m.modifiedFile(path, stats.additions, stats.removals))\n\t}\n\n\treturn baseStyle.\n\t\tWidth(m.width).\n\t\tRender(\n\t\t\tlipgloss.JoinVertical(\n\t\t\t\tlipgloss.Top,\n\t\t\t\tmodifiedFiles,\n\t\t\t\tlipgloss.JoinVertical(\n\t\t\t\t\tlipgloss.Left,\n\t\t\t\t\tfileViews...,\n\t\t\t\t),\n\t\t\t),\n\t\t)\n}\n\nfunc (m *sidebarCmp) SetSize(width, height int) tea.Cmd {\n\tm.width = width\n\tm.height = height\n\treturn nil\n}\n\nfunc (m *sidebarCmp) GetSize() (int, int) {\n\treturn m.width, m.height\n}\n\nfunc NewSidebarCmp(session session.Session, history history.Service) tea.Model {\n\treturn &sidebarCmp{\n\t\tsession: session,\n\t\thistory: history,\n\t}\n}\n\nfunc (m *sidebarCmp) loadModifiedFiles(ctx context.Context) {\n\tif m.history == nil || m.session.ID == \"\" {\n\t\treturn\n\t}\n\n\t// Get all latest files for this session\n\tlatestFiles, err := m.history.ListLatestSessionFiles(ctx, m.session.ID)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t// Get all files for this session (to find initial versions)\n\tallFiles, err := m.history.ListBySession(ctx, m.session.ID)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t// Clear the existing map to rebuild it\n\tm.modFiles = make(map[string]struct {\n\t\tadditions int\n\t\tremovals int\n\t})\n\n\t// Process each latest file\n\tfor _, file := range latestFiles {\n\t\t// Skip if this is the initial version (no changes to show)\n\t\tif file.Version == history.InitialVersion {\n\t\t\tcontinue\n\t\t}\n\n\t\t// Find the initial version for this specific file\n\t\tvar initialVersion history.File\n\t\tfor _, v := range allFiles {\n\t\t\tif v.Path == file.Path && v.Version == history.InitialVersion {\n\t\t\t\tinitialVersion = v\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\t// Skip if we can't find the initial version\n\t\tif initialVersion.ID == \"\" {\n\t\t\tcontinue\n\t\t}\n\t\tif initialVersion.Content == file.Content {\n\t\t\tcontinue\n\t\t}\n\n\t\t// Calculate diff between initial and latest version\n\t\t_, additions, removals := diff.GenerateDiff(initialVersion.Content, file.Content, file.Path)\n\n\t\t// Only add to modified files if there are changes\n\t\tif additions > 0 || removals > 0 {\n\t\t\t// Remove working directory prefix from file path\n\t\t\tdisplayPath := file.Path\n\t\t\tworkingDir := config.WorkingDirectory()\n\t\t\tdisplayPath = strings.TrimPrefix(displayPath, workingDir)\n\t\t\tdisplayPath = strings.TrimPrefix(displayPath, \"/\")\n\n\t\t\tm.modFiles[displayPath] = struct {\n\t\t\t\tadditions int\n\t\t\t\tremovals int\n\t\t\t}{\n\t\t\t\tadditions: additions,\n\t\t\t\tremovals: removals,\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc (m *sidebarCmp) processFileChanges(ctx context.Context, file history.File) {\n\t// Skip if this is the initial version (no changes to show)\n\tif file.Version == history.InitialVersion {\n\t\treturn\n\t}\n\n\t// Find the initial version for this file\n\tinitialVersion, err := m.findInitialVersion(ctx, file.Path)\n\tif err != nil || initialVersion.ID == \"\" {\n\t\treturn\n\t}\n\n\t// Skip if content hasn't changed\n\tif initialVersion.Content == file.Content {\n\t\t// If this file was previously modified but now matches the initial version,\n\t\t// remove it from the modified files list\n\t\tdisplayPath := getDisplayPath(file.Path)\n\t\tdelete(m.modFiles, displayPath)\n\t\treturn\n\t}\n\n\t// Calculate diff between initial and latest version\n\t_, additions, removals := diff.GenerateDiff(initialVersion.Content, file.Content, file.Path)\n\n\t// Only add to modified files if there are changes\n\tif additions > 0 || removals > 0 {\n\t\tdisplayPath := getDisplayPath(file.Path)\n\t\tm.modFiles[displayPath] = struct {\n\t\t\tadditions int\n\t\t\tremovals int\n\t\t}{\n\t\t\tadditions: additions,\n\t\t\tremovals: removals,\n\t\t}\n\t} else {\n\t\t// If no changes, remove from modified files\n\t\tdisplayPath := getDisplayPath(file.Path)\n\t\tdelete(m.modFiles, displayPath)\n\t}\n}\n\n// Helper function to find the initial version of a file\nfunc (m *sidebarCmp) findInitialVersion(ctx context.Context, path string) (history.File, error) {\n\t// Get all versions of this file for the session\n\tfileVersions, err := m.history.ListBySession(ctx, m.session.ID)\n\tif err != nil {\n\t\treturn history.File{}, err\n\t}\n\n\t// Find the initial version\n\tfor _, v := range fileVersions {\n\t\tif v.Path == path && v.Version == history.InitialVersion {\n\t\t\treturn v, nil\n\t\t}\n\t}\n\n\treturn history.File{}, fmt.Errorf(\"initial version not found\")\n}\n\n// Helper function to get the display path for a file\nfunc getDisplayPath(path string) string {\n\tworkingDir := config.WorkingDirectory()\n\tdisplayPath := strings.TrimPrefix(path, workingDir)\n\treturn strings.TrimPrefix(displayPath, \"/\")\n}\n"], ["/opencode/internal/tui/components/dialog/quit.go", "package dialog\n\nimport (\n\t\"strings\"\n\n\t\"github.com/charmbracelet/bubbles/key\"\n\ttea \"github.com/charmbracelet/bubbletea\"\n\t\"github.com/charmbracelet/lipgloss\"\n\t\"github.com/opencode-ai/opencode/internal/tui/layout\"\n\t\"github.com/opencode-ai/opencode/internal/tui/styles\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n\t\"github.com/opencode-ai/opencode/internal/tui/util\"\n)\n\nconst question = \"Are you sure you want to quit?\"\n\ntype CloseQuitMsg struct{}\n\ntype QuitDialog interface {\n\ttea.Model\n\tlayout.Bindings\n}\n\ntype quitDialogCmp struct {\n\tselectedNo bool\n}\n\ntype helpMapping struct {\n\tLeftRight key.Binding\n\tEnterSpace key.Binding\n\tYes key.Binding\n\tNo key.Binding\n\tTab key.Binding\n}\n\nvar helpKeys = helpMapping{\n\tLeftRight: key.NewBinding(\n\t\tkey.WithKeys(\"left\", \"right\"),\n\t\tkey.WithHelp(\"←/→\", \"switch options\"),\n\t),\n\tEnterSpace: key.NewBinding(\n\t\tkey.WithKeys(\"enter\", \" \"),\n\t\tkey.WithHelp(\"enter/space\", \"confirm\"),\n\t),\n\tYes: key.NewBinding(\n\t\tkey.WithKeys(\"y\", \"Y\"),\n\t\tkey.WithHelp(\"y/Y\", \"yes\"),\n\t),\n\tNo: key.NewBinding(\n\t\tkey.WithKeys(\"n\", \"N\"),\n\t\tkey.WithHelp(\"n/N\", \"no\"),\n\t),\n\tTab: key.NewBinding(\n\t\tkey.WithKeys(\"tab\"),\n\t\tkey.WithHelp(\"tab\", \"switch options\"),\n\t),\n}\n\nfunc (q *quitDialogCmp) Init() tea.Cmd {\n\treturn nil\n}\n\nfunc (q *quitDialogCmp) Update(msg tea.Msg) (tea.Model, tea.Cmd) {\n\tswitch msg := msg.(type) {\n\tcase tea.KeyMsg:\n\t\tswitch {\n\t\tcase key.Matches(msg, helpKeys.LeftRight) || key.Matches(msg, helpKeys.Tab):\n\t\t\tq.selectedNo = !q.selectedNo\n\t\t\treturn q, nil\n\t\tcase key.Matches(msg, helpKeys.EnterSpace):\n\t\t\tif !q.selectedNo {\n\t\t\t\treturn q, tea.Quit\n\t\t\t}\n\t\t\treturn q, util.CmdHandler(CloseQuitMsg{})\n\t\tcase key.Matches(msg, helpKeys.Yes):\n\t\t\treturn q, tea.Quit\n\t\tcase key.Matches(msg, helpKeys.No):\n\t\t\treturn q, util.CmdHandler(CloseQuitMsg{})\n\t\t}\n\t}\n\treturn q, nil\n}\n\nfunc (q *quitDialogCmp) View() string {\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\t\n\tyesStyle := baseStyle\n\tnoStyle := baseStyle\n\tspacerStyle := baseStyle.Background(t.Background())\n\n\tif q.selectedNo {\n\t\tnoStyle = noStyle.Background(t.Primary()).Foreground(t.Background())\n\t\tyesStyle = yesStyle.Background(t.Background()).Foreground(t.Primary())\n\t} else {\n\t\tyesStyle = yesStyle.Background(t.Primary()).Foreground(t.Background())\n\t\tnoStyle = noStyle.Background(t.Background()).Foreground(t.Primary())\n\t}\n\n\tyesButton := yesStyle.Padding(0, 1).Render(\"Yes\")\n\tnoButton := noStyle.Padding(0, 1).Render(\"No\")\n\n\tbuttons := lipgloss.JoinHorizontal(lipgloss.Left, yesButton, spacerStyle.Render(\" \"), noButton)\n\n\twidth := lipgloss.Width(question)\n\tremainingWidth := width - lipgloss.Width(buttons)\n\tif remainingWidth > 0 {\n\t\tbuttons = spacerStyle.Render(strings.Repeat(\" \", remainingWidth)) + buttons\n\t}\n\n\tcontent := baseStyle.Render(\n\t\tlipgloss.JoinVertical(\n\t\t\tlipgloss.Center,\n\t\t\tquestion,\n\t\t\t\"\",\n\t\t\tbuttons,\n\t\t),\n\t)\n\n\treturn baseStyle.Padding(1, 2).\n\t\tBorder(lipgloss.RoundedBorder()).\n\t\tBorderBackground(t.Background()).\n\t\tBorderForeground(t.TextMuted()).\n\t\tWidth(lipgloss.Width(content) + 4).\n\t\tRender(content)\n}\n\nfunc (q *quitDialogCmp) BindingKeys() []key.Binding {\n\treturn layout.KeyMapToSlice(helpKeys)\n}\n\nfunc NewQuitCmp() QuitDialog {\n\treturn &quitDialogCmp{\n\t\tselectedNo: true,\n\t}\n}\n"], ["/opencode/internal/tui/components/core/status.go", "package core\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\t\"time\"\n\n\ttea \"github.com/charmbracelet/bubbletea\"\n\t\"github.com/charmbracelet/lipgloss\"\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/llm/models\"\n\t\"github.com/opencode-ai/opencode/internal/lsp\"\n\t\"github.com/opencode-ai/opencode/internal/lsp/protocol\"\n\t\"github.com/opencode-ai/opencode/internal/pubsub\"\n\t\"github.com/opencode-ai/opencode/internal/session\"\n\t\"github.com/opencode-ai/opencode/internal/tui/components/chat\"\n\t\"github.com/opencode-ai/opencode/internal/tui/styles\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n\t\"github.com/opencode-ai/opencode/internal/tui/util\"\n)\n\ntype StatusCmp interface {\n\ttea.Model\n}\n\ntype statusCmp struct {\n\tinfo util.InfoMsg\n\twidth int\n\tmessageTTL time.Duration\n\tlspClients map[string]*lsp.Client\n\tsession session.Session\n}\n\n// clearMessageCmd is a command that clears status messages after a timeout\nfunc (m statusCmp) clearMessageCmd(ttl time.Duration) tea.Cmd {\n\treturn tea.Tick(ttl, func(time.Time) tea.Msg {\n\t\treturn util.ClearStatusMsg{}\n\t})\n}\n\nfunc (m statusCmp) Init() tea.Cmd {\n\treturn nil\n}\n\nfunc (m statusCmp) Update(msg tea.Msg) (tea.Model, tea.Cmd) {\n\tswitch msg := msg.(type) {\n\tcase tea.WindowSizeMsg:\n\t\tm.width = msg.Width\n\t\treturn m, nil\n\tcase chat.SessionSelectedMsg:\n\t\tm.session = msg\n\tcase chat.SessionClearedMsg:\n\t\tm.session = session.Session{}\n\tcase pubsub.Event[session.Session]:\n\t\tif msg.Type == pubsub.UpdatedEvent {\n\t\t\tif m.session.ID == msg.Payload.ID {\n\t\t\t\tm.session = msg.Payload\n\t\t\t}\n\t\t}\n\tcase util.InfoMsg:\n\t\tm.info = msg\n\t\tttl := msg.TTL\n\t\tif ttl == 0 {\n\t\t\tttl = m.messageTTL\n\t\t}\n\t\treturn m, m.clearMessageCmd(ttl)\n\tcase util.ClearStatusMsg:\n\t\tm.info = util.InfoMsg{}\n\t}\n\treturn m, nil\n}\n\nvar helpWidget = \"\"\n\n// getHelpWidget returns the help widget with current theme colors\nfunc getHelpWidget() string {\n\tt := theme.CurrentTheme()\n\thelpText := \"ctrl+? help\"\n\n\treturn styles.Padded().\n\t\tBackground(t.TextMuted()).\n\t\tForeground(t.BackgroundDarker()).\n\t\tBold(true).\n\t\tRender(helpText)\n}\n\nfunc formatTokensAndCost(tokens, contextWindow int64, cost float64) string {\n\t// Format tokens in human-readable format (e.g., 110K, 1.2M)\n\tvar formattedTokens string\n\tswitch {\n\tcase tokens >= 1_000_000:\n\t\tformattedTokens = fmt.Sprintf(\"%.1fM\", float64(tokens)/1_000_000)\n\tcase tokens >= 1_000:\n\t\tformattedTokens = fmt.Sprintf(\"%.1fK\", float64(tokens)/1_000)\n\tdefault:\n\t\tformattedTokens = fmt.Sprintf(\"%d\", tokens)\n\t}\n\n\t// Remove .0 suffix if present\n\tif strings.HasSuffix(formattedTokens, \".0K\") {\n\t\tformattedTokens = strings.Replace(formattedTokens, \".0K\", \"K\", 1)\n\t}\n\tif strings.HasSuffix(formattedTokens, \".0M\") {\n\t\tformattedTokens = strings.Replace(formattedTokens, \".0M\", \"M\", 1)\n\t}\n\n\t// Format cost with $ symbol and 2 decimal places\n\tformattedCost := fmt.Sprintf(\"$%.2f\", cost)\n\n\tpercentage := (float64(tokens) / float64(contextWindow)) * 100\n\tif percentage > 80 {\n\t\t// add the warning icon and percentage\n\t\tformattedTokens = fmt.Sprintf(\"%s(%d%%)\", styles.WarningIcon, int(percentage))\n\t}\n\n\treturn fmt.Sprintf(\"Context: %s, Cost: %s\", formattedTokens, formattedCost)\n}\n\nfunc (m statusCmp) View() string {\n\tt := theme.CurrentTheme()\n\tmodelID := config.Get().Agents[config.AgentCoder].Model\n\tmodel := models.SupportedModels[modelID]\n\n\t// Initialize the help widget\n\tstatus := getHelpWidget()\n\n\ttokenInfoWidth := 0\n\tif m.session.ID != \"\" {\n\t\ttotalTokens := m.session.PromptTokens + m.session.CompletionTokens\n\t\ttokens := formatTokensAndCost(totalTokens, model.ContextWindow, m.session.Cost)\n\t\ttokensStyle := styles.Padded().\n\t\t\tBackground(t.Text()).\n\t\t\tForeground(t.BackgroundSecondary())\n\t\tpercentage := (float64(totalTokens) / float64(model.ContextWindow)) * 100\n\t\tif percentage > 80 {\n\t\t\ttokensStyle = tokensStyle.Background(t.Warning())\n\t\t}\n\t\ttokenInfoWidth = lipgloss.Width(tokens) + 2\n\t\tstatus += tokensStyle.Render(tokens)\n\t}\n\n\tdiagnostics := styles.Padded().\n\t\tBackground(t.BackgroundDarker()).\n\t\tRender(m.projectDiagnostics())\n\n\tavailableWidht := max(0, m.width-lipgloss.Width(helpWidget)-lipgloss.Width(m.model())-lipgloss.Width(diagnostics)-tokenInfoWidth)\n\n\tif m.info.Msg != \"\" {\n\t\tinfoStyle := styles.Padded().\n\t\t\tForeground(t.Background()).\n\t\t\tWidth(availableWidht)\n\n\t\tswitch m.info.Type {\n\t\tcase util.InfoTypeInfo:\n\t\t\tinfoStyle = infoStyle.Background(t.Info())\n\t\tcase util.InfoTypeWarn:\n\t\t\tinfoStyle = infoStyle.Background(t.Warning())\n\t\tcase util.InfoTypeError:\n\t\t\tinfoStyle = infoStyle.Background(t.Error())\n\t\t}\n\n\t\tinfoWidth := availableWidht - 10\n\t\t// Truncate message if it's longer than available width\n\t\tmsg := m.info.Msg\n\t\tif len(msg) > infoWidth && infoWidth > 0 {\n\t\t\tmsg = msg[:infoWidth] + \"...\"\n\t\t}\n\t\tstatus += infoStyle.Render(msg)\n\t} else {\n\t\tstatus += styles.Padded().\n\t\t\tForeground(t.Text()).\n\t\t\tBackground(t.BackgroundSecondary()).\n\t\t\tWidth(availableWidht).\n\t\t\tRender(\"\")\n\t}\n\n\tstatus += diagnostics\n\tstatus += m.model()\n\treturn status\n}\n\nfunc (m *statusCmp) projectDiagnostics() string {\n\tt := theme.CurrentTheme()\n\n\t// Check if any LSP server is still initializing\n\tinitializing := false\n\tfor _, client := range m.lspClients {\n\t\tif client.GetServerState() == lsp.StateStarting {\n\t\t\tinitializing = true\n\t\t\tbreak\n\t\t}\n\t}\n\n\t// If any server is initializing, show that status\n\tif initializing {\n\t\treturn lipgloss.NewStyle().\n\t\t\tBackground(t.BackgroundDarker()).\n\t\t\tForeground(t.Warning()).\n\t\t\tRender(fmt.Sprintf(\"%s Initializing LSP...\", styles.SpinnerIcon))\n\t}\n\n\terrorDiagnostics := []protocol.Diagnostic{}\n\twarnDiagnostics := []protocol.Diagnostic{}\n\thintDiagnostics := []protocol.Diagnostic{}\n\tinfoDiagnostics := []protocol.Diagnostic{}\n\tfor _, client := range m.lspClients {\n\t\tfor _, d := range client.GetDiagnostics() {\n\t\t\tfor _, diag := range d {\n\t\t\t\tswitch diag.Severity {\n\t\t\t\tcase protocol.SeverityError:\n\t\t\t\t\terrorDiagnostics = append(errorDiagnostics, diag)\n\t\t\t\tcase protocol.SeverityWarning:\n\t\t\t\t\twarnDiagnostics = append(warnDiagnostics, diag)\n\t\t\t\tcase protocol.SeverityHint:\n\t\t\t\t\thintDiagnostics = append(hintDiagnostics, diag)\n\t\t\t\tcase protocol.SeverityInformation:\n\t\t\t\t\tinfoDiagnostics = append(infoDiagnostics, diag)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif len(errorDiagnostics) == 0 && len(warnDiagnostics) == 0 && len(hintDiagnostics) == 0 && len(infoDiagnostics) == 0 {\n\t\treturn \"No diagnostics\"\n\t}\n\n\tdiagnostics := []string{}\n\n\tif len(errorDiagnostics) > 0 {\n\t\terrStr := lipgloss.NewStyle().\n\t\t\tBackground(t.BackgroundDarker()).\n\t\t\tForeground(t.Error()).\n\t\t\tRender(fmt.Sprintf(\"%s %d\", styles.ErrorIcon, len(errorDiagnostics)))\n\t\tdiagnostics = append(diagnostics, errStr)\n\t}\n\tif len(warnDiagnostics) > 0 {\n\t\twarnStr := lipgloss.NewStyle().\n\t\t\tBackground(t.BackgroundDarker()).\n\t\t\tForeground(t.Warning()).\n\t\t\tRender(fmt.Sprintf(\"%s %d\", styles.WarningIcon, len(warnDiagnostics)))\n\t\tdiagnostics = append(diagnostics, warnStr)\n\t}\n\tif len(hintDiagnostics) > 0 {\n\t\thintStr := lipgloss.NewStyle().\n\t\t\tBackground(t.BackgroundDarker()).\n\t\t\tForeground(t.Text()).\n\t\t\tRender(fmt.Sprintf(\"%s %d\", styles.HintIcon, len(hintDiagnostics)))\n\t\tdiagnostics = append(diagnostics, hintStr)\n\t}\n\tif len(infoDiagnostics) > 0 {\n\t\tinfoStr := lipgloss.NewStyle().\n\t\t\tBackground(t.BackgroundDarker()).\n\t\t\tForeground(t.Info()).\n\t\t\tRender(fmt.Sprintf(\"%s %d\", styles.InfoIcon, len(infoDiagnostics)))\n\t\tdiagnostics = append(diagnostics, infoStr)\n\t}\n\n\treturn strings.Join(diagnostics, \" \")\n}\n\nfunc (m statusCmp) availableFooterMsgWidth(diagnostics, tokenInfo string) int {\n\ttokensWidth := 0\n\tif m.session.ID != \"\" {\n\t\ttokensWidth = lipgloss.Width(tokenInfo) + 2\n\t}\n\treturn max(0, m.width-lipgloss.Width(helpWidget)-lipgloss.Width(m.model())-lipgloss.Width(diagnostics)-tokensWidth)\n}\n\nfunc (m statusCmp) model() string {\n\tt := theme.CurrentTheme()\n\n\tcfg := config.Get()\n\n\tcoder, ok := cfg.Agents[config.AgentCoder]\n\tif !ok {\n\t\treturn \"Unknown\"\n\t}\n\tmodel := models.SupportedModels[coder.Model]\n\n\treturn styles.Padded().\n\t\tBackground(t.Secondary()).\n\t\tForeground(t.Background()).\n\t\tRender(model.Name)\n}\n\nfunc NewStatusCmp(lspClients map[string]*lsp.Client) StatusCmp {\n\thelpWidget = getHelpWidget()\n\n\treturn &statusCmp{\n\t\tmessageTTL: 10 * time.Second,\n\t\tlspClients: lspClients,\n\t}\n}\n"], ["/opencode/internal/tui/components/util/simple-list.go", "package utilComponents\n\nimport (\n\t\"github.com/charmbracelet/bubbles/key\"\n\ttea \"github.com/charmbracelet/bubbletea\"\n\t\"github.com/charmbracelet/lipgloss\"\n\t\"github.com/opencode-ai/opencode/internal/tui/layout\"\n\t\"github.com/opencode-ai/opencode/internal/tui/styles\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n)\n\ntype SimpleListItem interface {\n\tRender(selected bool, width int) string\n}\n\ntype SimpleList[T SimpleListItem] interface {\n\ttea.Model\n\tlayout.Bindings\n\tSetMaxWidth(maxWidth int)\n\tGetSelectedItem() (item T, idx int)\n\tSetItems(items []T)\n\tGetItems() []T\n}\n\ntype simpleListCmp[T SimpleListItem] struct {\n\tfallbackMsg string\n\titems []T\n\tselectedIdx int\n\tmaxWidth int\n\tmaxVisibleItems int\n\tuseAlphaNumericKeys bool\n\twidth int\n\theight int\n}\n\ntype simpleListKeyMap struct {\n\tUp key.Binding\n\tDown key.Binding\n\tUpAlpha key.Binding\n\tDownAlpha key.Binding\n}\n\nvar simpleListKeys = simpleListKeyMap{\n\tUp: key.NewBinding(\n\t\tkey.WithKeys(\"up\"),\n\t\tkey.WithHelp(\"↑\", \"previous list item\"),\n\t),\n\tDown: key.NewBinding(\n\t\tkey.WithKeys(\"down\"),\n\t\tkey.WithHelp(\"↓\", \"next list item\"),\n\t),\n\tUpAlpha: key.NewBinding(\n\t\tkey.WithKeys(\"k\"),\n\t\tkey.WithHelp(\"k\", \"previous list item\"),\n\t),\n\tDownAlpha: key.NewBinding(\n\t\tkey.WithKeys(\"j\"),\n\t\tkey.WithHelp(\"j\", \"next list item\"),\n\t),\n}\n\nfunc (c *simpleListCmp[T]) Init() tea.Cmd {\n\treturn nil\n}\n\nfunc (c *simpleListCmp[T]) Update(msg tea.Msg) (tea.Model, tea.Cmd) {\n\tswitch msg := msg.(type) {\n\tcase tea.KeyMsg:\n\t\tswitch {\n\t\tcase key.Matches(msg, simpleListKeys.Up) || (c.useAlphaNumericKeys && key.Matches(msg, simpleListKeys.UpAlpha)):\n\t\t\tif c.selectedIdx > 0 {\n\t\t\t\tc.selectedIdx--\n\t\t\t}\n\t\t\treturn c, nil\n\t\tcase key.Matches(msg, simpleListKeys.Down) || (c.useAlphaNumericKeys && key.Matches(msg, simpleListKeys.DownAlpha)):\n\t\t\tif c.selectedIdx < len(c.items)-1 {\n\t\t\t\tc.selectedIdx++\n\t\t\t}\n\t\t\treturn c, nil\n\t\t}\n\t}\n\n\treturn c, nil\n}\n\nfunc (c *simpleListCmp[T]) BindingKeys() []key.Binding {\n\treturn layout.KeyMapToSlice(simpleListKeys)\n}\n\nfunc (c *simpleListCmp[T]) GetSelectedItem() (T, int) {\n\tif len(c.items) > 0 {\n\t\treturn c.items[c.selectedIdx], c.selectedIdx\n\t}\n\n\tvar zero T\n\treturn zero, -1\n}\n\nfunc (c *simpleListCmp[T]) SetItems(items []T) {\n\tc.selectedIdx = 0\n\tc.items = items\n}\n\nfunc (c *simpleListCmp[T]) GetItems() []T {\n\treturn c.items\n}\n\nfunc (c *simpleListCmp[T]) SetMaxWidth(width int) {\n\tc.maxWidth = width\n}\n\nfunc (c *simpleListCmp[T]) View() string {\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\n\titems := c.items\n\tmaxWidth := c.maxWidth\n\tmaxVisibleItems := min(c.maxVisibleItems, len(items))\n\tstartIdx := 0\n\n\tif len(items) <= 0 {\n\t\treturn baseStyle.\n\t\t\tBackground(t.Background()).\n\t\t\tPadding(0, 1).\n\t\t\tWidth(maxWidth).\n\t\t\tRender(c.fallbackMsg)\n\t}\n\n\tif len(items) > maxVisibleItems {\n\t\thalfVisible := maxVisibleItems / 2\n\t\tif c.selectedIdx >= halfVisible && c.selectedIdx < len(items)-halfVisible {\n\t\t\tstartIdx = c.selectedIdx - halfVisible\n\t\t} else if c.selectedIdx >= len(items)-halfVisible {\n\t\t\tstartIdx = len(items) - maxVisibleItems\n\t\t}\n\t}\n\n\tendIdx := min(startIdx+maxVisibleItems, len(items))\n\n\tlistItems := make([]string, 0, maxVisibleItems)\n\n\tfor i := startIdx; i < endIdx; i++ {\n\t\titem := items[i]\n\t\ttitle := item.Render(i == c.selectedIdx, maxWidth)\n\t\tlistItems = append(listItems, title)\n\t}\n\n\treturn lipgloss.JoinVertical(lipgloss.Left, listItems...)\n}\n\nfunc NewSimpleList[T SimpleListItem](items []T, maxVisibleItems int, fallbackMsg string, useAlphaNumericKeys bool) SimpleList[T] {\n\treturn &simpleListCmp[T]{\n\t\tfallbackMsg: fallbackMsg,\n\t\titems: items,\n\t\tmaxVisibleItems: maxVisibleItems,\n\t\tuseAlphaNumericKeys: useAlphaNumericKeys,\n\t\tselectedIdx: 0,\n\t}\n}\n"], ["/opencode/internal/tui/components/dialog/complete.go", "package dialog\n\nimport (\n\t\"github.com/charmbracelet/bubbles/key\"\n\t\"github.com/charmbracelet/bubbles/textarea\"\n\ttea \"github.com/charmbracelet/bubbletea\"\n\t\"github.com/charmbracelet/lipgloss\"\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n\tutilComponents \"github.com/opencode-ai/opencode/internal/tui/components/util\"\n\t\"github.com/opencode-ai/opencode/internal/tui/layout\"\n\t\"github.com/opencode-ai/opencode/internal/tui/styles\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n\t\"github.com/opencode-ai/opencode/internal/tui/util\"\n)\n\ntype CompletionItem struct {\n\ttitle string\n\tTitle string\n\tValue string\n}\n\ntype CompletionItemI interface {\n\tutilComponents.SimpleListItem\n\tGetValue() string\n\tDisplayValue() string\n}\n\nfunc (ci *CompletionItem) Render(selected bool, width int) string {\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\n\titemStyle := baseStyle.\n\t\tWidth(width).\n\t\tPadding(0, 1)\n\n\tif selected {\n\t\titemStyle = itemStyle.\n\t\t\tBackground(t.Background()).\n\t\t\tForeground(t.Primary()).\n\t\t\tBold(true)\n\t}\n\n\ttitle := itemStyle.Render(\n\t\tci.GetValue(),\n\t)\n\n\treturn title\n}\n\nfunc (ci *CompletionItem) DisplayValue() string {\n\treturn ci.Title\n}\n\nfunc (ci *CompletionItem) GetValue() string {\n\treturn ci.Value\n}\n\nfunc NewCompletionItem(completionItem CompletionItem) CompletionItemI {\n\treturn &completionItem\n}\n\ntype CompletionProvider interface {\n\tGetId() string\n\tGetEntry() CompletionItemI\n\tGetChildEntries(query string) ([]CompletionItemI, error)\n}\n\ntype CompletionSelectedMsg struct {\n\tSearchString string\n\tCompletionValue string\n}\n\ntype CompletionDialogCompleteItemMsg struct {\n\tValue string\n}\n\ntype CompletionDialogCloseMsg struct{}\n\ntype CompletionDialog interface {\n\ttea.Model\n\tlayout.Bindings\n\tSetWidth(width int)\n}\n\ntype completionDialogCmp struct {\n\tquery string\n\tcompletionProvider CompletionProvider\n\twidth int\n\theight int\n\tpseudoSearchTextArea textarea.Model\n\tlistView utilComponents.SimpleList[CompletionItemI]\n}\n\ntype completionDialogKeyMap struct {\n\tComplete key.Binding\n\tCancel key.Binding\n}\n\nvar completionDialogKeys = completionDialogKeyMap{\n\tComplete: key.NewBinding(\n\t\tkey.WithKeys(\"tab\", \"enter\"),\n\t),\n\tCancel: key.NewBinding(\n\t\tkey.WithKeys(\" \", \"esc\", \"backspace\"),\n\t),\n}\n\nfunc (c *completionDialogCmp) Init() tea.Cmd {\n\treturn nil\n}\n\nfunc (c *completionDialogCmp) complete(item CompletionItemI) tea.Cmd {\n\tvalue := c.pseudoSearchTextArea.Value()\n\n\tif value == \"\" {\n\t\treturn nil\n\t}\n\n\treturn tea.Batch(\n\t\tutil.CmdHandler(CompletionSelectedMsg{\n\t\t\tSearchString: value,\n\t\t\tCompletionValue: item.GetValue(),\n\t\t}),\n\t\tc.close(),\n\t)\n}\n\nfunc (c *completionDialogCmp) close() tea.Cmd {\n\tc.listView.SetItems([]CompletionItemI{})\n\tc.pseudoSearchTextArea.Reset()\n\tc.pseudoSearchTextArea.Blur()\n\n\treturn util.CmdHandler(CompletionDialogCloseMsg{})\n}\n\nfunc (c *completionDialogCmp) Update(msg tea.Msg) (tea.Model, tea.Cmd) {\n\tvar cmds []tea.Cmd\n\tswitch msg := msg.(type) {\n\tcase tea.KeyMsg:\n\t\tif c.pseudoSearchTextArea.Focused() {\n\n\t\t\tif !key.Matches(msg, completionDialogKeys.Complete) {\n\n\t\t\t\tvar cmd tea.Cmd\n\t\t\t\tc.pseudoSearchTextArea, cmd = c.pseudoSearchTextArea.Update(msg)\n\t\t\t\tcmds = append(cmds, cmd)\n\n\t\t\t\tvar query string\n\t\t\t\tquery = c.pseudoSearchTextArea.Value()\n\t\t\t\tif query != \"\" {\n\t\t\t\t\tquery = query[1:]\n\t\t\t\t}\n\n\t\t\t\tif query != c.query {\n\t\t\t\t\tlogging.Info(\"Query\", query)\n\t\t\t\t\titems, err := c.completionProvider.GetChildEntries(query)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlogging.Error(\"Failed to get child entries\", err)\n\t\t\t\t\t}\n\n\t\t\t\t\tc.listView.SetItems(items)\n\t\t\t\t\tc.query = query\n\t\t\t\t}\n\n\t\t\t\tu, cmd := c.listView.Update(msg)\n\t\t\t\tc.listView = u.(utilComponents.SimpleList[CompletionItemI])\n\n\t\t\t\tcmds = append(cmds, cmd)\n\t\t\t}\n\n\t\t\tswitch {\n\t\t\tcase key.Matches(msg, completionDialogKeys.Complete):\n\t\t\t\titem, i := c.listView.GetSelectedItem()\n\t\t\t\tif i == -1 {\n\t\t\t\t\treturn c, nil\n\t\t\t\t}\n\n\t\t\t\tcmd := c.complete(item)\n\n\t\t\t\treturn c, cmd\n\t\t\tcase key.Matches(msg, completionDialogKeys.Cancel):\n\t\t\t\t// Only close on backspace when there are no characters left\n\t\t\t\tif msg.String() != \"backspace\" || len(c.pseudoSearchTextArea.Value()) <= 0 {\n\t\t\t\t\treturn c, c.close()\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn c, tea.Batch(cmds...)\n\t\t} else {\n\t\t\titems, err := c.completionProvider.GetChildEntries(\"\")\n\t\t\tif err != nil {\n\t\t\t\tlogging.Error(\"Failed to get child entries\", err)\n\t\t\t}\n\n\t\t\tc.listView.SetItems(items)\n\t\t\tc.pseudoSearchTextArea.SetValue(msg.String())\n\t\t\treturn c, c.pseudoSearchTextArea.Focus()\n\t\t}\n\tcase tea.WindowSizeMsg:\n\t\tc.width = msg.Width\n\t\tc.height = msg.Height\n\t}\n\n\treturn c, tea.Batch(cmds...)\n}\n\nfunc (c *completionDialogCmp) View() string {\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\n\tmaxWidth := 40\n\n\tcompletions := c.listView.GetItems()\n\n\tfor _, cmd := range completions {\n\t\ttitle := cmd.DisplayValue()\n\t\tif len(title) > maxWidth-4 {\n\t\t\tmaxWidth = len(title) + 4\n\t\t}\n\t}\n\n\tc.listView.SetMaxWidth(maxWidth)\n\n\treturn baseStyle.Padding(0, 0).\n\t\tBorder(lipgloss.NormalBorder()).\n\t\tBorderBottom(false).\n\t\tBorderRight(false).\n\t\tBorderLeft(false).\n\t\tBorderBackground(t.Background()).\n\t\tBorderForeground(t.TextMuted()).\n\t\tWidth(c.width).\n\t\tRender(c.listView.View())\n}\n\nfunc (c *completionDialogCmp) SetWidth(width int) {\n\tc.width = width\n}\n\nfunc (c *completionDialogCmp) BindingKeys() []key.Binding {\n\treturn layout.KeyMapToSlice(completionDialogKeys)\n}\n\nfunc NewCompletionDialogCmp(completionProvider CompletionProvider) CompletionDialog {\n\tti := textarea.New()\n\n\titems, err := completionProvider.GetChildEntries(\"\")\n\tif err != nil {\n\t\tlogging.Error(\"Failed to get child entries\", err)\n\t}\n\n\tli := utilComponents.NewSimpleList(\n\t\titems,\n\t\t7,\n\t\t\"No file matches found\",\n\t\tfalse,\n\t)\n\n\treturn &completionDialogCmp{\n\t\tquery: \"\",\n\t\tcompletionProvider: completionProvider,\n\t\tpseudoSearchTextArea: ti,\n\t\tlistView: li,\n\t}\n}\n"], ["/opencode/internal/tui/components/logs/details.go", "package logs\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/charmbracelet/bubbles/key\"\n\t\"github.com/charmbracelet/bubbles/viewport\"\n\ttea \"github.com/charmbracelet/bubbletea\"\n\t\"github.com/charmbracelet/lipgloss\"\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n\t\"github.com/opencode-ai/opencode/internal/tui/layout\"\n\t\"github.com/opencode-ai/opencode/internal/tui/styles\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n)\n\ntype DetailComponent interface {\n\ttea.Model\n\tlayout.Sizeable\n\tlayout.Bindings\n}\n\ntype detailCmp struct {\n\twidth, height int\n\tcurrentLog logging.LogMessage\n\tviewport viewport.Model\n}\n\nfunc (i *detailCmp) Init() tea.Cmd {\n\tmessages := logging.List()\n\tif len(messages) == 0 {\n\t\treturn nil\n\t}\n\ti.currentLog = messages[0]\n\treturn nil\n}\n\nfunc (i *detailCmp) Update(msg tea.Msg) (tea.Model, tea.Cmd) {\n\tswitch msg := msg.(type) {\n\tcase selectedLogMsg:\n\t\tif msg.ID != i.currentLog.ID {\n\t\t\ti.currentLog = logging.LogMessage(msg)\n\t\t\ti.updateContent()\n\t\t}\n\t}\n\n\treturn i, nil\n}\n\nfunc (i *detailCmp) updateContent() {\n\tvar content strings.Builder\n\tt := theme.CurrentTheme()\n\n\t// Format the header with timestamp and level\n\ttimeStyle := lipgloss.NewStyle().Foreground(t.TextMuted())\n\tlevelStyle := getLevelStyle(i.currentLog.Level)\n\n\theader := lipgloss.JoinHorizontal(\n\t\tlipgloss.Center,\n\t\ttimeStyle.Render(i.currentLog.Time.Format(time.RFC3339)),\n\t\t\" \",\n\t\tlevelStyle.Render(i.currentLog.Level),\n\t)\n\n\tcontent.WriteString(lipgloss.NewStyle().Bold(true).Render(header))\n\tcontent.WriteString(\"\\n\\n\")\n\n\t// Message with styling\n\tmessageStyle := lipgloss.NewStyle().Bold(true).Foreground(t.Text())\n\tcontent.WriteString(messageStyle.Render(\"Message:\"))\n\tcontent.WriteString(\"\\n\")\n\tcontent.WriteString(lipgloss.NewStyle().Padding(0, 2).Render(i.currentLog.Message))\n\tcontent.WriteString(\"\\n\\n\")\n\n\t// Attributes section\n\tif len(i.currentLog.Attributes) > 0 {\n\t\tattrHeaderStyle := lipgloss.NewStyle().Bold(true).Foreground(t.Text())\n\t\tcontent.WriteString(attrHeaderStyle.Render(\"Attributes:\"))\n\t\tcontent.WriteString(\"\\n\")\n\n\t\t// Create a table-like display for attributes\n\t\tkeyStyle := lipgloss.NewStyle().Foreground(t.Primary()).Bold(true)\n\t\tvalueStyle := lipgloss.NewStyle().Foreground(t.Text())\n\n\t\tfor _, attr := range i.currentLog.Attributes {\n\t\t\tattrLine := fmt.Sprintf(\"%s: %s\",\n\t\t\t\tkeyStyle.Render(attr.Key),\n\t\t\t\tvalueStyle.Render(attr.Value),\n\t\t\t)\n\t\t\tcontent.WriteString(lipgloss.NewStyle().Padding(0, 2).Render(attrLine))\n\t\t\tcontent.WriteString(\"\\n\")\n\t\t}\n\t}\n\n\ti.viewport.SetContent(content.String())\n}\n\nfunc getLevelStyle(level string) lipgloss.Style {\n\tstyle := lipgloss.NewStyle().Bold(true)\n\tt := theme.CurrentTheme()\n\t\n\tswitch strings.ToLower(level) {\n\tcase \"info\":\n\t\treturn style.Foreground(t.Info())\n\tcase \"warn\", \"warning\":\n\t\treturn style.Foreground(t.Warning())\n\tcase \"error\", \"err\":\n\t\treturn style.Foreground(t.Error())\n\tcase \"debug\":\n\t\treturn style.Foreground(t.Success())\n\tdefault:\n\t\treturn style.Foreground(t.Text())\n\t}\n}\n\nfunc (i *detailCmp) View() string {\n\tt := theme.CurrentTheme()\n\treturn styles.ForceReplaceBackgroundWithLipgloss(i.viewport.View(), t.Background())\n}\n\nfunc (i *detailCmp) GetSize() (int, int) {\n\treturn i.width, i.height\n}\n\nfunc (i *detailCmp) SetSize(width int, height int) tea.Cmd {\n\ti.width = width\n\ti.height = height\n\ti.viewport.Width = i.width\n\ti.viewport.Height = i.height\n\ti.updateContent()\n\treturn nil\n}\n\nfunc (i *detailCmp) BindingKeys() []key.Binding {\n\treturn layout.KeyMapToSlice(i.viewport.KeyMap)\n}\n\nfunc NewLogsDetails() DetailComponent {\n\treturn &detailCmp{\n\t\tviewport: viewport.New(0, 0),\n\t}\n}\n"], ["/opencode/internal/tui/layout/overlay.go", "package layout\n\nimport (\n\t\"strings\"\n\n\t\"github.com/charmbracelet/lipgloss\"\n\tchAnsi \"github.com/charmbracelet/x/ansi\"\n\t\"github.com/muesli/ansi\"\n\t\"github.com/muesli/reflow/truncate\"\n\t\"github.com/muesli/termenv\"\n\t\"github.com/opencode-ai/opencode/internal/tui/styles\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n\t\"github.com/opencode-ai/opencode/internal/tui/util\"\n)\n\n// Most of this code is borrowed from\n// https://github.com/charmbracelet/lipgloss/pull/102\n// as well as the lipgloss library, with some modification for what I needed.\n\n// Split a string into lines, additionally returning the size of the widest\n// line.\nfunc getLines(s string) (lines []string, widest int) {\n\tlines = strings.Split(s, \"\\n\")\n\n\tfor _, l := range lines {\n\t\tw := ansi.PrintableRuneWidth(l)\n\t\tif widest < w {\n\t\t\twidest = w\n\t\t}\n\t}\n\n\treturn lines, widest\n}\n\n// PlaceOverlay places fg on top of bg.\nfunc PlaceOverlay(\n\tx, y int,\n\tfg, bg string,\n\tshadow bool, opts ...WhitespaceOption,\n) string {\n\tfgLines, fgWidth := getLines(fg)\n\tbgLines, bgWidth := getLines(bg)\n\tbgHeight := len(bgLines)\n\tfgHeight := len(fgLines)\n\n\tif shadow {\n\t\tt := theme.CurrentTheme()\n\t\tbaseStyle := styles.BaseStyle()\n\n\t\tvar shadowbg string = \"\"\n\t\tshadowchar := lipgloss.NewStyle().\n\t\t\tBackground(t.BackgroundDarker()).\n\t\t\tForeground(t.Background()).\n\t\t\tRender(\"░\")\n\t\tbgchar := baseStyle.Render(\" \")\n\t\tfor i := 0; i <= fgHeight; i++ {\n\t\t\tif i == 0 {\n\t\t\t\tshadowbg += bgchar + strings.Repeat(bgchar, fgWidth) + \"\\n\"\n\t\t\t} else {\n\t\t\t\tshadowbg += bgchar + strings.Repeat(shadowchar, fgWidth) + \"\\n\"\n\t\t\t}\n\t\t}\n\n\t\tfg = PlaceOverlay(0, 0, fg, shadowbg, false, opts...)\n\t\tfgLines, fgWidth = getLines(fg)\n\t\tfgHeight = len(fgLines)\n\t}\n\n\tif fgWidth >= bgWidth && fgHeight >= bgHeight {\n\t\t// FIXME: return fg or bg?\n\t\treturn fg\n\t}\n\t// TODO: allow placement outside of the bg box?\n\tx = util.Clamp(x, 0, bgWidth-fgWidth)\n\ty = util.Clamp(y, 0, bgHeight-fgHeight)\n\n\tws := &whitespace{}\n\tfor _, opt := range opts {\n\t\topt(ws)\n\t}\n\n\tvar b strings.Builder\n\tfor i, bgLine := range bgLines {\n\t\tif i > 0 {\n\t\t\tb.WriteByte('\\n')\n\t\t}\n\t\tif i < y || i >= y+fgHeight {\n\t\t\tb.WriteString(bgLine)\n\t\t\tcontinue\n\t\t}\n\n\t\tpos := 0\n\t\tif x > 0 {\n\t\t\tleft := truncate.String(bgLine, uint(x))\n\t\t\tpos = ansi.PrintableRuneWidth(left)\n\t\t\tb.WriteString(left)\n\t\t\tif pos < x {\n\t\t\t\tb.WriteString(ws.render(x - pos))\n\t\t\t\tpos = x\n\t\t\t}\n\t\t}\n\n\t\tfgLine := fgLines[i-y]\n\t\tb.WriteString(fgLine)\n\t\tpos += ansi.PrintableRuneWidth(fgLine)\n\n\t\tright := cutLeft(bgLine, pos)\n\t\tbgWidth := ansi.PrintableRuneWidth(bgLine)\n\t\trightWidth := ansi.PrintableRuneWidth(right)\n\t\tif rightWidth <= bgWidth-pos {\n\t\t\tb.WriteString(ws.render(bgWidth - rightWidth - pos))\n\t\t}\n\n\t\tb.WriteString(right)\n\t}\n\n\treturn b.String()\n}\n\n// cutLeft cuts printable characters from the left.\n// This function is heavily based on muesli's ansi and truncate packages.\nfunc cutLeft(s string, cutWidth int) string {\n\treturn chAnsi.Cut(s, cutWidth, lipgloss.Width(s))\n}\n\nfunc max(a, b int) int {\n\tif a > b {\n\t\treturn a\n\t}\n\treturn b\n}\n\ntype whitespace struct {\n\tstyle termenv.Style\n\tchars string\n}\n\n// Render whitespaces.\nfunc (w whitespace) render(width int) string {\n\tif w.chars == \"\" {\n\t\tw.chars = \" \"\n\t}\n\n\tr := []rune(w.chars)\n\tj := 0\n\tb := strings.Builder{}\n\n\t// Cycle through runes and print them into the whitespace.\n\tfor i := 0; i < width; {\n\t\tb.WriteRune(r[j])\n\t\tj++\n\t\tif j >= len(r) {\n\t\t\tj = 0\n\t\t}\n\t\ti += ansi.PrintableRuneWidth(string(r[j]))\n\t}\n\n\t// Fill any extra gaps white spaces. This might be necessary if any runes\n\t// are more than one cell wide, which could leave a one-rune gap.\n\tshort := width - ansi.PrintableRuneWidth(b.String())\n\tif short > 0 {\n\t\tb.WriteString(strings.Repeat(\" \", short))\n\t}\n\n\treturn w.style.Styled(b.String())\n}\n\n// WhitespaceOption sets a styling rule for rendering whitespace.\ntype WhitespaceOption func(*whitespace)\n"], ["/opencode/internal/tui/tui.go", "package tui\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"strings\"\n\n\t\"github.com/charmbracelet/bubbles/key\"\n\ttea \"github.com/charmbracelet/bubbletea\"\n\t\"github.com/charmbracelet/lipgloss\"\n\t\"github.com/opencode-ai/opencode/internal/app\"\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/llm/agent\"\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n\t\"github.com/opencode-ai/opencode/internal/permission\"\n\t\"github.com/opencode-ai/opencode/internal/pubsub\"\n\t\"github.com/opencode-ai/opencode/internal/session\"\n\t\"github.com/opencode-ai/opencode/internal/tui/components/chat\"\n\t\"github.com/opencode-ai/opencode/internal/tui/components/core\"\n\t\"github.com/opencode-ai/opencode/internal/tui/components/dialog\"\n\t\"github.com/opencode-ai/opencode/internal/tui/layout\"\n\t\"github.com/opencode-ai/opencode/internal/tui/page\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n\t\"github.com/opencode-ai/opencode/internal/tui/util\"\n)\n\ntype keyMap struct {\n\tLogs key.Binding\n\tQuit key.Binding\n\tHelp key.Binding\n\tSwitchSession key.Binding\n\tCommands key.Binding\n\tFilepicker key.Binding\n\tModels key.Binding\n\tSwitchTheme key.Binding\n}\n\ntype startCompactSessionMsg struct{}\n\nconst (\n\tquitKey = \"q\"\n)\n\nvar keys = keyMap{\n\tLogs: key.NewBinding(\n\t\tkey.WithKeys(\"ctrl+l\"),\n\t\tkey.WithHelp(\"ctrl+l\", \"logs\"),\n\t),\n\n\tQuit: key.NewBinding(\n\t\tkey.WithKeys(\"ctrl+c\"),\n\t\tkey.WithHelp(\"ctrl+c\", \"quit\"),\n\t),\n\tHelp: key.NewBinding(\n\t\tkey.WithKeys(\"ctrl+_\", \"ctrl+h\"),\n\t\tkey.WithHelp(\"ctrl+?\", \"toggle help\"),\n\t),\n\n\tSwitchSession: key.NewBinding(\n\t\tkey.WithKeys(\"ctrl+s\"),\n\t\tkey.WithHelp(\"ctrl+s\", \"switch session\"),\n\t),\n\n\tCommands: key.NewBinding(\n\t\tkey.WithKeys(\"ctrl+k\"),\n\t\tkey.WithHelp(\"ctrl+k\", \"commands\"),\n\t),\n\tFilepicker: key.NewBinding(\n\t\tkey.WithKeys(\"ctrl+f\"),\n\t\tkey.WithHelp(\"ctrl+f\", \"select files to upload\"),\n\t),\n\tModels: key.NewBinding(\n\t\tkey.WithKeys(\"ctrl+o\"),\n\t\tkey.WithHelp(\"ctrl+o\", \"model selection\"),\n\t),\n\n\tSwitchTheme: key.NewBinding(\n\t\tkey.WithKeys(\"ctrl+t\"),\n\t\tkey.WithHelp(\"ctrl+t\", \"switch theme\"),\n\t),\n}\n\nvar helpEsc = key.NewBinding(\n\tkey.WithKeys(\"?\"),\n\tkey.WithHelp(\"?\", \"toggle help\"),\n)\n\nvar returnKey = key.NewBinding(\n\tkey.WithKeys(\"esc\"),\n\tkey.WithHelp(\"esc\", \"close\"),\n)\n\nvar logsKeyReturnKey = key.NewBinding(\n\tkey.WithKeys(\"esc\", \"backspace\", quitKey),\n\tkey.WithHelp(\"esc/q\", \"go back\"),\n)\n\ntype appModel struct {\n\twidth, height int\n\tcurrentPage page.PageID\n\tpreviousPage page.PageID\n\tpages map[page.PageID]tea.Model\n\tloadedPages map[page.PageID]bool\n\tstatus core.StatusCmp\n\tapp *app.App\n\tselectedSession session.Session\n\n\tshowPermissions bool\n\tpermissions dialog.PermissionDialogCmp\n\n\tshowHelp bool\n\thelp dialog.HelpCmp\n\n\tshowQuit bool\n\tquit dialog.QuitDialog\n\n\tshowSessionDialog bool\n\tsessionDialog dialog.SessionDialog\n\n\tshowCommandDialog bool\n\tcommandDialog dialog.CommandDialog\n\tcommands []dialog.Command\n\n\tshowModelDialog bool\n\tmodelDialog dialog.ModelDialog\n\n\tshowInitDialog bool\n\tinitDialog dialog.InitDialogCmp\n\n\tshowFilepicker bool\n\tfilepicker dialog.FilepickerCmp\n\n\tshowThemeDialog bool\n\tthemeDialog dialog.ThemeDialog\n\n\tshowMultiArgumentsDialog bool\n\tmultiArgumentsDialog dialog.MultiArgumentsDialogCmp\n\n\tisCompacting bool\n\tcompactingMessage string\n}\n\nfunc (a appModel) Init() tea.Cmd {\n\tvar cmds []tea.Cmd\n\tcmd := a.pages[a.currentPage].Init()\n\ta.loadedPages[a.currentPage] = true\n\tcmds = append(cmds, cmd)\n\tcmd = a.status.Init()\n\tcmds = append(cmds, cmd)\n\tcmd = a.quit.Init()\n\tcmds = append(cmds, cmd)\n\tcmd = a.help.Init()\n\tcmds = append(cmds, cmd)\n\tcmd = a.sessionDialog.Init()\n\tcmds = append(cmds, cmd)\n\tcmd = a.commandDialog.Init()\n\tcmds = append(cmds, cmd)\n\tcmd = a.modelDialog.Init()\n\tcmds = append(cmds, cmd)\n\tcmd = a.initDialog.Init()\n\tcmds = append(cmds, cmd)\n\tcmd = a.filepicker.Init()\n\tcmds = append(cmds, cmd)\n\tcmd = a.themeDialog.Init()\n\tcmds = append(cmds, cmd)\n\n\t// Check if we should show the init dialog\n\tcmds = append(cmds, func() tea.Msg {\n\t\tshouldShow, err := config.ShouldShowInitDialog()\n\t\tif err != nil {\n\t\t\treturn util.InfoMsg{\n\t\t\t\tType: util.InfoTypeError,\n\t\t\t\tMsg: \"Failed to check init status: \" + err.Error(),\n\t\t\t}\n\t\t}\n\t\treturn dialog.ShowInitDialogMsg{Show: shouldShow}\n\t})\n\n\treturn tea.Batch(cmds...)\n}\n\nfunc (a appModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {\n\tvar cmds []tea.Cmd\n\tvar cmd tea.Cmd\n\tswitch msg := msg.(type) {\n\tcase tea.WindowSizeMsg:\n\t\tmsg.Height -= 1 // Make space for the status bar\n\t\ta.width, a.height = msg.Width, msg.Height\n\n\t\ts, _ := a.status.Update(msg)\n\t\ta.status = s.(core.StatusCmp)\n\t\ta.pages[a.currentPage], cmd = a.pages[a.currentPage].Update(msg)\n\t\tcmds = append(cmds, cmd)\n\n\t\tprm, permCmd := a.permissions.Update(msg)\n\t\ta.permissions = prm.(dialog.PermissionDialogCmp)\n\t\tcmds = append(cmds, permCmd)\n\n\t\thelp, helpCmd := a.help.Update(msg)\n\t\ta.help = help.(dialog.HelpCmp)\n\t\tcmds = append(cmds, helpCmd)\n\n\t\tsession, sessionCmd := a.sessionDialog.Update(msg)\n\t\ta.sessionDialog = session.(dialog.SessionDialog)\n\t\tcmds = append(cmds, sessionCmd)\n\n\t\tcommand, commandCmd := a.commandDialog.Update(msg)\n\t\ta.commandDialog = command.(dialog.CommandDialog)\n\t\tcmds = append(cmds, commandCmd)\n\n\t\tfilepicker, filepickerCmd := a.filepicker.Update(msg)\n\t\ta.filepicker = filepicker.(dialog.FilepickerCmp)\n\t\tcmds = append(cmds, filepickerCmd)\n\n\t\ta.initDialog.SetSize(msg.Width, msg.Height)\n\n\t\tif a.showMultiArgumentsDialog {\n\t\t\ta.multiArgumentsDialog.SetSize(msg.Width, msg.Height)\n\t\t\targs, argsCmd := a.multiArgumentsDialog.Update(msg)\n\t\t\ta.multiArgumentsDialog = args.(dialog.MultiArgumentsDialogCmp)\n\t\t\tcmds = append(cmds, argsCmd, a.multiArgumentsDialog.Init())\n\t\t}\n\n\t\treturn a, tea.Batch(cmds...)\n\t// Status\n\tcase util.InfoMsg:\n\t\ts, cmd := a.status.Update(msg)\n\t\ta.status = s.(core.StatusCmp)\n\t\tcmds = append(cmds, cmd)\n\t\treturn a, tea.Batch(cmds...)\n\tcase pubsub.Event[logging.LogMessage]:\n\t\tif msg.Payload.Persist {\n\t\t\tswitch msg.Payload.Level {\n\t\t\tcase \"error\":\n\t\t\t\ts, cmd := a.status.Update(util.InfoMsg{\n\t\t\t\t\tType: util.InfoTypeError,\n\t\t\t\t\tMsg: msg.Payload.Message,\n\t\t\t\t\tTTL: msg.Payload.PersistTime,\n\t\t\t\t})\n\t\t\t\ta.status = s.(core.StatusCmp)\n\t\t\t\tcmds = append(cmds, cmd)\n\t\t\tcase \"info\":\n\t\t\t\ts, cmd := a.status.Update(util.InfoMsg{\n\t\t\t\t\tType: util.InfoTypeInfo,\n\t\t\t\t\tMsg: msg.Payload.Message,\n\t\t\t\t\tTTL: msg.Payload.PersistTime,\n\t\t\t\t})\n\t\t\t\ta.status = s.(core.StatusCmp)\n\t\t\t\tcmds = append(cmds, cmd)\n\n\t\t\tcase \"warn\":\n\t\t\t\ts, cmd := a.status.Update(util.InfoMsg{\n\t\t\t\t\tType: util.InfoTypeWarn,\n\t\t\t\t\tMsg: msg.Payload.Message,\n\t\t\t\t\tTTL: msg.Payload.PersistTime,\n\t\t\t\t})\n\n\t\t\t\ta.status = s.(core.StatusCmp)\n\t\t\t\tcmds = append(cmds, cmd)\n\t\t\tdefault:\n\t\t\t\ts, cmd := a.status.Update(util.InfoMsg{\n\t\t\t\t\tType: util.InfoTypeInfo,\n\t\t\t\t\tMsg: msg.Payload.Message,\n\t\t\t\t\tTTL: msg.Payload.PersistTime,\n\t\t\t\t})\n\t\t\t\ta.status = s.(core.StatusCmp)\n\t\t\t\tcmds = append(cmds, cmd)\n\t\t\t}\n\t\t}\n\tcase util.ClearStatusMsg:\n\t\ts, _ := a.status.Update(msg)\n\t\ta.status = s.(core.StatusCmp)\n\n\t// Permission\n\tcase pubsub.Event[permission.PermissionRequest]:\n\t\ta.showPermissions = true\n\t\treturn a, a.permissions.SetPermissions(msg.Payload)\n\tcase dialog.PermissionResponseMsg:\n\t\tvar cmd tea.Cmd\n\t\tswitch msg.Action {\n\t\tcase dialog.PermissionAllow:\n\t\t\ta.app.Permissions.Grant(msg.Permission)\n\t\tcase dialog.PermissionAllowForSession:\n\t\t\ta.app.Permissions.GrantPersistant(msg.Permission)\n\t\tcase dialog.PermissionDeny:\n\t\t\ta.app.Permissions.Deny(msg.Permission)\n\t\t}\n\t\ta.showPermissions = false\n\t\treturn a, cmd\n\n\tcase page.PageChangeMsg:\n\t\treturn a, a.moveToPage(msg.ID)\n\n\tcase dialog.CloseQuitMsg:\n\t\ta.showQuit = false\n\t\treturn a, nil\n\n\tcase dialog.CloseSessionDialogMsg:\n\t\ta.showSessionDialog = false\n\t\treturn a, nil\n\n\tcase dialog.CloseCommandDialogMsg:\n\t\ta.showCommandDialog = false\n\t\treturn a, nil\n\n\tcase startCompactSessionMsg:\n\t\t// Start compacting the current session\n\t\ta.isCompacting = true\n\t\ta.compactingMessage = \"Starting summarization...\"\n\n\t\tif a.selectedSession.ID == \"\" {\n\t\t\ta.isCompacting = false\n\t\t\treturn a, util.ReportWarn(\"No active session to summarize\")\n\t\t}\n\n\t\t// Start the summarization process\n\t\treturn a, func() tea.Msg {\n\t\t\tctx := context.Background()\n\t\t\ta.app.CoderAgent.Summarize(ctx, a.selectedSession.ID)\n\t\t\treturn nil\n\t\t}\n\n\tcase pubsub.Event[agent.AgentEvent]:\n\t\tpayload := msg.Payload\n\t\tif payload.Error != nil {\n\t\t\ta.isCompacting = false\n\t\t\treturn a, util.ReportError(payload.Error)\n\t\t}\n\n\t\ta.compactingMessage = payload.Progress\n\n\t\tif payload.Done && payload.Type == agent.AgentEventTypeSummarize {\n\t\t\ta.isCompacting = false\n\t\t\treturn a, util.ReportInfo(\"Session summarization complete\")\n\t\t} else if payload.Done && payload.Type == agent.AgentEventTypeResponse && a.selectedSession.ID != \"\" {\n\t\t\tmodel := a.app.CoderAgent.Model()\n\t\t\tcontextWindow := model.ContextWindow\n\t\t\ttokens := a.selectedSession.CompletionTokens + a.selectedSession.PromptTokens\n\t\t\tif (tokens >= int64(float64(contextWindow)*0.95)) && config.Get().AutoCompact {\n\t\t\t\treturn a, util.CmdHandler(startCompactSessionMsg{})\n\t\t\t}\n\t\t}\n\t\t// Continue listening for events\n\t\treturn a, nil\n\n\tcase dialog.CloseThemeDialogMsg:\n\t\ta.showThemeDialog = false\n\t\treturn a, nil\n\n\tcase dialog.ThemeChangedMsg:\n\t\ta.pages[a.currentPage], cmd = a.pages[a.currentPage].Update(msg)\n\t\ta.showThemeDialog = false\n\t\treturn a, tea.Batch(cmd, util.ReportInfo(\"Theme changed to: \"+msg.ThemeName))\n\n\tcase dialog.CloseModelDialogMsg:\n\t\ta.showModelDialog = false\n\t\treturn a, nil\n\n\tcase dialog.ModelSelectedMsg:\n\t\ta.showModelDialog = false\n\n\t\tmodel, err := a.app.CoderAgent.Update(config.AgentCoder, msg.Model.ID)\n\t\tif err != nil {\n\t\t\treturn a, util.ReportError(err)\n\t\t}\n\n\t\treturn a, util.ReportInfo(fmt.Sprintf(\"Model changed to %s\", model.Name))\n\n\tcase dialog.ShowInitDialogMsg:\n\t\ta.showInitDialog = msg.Show\n\t\treturn a, nil\n\n\tcase dialog.CloseInitDialogMsg:\n\t\ta.showInitDialog = false\n\t\tif msg.Initialize {\n\t\t\t// Run the initialization command\n\t\t\tfor _, cmd := range a.commands {\n\t\t\t\tif cmd.ID == \"init\" {\n\t\t\t\t\t// Mark the project as initialized\n\t\t\t\t\tif err := config.MarkProjectInitialized(); err != nil {\n\t\t\t\t\t\treturn a, util.ReportError(err)\n\t\t\t\t\t}\n\t\t\t\t\treturn a, cmd.Handler(cmd)\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\t// Mark the project as initialized without running the command\n\t\t\tif err := config.MarkProjectInitialized(); err != nil {\n\t\t\t\treturn a, util.ReportError(err)\n\t\t\t}\n\t\t}\n\t\treturn a, nil\n\n\tcase chat.SessionSelectedMsg:\n\t\ta.selectedSession = msg\n\t\ta.sessionDialog.SetSelectedSession(msg.ID)\n\n\tcase pubsub.Event[session.Session]:\n\t\tif msg.Type == pubsub.UpdatedEvent && msg.Payload.ID == a.selectedSession.ID {\n\t\t\ta.selectedSession = msg.Payload\n\t\t}\n\tcase dialog.SessionSelectedMsg:\n\t\ta.showSessionDialog = false\n\t\tif a.currentPage == page.ChatPage {\n\t\t\treturn a, util.CmdHandler(chat.SessionSelectedMsg(msg.Session))\n\t\t}\n\t\treturn a, nil\n\n\tcase dialog.CommandSelectedMsg:\n\t\ta.showCommandDialog = false\n\t\t// Execute the command handler if available\n\t\tif msg.Command.Handler != nil {\n\t\t\treturn a, msg.Command.Handler(msg.Command)\n\t\t}\n\t\treturn a, util.ReportInfo(\"Command selected: \" + msg.Command.Title)\n\n\tcase dialog.ShowMultiArgumentsDialogMsg:\n\t\t// Show multi-arguments dialog\n\t\ta.multiArgumentsDialog = dialog.NewMultiArgumentsDialogCmp(msg.CommandID, msg.Content, msg.ArgNames)\n\t\ta.showMultiArgumentsDialog = true\n\t\treturn a, a.multiArgumentsDialog.Init()\n\n\tcase dialog.CloseMultiArgumentsDialogMsg:\n\t\t// Close multi-arguments dialog\n\t\ta.showMultiArgumentsDialog = false\n\n\t\t// If submitted, replace all named arguments and run the command\n\t\tif msg.Submit {\n\t\t\tcontent := msg.Content\n\n\t\t\t// Replace each named argument with its value\n\t\t\tfor name, value := range msg.Args {\n\t\t\t\tplaceholder := \"$\" + name\n\t\t\t\tcontent = strings.ReplaceAll(content, placeholder, value)\n\t\t\t}\n\n\t\t\t// Execute the command with arguments\n\t\t\treturn a, util.CmdHandler(dialog.CommandRunCustomMsg{\n\t\t\t\tContent: content,\n\t\t\t\tArgs: msg.Args,\n\t\t\t})\n\t\t}\n\t\treturn a, nil\n\n\tcase tea.KeyMsg:\n\t\t// If multi-arguments dialog is open, let it handle the key press first\n\t\tif a.showMultiArgumentsDialog {\n\t\t\targs, cmd := a.multiArgumentsDialog.Update(msg)\n\t\t\ta.multiArgumentsDialog = args.(dialog.MultiArgumentsDialogCmp)\n\t\t\treturn a, cmd\n\t\t}\n\n\t\tswitch {\n\n\t\tcase key.Matches(msg, keys.Quit):\n\t\t\ta.showQuit = !a.showQuit\n\t\t\tif a.showHelp {\n\t\t\t\ta.showHelp = false\n\t\t\t}\n\t\t\tif a.showSessionDialog {\n\t\t\t\ta.showSessionDialog = false\n\t\t\t}\n\t\t\tif a.showCommandDialog {\n\t\t\t\ta.showCommandDialog = false\n\t\t\t}\n\t\t\tif a.showFilepicker {\n\t\t\t\ta.showFilepicker = false\n\t\t\t\ta.filepicker.ToggleFilepicker(a.showFilepicker)\n\t\t\t}\n\t\t\tif a.showModelDialog {\n\t\t\t\ta.showModelDialog = false\n\t\t\t}\n\t\t\tif a.showMultiArgumentsDialog {\n\t\t\t\ta.showMultiArgumentsDialog = false\n\t\t\t}\n\t\t\treturn a, nil\n\t\tcase key.Matches(msg, keys.SwitchSession):\n\t\t\tif a.currentPage == page.ChatPage && !a.showQuit && !a.showPermissions && !a.showCommandDialog {\n\t\t\t\t// Load sessions and show the dialog\n\t\t\t\tsessions, err := a.app.Sessions.List(context.Background())\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn a, util.ReportError(err)\n\t\t\t\t}\n\t\t\t\tif len(sessions) == 0 {\n\t\t\t\t\treturn a, util.ReportWarn(\"No sessions available\")\n\t\t\t\t}\n\t\t\t\ta.sessionDialog.SetSessions(sessions)\n\t\t\t\ta.showSessionDialog = true\n\t\t\t\treturn a, nil\n\t\t\t}\n\t\t\treturn a, nil\n\t\tcase key.Matches(msg, keys.Commands):\n\t\t\tif a.currentPage == page.ChatPage && !a.showQuit && !a.showPermissions && !a.showSessionDialog && !a.showThemeDialog && !a.showFilepicker {\n\t\t\t\t// Show commands dialog\n\t\t\t\tif len(a.commands) == 0 {\n\t\t\t\t\treturn a, util.ReportWarn(\"No commands available\")\n\t\t\t\t}\n\t\t\t\ta.commandDialog.SetCommands(a.commands)\n\t\t\t\ta.showCommandDialog = true\n\t\t\t\treturn a, nil\n\t\t\t}\n\t\t\treturn a, nil\n\t\tcase key.Matches(msg, keys.Models):\n\t\t\tif a.showModelDialog {\n\t\t\t\ta.showModelDialog = false\n\t\t\t\treturn a, nil\n\t\t\t}\n\t\t\tif a.currentPage == page.ChatPage && !a.showQuit && !a.showPermissions && !a.showSessionDialog && !a.showCommandDialog {\n\t\t\t\ta.showModelDialog = true\n\t\t\t\treturn a, nil\n\t\t\t}\n\t\t\treturn a, nil\n\t\tcase key.Matches(msg, keys.SwitchTheme):\n\t\t\tif !a.showQuit && !a.showPermissions && !a.showSessionDialog && !a.showCommandDialog {\n\t\t\t\t// Show theme switcher dialog\n\t\t\t\ta.showThemeDialog = true\n\t\t\t\t// Theme list is dynamically loaded by the dialog component\n\t\t\t\treturn a, a.themeDialog.Init()\n\t\t\t}\n\t\t\treturn a, nil\n\t\tcase key.Matches(msg, returnKey) || key.Matches(msg):\n\t\t\tif msg.String() == quitKey {\n\t\t\t\tif a.currentPage == page.LogsPage {\n\t\t\t\t\treturn a, a.moveToPage(page.ChatPage)\n\t\t\t\t}\n\t\t\t} else if !a.filepicker.IsCWDFocused() {\n\t\t\t\tif a.showQuit {\n\t\t\t\t\ta.showQuit = !a.showQuit\n\t\t\t\t\treturn a, nil\n\t\t\t\t}\n\t\t\t\tif a.showHelp {\n\t\t\t\t\ta.showHelp = !a.showHelp\n\t\t\t\t\treturn a, nil\n\t\t\t\t}\n\t\t\t\tif a.showInitDialog {\n\t\t\t\t\ta.showInitDialog = false\n\t\t\t\t\t// Mark the project as initialized without running the command\n\t\t\t\t\tif err := config.MarkProjectInitialized(); err != nil {\n\t\t\t\t\t\treturn a, util.ReportError(err)\n\t\t\t\t\t}\n\t\t\t\t\treturn a, nil\n\t\t\t\t}\n\t\t\t\tif a.showFilepicker {\n\t\t\t\t\ta.showFilepicker = false\n\t\t\t\t\ta.filepicker.ToggleFilepicker(a.showFilepicker)\n\t\t\t\t\treturn a, nil\n\t\t\t\t}\n\t\t\t\tif a.currentPage == page.LogsPage {\n\t\t\t\t\treturn a, a.moveToPage(page.ChatPage)\n\t\t\t\t}\n\t\t\t}\n\t\tcase key.Matches(msg, keys.Logs):\n\t\t\treturn a, a.moveToPage(page.LogsPage)\n\t\tcase key.Matches(msg, keys.Help):\n\t\t\tif a.showQuit {\n\t\t\t\treturn a, nil\n\t\t\t}\n\t\t\ta.showHelp = !a.showHelp\n\t\t\treturn a, nil\n\t\tcase key.Matches(msg, helpEsc):\n\t\t\tif a.app.CoderAgent.IsBusy() {\n\t\t\t\tif a.showQuit {\n\t\t\t\t\treturn a, nil\n\t\t\t\t}\n\t\t\t\ta.showHelp = !a.showHelp\n\t\t\t\treturn a, nil\n\t\t\t}\n\t\tcase key.Matches(msg, keys.Filepicker):\n\t\t\ta.showFilepicker = !a.showFilepicker\n\t\t\ta.filepicker.ToggleFilepicker(a.showFilepicker)\n\t\t\treturn a, nil\n\t\t}\n\tdefault:\n\t\tf, filepickerCmd := a.filepicker.Update(msg)\n\t\ta.filepicker = f.(dialog.FilepickerCmp)\n\t\tcmds = append(cmds, filepickerCmd)\n\n\t}\n\n\tif a.showFilepicker {\n\t\tf, filepickerCmd := a.filepicker.Update(msg)\n\t\ta.filepicker = f.(dialog.FilepickerCmp)\n\t\tcmds = append(cmds, filepickerCmd)\n\t\t// Only block key messages send all other messages down\n\t\tif _, ok := msg.(tea.KeyMsg); ok {\n\t\t\treturn a, tea.Batch(cmds...)\n\t\t}\n\t}\n\n\tif a.showQuit {\n\t\tq, quitCmd := a.quit.Update(msg)\n\t\ta.quit = q.(dialog.QuitDialog)\n\t\tcmds = append(cmds, quitCmd)\n\t\t// Only block key messages send all other messages down\n\t\tif _, ok := msg.(tea.KeyMsg); ok {\n\t\t\treturn a, tea.Batch(cmds...)\n\t\t}\n\t}\n\tif a.showPermissions {\n\t\td, permissionsCmd := a.permissions.Update(msg)\n\t\ta.permissions = d.(dialog.PermissionDialogCmp)\n\t\tcmds = append(cmds, permissionsCmd)\n\t\t// Only block key messages send all other messages down\n\t\tif _, ok := msg.(tea.KeyMsg); ok {\n\t\t\treturn a, tea.Batch(cmds...)\n\t\t}\n\t}\n\n\tif a.showSessionDialog {\n\t\td, sessionCmd := a.sessionDialog.Update(msg)\n\t\ta.sessionDialog = d.(dialog.SessionDialog)\n\t\tcmds = append(cmds, sessionCmd)\n\t\t// Only block key messages send all other messages down\n\t\tif _, ok := msg.(tea.KeyMsg); ok {\n\t\t\treturn a, tea.Batch(cmds...)\n\t\t}\n\t}\n\n\tif a.showCommandDialog {\n\t\td, commandCmd := a.commandDialog.Update(msg)\n\t\ta.commandDialog = d.(dialog.CommandDialog)\n\t\tcmds = append(cmds, commandCmd)\n\t\t// Only block key messages send all other messages down\n\t\tif _, ok := msg.(tea.KeyMsg); ok {\n\t\t\treturn a, tea.Batch(cmds...)\n\t\t}\n\t}\n\n\tif a.showModelDialog {\n\t\td, modelCmd := a.modelDialog.Update(msg)\n\t\ta.modelDialog = d.(dialog.ModelDialog)\n\t\tcmds = append(cmds, modelCmd)\n\t\t// Only block key messages send all other messages down\n\t\tif _, ok := msg.(tea.KeyMsg); ok {\n\t\t\treturn a, tea.Batch(cmds...)\n\t\t}\n\t}\n\n\tif a.showInitDialog {\n\t\td, initCmd := a.initDialog.Update(msg)\n\t\ta.initDialog = d.(dialog.InitDialogCmp)\n\t\tcmds = append(cmds, initCmd)\n\t\t// Only block key messages send all other messages down\n\t\tif _, ok := msg.(tea.KeyMsg); ok {\n\t\t\treturn a, tea.Batch(cmds...)\n\t\t}\n\t}\n\n\tif a.showThemeDialog {\n\t\td, themeCmd := a.themeDialog.Update(msg)\n\t\ta.themeDialog = d.(dialog.ThemeDialog)\n\t\tcmds = append(cmds, themeCmd)\n\t\t// Only block key messages send all other messages down\n\t\tif _, ok := msg.(tea.KeyMsg); ok {\n\t\t\treturn a, tea.Batch(cmds...)\n\t\t}\n\t}\n\n\ts, _ := a.status.Update(msg)\n\ta.status = s.(core.StatusCmp)\n\ta.pages[a.currentPage], cmd = a.pages[a.currentPage].Update(msg)\n\tcmds = append(cmds, cmd)\n\treturn a, tea.Batch(cmds...)\n}\n\n// RegisterCommand adds a command to the command dialog\nfunc (a *appModel) RegisterCommand(cmd dialog.Command) {\n\ta.commands = append(a.commands, cmd)\n}\n\nfunc (a *appModel) findCommand(id string) (dialog.Command, bool) {\n\tfor _, cmd := range a.commands {\n\t\tif cmd.ID == id {\n\t\t\treturn cmd, true\n\t\t}\n\t}\n\treturn dialog.Command{}, false\n}\n\nfunc (a *appModel) moveToPage(pageID page.PageID) tea.Cmd {\n\tif a.app.CoderAgent.IsBusy() {\n\t\t// For now we don't move to any page if the agent is busy\n\t\treturn util.ReportWarn(\"Agent is busy, please wait...\")\n\t}\n\n\tvar cmds []tea.Cmd\n\tif _, ok := a.loadedPages[pageID]; !ok {\n\t\tcmd := a.pages[pageID].Init()\n\t\tcmds = append(cmds, cmd)\n\t\ta.loadedPages[pageID] = true\n\t}\n\ta.previousPage = a.currentPage\n\ta.currentPage = pageID\n\tif sizable, ok := a.pages[a.currentPage].(layout.Sizeable); ok {\n\t\tcmd := sizable.SetSize(a.width, a.height)\n\t\tcmds = append(cmds, cmd)\n\t}\n\n\treturn tea.Batch(cmds...)\n}\n\nfunc (a appModel) View() string {\n\tcomponents := []string{\n\t\ta.pages[a.currentPage].View(),\n\t}\n\n\tcomponents = append(components, a.status.View())\n\n\tappView := lipgloss.JoinVertical(lipgloss.Top, components...)\n\n\tif a.showPermissions {\n\t\toverlay := a.permissions.View()\n\t\trow := lipgloss.Height(appView) / 2\n\t\trow -= lipgloss.Height(overlay) / 2\n\t\tcol := lipgloss.Width(appView) / 2\n\t\tcol -= lipgloss.Width(overlay) / 2\n\t\tappView = layout.PlaceOverlay(\n\t\t\tcol,\n\t\t\trow,\n\t\t\toverlay,\n\t\t\tappView,\n\t\t\ttrue,\n\t\t)\n\t}\n\n\tif a.showFilepicker {\n\t\toverlay := a.filepicker.View()\n\t\trow := lipgloss.Height(appView) / 2\n\t\trow -= lipgloss.Height(overlay) / 2\n\t\tcol := lipgloss.Width(appView) / 2\n\t\tcol -= lipgloss.Width(overlay) / 2\n\t\tappView = layout.PlaceOverlay(\n\t\t\tcol,\n\t\t\trow,\n\t\t\toverlay,\n\t\t\tappView,\n\t\t\ttrue,\n\t\t)\n\n\t}\n\n\t// Show compacting status overlay\n\tif a.isCompacting {\n\t\tt := theme.CurrentTheme()\n\t\tstyle := lipgloss.NewStyle().\n\t\t\tBorder(lipgloss.RoundedBorder()).\n\t\t\tBorderForeground(t.BorderFocused()).\n\t\t\tBorderBackground(t.Background()).\n\t\t\tPadding(1, 2).\n\t\t\tBackground(t.Background()).\n\t\t\tForeground(t.Text())\n\n\t\toverlay := style.Render(\"Summarizing\\n\" + a.compactingMessage)\n\t\trow := lipgloss.Height(appView) / 2\n\t\trow -= lipgloss.Height(overlay) / 2\n\t\tcol := lipgloss.Width(appView) / 2\n\t\tcol -= lipgloss.Width(overlay) / 2\n\t\tappView = layout.PlaceOverlay(\n\t\t\tcol,\n\t\t\trow,\n\t\t\toverlay,\n\t\t\tappView,\n\t\t\ttrue,\n\t\t)\n\t}\n\n\tif a.showHelp {\n\t\tbindings := layout.KeyMapToSlice(keys)\n\t\tif p, ok := a.pages[a.currentPage].(layout.Bindings); ok {\n\t\t\tbindings = append(bindings, p.BindingKeys()...)\n\t\t}\n\t\tif a.showPermissions {\n\t\t\tbindings = append(bindings, a.permissions.BindingKeys()...)\n\t\t}\n\t\tif a.currentPage == page.LogsPage {\n\t\t\tbindings = append(bindings, logsKeyReturnKey)\n\t\t}\n\t\tif !a.app.CoderAgent.IsBusy() {\n\t\t\tbindings = append(bindings, helpEsc)\n\t\t}\n\t\ta.help.SetBindings(bindings)\n\n\t\toverlay := a.help.View()\n\t\trow := lipgloss.Height(appView) / 2\n\t\trow -= lipgloss.Height(overlay) / 2\n\t\tcol := lipgloss.Width(appView) / 2\n\t\tcol -= lipgloss.Width(overlay) / 2\n\t\tappView = layout.PlaceOverlay(\n\t\t\tcol,\n\t\t\trow,\n\t\t\toverlay,\n\t\t\tappView,\n\t\t\ttrue,\n\t\t)\n\t}\n\n\tif a.showQuit {\n\t\toverlay := a.quit.View()\n\t\trow := lipgloss.Height(appView) / 2\n\t\trow -= lipgloss.Height(overlay) / 2\n\t\tcol := lipgloss.Width(appView) / 2\n\t\tcol -= lipgloss.Width(overlay) / 2\n\t\tappView = layout.PlaceOverlay(\n\t\t\tcol,\n\t\t\trow,\n\t\t\toverlay,\n\t\t\tappView,\n\t\t\ttrue,\n\t\t)\n\t}\n\n\tif a.showSessionDialog {\n\t\toverlay := a.sessionDialog.View()\n\t\trow := lipgloss.Height(appView) / 2\n\t\trow -= lipgloss.Height(overlay) / 2\n\t\tcol := lipgloss.Width(appView) / 2\n\t\tcol -= lipgloss.Width(overlay) / 2\n\t\tappView = layout.PlaceOverlay(\n\t\t\tcol,\n\t\t\trow,\n\t\t\toverlay,\n\t\t\tappView,\n\t\t\ttrue,\n\t\t)\n\t}\n\n\tif a.showModelDialog {\n\t\toverlay := a.modelDialog.View()\n\t\trow := lipgloss.Height(appView) / 2\n\t\trow -= lipgloss.Height(overlay) / 2\n\t\tcol := lipgloss.Width(appView) / 2\n\t\tcol -= lipgloss.Width(overlay) / 2\n\t\tappView = layout.PlaceOverlay(\n\t\t\tcol,\n\t\t\trow,\n\t\t\toverlay,\n\t\t\tappView,\n\t\t\ttrue,\n\t\t)\n\t}\n\n\tif a.showCommandDialog {\n\t\toverlay := a.commandDialog.View()\n\t\trow := lipgloss.Height(appView) / 2\n\t\trow -= lipgloss.Height(overlay) / 2\n\t\tcol := lipgloss.Width(appView) / 2\n\t\tcol -= lipgloss.Width(overlay) / 2\n\t\tappView = layout.PlaceOverlay(\n\t\t\tcol,\n\t\t\trow,\n\t\t\toverlay,\n\t\t\tappView,\n\t\t\ttrue,\n\t\t)\n\t}\n\n\tif a.showInitDialog {\n\t\toverlay := a.initDialog.View()\n\t\tappView = layout.PlaceOverlay(\n\t\t\ta.width/2-lipgloss.Width(overlay)/2,\n\t\t\ta.height/2-lipgloss.Height(overlay)/2,\n\t\t\toverlay,\n\t\t\tappView,\n\t\t\ttrue,\n\t\t)\n\t}\n\n\tif a.showThemeDialog {\n\t\toverlay := a.themeDialog.View()\n\t\trow := lipgloss.Height(appView) / 2\n\t\trow -= lipgloss.Height(overlay) / 2\n\t\tcol := lipgloss.Width(appView) / 2\n\t\tcol -= lipgloss.Width(overlay) / 2\n\t\tappView = layout.PlaceOverlay(\n\t\t\tcol,\n\t\t\trow,\n\t\t\toverlay,\n\t\t\tappView,\n\t\t\ttrue,\n\t\t)\n\t}\n\n\tif a.showMultiArgumentsDialog {\n\t\toverlay := a.multiArgumentsDialog.View()\n\t\trow := lipgloss.Height(appView) / 2\n\t\trow -= lipgloss.Height(overlay) / 2\n\t\tcol := lipgloss.Width(appView) / 2\n\t\tcol -= lipgloss.Width(overlay) / 2\n\t\tappView = layout.PlaceOverlay(\n\t\t\tcol,\n\t\t\trow,\n\t\t\toverlay,\n\t\t\tappView,\n\t\t\ttrue,\n\t\t)\n\t}\n\n\treturn appView\n}\n\nfunc New(app *app.App) tea.Model {\n\tstartPage := page.ChatPage\n\tmodel := &appModel{\n\t\tcurrentPage: startPage,\n\t\tloadedPages: make(map[page.PageID]bool),\n\t\tstatus: core.NewStatusCmp(app.LSPClients),\n\t\thelp: dialog.NewHelpCmp(),\n\t\tquit: dialog.NewQuitCmp(),\n\t\tsessionDialog: dialog.NewSessionDialogCmp(),\n\t\tcommandDialog: dialog.NewCommandDialogCmp(),\n\t\tmodelDialog: dialog.NewModelDialogCmp(),\n\t\tpermissions: dialog.NewPermissionDialogCmp(),\n\t\tinitDialog: dialog.NewInitDialogCmp(),\n\t\tthemeDialog: dialog.NewThemeDialogCmp(),\n\t\tapp: app,\n\t\tcommands: []dialog.Command{},\n\t\tpages: map[page.PageID]tea.Model{\n\t\t\tpage.ChatPage: page.NewChatPage(app),\n\t\t\tpage.LogsPage: page.NewLogsPage(),\n\t\t},\n\t\tfilepicker: dialog.NewFilepickerCmp(app),\n\t}\n\n\tmodel.RegisterCommand(dialog.Command{\n\t\tID: \"init\",\n\t\tTitle: \"Initialize Project\",\n\t\tDescription: \"Create/Update the OpenCode.md memory file\",\n\t\tHandler: func(cmd dialog.Command) tea.Cmd {\n\t\t\tprompt := `Please analyze this codebase and create a OpenCode.md file containing:\n1. Build/lint/test commands - especially for running a single test\n2. Code style guidelines including imports, formatting, types, naming conventions, error handling, etc.\n\nThe file you create will be given to agentic coding agents (such as yourself) that operate in this repository. Make it about 20 lines long.\nIf there's already a opencode.md, improve it.\nIf there are Cursor rules (in .cursor/rules/ or .cursorrules) or Copilot rules (in .github/copilot-instructions.md), make sure to include them.`\n\t\t\treturn tea.Batch(\n\t\t\t\tutil.CmdHandler(chat.SendMsg{\n\t\t\t\t\tText: prompt,\n\t\t\t\t}),\n\t\t\t)\n\t\t},\n\t})\n\n\tmodel.RegisterCommand(dialog.Command{\n\t\tID: \"compact\",\n\t\tTitle: \"Compact Session\",\n\t\tDescription: \"Summarize the current session and create a new one with the summary\",\n\t\tHandler: func(cmd dialog.Command) tea.Cmd {\n\t\t\treturn func() tea.Msg {\n\t\t\t\treturn startCompactSessionMsg{}\n\t\t\t}\n\t\t},\n\t})\n\t// Load custom commands\n\tcustomCommands, err := dialog.LoadCustomCommands()\n\tif err != nil {\n\t\tlogging.Warn(\"Failed to load custom commands\", \"error\", err)\n\t} else {\n\t\tfor _, cmd := range customCommands {\n\t\t\tmodel.RegisterCommand(cmd)\n\t\t}\n\t}\n\n\treturn model\n}\n"], ["/opencode/internal/tui/page/chat.go", "package page\n\nimport (\n\t\"context\"\n\t\"strings\"\n\n\t\"github.com/charmbracelet/bubbles/key\"\n\ttea \"github.com/charmbracelet/bubbletea\"\n\t\"github.com/charmbracelet/lipgloss\"\n\t\"github.com/opencode-ai/opencode/internal/app\"\n\t\"github.com/opencode-ai/opencode/internal/completions\"\n\t\"github.com/opencode-ai/opencode/internal/message\"\n\t\"github.com/opencode-ai/opencode/internal/session\"\n\t\"github.com/opencode-ai/opencode/internal/tui/components/chat\"\n\t\"github.com/opencode-ai/opencode/internal/tui/components/dialog\"\n\t\"github.com/opencode-ai/opencode/internal/tui/layout\"\n\t\"github.com/opencode-ai/opencode/internal/tui/util\"\n)\n\nvar ChatPage PageID = \"chat\"\n\ntype chatPage struct {\n\tapp *app.App\n\teditor layout.Container\n\tmessages layout.Container\n\tlayout layout.SplitPaneLayout\n\tsession session.Session\n\tcompletionDialog dialog.CompletionDialog\n\tshowCompletionDialog bool\n}\n\ntype ChatKeyMap struct {\n\tShowCompletionDialog key.Binding\n\tNewSession key.Binding\n\tCancel key.Binding\n}\n\nvar keyMap = ChatKeyMap{\n\tShowCompletionDialog: key.NewBinding(\n\t\tkey.WithKeys(\"@\"),\n\t\tkey.WithHelp(\"@\", \"Complete\"),\n\t),\n\tNewSession: key.NewBinding(\n\t\tkey.WithKeys(\"ctrl+n\"),\n\t\tkey.WithHelp(\"ctrl+n\", \"new session\"),\n\t),\n\tCancel: key.NewBinding(\n\t\tkey.WithKeys(\"esc\"),\n\t\tkey.WithHelp(\"esc\", \"cancel\"),\n\t),\n}\n\nfunc (p *chatPage) Init() tea.Cmd {\n\tcmds := []tea.Cmd{\n\t\tp.layout.Init(),\n\t\tp.completionDialog.Init(),\n\t}\n\treturn tea.Batch(cmds...)\n}\n\nfunc (p *chatPage) Update(msg tea.Msg) (tea.Model, tea.Cmd) {\n\tvar cmds []tea.Cmd\n\tswitch msg := msg.(type) {\n\tcase tea.WindowSizeMsg:\n\t\tcmd := p.layout.SetSize(msg.Width, msg.Height)\n\t\tcmds = append(cmds, cmd)\n\tcase dialog.CompletionDialogCloseMsg:\n\t\tp.showCompletionDialog = false\n\tcase chat.SendMsg:\n\t\tcmd := p.sendMessage(msg.Text, msg.Attachments)\n\t\tif cmd != nil {\n\t\t\treturn p, cmd\n\t\t}\n\tcase dialog.CommandRunCustomMsg:\n\t\t// Check if the agent is busy before executing custom commands\n\t\tif p.app.CoderAgent.IsBusy() {\n\t\t\treturn p, util.ReportWarn(\"Agent is busy, please wait before executing a command...\")\n\t\t}\n\t\t\n\t\t// Process the command content with arguments if any\n\t\tcontent := msg.Content\n\t\tif msg.Args != nil {\n\t\t\t// Replace all named arguments with their values\n\t\t\tfor name, value := range msg.Args {\n\t\t\t\tplaceholder := \"$\" + name\n\t\t\t\tcontent = strings.ReplaceAll(content, placeholder, value)\n\t\t\t}\n\t\t}\n\t\t\n\t\t// Handle custom command execution\n\t\tcmd := p.sendMessage(content, nil)\n\t\tif cmd != nil {\n\t\t\treturn p, cmd\n\t\t}\n\tcase chat.SessionSelectedMsg:\n\t\tif p.session.ID == \"\" {\n\t\t\tcmd := p.setSidebar()\n\t\t\tif cmd != nil {\n\t\t\t\tcmds = append(cmds, cmd)\n\t\t\t}\n\t\t}\n\t\tp.session = msg\n\tcase tea.KeyMsg:\n\t\tswitch {\n\t\tcase key.Matches(msg, keyMap.ShowCompletionDialog):\n\t\t\tp.showCompletionDialog = true\n\t\t\t// Continue sending keys to layout->chat\n\t\tcase key.Matches(msg, keyMap.NewSession):\n\t\t\tp.session = session.Session{}\n\t\t\treturn p, tea.Batch(\n\t\t\t\tp.clearSidebar(),\n\t\t\t\tutil.CmdHandler(chat.SessionClearedMsg{}),\n\t\t\t)\n\t\tcase key.Matches(msg, keyMap.Cancel):\n\t\t\tif p.session.ID != \"\" {\n\t\t\t\t// Cancel the current session's generation process\n\t\t\t\t// This allows users to interrupt long-running operations\n\t\t\t\tp.app.CoderAgent.Cancel(p.session.ID)\n\t\t\t\treturn p, nil\n\t\t\t}\n\t\t}\n\t}\n\tif p.showCompletionDialog {\n\t\tcontext, contextCmd := p.completionDialog.Update(msg)\n\t\tp.completionDialog = context.(dialog.CompletionDialog)\n\t\tcmds = append(cmds, contextCmd)\n\n\t\t// Doesn't forward event if enter key is pressed\n\t\tif keyMsg, ok := msg.(tea.KeyMsg); ok {\n\t\t\tif keyMsg.String() == \"enter\" {\n\t\t\t\treturn p, tea.Batch(cmds...)\n\t\t\t}\n\t\t}\n\t}\n\n\tu, cmd := p.layout.Update(msg)\n\tcmds = append(cmds, cmd)\n\tp.layout = u.(layout.SplitPaneLayout)\n\n\treturn p, tea.Batch(cmds...)\n}\n\nfunc (p *chatPage) setSidebar() tea.Cmd {\n\tsidebarContainer := layout.NewContainer(\n\t\tchat.NewSidebarCmp(p.session, p.app.History),\n\t\tlayout.WithPadding(1, 1, 1, 1),\n\t)\n\treturn tea.Batch(p.layout.SetRightPanel(sidebarContainer), sidebarContainer.Init())\n}\n\nfunc (p *chatPage) clearSidebar() tea.Cmd {\n\treturn p.layout.ClearRightPanel()\n}\n\nfunc (p *chatPage) sendMessage(text string, attachments []message.Attachment) tea.Cmd {\n\tvar cmds []tea.Cmd\n\tif p.session.ID == \"\" {\n\t\tsession, err := p.app.Sessions.Create(context.Background(), \"New Session\")\n\t\tif err != nil {\n\t\t\treturn util.ReportError(err)\n\t\t}\n\n\t\tp.session = session\n\t\tcmd := p.setSidebar()\n\t\tif cmd != nil {\n\t\t\tcmds = append(cmds, cmd)\n\t\t}\n\t\tcmds = append(cmds, util.CmdHandler(chat.SessionSelectedMsg(session)))\n\t}\n\n\t_, err := p.app.CoderAgent.Run(context.Background(), p.session.ID, text, attachments...)\n\tif err != nil {\n\t\treturn util.ReportError(err)\n\t}\n\treturn tea.Batch(cmds...)\n}\n\nfunc (p *chatPage) SetSize(width, height int) tea.Cmd {\n\treturn p.layout.SetSize(width, height)\n}\n\nfunc (p *chatPage) GetSize() (int, int) {\n\treturn p.layout.GetSize()\n}\n\nfunc (p *chatPage) View() string {\n\tlayoutView := p.layout.View()\n\n\tif p.showCompletionDialog {\n\t\t_, layoutHeight := p.layout.GetSize()\n\t\teditorWidth, editorHeight := p.editor.GetSize()\n\n\t\tp.completionDialog.SetWidth(editorWidth)\n\t\toverlay := p.completionDialog.View()\n\n\t\tlayoutView = layout.PlaceOverlay(\n\t\t\t0,\n\t\t\tlayoutHeight-editorHeight-lipgloss.Height(overlay),\n\t\t\toverlay,\n\t\t\tlayoutView,\n\t\t\tfalse,\n\t\t)\n\t}\n\n\treturn layoutView\n}\n\nfunc (p *chatPage) BindingKeys() []key.Binding {\n\tbindings := layout.KeyMapToSlice(keyMap)\n\tbindings = append(bindings, p.messages.BindingKeys()...)\n\tbindings = append(bindings, p.editor.BindingKeys()...)\n\treturn bindings\n}\n\nfunc NewChatPage(app *app.App) tea.Model {\n\tcg := completions.NewFileAndFolderContextGroup()\n\tcompletionDialog := dialog.NewCompletionDialogCmp(cg)\n\n\tmessagesContainer := layout.NewContainer(\n\t\tchat.NewMessagesCmp(app),\n\t\tlayout.WithPadding(1, 1, 0, 1),\n\t)\n\teditorContainer := layout.NewContainer(\n\t\tchat.NewEditorCmp(app),\n\t\tlayout.WithBorder(true, false, false, false),\n\t)\n\treturn &chatPage{\n\t\tapp: app,\n\t\teditor: editorContainer,\n\t\tmessages: messagesContainer,\n\t\tcompletionDialog: completionDialog,\n\t\tlayout: layout.NewSplitPane(\n\t\t\tlayout.WithLeftPanel(messagesContainer),\n\t\t\tlayout.WithBottomPanel(editorContainer),\n\t\t),\n\t}\n}\n"], ["/opencode/internal/tui/components/chat/chat.go", "package chat\n\nimport (\n\t\"fmt\"\n\t\"sort\"\n\n\t\"github.com/charmbracelet/lipgloss\"\n\t\"github.com/charmbracelet/x/ansi\"\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/message\"\n\t\"github.com/opencode-ai/opencode/internal/session\"\n\t\"github.com/opencode-ai/opencode/internal/tui/styles\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n\t\"github.com/opencode-ai/opencode/internal/version\"\n)\n\ntype SendMsg struct {\n\tText string\n\tAttachments []message.Attachment\n}\n\ntype SessionSelectedMsg = session.Session\n\ntype SessionClearedMsg struct{}\n\ntype EditorFocusMsg bool\n\nfunc header(width int) string {\n\treturn lipgloss.JoinVertical(\n\t\tlipgloss.Top,\n\t\tlogo(width),\n\t\trepo(width),\n\t\t\"\",\n\t\tcwd(width),\n\t)\n}\n\nfunc lspsConfigured(width int) string {\n\tcfg := config.Get()\n\ttitle := \"LSP Configuration\"\n\ttitle = ansi.Truncate(title, width, \"…\")\n\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\n\tlsps := baseStyle.\n\t\tWidth(width).\n\t\tForeground(t.Primary()).\n\t\tBold(true).\n\t\tRender(title)\n\n\t// Get LSP names and sort them for consistent ordering\n\tvar lspNames []string\n\tfor name := range cfg.LSP {\n\t\tlspNames = append(lspNames, name)\n\t}\n\tsort.Strings(lspNames)\n\n\tvar lspViews []string\n\tfor _, name := range lspNames {\n\t\tlsp := cfg.LSP[name]\n\t\tlspName := baseStyle.\n\t\t\tForeground(t.Text()).\n\t\t\tRender(fmt.Sprintf(\"• %s\", name))\n\n\t\tcmd := lsp.Command\n\t\tcmd = ansi.Truncate(cmd, width-lipgloss.Width(lspName)-3, \"…\")\n\n\t\tlspPath := baseStyle.\n\t\t\tForeground(t.TextMuted()).\n\t\t\tRender(fmt.Sprintf(\" (%s)\", cmd))\n\n\t\tlspViews = append(lspViews,\n\t\t\tbaseStyle.\n\t\t\t\tWidth(width).\n\t\t\t\tRender(\n\t\t\t\t\tlipgloss.JoinHorizontal(\n\t\t\t\t\t\tlipgloss.Left,\n\t\t\t\t\t\tlspName,\n\t\t\t\t\t\tlspPath,\n\t\t\t\t\t),\n\t\t\t\t),\n\t\t)\n\t}\n\n\treturn baseStyle.\n\t\tWidth(width).\n\t\tRender(\n\t\t\tlipgloss.JoinVertical(\n\t\t\t\tlipgloss.Left,\n\t\t\t\tlsps,\n\t\t\t\tlipgloss.JoinVertical(\n\t\t\t\t\tlipgloss.Left,\n\t\t\t\t\tlspViews...,\n\t\t\t\t),\n\t\t\t),\n\t\t)\n}\n\nfunc logo(width int) string {\n\tlogo := fmt.Sprintf(\"%s %s\", styles.OpenCodeIcon, \"OpenCode\")\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\n\tversionText := baseStyle.\n\t\tForeground(t.TextMuted()).\n\t\tRender(version.Version)\n\n\treturn baseStyle.\n\t\tBold(true).\n\t\tWidth(width).\n\t\tRender(\n\t\t\tlipgloss.JoinHorizontal(\n\t\t\t\tlipgloss.Left,\n\t\t\t\tlogo,\n\t\t\t\t\" \",\n\t\t\t\tversionText,\n\t\t\t),\n\t\t)\n}\n\nfunc repo(width int) string {\n\trepo := \"https://github.com/opencode-ai/opencode\"\n\tt := theme.CurrentTheme()\n\n\treturn styles.BaseStyle().\n\t\tForeground(t.TextMuted()).\n\t\tWidth(width).\n\t\tRender(repo)\n}\n\nfunc cwd(width int) string {\n\tcwd := fmt.Sprintf(\"cwd: %s\", config.WorkingDirectory())\n\tt := theme.CurrentTheme()\n\n\treturn styles.BaseStyle().\n\t\tForeground(t.TextMuted()).\n\t\tWidth(width).\n\t\tRender(cwd)\n}\n\n"], ["/opencode/internal/tui/layout/split.go", "package layout\n\nimport (\n\t\"github.com/charmbracelet/bubbles/key\"\n\ttea \"github.com/charmbracelet/bubbletea\"\n\t\"github.com/charmbracelet/lipgloss\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n)\n\ntype SplitPaneLayout interface {\n\ttea.Model\n\tSizeable\n\tBindings\n\tSetLeftPanel(panel Container) tea.Cmd\n\tSetRightPanel(panel Container) tea.Cmd\n\tSetBottomPanel(panel Container) tea.Cmd\n\n\tClearLeftPanel() tea.Cmd\n\tClearRightPanel() tea.Cmd\n\tClearBottomPanel() tea.Cmd\n}\n\ntype splitPaneLayout struct {\n\twidth int\n\theight int\n\tratio float64\n\tverticalRatio float64\n\n\trightPanel Container\n\tleftPanel Container\n\tbottomPanel Container\n}\n\ntype SplitPaneOption func(*splitPaneLayout)\n\nfunc (s *splitPaneLayout) Init() tea.Cmd {\n\tvar cmds []tea.Cmd\n\n\tif s.leftPanel != nil {\n\t\tcmds = append(cmds, s.leftPanel.Init())\n\t}\n\n\tif s.rightPanel != nil {\n\t\tcmds = append(cmds, s.rightPanel.Init())\n\t}\n\n\tif s.bottomPanel != nil {\n\t\tcmds = append(cmds, s.bottomPanel.Init())\n\t}\n\n\treturn tea.Batch(cmds...)\n}\n\nfunc (s *splitPaneLayout) Update(msg tea.Msg) (tea.Model, tea.Cmd) {\n\tvar cmds []tea.Cmd\n\tswitch msg := msg.(type) {\n\tcase tea.WindowSizeMsg:\n\t\treturn s, s.SetSize(msg.Width, msg.Height)\n\t}\n\n\tif s.rightPanel != nil {\n\t\tu, cmd := s.rightPanel.Update(msg)\n\t\ts.rightPanel = u.(Container)\n\t\tif cmd != nil {\n\t\t\tcmds = append(cmds, cmd)\n\t\t}\n\t}\n\n\tif s.leftPanel != nil {\n\t\tu, cmd := s.leftPanel.Update(msg)\n\t\ts.leftPanel = u.(Container)\n\t\tif cmd != nil {\n\t\t\tcmds = append(cmds, cmd)\n\t\t}\n\t}\n\n\tif s.bottomPanel != nil {\n\t\tu, cmd := s.bottomPanel.Update(msg)\n\t\ts.bottomPanel = u.(Container)\n\t\tif cmd != nil {\n\t\t\tcmds = append(cmds, cmd)\n\t\t}\n\t}\n\n\treturn s, tea.Batch(cmds...)\n}\n\nfunc (s *splitPaneLayout) View() string {\n\tvar topSection string\n\n\tif s.leftPanel != nil && s.rightPanel != nil {\n\t\tleftView := s.leftPanel.View()\n\t\trightView := s.rightPanel.View()\n\t\ttopSection = lipgloss.JoinHorizontal(lipgloss.Top, leftView, rightView)\n\t} else if s.leftPanel != nil {\n\t\ttopSection = s.leftPanel.View()\n\t} else if s.rightPanel != nil {\n\t\ttopSection = s.rightPanel.View()\n\t} else {\n\t\ttopSection = \"\"\n\t}\n\n\tvar finalView string\n\n\tif s.bottomPanel != nil && topSection != \"\" {\n\t\tbottomView := s.bottomPanel.View()\n\t\tfinalView = lipgloss.JoinVertical(lipgloss.Left, topSection, bottomView)\n\t} else if s.bottomPanel != nil {\n\t\tfinalView = s.bottomPanel.View()\n\t} else {\n\t\tfinalView = topSection\n\t}\n\n\tif finalView != \"\" {\n\t\tt := theme.CurrentTheme()\n\n\t\tstyle := lipgloss.NewStyle().\n\t\t\tWidth(s.width).\n\t\t\tHeight(s.height).\n\t\t\tBackground(t.Background())\n\n\t\treturn style.Render(finalView)\n\t}\n\n\treturn finalView\n}\n\nfunc (s *splitPaneLayout) SetSize(width, height int) tea.Cmd {\n\ts.width = width\n\ts.height = height\n\n\tvar topHeight, bottomHeight int\n\tif s.bottomPanel != nil {\n\t\ttopHeight = int(float64(height) * s.verticalRatio)\n\t\tbottomHeight = height - topHeight\n\t} else {\n\t\ttopHeight = height\n\t\tbottomHeight = 0\n\t}\n\n\tvar leftWidth, rightWidth int\n\tif s.leftPanel != nil && s.rightPanel != nil {\n\t\tleftWidth = int(float64(width) * s.ratio)\n\t\trightWidth = width - leftWidth\n\t} else if s.leftPanel != nil {\n\t\tleftWidth = width\n\t\trightWidth = 0\n\t} else if s.rightPanel != nil {\n\t\tleftWidth = 0\n\t\trightWidth = width\n\t}\n\n\tvar cmds []tea.Cmd\n\tif s.leftPanel != nil {\n\t\tcmd := s.leftPanel.SetSize(leftWidth, topHeight)\n\t\tcmds = append(cmds, cmd)\n\t}\n\n\tif s.rightPanel != nil {\n\t\tcmd := s.rightPanel.SetSize(rightWidth, topHeight)\n\t\tcmds = append(cmds, cmd)\n\t}\n\n\tif s.bottomPanel != nil {\n\t\tcmd := s.bottomPanel.SetSize(width, bottomHeight)\n\t\tcmds = append(cmds, cmd)\n\t}\n\treturn tea.Batch(cmds...)\n}\n\nfunc (s *splitPaneLayout) GetSize() (int, int) {\n\treturn s.width, s.height\n}\n\nfunc (s *splitPaneLayout) SetLeftPanel(panel Container) tea.Cmd {\n\ts.leftPanel = panel\n\tif s.width > 0 && s.height > 0 {\n\t\treturn s.SetSize(s.width, s.height)\n\t}\n\treturn nil\n}\n\nfunc (s *splitPaneLayout) SetRightPanel(panel Container) tea.Cmd {\n\ts.rightPanel = panel\n\tif s.width > 0 && s.height > 0 {\n\t\treturn s.SetSize(s.width, s.height)\n\t}\n\treturn nil\n}\n\nfunc (s *splitPaneLayout) SetBottomPanel(panel Container) tea.Cmd {\n\ts.bottomPanel = panel\n\tif s.width > 0 && s.height > 0 {\n\t\treturn s.SetSize(s.width, s.height)\n\t}\n\treturn nil\n}\n\nfunc (s *splitPaneLayout) ClearLeftPanel() tea.Cmd {\n\ts.leftPanel = nil\n\tif s.width > 0 && s.height > 0 {\n\t\treturn s.SetSize(s.width, s.height)\n\t}\n\treturn nil\n}\n\nfunc (s *splitPaneLayout) ClearRightPanel() tea.Cmd {\n\ts.rightPanel = nil\n\tif s.width > 0 && s.height > 0 {\n\t\treturn s.SetSize(s.width, s.height)\n\t}\n\treturn nil\n}\n\nfunc (s *splitPaneLayout) ClearBottomPanel() tea.Cmd {\n\ts.bottomPanel = nil\n\tif s.width > 0 && s.height > 0 {\n\t\treturn s.SetSize(s.width, s.height)\n\t}\n\treturn nil\n}\n\nfunc (s *splitPaneLayout) BindingKeys() []key.Binding {\n\tkeys := []key.Binding{}\n\tif s.leftPanel != nil {\n\t\tif b, ok := s.leftPanel.(Bindings); ok {\n\t\t\tkeys = append(keys, b.BindingKeys()...)\n\t\t}\n\t}\n\tif s.rightPanel != nil {\n\t\tif b, ok := s.rightPanel.(Bindings); ok {\n\t\t\tkeys = append(keys, b.BindingKeys()...)\n\t\t}\n\t}\n\tif s.bottomPanel != nil {\n\t\tif b, ok := s.bottomPanel.(Bindings); ok {\n\t\t\tkeys = append(keys, b.BindingKeys()...)\n\t\t}\n\t}\n\treturn keys\n}\n\nfunc NewSplitPane(options ...SplitPaneOption) SplitPaneLayout {\n\n\tlayout := &splitPaneLayout{\n\t\tratio: 0.7,\n\t\tverticalRatio: 0.9, // Default 90% for top section, 10% for bottom\n\t}\n\tfor _, option := range options {\n\t\toption(layout)\n\t}\n\treturn layout\n}\n\nfunc WithLeftPanel(panel Container) SplitPaneOption {\n\treturn func(s *splitPaneLayout) {\n\t\ts.leftPanel = panel\n\t}\n}\n\nfunc WithRightPanel(panel Container) SplitPaneOption {\n\treturn func(s *splitPaneLayout) {\n\t\ts.rightPanel = panel\n\t}\n}\n\nfunc WithRatio(ratio float64) SplitPaneOption {\n\treturn func(s *splitPaneLayout) {\n\t\ts.ratio = ratio\n\t}\n}\n\nfunc WithBottomPanel(panel Container) SplitPaneOption {\n\treturn func(s *splitPaneLayout) {\n\t\ts.bottomPanel = panel\n\t}\n}\n\nfunc WithVerticalRatio(ratio float64) SplitPaneOption {\n\treturn func(s *splitPaneLayout) {\n\t\ts.verticalRatio = ratio\n\t}\n}\n"], ["/opencode/internal/tui/layout/container.go", "package layout\n\nimport (\n\t\"github.com/charmbracelet/bubbles/key\"\n\ttea \"github.com/charmbracelet/bubbletea\"\n\t\"github.com/charmbracelet/lipgloss\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n)\n\ntype Container interface {\n\ttea.Model\n\tSizeable\n\tBindings\n}\ntype container struct {\n\twidth int\n\theight int\n\n\tcontent tea.Model\n\n\t// Style options\n\tpaddingTop int\n\tpaddingRight int\n\tpaddingBottom int\n\tpaddingLeft int\n\n\tborderTop bool\n\tborderRight bool\n\tborderBottom bool\n\tborderLeft bool\n\tborderStyle lipgloss.Border\n}\n\nfunc (c *container) Init() tea.Cmd {\n\treturn c.content.Init()\n}\n\nfunc (c *container) Update(msg tea.Msg) (tea.Model, tea.Cmd) {\n\tu, cmd := c.content.Update(msg)\n\tc.content = u\n\treturn c, cmd\n}\n\nfunc (c *container) View() string {\n\tt := theme.CurrentTheme()\n\tstyle := lipgloss.NewStyle()\n\twidth := c.width\n\theight := c.height\n\n\tstyle = style.Background(t.Background())\n\n\t// Apply border if any side is enabled\n\tif c.borderTop || c.borderRight || c.borderBottom || c.borderLeft {\n\t\t// Adjust width and height for borders\n\t\tif c.borderTop {\n\t\t\theight--\n\t\t}\n\t\tif c.borderBottom {\n\t\t\theight--\n\t\t}\n\t\tif c.borderLeft {\n\t\t\twidth--\n\t\t}\n\t\tif c.borderRight {\n\t\t\twidth--\n\t\t}\n\t\tstyle = style.Border(c.borderStyle, c.borderTop, c.borderRight, c.borderBottom, c.borderLeft)\n\t\tstyle = style.BorderBackground(t.Background()).BorderForeground(t.BorderNormal())\n\t}\n\tstyle = style.\n\t\tWidth(width).\n\t\tHeight(height).\n\t\tPaddingTop(c.paddingTop).\n\t\tPaddingRight(c.paddingRight).\n\t\tPaddingBottom(c.paddingBottom).\n\t\tPaddingLeft(c.paddingLeft)\n\n\treturn style.Render(c.content.View())\n}\n\nfunc (c *container) SetSize(width, height int) tea.Cmd {\n\tc.width = width\n\tc.height = height\n\n\t// If the content implements Sizeable, adjust its size to account for padding and borders\n\tif sizeable, ok := c.content.(Sizeable); ok {\n\t\t// Calculate horizontal space taken by padding and borders\n\t\thorizontalSpace := c.paddingLeft + c.paddingRight\n\t\tif c.borderLeft {\n\t\t\thorizontalSpace++\n\t\t}\n\t\tif c.borderRight {\n\t\t\thorizontalSpace++\n\t\t}\n\n\t\t// Calculate vertical space taken by padding and borders\n\t\tverticalSpace := c.paddingTop + c.paddingBottom\n\t\tif c.borderTop {\n\t\t\tverticalSpace++\n\t\t}\n\t\tif c.borderBottom {\n\t\t\tverticalSpace++\n\t\t}\n\n\t\t// Set content size with adjusted dimensions\n\t\tcontentWidth := max(0, width-horizontalSpace)\n\t\tcontentHeight := max(0, height-verticalSpace)\n\t\treturn sizeable.SetSize(contentWidth, contentHeight)\n\t}\n\treturn nil\n}\n\nfunc (c *container) GetSize() (int, int) {\n\treturn c.width, c.height\n}\n\nfunc (c *container) BindingKeys() []key.Binding {\n\tif b, ok := c.content.(Bindings); ok {\n\t\treturn b.BindingKeys()\n\t}\n\treturn []key.Binding{}\n}\n\ntype ContainerOption func(*container)\n\nfunc NewContainer(content tea.Model, options ...ContainerOption) Container {\n\n\tc := &container{\n\t\tcontent: content,\n\t\tborderStyle: lipgloss.NormalBorder(),\n\t}\n\n\tfor _, option := range options {\n\t\toption(c)\n\t}\n\n\treturn c\n}\n\n// Padding options\nfunc WithPadding(top, right, bottom, left int) ContainerOption {\n\treturn func(c *container) {\n\t\tc.paddingTop = top\n\t\tc.paddingRight = right\n\t\tc.paddingBottom = bottom\n\t\tc.paddingLeft = left\n\t}\n}\n\nfunc WithPaddingAll(padding int) ContainerOption {\n\treturn WithPadding(padding, padding, padding, padding)\n}\n\nfunc WithPaddingHorizontal(padding int) ContainerOption {\n\treturn func(c *container) {\n\t\tc.paddingLeft = padding\n\t\tc.paddingRight = padding\n\t}\n}\n\nfunc WithPaddingVertical(padding int) ContainerOption {\n\treturn func(c *container) {\n\t\tc.paddingTop = padding\n\t\tc.paddingBottom = padding\n\t}\n}\n\nfunc WithBorder(top, right, bottom, left bool) ContainerOption {\n\treturn func(c *container) {\n\t\tc.borderTop = top\n\t\tc.borderRight = right\n\t\tc.borderBottom = bottom\n\t\tc.borderLeft = left\n\t}\n}\n\nfunc WithBorderAll() ContainerOption {\n\treturn WithBorder(true, true, true, true)\n}\n\nfunc WithBorderHorizontal() ContainerOption {\n\treturn WithBorder(true, false, true, false)\n}\n\nfunc WithBorderVertical() ContainerOption {\n\treturn WithBorder(false, true, false, true)\n}\n\nfunc WithBorderStyle(style lipgloss.Border) ContainerOption {\n\treturn func(c *container) {\n\t\tc.borderStyle = style\n\t}\n}\n\nfunc WithRoundedBorder() ContainerOption {\n\treturn WithBorderStyle(lipgloss.RoundedBorder())\n}\n\nfunc WithThickBorder() ContainerOption {\n\treturn WithBorderStyle(lipgloss.ThickBorder())\n}\n\nfunc WithDoubleBorder() ContainerOption {\n\treturn WithBorderStyle(lipgloss.DoubleBorder())\n}\n"], ["/opencode/internal/tui/page/logs.go", "package page\n\nimport (\n\t\"github.com/charmbracelet/bubbles/key\"\n\ttea \"github.com/charmbracelet/bubbletea\"\n\t\"github.com/charmbracelet/lipgloss\"\n\t\"github.com/opencode-ai/opencode/internal/tui/components/logs\"\n\t\"github.com/opencode-ai/opencode/internal/tui/layout\"\n\t\"github.com/opencode-ai/opencode/internal/tui/styles\"\n)\n\nvar LogsPage PageID = \"logs\"\n\ntype LogPage interface {\n\ttea.Model\n\tlayout.Sizeable\n\tlayout.Bindings\n}\ntype logsPage struct {\n\twidth, height int\n\ttable layout.Container\n\tdetails layout.Container\n}\n\nfunc (p *logsPage) Update(msg tea.Msg) (tea.Model, tea.Cmd) {\n\tvar cmds []tea.Cmd\n\tswitch msg := msg.(type) {\n\tcase tea.WindowSizeMsg:\n\t\tp.width = msg.Width\n\t\tp.height = msg.Height\n\t\treturn p, p.SetSize(msg.Width, msg.Height)\n\t}\n\n\ttable, cmd := p.table.Update(msg)\n\tcmds = append(cmds, cmd)\n\tp.table = table.(layout.Container)\n\tdetails, cmd := p.details.Update(msg)\n\tcmds = append(cmds, cmd)\n\tp.details = details.(layout.Container)\n\n\treturn p, tea.Batch(cmds...)\n}\n\nfunc (p *logsPage) View() string {\n\tstyle := styles.BaseStyle().Width(p.width).Height(p.height)\n\treturn style.Render(lipgloss.JoinVertical(lipgloss.Top,\n\t\tp.table.View(),\n\t\tp.details.View(),\n\t))\n}\n\nfunc (p *logsPage) BindingKeys() []key.Binding {\n\treturn p.table.BindingKeys()\n}\n\n// GetSize implements LogPage.\nfunc (p *logsPage) GetSize() (int, int) {\n\treturn p.width, p.height\n}\n\n// SetSize implements LogPage.\nfunc (p *logsPage) SetSize(width int, height int) tea.Cmd {\n\tp.width = width\n\tp.height = height\n\treturn tea.Batch(\n\t\tp.table.SetSize(width, height/2),\n\t\tp.details.SetSize(width, height/2),\n\t)\n}\n\nfunc (p *logsPage) Init() tea.Cmd {\n\treturn tea.Batch(\n\t\tp.table.Init(),\n\t\tp.details.Init(),\n\t)\n}\n\nfunc NewLogsPage() LogPage {\n\treturn &logsPage{\n\t\ttable: layout.NewContainer(logs.NewLogsTable(), layout.WithBorderAll()),\n\t\tdetails: layout.NewContainer(logs.NewLogsDetails(), layout.WithBorderAll()),\n\t}\n}\n"], ["/opencode/internal/tui/components/logs/table.go", "package logs\n\nimport (\n\t\"encoding/json\"\n\t\"slices\"\n\n\t\"github.com/charmbracelet/bubbles/key\"\n\t\"github.com/charmbracelet/bubbles/table\"\n\ttea \"github.com/charmbracelet/bubbletea\"\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n\t\"github.com/opencode-ai/opencode/internal/pubsub\"\n\t\"github.com/opencode-ai/opencode/internal/tui/layout\"\n\t\"github.com/opencode-ai/opencode/internal/tui/styles\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n\t\"github.com/opencode-ai/opencode/internal/tui/util\"\n)\n\ntype TableComponent interface {\n\ttea.Model\n\tlayout.Sizeable\n\tlayout.Bindings\n}\n\ntype tableCmp struct {\n\ttable table.Model\n}\n\ntype selectedLogMsg logging.LogMessage\n\nfunc (i *tableCmp) Init() tea.Cmd {\n\ti.setRows()\n\treturn nil\n}\n\nfunc (i *tableCmp) Update(msg tea.Msg) (tea.Model, tea.Cmd) {\n\tvar cmds []tea.Cmd\n\tswitch msg.(type) {\n\tcase pubsub.Event[logging.LogMessage]:\n\t\ti.setRows()\n\t\treturn i, nil\n\t}\n\tprevSelectedRow := i.table.SelectedRow()\n\tt, cmd := i.table.Update(msg)\n\tcmds = append(cmds, cmd)\n\ti.table = t\n\tselectedRow := i.table.SelectedRow()\n\tif selectedRow != nil {\n\t\tif prevSelectedRow == nil || selectedRow[0] == prevSelectedRow[0] {\n\t\t\tvar log logging.LogMessage\n\t\t\tfor _, row := range logging.List() {\n\t\t\t\tif row.ID == selectedRow[0] {\n\t\t\t\t\tlog = row\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\tif log.ID != \"\" {\n\t\t\t\tcmds = append(cmds, util.CmdHandler(selectedLogMsg(log)))\n\t\t\t}\n\t\t}\n\t}\n\treturn i, tea.Batch(cmds...)\n}\n\nfunc (i *tableCmp) View() string {\n\tt := theme.CurrentTheme()\n\tdefaultStyles := table.DefaultStyles()\n\tdefaultStyles.Selected = defaultStyles.Selected.Foreground(t.Primary())\n\ti.table.SetStyles(defaultStyles)\n\treturn styles.ForceReplaceBackgroundWithLipgloss(i.table.View(), t.Background())\n}\n\nfunc (i *tableCmp) GetSize() (int, int) {\n\treturn i.table.Width(), i.table.Height()\n}\n\nfunc (i *tableCmp) SetSize(width int, height int) tea.Cmd {\n\ti.table.SetWidth(width)\n\ti.table.SetHeight(height)\n\tcloumns := i.table.Columns()\n\tfor i, col := range cloumns {\n\t\tcol.Width = (width / len(cloumns)) - 2\n\t\tcloumns[i] = col\n\t}\n\ti.table.SetColumns(cloumns)\n\treturn nil\n}\n\nfunc (i *tableCmp) BindingKeys() []key.Binding {\n\treturn layout.KeyMapToSlice(i.table.KeyMap)\n}\n\nfunc (i *tableCmp) setRows() {\n\trows := []table.Row{}\n\n\tlogs := logging.List()\n\tslices.SortFunc(logs, func(a, b logging.LogMessage) int {\n\t\tif a.Time.Before(b.Time) {\n\t\t\treturn 1\n\t\t}\n\t\tif a.Time.After(b.Time) {\n\t\t\treturn -1\n\t\t}\n\t\treturn 0\n\t})\n\n\tfor _, log := range logs {\n\t\tbm, _ := json.Marshal(log.Attributes)\n\n\t\trow := table.Row{\n\t\t\tlog.ID,\n\t\t\tlog.Time.Format(\"15:04:05\"),\n\t\t\tlog.Level,\n\t\t\tlog.Message,\n\t\t\tstring(bm),\n\t\t}\n\t\trows = append(rows, row)\n\t}\n\ti.table.SetRows(rows)\n}\n\nfunc NewLogsTable() TableComponent {\n\tcolumns := []table.Column{\n\t\t{Title: \"ID\", Width: 4},\n\t\t{Title: \"Time\", Width: 4},\n\t\t{Title: \"Level\", Width: 10},\n\t\t{Title: \"Message\", Width: 10},\n\t\t{Title: \"Attributes\", Width: 10},\n\t}\n\n\ttableModel := table.New(\n\t\ttable.WithColumns(columns),\n\t)\n\ttableModel.Focus()\n\treturn &tableCmp{\n\t\ttable: tableModel,\n\t}\n}\n"], ["/opencode/internal/diff/patch.go", "package diff\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"strings\"\n)\n\ntype ActionType string\n\nconst (\n\tActionAdd ActionType = \"add\"\n\tActionDelete ActionType = \"delete\"\n\tActionUpdate ActionType = \"update\"\n)\n\ntype FileChange struct {\n\tType ActionType\n\tOldContent *string\n\tNewContent *string\n\tMovePath *string\n}\n\ntype Commit struct {\n\tChanges map[string]FileChange\n}\n\ntype Chunk struct {\n\tOrigIndex int // line index of the first line in the original file\n\tDelLines []string // lines to delete\n\tInsLines []string // lines to insert\n}\n\ntype PatchAction struct {\n\tType ActionType\n\tNewFile *string\n\tChunks []Chunk\n\tMovePath *string\n}\n\ntype Patch struct {\n\tActions map[string]PatchAction\n}\n\ntype DiffError struct {\n\tmessage string\n}\n\nfunc (e DiffError) Error() string {\n\treturn e.message\n}\n\n// Helper functions for error handling\nfunc NewDiffError(message string) DiffError {\n\treturn DiffError{message: message}\n}\n\nfunc fileError(action, reason, path string) DiffError {\n\treturn NewDiffError(fmt.Sprintf(\"%s File Error: %s: %s\", action, reason, path))\n}\n\nfunc contextError(index int, context string, isEOF bool) DiffError {\n\tprefix := \"Invalid Context\"\n\tif isEOF {\n\t\tprefix = \"Invalid EOF Context\"\n\t}\n\treturn NewDiffError(fmt.Sprintf(\"%s %d:\\n%s\", prefix, index, context))\n}\n\ntype Parser struct {\n\tcurrentFiles map[string]string\n\tlines []string\n\tindex int\n\tpatch Patch\n\tfuzz int\n}\n\nfunc NewParser(currentFiles map[string]string, lines []string) *Parser {\n\treturn &Parser{\n\t\tcurrentFiles: currentFiles,\n\t\tlines: lines,\n\t\tindex: 0,\n\t\tpatch: Patch{Actions: make(map[string]PatchAction, len(currentFiles))},\n\t\tfuzz: 0,\n\t}\n}\n\nfunc (p *Parser) isDone(prefixes []string) bool {\n\tif p.index >= len(p.lines) {\n\t\treturn true\n\t}\n\tfor _, prefix := range prefixes {\n\t\tif strings.HasPrefix(p.lines[p.index], prefix) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc (p *Parser) startsWith(prefix any) bool {\n\tvar prefixes []string\n\tswitch v := prefix.(type) {\n\tcase string:\n\t\tprefixes = []string{v}\n\tcase []string:\n\t\tprefixes = v\n\t}\n\n\tfor _, pfx := range prefixes {\n\t\tif strings.HasPrefix(p.lines[p.index], pfx) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc (p *Parser) readStr(prefix string, returnEverything bool) string {\n\tif p.index >= len(p.lines) {\n\t\treturn \"\" // Changed from panic to return empty string for safer operation\n\t}\n\tif strings.HasPrefix(p.lines[p.index], prefix) {\n\t\tvar text string\n\t\tif returnEverything {\n\t\t\ttext = p.lines[p.index]\n\t\t} else {\n\t\t\ttext = p.lines[p.index][len(prefix):]\n\t\t}\n\t\tp.index++\n\t\treturn text\n\t}\n\treturn \"\"\n}\n\nfunc (p *Parser) Parse() error {\n\tendPatchPrefixes := []string{\"*** End Patch\"}\n\n\tfor !p.isDone(endPatchPrefixes) {\n\t\tpath := p.readStr(\"*** Update File: \", false)\n\t\tif path != \"\" {\n\t\t\tif _, exists := p.patch.Actions[path]; exists {\n\t\t\t\treturn fileError(\"Update\", \"Duplicate Path\", path)\n\t\t\t}\n\t\t\tmoveTo := p.readStr(\"*** Move to: \", false)\n\t\t\tif _, exists := p.currentFiles[path]; !exists {\n\t\t\t\treturn fileError(\"Update\", \"Missing File\", path)\n\t\t\t}\n\t\t\ttext := p.currentFiles[path]\n\t\t\taction, err := p.parseUpdateFile(text)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif moveTo != \"\" {\n\t\t\t\taction.MovePath = &moveTo\n\t\t\t}\n\t\t\tp.patch.Actions[path] = action\n\t\t\tcontinue\n\t\t}\n\n\t\tpath = p.readStr(\"*** Delete File: \", false)\n\t\tif path != \"\" {\n\t\t\tif _, exists := p.patch.Actions[path]; exists {\n\t\t\t\treturn fileError(\"Delete\", \"Duplicate Path\", path)\n\t\t\t}\n\t\t\tif _, exists := p.currentFiles[path]; !exists {\n\t\t\t\treturn fileError(\"Delete\", \"Missing File\", path)\n\t\t\t}\n\t\t\tp.patch.Actions[path] = PatchAction{Type: ActionDelete, Chunks: []Chunk{}}\n\t\t\tcontinue\n\t\t}\n\n\t\tpath = p.readStr(\"*** Add File: \", false)\n\t\tif path != \"\" {\n\t\t\tif _, exists := p.patch.Actions[path]; exists {\n\t\t\t\treturn fileError(\"Add\", \"Duplicate Path\", path)\n\t\t\t}\n\t\t\tif _, exists := p.currentFiles[path]; exists {\n\t\t\t\treturn fileError(\"Add\", \"File already exists\", path)\n\t\t\t}\n\t\t\taction, err := p.parseAddFile()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tp.patch.Actions[path] = action\n\t\t\tcontinue\n\t\t}\n\n\t\treturn NewDiffError(fmt.Sprintf(\"Unknown Line: %s\", p.lines[p.index]))\n\t}\n\n\tif !p.startsWith(\"*** End Patch\") {\n\t\treturn NewDiffError(\"Missing End Patch\")\n\t}\n\tp.index++\n\n\treturn nil\n}\n\nfunc (p *Parser) parseUpdateFile(text string) (PatchAction, error) {\n\taction := PatchAction{Type: ActionUpdate, Chunks: []Chunk{}}\n\tfileLines := strings.Split(text, \"\\n\")\n\tindex := 0\n\n\tendPrefixes := []string{\n\t\t\"*** End Patch\",\n\t\t\"*** Update File:\",\n\t\t\"*** Delete File:\",\n\t\t\"*** Add File:\",\n\t\t\"*** End of File\",\n\t}\n\n\tfor !p.isDone(endPrefixes) {\n\t\tdefStr := p.readStr(\"@@ \", false)\n\t\tsectionStr := \"\"\n\t\tif defStr == \"\" && p.index < len(p.lines) && p.lines[p.index] == \"@@\" {\n\t\t\tsectionStr = p.lines[p.index]\n\t\t\tp.index++\n\t\t}\n\t\tif defStr == \"\" && sectionStr == \"\" && index != 0 {\n\t\t\treturn action, NewDiffError(fmt.Sprintf(\"Invalid Line:\\n%s\", p.lines[p.index]))\n\t\t}\n\t\tif strings.TrimSpace(defStr) != \"\" {\n\t\t\tfound := false\n\t\t\tfor i := range fileLines[:index] {\n\t\t\t\tif fileLines[i] == defStr {\n\t\t\t\t\tfound = true\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif !found {\n\t\t\t\tfor i := index; i < len(fileLines); i++ {\n\t\t\t\t\tif fileLines[i] == defStr {\n\t\t\t\t\t\tindex = i + 1\n\t\t\t\t\t\tfound = true\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif !found {\n\t\t\t\tfor i := range fileLines[:index] {\n\t\t\t\t\tif strings.TrimSpace(fileLines[i]) == strings.TrimSpace(defStr) {\n\t\t\t\t\t\tfound = true\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif !found {\n\t\t\t\tfor i := index; i < len(fileLines); i++ {\n\t\t\t\t\tif strings.TrimSpace(fileLines[i]) == strings.TrimSpace(defStr) {\n\t\t\t\t\t\tindex = i + 1\n\t\t\t\t\t\tp.fuzz++\n\t\t\t\t\t\tfound = true\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tnextChunkContext, chunks, endPatchIndex, eof := peekNextSection(p.lines, p.index)\n\t\tnewIndex, fuzz := findContext(fileLines, nextChunkContext, index, eof)\n\t\tif newIndex == -1 {\n\t\t\tctxText := strings.Join(nextChunkContext, \"\\n\")\n\t\t\treturn action, contextError(index, ctxText, eof)\n\t\t}\n\t\tp.fuzz += fuzz\n\n\t\tfor _, ch := range chunks {\n\t\t\tch.OrigIndex += newIndex\n\t\t\taction.Chunks = append(action.Chunks, ch)\n\t\t}\n\t\tindex = newIndex + len(nextChunkContext)\n\t\tp.index = endPatchIndex\n\t}\n\treturn action, nil\n}\n\nfunc (p *Parser) parseAddFile() (PatchAction, error) {\n\tlines := make([]string, 0, 16) // Preallocate space for better performance\n\tendPrefixes := []string{\n\t\t\"*** End Patch\",\n\t\t\"*** Update File:\",\n\t\t\"*** Delete File:\",\n\t\t\"*** Add File:\",\n\t}\n\n\tfor !p.isDone(endPrefixes) {\n\t\ts := p.readStr(\"\", true)\n\t\tif !strings.HasPrefix(s, \"+\") {\n\t\t\treturn PatchAction{}, NewDiffError(fmt.Sprintf(\"Invalid Add File Line: %s\", s))\n\t\t}\n\t\tlines = append(lines, s[1:])\n\t}\n\n\tnewFile := strings.Join(lines, \"\\n\")\n\treturn PatchAction{\n\t\tType: ActionAdd,\n\t\tNewFile: &newFile,\n\t\tChunks: []Chunk{},\n\t}, nil\n}\n\n// Refactored to use a matcher function for each comparison type\nfunc findContextCore(lines []string, context []string, start int) (int, int) {\n\tif len(context) == 0 {\n\t\treturn start, 0\n\t}\n\n\t// Try exact match\n\tif idx, fuzz := tryFindMatch(lines, context, start, func(a, b string) bool {\n\t\treturn a == b\n\t}); idx >= 0 {\n\t\treturn idx, fuzz\n\t}\n\n\t// Try trimming right whitespace\n\tif idx, fuzz := tryFindMatch(lines, context, start, func(a, b string) bool {\n\t\treturn strings.TrimRight(a, \" \\t\") == strings.TrimRight(b, \" \\t\")\n\t}); idx >= 0 {\n\t\treturn idx, fuzz\n\t}\n\n\t// Try trimming all whitespace\n\tif idx, fuzz := tryFindMatch(lines, context, start, func(a, b string) bool {\n\t\treturn strings.TrimSpace(a) == strings.TrimSpace(b)\n\t}); idx >= 0 {\n\t\treturn idx, fuzz\n\t}\n\n\treturn -1, 0\n}\n\n// Helper function to DRY up the match logic\nfunc tryFindMatch(lines []string, context []string, start int,\n\tcompareFunc func(string, string) bool,\n) (int, int) {\n\tfor i := start; i < len(lines); i++ {\n\t\tif i+len(context) <= len(lines) {\n\t\t\tmatch := true\n\t\t\tfor j := range context {\n\t\t\t\tif !compareFunc(lines[i+j], context[j]) {\n\t\t\t\t\tmatch = false\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\tif match {\n\t\t\t\t// Return fuzz level: 0 for exact, 1 for trimRight, 100 for trimSpace\n\t\t\t\tvar fuzz int\n\t\t\t\tif compareFunc(\"a \", \"a\") && !compareFunc(\"a\", \"b\") {\n\t\t\t\t\tfuzz = 1\n\t\t\t\t} else if compareFunc(\"a \", \"a\") {\n\t\t\t\t\tfuzz = 100\n\t\t\t\t}\n\t\t\t\treturn i, fuzz\n\t\t\t}\n\t\t}\n\t}\n\treturn -1, 0\n}\n\nfunc findContext(lines []string, context []string, start int, eof bool) (int, int) {\n\tif eof {\n\t\tnewIndex, fuzz := findContextCore(lines, context, len(lines)-len(context))\n\t\tif newIndex != -1 {\n\t\t\treturn newIndex, fuzz\n\t\t}\n\t\tnewIndex, fuzz = findContextCore(lines, context, start)\n\t\treturn newIndex, fuzz + 10000\n\t}\n\treturn findContextCore(lines, context, start)\n}\n\nfunc peekNextSection(lines []string, initialIndex int) ([]string, []Chunk, int, bool) {\n\tindex := initialIndex\n\told := make([]string, 0, 32) // Preallocate for better performance\n\tdelLines := make([]string, 0, 8)\n\tinsLines := make([]string, 0, 8)\n\tchunks := make([]Chunk, 0, 4)\n\tmode := \"keep\"\n\n\t// End conditions for the section\n\tendSectionConditions := func(s string) bool {\n\t\treturn strings.HasPrefix(s, \"@@\") ||\n\t\t\tstrings.HasPrefix(s, \"*** End Patch\") ||\n\t\t\tstrings.HasPrefix(s, \"*** Update File:\") ||\n\t\t\tstrings.HasPrefix(s, \"*** Delete File:\") ||\n\t\t\tstrings.HasPrefix(s, \"*** Add File:\") ||\n\t\t\tstrings.HasPrefix(s, \"*** End of File\") ||\n\t\t\ts == \"***\" ||\n\t\t\tstrings.HasPrefix(s, \"***\")\n\t}\n\n\tfor index < len(lines) {\n\t\ts := lines[index]\n\t\tif endSectionConditions(s) {\n\t\t\tbreak\n\t\t}\n\t\tindex++\n\t\tlastMode := mode\n\t\tline := s\n\n\t\tif len(line) > 0 {\n\t\t\tswitch line[0] {\n\t\t\tcase '+':\n\t\t\t\tmode = \"add\"\n\t\t\tcase '-':\n\t\t\t\tmode = \"delete\"\n\t\t\tcase ' ':\n\t\t\t\tmode = \"keep\"\n\t\t\tdefault:\n\t\t\t\tmode = \"keep\"\n\t\t\t\tline = \" \" + line\n\t\t\t}\n\t\t} else {\n\t\t\tmode = \"keep\"\n\t\t\tline = \" \"\n\t\t}\n\n\t\tline = line[1:]\n\t\tif mode == \"keep\" && lastMode != mode {\n\t\t\tif len(insLines) > 0 || len(delLines) > 0 {\n\t\t\t\tchunks = append(chunks, Chunk{\n\t\t\t\t\tOrigIndex: len(old) - len(delLines),\n\t\t\t\t\tDelLines: delLines,\n\t\t\t\t\tInsLines: insLines,\n\t\t\t\t})\n\t\t\t}\n\t\t\tdelLines = make([]string, 0, 8)\n\t\t\tinsLines = make([]string, 0, 8)\n\t\t}\n\t\tswitch mode {\n\t\tcase \"delete\":\n\t\t\tdelLines = append(delLines, line)\n\t\t\told = append(old, line)\n\t\tcase \"add\":\n\t\t\tinsLines = append(insLines, line)\n\t\tdefault:\n\t\t\told = append(old, line)\n\t\t}\n\t}\n\n\tif len(insLines) > 0 || len(delLines) > 0 {\n\t\tchunks = append(chunks, Chunk{\n\t\t\tOrigIndex: len(old) - len(delLines),\n\t\t\tDelLines: delLines,\n\t\t\tInsLines: insLines,\n\t\t})\n\t}\n\n\tif index < len(lines) && lines[index] == \"*** End of File\" {\n\t\tindex++\n\t\treturn old, chunks, index, true\n\t}\n\treturn old, chunks, index, false\n}\n\nfunc TextToPatch(text string, orig map[string]string) (Patch, int, error) {\n\ttext = strings.TrimSpace(text)\n\tlines := strings.Split(text, \"\\n\")\n\tif len(lines) < 2 || !strings.HasPrefix(lines[0], \"*** Begin Patch\") || lines[len(lines)-1] != \"*** End Patch\" {\n\t\treturn Patch{}, 0, NewDiffError(\"Invalid patch text\")\n\t}\n\tparser := NewParser(orig, lines)\n\tparser.index = 1\n\tif err := parser.Parse(); err != nil {\n\t\treturn Patch{}, 0, err\n\t}\n\treturn parser.patch, parser.fuzz, nil\n}\n\nfunc IdentifyFilesNeeded(text string) []string {\n\ttext = strings.TrimSpace(text)\n\tlines := strings.Split(text, \"\\n\")\n\tresult := make(map[string]bool)\n\n\tfor _, line := range lines {\n\t\tif strings.HasPrefix(line, \"*** Update File: \") {\n\t\t\tresult[line[len(\"*** Update File: \"):]] = true\n\t\t}\n\t\tif strings.HasPrefix(line, \"*** Delete File: \") {\n\t\t\tresult[line[len(\"*** Delete File: \"):]] = true\n\t\t}\n\t}\n\n\tfiles := make([]string, 0, len(result))\n\tfor file := range result {\n\t\tfiles = append(files, file)\n\t}\n\treturn files\n}\n\nfunc IdentifyFilesAdded(text string) []string {\n\ttext = strings.TrimSpace(text)\n\tlines := strings.Split(text, \"\\n\")\n\tresult := make(map[string]bool)\n\n\tfor _, line := range lines {\n\t\tif strings.HasPrefix(line, \"*** Add File: \") {\n\t\t\tresult[line[len(\"*** Add File: \"):]] = true\n\t\t}\n\t}\n\n\tfiles := make([]string, 0, len(result))\n\tfor file := range result {\n\t\tfiles = append(files, file)\n\t}\n\treturn files\n}\n\nfunc getUpdatedFile(text string, action PatchAction, path string) (string, error) {\n\tif action.Type != ActionUpdate {\n\t\treturn \"\", errors.New(\"expected UPDATE action\")\n\t}\n\torigLines := strings.Split(text, \"\\n\")\n\tdestLines := make([]string, 0, len(origLines)) // Preallocate with capacity\n\torigIndex := 0\n\n\tfor _, chunk := range action.Chunks {\n\t\tif chunk.OrigIndex > len(origLines) {\n\t\t\treturn \"\", NewDiffError(fmt.Sprintf(\"%s: chunk.orig_index %d > len(lines) %d\", path, chunk.OrigIndex, len(origLines)))\n\t\t}\n\t\tif origIndex > chunk.OrigIndex {\n\t\t\treturn \"\", NewDiffError(fmt.Sprintf(\"%s: orig_index %d > chunk.orig_index %d\", path, origIndex, chunk.OrigIndex))\n\t\t}\n\t\tdestLines = append(destLines, origLines[origIndex:chunk.OrigIndex]...)\n\t\tdelta := chunk.OrigIndex - origIndex\n\t\torigIndex += delta\n\n\t\tif len(chunk.InsLines) > 0 {\n\t\t\tdestLines = append(destLines, chunk.InsLines...)\n\t\t}\n\t\torigIndex += len(chunk.DelLines)\n\t}\n\n\tdestLines = append(destLines, origLines[origIndex:]...)\n\treturn strings.Join(destLines, \"\\n\"), nil\n}\n\nfunc PatchToCommit(patch Patch, orig map[string]string) (Commit, error) {\n\tcommit := Commit{Changes: make(map[string]FileChange, len(patch.Actions))}\n\tfor pathKey, action := range patch.Actions {\n\t\tswitch action.Type {\n\t\tcase ActionDelete:\n\t\t\toldContent := orig[pathKey]\n\t\t\tcommit.Changes[pathKey] = FileChange{\n\t\t\t\tType: ActionDelete,\n\t\t\t\tOldContent: &oldContent,\n\t\t\t}\n\t\tcase ActionAdd:\n\t\t\tcommit.Changes[pathKey] = FileChange{\n\t\t\t\tType: ActionAdd,\n\t\t\t\tNewContent: action.NewFile,\n\t\t\t}\n\t\tcase ActionUpdate:\n\t\t\tnewContent, err := getUpdatedFile(orig[pathKey], action, pathKey)\n\t\t\tif err != nil {\n\t\t\t\treturn Commit{}, err\n\t\t\t}\n\t\t\toldContent := orig[pathKey]\n\t\t\tfileChange := FileChange{\n\t\t\t\tType: ActionUpdate,\n\t\t\t\tOldContent: &oldContent,\n\t\t\t\tNewContent: &newContent,\n\t\t\t}\n\t\t\tif action.MovePath != nil {\n\t\t\t\tfileChange.MovePath = action.MovePath\n\t\t\t}\n\t\t\tcommit.Changes[pathKey] = fileChange\n\t\t}\n\t}\n\treturn commit, nil\n}\n\nfunc AssembleChanges(orig map[string]string, updatedFiles map[string]string) Commit {\n\tcommit := Commit{Changes: make(map[string]FileChange, len(updatedFiles))}\n\tfor p, newContent := range updatedFiles {\n\t\toldContent, exists := orig[p]\n\t\tif exists && oldContent == newContent {\n\t\t\tcontinue\n\t\t}\n\n\t\tif exists && newContent != \"\" {\n\t\t\tcommit.Changes[p] = FileChange{\n\t\t\t\tType: ActionUpdate,\n\t\t\t\tOldContent: &oldContent,\n\t\t\t\tNewContent: &newContent,\n\t\t\t}\n\t\t} else if newContent != \"\" {\n\t\t\tcommit.Changes[p] = FileChange{\n\t\t\t\tType: ActionAdd,\n\t\t\t\tNewContent: &newContent,\n\t\t\t}\n\t\t} else if exists {\n\t\t\tcommit.Changes[p] = FileChange{\n\t\t\t\tType: ActionDelete,\n\t\t\t\tOldContent: &oldContent,\n\t\t\t}\n\t\t} else {\n\t\t\treturn commit // Changed from panic to simply return current commit\n\t\t}\n\t}\n\treturn commit\n}\n\nfunc LoadFiles(paths []string, openFn func(string) (string, error)) (map[string]string, error) {\n\torig := make(map[string]string, len(paths))\n\tfor _, p := range paths {\n\t\tcontent, err := openFn(p)\n\t\tif err != nil {\n\t\t\treturn nil, fileError(\"Open\", \"File not found\", p)\n\t\t}\n\t\torig[p] = content\n\t}\n\treturn orig, nil\n}\n\nfunc ApplyCommit(commit Commit, writeFn func(string, string) error, removeFn func(string) error) error {\n\tfor p, change := range commit.Changes {\n\t\tswitch change.Type {\n\t\tcase ActionDelete:\n\t\t\tif err := removeFn(p); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\tcase ActionAdd:\n\t\t\tif change.NewContent == nil {\n\t\t\t\treturn NewDiffError(fmt.Sprintf(\"Add action for %s has nil new_content\", p))\n\t\t\t}\n\t\t\tif err := writeFn(p, *change.NewContent); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\tcase ActionUpdate:\n\t\t\tif change.NewContent == nil {\n\t\t\t\treturn NewDiffError(fmt.Sprintf(\"Update action for %s has nil new_content\", p))\n\t\t\t}\n\t\t\tif change.MovePath != nil {\n\t\t\t\tif err := writeFn(*change.MovePath, *change.NewContent); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tif err := removeFn(p); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif err := writeFn(p, *change.NewContent); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc ProcessPatch(text string, openFn func(string) (string, error), writeFn func(string, string) error, removeFn func(string) error) (string, error) {\n\tif !strings.HasPrefix(text, \"*** Begin Patch\") {\n\t\treturn \"\", NewDiffError(\"Patch must start with *** Begin Patch\")\n\t}\n\tpaths := IdentifyFilesNeeded(text)\n\torig, err := LoadFiles(paths, openFn)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tpatch, fuzz, err := TextToPatch(text, orig)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif fuzz > 0 {\n\t\treturn \"\", NewDiffError(fmt.Sprintf(\"Patch contains fuzzy matches (fuzz level: %d)\", fuzz))\n\t}\n\n\tcommit, err := PatchToCommit(patch, orig)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif err := ApplyCommit(commit, writeFn, removeFn); err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn \"Patch applied successfully\", nil\n}\n\nfunc OpenFile(p string) (string, error) {\n\tdata, err := os.ReadFile(p)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn string(data), nil\n}\n\nfunc WriteFile(p string, content string) error {\n\tif filepath.IsAbs(p) {\n\t\treturn NewDiffError(\"We do not support absolute paths.\")\n\t}\n\n\tdir := filepath.Dir(p)\n\tif dir != \".\" {\n\t\tif err := os.MkdirAll(dir, 0o755); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn os.WriteFile(p, []byte(content), 0o644)\n}\n\nfunc RemoveFile(p string) error {\n\treturn os.Remove(p)\n}\n\nfunc ValidatePatch(patchText string, files map[string]string) (bool, string, error) {\n\tif !strings.HasPrefix(patchText, \"*** Begin Patch\") {\n\t\treturn false, \"Patch must start with *** Begin Patch\", nil\n\t}\n\n\tneededFiles := IdentifyFilesNeeded(patchText)\n\tfor _, filePath := range neededFiles {\n\t\tif _, exists := files[filePath]; !exists {\n\t\t\treturn false, fmt.Sprintf(\"File not found: %s\", filePath), nil\n\t\t}\n\t}\n\n\tpatch, fuzz, err := TextToPatch(patchText, files)\n\tif err != nil {\n\t\treturn false, err.Error(), nil\n\t}\n\n\tif fuzz > 0 {\n\t\treturn false, fmt.Sprintf(\"Patch contains fuzzy matches (fuzz level: %d)\", fuzz), nil\n\t}\n\n\t_, err = PatchToCommit(patch, files)\n\tif err != nil {\n\t\treturn false, err.Error(), nil\n\t}\n\n\treturn true, \"Patch is valid\", nil\n}\n"], ["/opencode/internal/tui/image/images.go", "package image\n\nimport (\n\t\"fmt\"\n\t\"image\"\n\t\"os\"\n\t\"strings\"\n\n\t\"github.com/charmbracelet/lipgloss\"\n\t\"github.com/disintegration/imaging\"\n\t\"github.com/lucasb-eyer/go-colorful\"\n)\n\nfunc ValidateFileSize(filePath string, sizeLimit int64) (bool, error) {\n\tfileInfo, err := os.Stat(filePath)\n\tif err != nil {\n\t\treturn false, fmt.Errorf(\"error getting file info: %w\", err)\n\t}\n\n\tif fileInfo.Size() > sizeLimit {\n\t\treturn true, nil\n\t}\n\n\treturn false, nil\n}\n\nfunc ToString(width int, img image.Image) string {\n\timg = imaging.Resize(img, width, 0, imaging.Lanczos)\n\tb := img.Bounds()\n\timageWidth := b.Max.X\n\th := b.Max.Y\n\tstr := strings.Builder{}\n\n\tfor heightCounter := 0; heightCounter < h; heightCounter += 2 {\n\t\tfor x := range imageWidth {\n\t\t\tc1, _ := colorful.MakeColor(img.At(x, heightCounter))\n\t\t\tcolor1 := lipgloss.Color(c1.Hex())\n\n\t\t\tvar color2 lipgloss.Color\n\t\t\tif heightCounter+1 < h {\n\t\t\t\tc2, _ := colorful.MakeColor(img.At(x, heightCounter+1))\n\t\t\t\tcolor2 = lipgloss.Color(c2.Hex())\n\t\t\t} else {\n\t\t\t\tcolor2 = color1\n\t\t\t}\n\n\t\t\tstr.WriteString(lipgloss.NewStyle().Foreground(color1).\n\t\t\t\tBackground(color2).Render(\"▀\"))\n\t\t}\n\n\t\tstr.WriteString(\"\\n\")\n\t}\n\n\treturn str.String()\n}\n\nfunc ImagePreview(width int, filename string) (string, error) {\n\timageContent, err := os.Open(filename)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer imageContent.Close()\n\n\timg, _, err := image.Decode(imageContent)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\timageString := ToString(width, img)\n\n\treturn imageString, nil\n}\n"], ["/opencode/internal/tui/styles/background.go", "package styles\n\nimport (\n\t\"fmt\"\n\t\"regexp\"\n\t\"strings\"\n\n\t\"github.com/charmbracelet/lipgloss\"\n)\n\nvar ansiEscape = regexp.MustCompile(\"\\x1b\\\\[[0-9;]*m\")\n\nfunc getColorRGB(c lipgloss.TerminalColor) (uint8, uint8, uint8) {\n\tr, g, b, a := c.RGBA()\n\n\t// Un-premultiply alpha if needed\n\tif a > 0 && a < 0xffff {\n\t\tr = (r * 0xffff) / a\n\t\tg = (g * 0xffff) / a\n\t\tb = (b * 0xffff) / a\n\t}\n\n\t// Convert from 16-bit to 8-bit color\n\treturn uint8(r >> 8), uint8(g >> 8), uint8(b >> 8)\n}\n\n// ForceReplaceBackgroundWithLipgloss replaces any ANSI background color codes\n// in `input` with a single 24‑bit background (48;2;R;G;B).\nfunc ForceReplaceBackgroundWithLipgloss(input string, newBgColor lipgloss.TerminalColor) string {\n\t// Precompute our new-bg sequence once\n\tr, g, b := getColorRGB(newBgColor)\n\tnewBg := fmt.Sprintf(\"48;2;%d;%d;%d\", r, g, b)\n\n\treturn ansiEscape.ReplaceAllStringFunc(input, func(seq string) string {\n\t\tconst (\n\t\t\tescPrefixLen = 2 // \"\\x1b[\"\n\t\t\tescSuffixLen = 1 // \"m\"\n\t\t)\n\n\t\traw := seq\n\t\tstart := escPrefixLen\n\t\tend := len(raw) - escSuffixLen\n\n\t\tvar sb strings.Builder\n\t\t// reserve enough space: original content minus bg codes + our newBg\n\t\tsb.Grow((end - start) + len(newBg) + 2)\n\n\t\t// scan from start..end, token by token\n\t\tfor i := start; i < end; {\n\t\t\t// find the next ';' or end\n\t\t\tj := i\n\t\t\tfor j < end && raw[j] != ';' {\n\t\t\t\tj++\n\t\t\t}\n\t\t\ttoken := raw[i:j]\n\n\t\t\t// fast‑path: skip \"48;5;N\" or \"48;2;R;G;B\"\n\t\t\tif len(token) == 2 && token[0] == '4' && token[1] == '8' {\n\t\t\t\tk := j + 1\n\t\t\t\tif k < end {\n\t\t\t\t\t// find next token\n\t\t\t\t\tl := k\n\t\t\t\t\tfor l < end && raw[l] != ';' {\n\t\t\t\t\t\tl++\n\t\t\t\t\t}\n\t\t\t\t\tnext := raw[k:l]\n\t\t\t\t\tif next == \"5\" {\n\t\t\t\t\t\t// skip \"48;5;N\"\n\t\t\t\t\t\tm := l + 1\n\t\t\t\t\t\tfor m < end && raw[m] != ';' {\n\t\t\t\t\t\t\tm++\n\t\t\t\t\t\t}\n\t\t\t\t\t\ti = m + 1\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t} else if next == \"2\" {\n\t\t\t\t\t\t// skip \"48;2;R;G;B\"\n\t\t\t\t\t\tm := l + 1\n\t\t\t\t\t\tfor count := 0; count < 3 && m < end; count++ {\n\t\t\t\t\t\t\tfor m < end && raw[m] != ';' {\n\t\t\t\t\t\t\t\tm++\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tm++\n\t\t\t\t\t\t}\n\t\t\t\t\t\ti = m\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// decide whether to keep this token\n\t\t\t// manually parse ASCII digits to int\n\t\t\tisNum := true\n\t\t\tval := 0\n\t\t\tfor p := i; p < j; p++ {\n\t\t\t\tc := raw[p]\n\t\t\t\tif c < '0' || c > '9' {\n\t\t\t\t\tisNum = false\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tval = val*10 + int(c-'0')\n\t\t\t}\n\t\t\tkeep := !isNum ||\n\t\t\t\t((val < 40 || val > 47) && (val < 100 || val > 107) && val != 49)\n\n\t\t\tif keep {\n\t\t\t\tif sb.Len() > 0 {\n\t\t\t\t\tsb.WriteByte(';')\n\t\t\t\t}\n\t\t\t\tsb.WriteString(token)\n\t\t\t}\n\t\t\t// advance past this token (and the semicolon)\n\t\t\ti = j + 1\n\t\t}\n\n\t\t// append our new background\n\t\tif sb.Len() > 0 {\n\t\t\tsb.WriteByte(';')\n\t\t}\n\t\tsb.WriteString(newBg)\n\n\t\treturn \"\\x1b[\" + sb.String() + \"m\"\n\t})\n}\n"], ["/opencode/internal/llm/agent/agent.go", "package agent\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/llm/models\"\n\t\"github.com/opencode-ai/opencode/internal/llm/prompt\"\n\t\"github.com/opencode-ai/opencode/internal/llm/provider\"\n\t\"github.com/opencode-ai/opencode/internal/llm/tools\"\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n\t\"github.com/opencode-ai/opencode/internal/message\"\n\t\"github.com/opencode-ai/opencode/internal/permission\"\n\t\"github.com/opencode-ai/opencode/internal/pubsub\"\n\t\"github.com/opencode-ai/opencode/internal/session\"\n)\n\n// Common errors\nvar (\n\tErrRequestCancelled = errors.New(\"request cancelled by user\")\n\tErrSessionBusy = errors.New(\"session is currently processing another request\")\n)\n\ntype AgentEventType string\n\nconst (\n\tAgentEventTypeError AgentEventType = \"error\"\n\tAgentEventTypeResponse AgentEventType = \"response\"\n\tAgentEventTypeSummarize AgentEventType = \"summarize\"\n)\n\ntype AgentEvent struct {\n\tType AgentEventType\n\tMessage message.Message\n\tError error\n\n\t// When summarizing\n\tSessionID string\n\tProgress string\n\tDone bool\n}\n\ntype Service interface {\n\tpubsub.Suscriber[AgentEvent]\n\tModel() models.Model\n\tRun(ctx context.Context, sessionID string, content string, attachments ...message.Attachment) (<-chan AgentEvent, error)\n\tCancel(sessionID string)\n\tIsSessionBusy(sessionID string) bool\n\tIsBusy() bool\n\tUpdate(agentName config.AgentName, modelID models.ModelID) (models.Model, error)\n\tSummarize(ctx context.Context, sessionID string) error\n}\n\ntype agent struct {\n\t*pubsub.Broker[AgentEvent]\n\tsessions session.Service\n\tmessages message.Service\n\n\ttools []tools.BaseTool\n\tprovider provider.Provider\n\n\ttitleProvider provider.Provider\n\tsummarizeProvider provider.Provider\n\n\tactiveRequests sync.Map\n}\n\nfunc NewAgent(\n\tagentName config.AgentName,\n\tsessions session.Service,\n\tmessages message.Service,\n\tagentTools []tools.BaseTool,\n) (Service, error) {\n\tagentProvider, err := createAgentProvider(agentName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar titleProvider provider.Provider\n\t// Only generate titles for the coder agent\n\tif agentName == config.AgentCoder {\n\t\ttitleProvider, err = createAgentProvider(config.AgentTitle)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tvar summarizeProvider provider.Provider\n\tif agentName == config.AgentCoder {\n\t\tsummarizeProvider, err = createAgentProvider(config.AgentSummarizer)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tagent := &agent{\n\t\tBroker: pubsub.NewBroker[AgentEvent](),\n\t\tprovider: agentProvider,\n\t\tmessages: messages,\n\t\tsessions: sessions,\n\t\ttools: agentTools,\n\t\ttitleProvider: titleProvider,\n\t\tsummarizeProvider: summarizeProvider,\n\t\tactiveRequests: sync.Map{},\n\t}\n\n\treturn agent, nil\n}\n\nfunc (a *agent) Model() models.Model {\n\treturn a.provider.Model()\n}\n\nfunc (a *agent) Cancel(sessionID string) {\n\t// Cancel regular requests\n\tif cancelFunc, exists := a.activeRequests.LoadAndDelete(sessionID); exists {\n\t\tif cancel, ok := cancelFunc.(context.CancelFunc); ok {\n\t\t\tlogging.InfoPersist(fmt.Sprintf(\"Request cancellation initiated for session: %s\", sessionID))\n\t\t\tcancel()\n\t\t}\n\t}\n\n\t// Also check for summarize requests\n\tif cancelFunc, exists := a.activeRequests.LoadAndDelete(sessionID + \"-summarize\"); exists {\n\t\tif cancel, ok := cancelFunc.(context.CancelFunc); ok {\n\t\t\tlogging.InfoPersist(fmt.Sprintf(\"Summarize cancellation initiated for session: %s\", sessionID))\n\t\t\tcancel()\n\t\t}\n\t}\n}\n\nfunc (a *agent) IsBusy() bool {\n\tbusy := false\n\ta.activeRequests.Range(func(key, value interface{}) bool {\n\t\tif cancelFunc, ok := value.(context.CancelFunc); ok {\n\t\t\tif cancelFunc != nil {\n\t\t\t\tbusy = true\n\t\t\t\treturn false // Stop iterating\n\t\t\t}\n\t\t}\n\t\treturn true // Continue iterating\n\t})\n\treturn busy\n}\n\nfunc (a *agent) IsSessionBusy(sessionID string) bool {\n\t_, busy := a.activeRequests.Load(sessionID)\n\treturn busy\n}\n\nfunc (a *agent) generateTitle(ctx context.Context, sessionID string, content string) error {\n\tif content == \"\" {\n\t\treturn nil\n\t}\n\tif a.titleProvider == nil {\n\t\treturn nil\n\t}\n\tsession, err := a.sessions.Get(ctx, sessionID)\n\tif err != nil {\n\t\treturn err\n\t}\n\tctx = context.WithValue(ctx, tools.SessionIDContextKey, sessionID)\n\tparts := []message.ContentPart{message.TextContent{Text: content}}\n\tresponse, err := a.titleProvider.SendMessages(\n\t\tctx,\n\t\t[]message.Message{\n\t\t\t{\n\t\t\t\tRole: message.User,\n\t\t\t\tParts: parts,\n\t\t\t},\n\t\t},\n\t\tmake([]tools.BaseTool, 0),\n\t)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ttitle := strings.TrimSpace(strings.ReplaceAll(response.Content, \"\\n\", \" \"))\n\tif title == \"\" {\n\t\treturn nil\n\t}\n\n\tsession.Title = title\n\t_, err = a.sessions.Save(ctx, session)\n\treturn err\n}\n\nfunc (a *agent) err(err error) AgentEvent {\n\treturn AgentEvent{\n\t\tType: AgentEventTypeError,\n\t\tError: err,\n\t}\n}\n\nfunc (a *agent) Run(ctx context.Context, sessionID string, content string, attachments ...message.Attachment) (<-chan AgentEvent, error) {\n\tif !a.provider.Model().SupportsAttachments && attachments != nil {\n\t\tattachments = nil\n\t}\n\tevents := make(chan AgentEvent)\n\tif a.IsSessionBusy(sessionID) {\n\t\treturn nil, ErrSessionBusy\n\t}\n\n\tgenCtx, cancel := context.WithCancel(ctx)\n\n\ta.activeRequests.Store(sessionID, cancel)\n\tgo func() {\n\t\tlogging.Debug(\"Request started\", \"sessionID\", sessionID)\n\t\tdefer logging.RecoverPanic(\"agent.Run\", func() {\n\t\t\tevents <- a.err(fmt.Errorf(\"panic while running the agent\"))\n\t\t})\n\t\tvar attachmentParts []message.ContentPart\n\t\tfor _, attachment := range attachments {\n\t\t\tattachmentParts = append(attachmentParts, message.BinaryContent{Path: attachment.FilePath, MIMEType: attachment.MimeType, Data: attachment.Content})\n\t\t}\n\t\tresult := a.processGeneration(genCtx, sessionID, content, attachmentParts)\n\t\tif result.Error != nil && !errors.Is(result.Error, ErrRequestCancelled) && !errors.Is(result.Error, context.Canceled) {\n\t\t\tlogging.ErrorPersist(result.Error.Error())\n\t\t}\n\t\tlogging.Debug(\"Request completed\", \"sessionID\", sessionID)\n\t\ta.activeRequests.Delete(sessionID)\n\t\tcancel()\n\t\ta.Publish(pubsub.CreatedEvent, result)\n\t\tevents <- result\n\t\tclose(events)\n\t}()\n\treturn events, nil\n}\n\nfunc (a *agent) processGeneration(ctx context.Context, sessionID, content string, attachmentParts []message.ContentPart) AgentEvent {\n\tcfg := config.Get()\n\t// List existing messages; if none, start title generation asynchronously.\n\tmsgs, err := a.messages.List(ctx, sessionID)\n\tif err != nil {\n\t\treturn a.err(fmt.Errorf(\"failed to list messages: %w\", err))\n\t}\n\tif len(msgs) == 0 {\n\t\tgo func() {\n\t\t\tdefer logging.RecoverPanic(\"agent.Run\", func() {\n\t\t\t\tlogging.ErrorPersist(\"panic while generating title\")\n\t\t\t})\n\t\t\ttitleErr := a.generateTitle(context.Background(), sessionID, content)\n\t\t\tif titleErr != nil {\n\t\t\t\tlogging.ErrorPersist(fmt.Sprintf(\"failed to generate title: %v\", titleErr))\n\t\t\t}\n\t\t}()\n\t}\n\tsession, err := a.sessions.Get(ctx, sessionID)\n\tif err != nil {\n\t\treturn a.err(fmt.Errorf(\"failed to get session: %w\", err))\n\t}\n\tif session.SummaryMessageID != \"\" {\n\t\tsummaryMsgInex := -1\n\t\tfor i, msg := range msgs {\n\t\t\tif msg.ID == session.SummaryMessageID {\n\t\t\t\tsummaryMsgInex = i\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif summaryMsgInex != -1 {\n\t\t\tmsgs = msgs[summaryMsgInex:]\n\t\t\tmsgs[0].Role = message.User\n\t\t}\n\t}\n\n\tuserMsg, err := a.createUserMessage(ctx, sessionID, content, attachmentParts)\n\tif err != nil {\n\t\treturn a.err(fmt.Errorf(\"failed to create user message: %w\", err))\n\t}\n\t// Append the new user message to the conversation history.\n\tmsgHistory := append(msgs, userMsg)\n\n\tfor {\n\t\t// Check for cancellation before each iteration\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn a.err(ctx.Err())\n\t\tdefault:\n\t\t\t// Continue processing\n\t\t}\n\t\tagentMessage, toolResults, err := a.streamAndHandleEvents(ctx, sessionID, msgHistory)\n\t\tif err != nil {\n\t\t\tif errors.Is(err, context.Canceled) {\n\t\t\t\tagentMessage.AddFinish(message.FinishReasonCanceled)\n\t\t\t\ta.messages.Update(context.Background(), agentMessage)\n\t\t\t\treturn a.err(ErrRequestCancelled)\n\t\t\t}\n\t\t\treturn a.err(fmt.Errorf(\"failed to process events: %w\", err))\n\t\t}\n\t\tif cfg.Debug {\n\t\t\tseqId := (len(msgHistory) + 1) / 2\n\t\t\ttoolResultFilepath := logging.WriteToolResultsJson(sessionID, seqId, toolResults)\n\t\t\tlogging.Info(\"Result\", \"message\", agentMessage.FinishReason(), \"toolResults\", \"{}\", \"filepath\", toolResultFilepath)\n\t\t} else {\n\t\t\tlogging.Info(\"Result\", \"message\", agentMessage.FinishReason(), \"toolResults\", toolResults)\n\t\t}\n\t\tif (agentMessage.FinishReason() == message.FinishReasonToolUse) && toolResults != nil {\n\t\t\t// We are not done, we need to respond with the tool response\n\t\t\tmsgHistory = append(msgHistory, agentMessage, *toolResults)\n\t\t\tcontinue\n\t\t}\n\t\treturn AgentEvent{\n\t\t\tType: AgentEventTypeResponse,\n\t\t\tMessage: agentMessage,\n\t\t\tDone: true,\n\t\t}\n\t}\n}\n\nfunc (a *agent) createUserMessage(ctx context.Context, sessionID, content string, attachmentParts []message.ContentPart) (message.Message, error) {\n\tparts := []message.ContentPart{message.TextContent{Text: content}}\n\tparts = append(parts, attachmentParts...)\n\treturn a.messages.Create(ctx, sessionID, message.CreateMessageParams{\n\t\tRole: message.User,\n\t\tParts: parts,\n\t})\n}\n\nfunc (a *agent) streamAndHandleEvents(ctx context.Context, sessionID string, msgHistory []message.Message) (message.Message, *message.Message, error) {\n\tctx = context.WithValue(ctx, tools.SessionIDContextKey, sessionID)\n\teventChan := a.provider.StreamResponse(ctx, msgHistory, a.tools)\n\n\tassistantMsg, err := a.messages.Create(ctx, sessionID, message.CreateMessageParams{\n\t\tRole: message.Assistant,\n\t\tParts: []message.ContentPart{},\n\t\tModel: a.provider.Model().ID,\n\t})\n\tif err != nil {\n\t\treturn assistantMsg, nil, fmt.Errorf(\"failed to create assistant message: %w\", err)\n\t}\n\n\t// Add the session and message ID into the context if needed by tools.\n\tctx = context.WithValue(ctx, tools.MessageIDContextKey, assistantMsg.ID)\n\n\t// Process each event in the stream.\n\tfor event := range eventChan {\n\t\tif processErr := a.processEvent(ctx, sessionID, &assistantMsg, event); processErr != nil {\n\t\t\ta.finishMessage(ctx, &assistantMsg, message.FinishReasonCanceled)\n\t\t\treturn assistantMsg, nil, processErr\n\t\t}\n\t\tif ctx.Err() != nil {\n\t\t\ta.finishMessage(context.Background(), &assistantMsg, message.FinishReasonCanceled)\n\t\t\treturn assistantMsg, nil, ctx.Err()\n\t\t}\n\t}\n\n\ttoolResults := make([]message.ToolResult, len(assistantMsg.ToolCalls()))\n\ttoolCalls := assistantMsg.ToolCalls()\n\tfor i, toolCall := range toolCalls {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\ta.finishMessage(context.Background(), &assistantMsg, message.FinishReasonCanceled)\n\t\t\t// Make all future tool calls cancelled\n\t\t\tfor j := i; j < len(toolCalls); j++ {\n\t\t\t\ttoolResults[j] = message.ToolResult{\n\t\t\t\t\tToolCallID: toolCalls[j].ID,\n\t\t\t\t\tContent: \"Tool execution canceled by user\",\n\t\t\t\t\tIsError: true,\n\t\t\t\t}\n\t\t\t}\n\t\t\tgoto out\n\t\tdefault:\n\t\t\t// Continue processing\n\t\t\tvar tool tools.BaseTool\n\t\t\tfor _, availableTool := range a.tools {\n\t\t\t\tif availableTool.Info().Name == toolCall.Name {\n\t\t\t\t\ttool = availableTool\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\t// Monkey patch for Copilot Sonnet-4 tool repetition obfuscation\n\t\t\t\t// if strings.HasPrefix(toolCall.Name, availableTool.Info().Name) &&\n\t\t\t\t// \tstrings.HasPrefix(toolCall.Name, availableTool.Info().Name+availableTool.Info().Name) {\n\t\t\t\t// \ttool = availableTool\n\t\t\t\t// \tbreak\n\t\t\t\t// }\n\t\t\t}\n\n\t\t\t// Tool not found\n\t\t\tif tool == nil {\n\t\t\t\ttoolResults[i] = message.ToolResult{\n\t\t\t\t\tToolCallID: toolCall.ID,\n\t\t\t\t\tContent: fmt.Sprintf(\"Tool not found: %s\", toolCall.Name),\n\t\t\t\t\tIsError: true,\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\ttoolResult, toolErr := tool.Run(ctx, tools.ToolCall{\n\t\t\t\tID: toolCall.ID,\n\t\t\t\tName: toolCall.Name,\n\t\t\t\tInput: toolCall.Input,\n\t\t\t})\n\t\t\tif toolErr != nil {\n\t\t\t\tif errors.Is(toolErr, permission.ErrorPermissionDenied) {\n\t\t\t\t\ttoolResults[i] = message.ToolResult{\n\t\t\t\t\t\tToolCallID: toolCall.ID,\n\t\t\t\t\t\tContent: \"Permission denied\",\n\t\t\t\t\t\tIsError: true,\n\t\t\t\t\t}\n\t\t\t\t\tfor j := i + 1; j < len(toolCalls); j++ {\n\t\t\t\t\t\ttoolResults[j] = message.ToolResult{\n\t\t\t\t\t\t\tToolCallID: toolCalls[j].ID,\n\t\t\t\t\t\t\tContent: \"Tool execution canceled by user\",\n\t\t\t\t\t\t\tIsError: true,\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\ta.finishMessage(ctx, &assistantMsg, message.FinishReasonPermissionDenied)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\ttoolResults[i] = message.ToolResult{\n\t\t\t\tToolCallID: toolCall.ID,\n\t\t\t\tContent: toolResult.Content,\n\t\t\t\tMetadata: toolResult.Metadata,\n\t\t\t\tIsError: toolResult.IsError,\n\t\t\t}\n\t\t}\n\t}\nout:\n\tif len(toolResults) == 0 {\n\t\treturn assistantMsg, nil, nil\n\t}\n\tparts := make([]message.ContentPart, 0)\n\tfor _, tr := range toolResults {\n\t\tparts = append(parts, tr)\n\t}\n\tmsg, err := a.messages.Create(context.Background(), assistantMsg.SessionID, message.CreateMessageParams{\n\t\tRole: message.Tool,\n\t\tParts: parts,\n\t})\n\tif err != nil {\n\t\treturn assistantMsg, nil, fmt.Errorf(\"failed to create cancelled tool message: %w\", err)\n\t}\n\n\treturn assistantMsg, &msg, err\n}\n\nfunc (a *agent) finishMessage(ctx context.Context, msg *message.Message, finishReson message.FinishReason) {\n\tmsg.AddFinish(finishReson)\n\t_ = a.messages.Update(ctx, *msg)\n}\n\nfunc (a *agent) processEvent(ctx context.Context, sessionID string, assistantMsg *message.Message, event provider.ProviderEvent) error {\n\tselect {\n\tcase <-ctx.Done():\n\t\treturn ctx.Err()\n\tdefault:\n\t\t// Continue processing.\n\t}\n\n\tswitch event.Type {\n\tcase provider.EventThinkingDelta:\n\t\tassistantMsg.AppendReasoningContent(event.Content)\n\t\treturn a.messages.Update(ctx, *assistantMsg)\n\tcase provider.EventContentDelta:\n\t\tassistantMsg.AppendContent(event.Content)\n\t\treturn a.messages.Update(ctx, *assistantMsg)\n\tcase provider.EventToolUseStart:\n\t\tassistantMsg.AddToolCall(*event.ToolCall)\n\t\treturn a.messages.Update(ctx, *assistantMsg)\n\t// TODO: see how to handle this\n\t// case provider.EventToolUseDelta:\n\t// \ttm := time.Unix(assistantMsg.UpdatedAt, 0)\n\t// \tassistantMsg.AppendToolCallInput(event.ToolCall.ID, event.ToolCall.Input)\n\t// \tif time.Since(tm) > 1000*time.Millisecond {\n\t// \t\terr := a.messages.Update(ctx, *assistantMsg)\n\t// \t\tassistantMsg.UpdatedAt = time.Now().Unix()\n\t// \t\treturn err\n\t// \t}\n\tcase provider.EventToolUseStop:\n\t\tassistantMsg.FinishToolCall(event.ToolCall.ID)\n\t\treturn a.messages.Update(ctx, *assistantMsg)\n\tcase provider.EventError:\n\t\tif errors.Is(event.Error, context.Canceled) {\n\t\t\tlogging.InfoPersist(fmt.Sprintf(\"Event processing canceled for session: %s\", sessionID))\n\t\t\treturn context.Canceled\n\t\t}\n\t\tlogging.ErrorPersist(event.Error.Error())\n\t\treturn event.Error\n\tcase provider.EventComplete:\n\t\tassistantMsg.SetToolCalls(event.Response.ToolCalls)\n\t\tassistantMsg.AddFinish(event.Response.FinishReason)\n\t\tif err := a.messages.Update(ctx, *assistantMsg); err != nil {\n\t\t\treturn fmt.Errorf(\"failed to update message: %w\", err)\n\t\t}\n\t\treturn a.TrackUsage(ctx, sessionID, a.provider.Model(), event.Response.Usage)\n\t}\n\n\treturn nil\n}\n\nfunc (a *agent) TrackUsage(ctx context.Context, sessionID string, model models.Model, usage provider.TokenUsage) error {\n\tsess, err := a.sessions.Get(ctx, sessionID)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to get session: %w\", err)\n\t}\n\n\tcost := model.CostPer1MInCached/1e6*float64(usage.CacheCreationTokens) +\n\t\tmodel.CostPer1MOutCached/1e6*float64(usage.CacheReadTokens) +\n\t\tmodel.CostPer1MIn/1e6*float64(usage.InputTokens) +\n\t\tmodel.CostPer1MOut/1e6*float64(usage.OutputTokens)\n\n\tsess.Cost += cost\n\tsess.CompletionTokens = usage.OutputTokens + usage.CacheReadTokens\n\tsess.PromptTokens = usage.InputTokens + usage.CacheCreationTokens\n\n\t_, err = a.sessions.Save(ctx, sess)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to save session: %w\", err)\n\t}\n\treturn nil\n}\n\nfunc (a *agent) Update(agentName config.AgentName, modelID models.ModelID) (models.Model, error) {\n\tif a.IsBusy() {\n\t\treturn models.Model{}, fmt.Errorf(\"cannot change model while processing requests\")\n\t}\n\n\tif err := config.UpdateAgentModel(agentName, modelID); err != nil {\n\t\treturn models.Model{}, fmt.Errorf(\"failed to update config: %w\", err)\n\t}\n\n\tprovider, err := createAgentProvider(agentName)\n\tif err != nil {\n\t\treturn models.Model{}, fmt.Errorf(\"failed to create provider for model %s: %w\", modelID, err)\n\t}\n\n\ta.provider = provider\n\n\treturn a.provider.Model(), nil\n}\n\nfunc (a *agent) Summarize(ctx context.Context, sessionID string) error {\n\tif a.summarizeProvider == nil {\n\t\treturn fmt.Errorf(\"summarize provider not available\")\n\t}\n\n\t// Check if session is busy\n\tif a.IsSessionBusy(sessionID) {\n\t\treturn ErrSessionBusy\n\t}\n\n\t// Create a new context with cancellation\n\tsummarizeCtx, cancel := context.WithCancel(ctx)\n\n\t// Store the cancel function in activeRequests to allow cancellation\n\ta.activeRequests.Store(sessionID+\"-summarize\", cancel)\n\n\tgo func() {\n\t\tdefer a.activeRequests.Delete(sessionID + \"-summarize\")\n\t\tdefer cancel()\n\t\tevent := AgentEvent{\n\t\t\tType: AgentEventTypeSummarize,\n\t\t\tProgress: \"Starting summarization...\",\n\t\t}\n\n\t\ta.Publish(pubsub.CreatedEvent, event)\n\t\t// Get all messages from the session\n\t\tmsgs, err := a.messages.List(summarizeCtx, sessionID)\n\t\tif err != nil {\n\t\t\tevent = AgentEvent{\n\t\t\t\tType: AgentEventTypeError,\n\t\t\t\tError: fmt.Errorf(\"failed to list messages: %w\", err),\n\t\t\t\tDone: true,\n\t\t\t}\n\t\t\ta.Publish(pubsub.CreatedEvent, event)\n\t\t\treturn\n\t\t}\n\t\tsummarizeCtx = context.WithValue(summarizeCtx, tools.SessionIDContextKey, sessionID)\n\n\t\tif len(msgs) == 0 {\n\t\t\tevent = AgentEvent{\n\t\t\t\tType: AgentEventTypeError,\n\t\t\t\tError: fmt.Errorf(\"no messages to summarize\"),\n\t\t\t\tDone: true,\n\t\t\t}\n\t\t\ta.Publish(pubsub.CreatedEvent, event)\n\t\t\treturn\n\t\t}\n\n\t\tevent = AgentEvent{\n\t\t\tType: AgentEventTypeSummarize,\n\t\t\tProgress: \"Analyzing conversation...\",\n\t\t}\n\t\ta.Publish(pubsub.CreatedEvent, event)\n\n\t\t// Add a system message to guide the summarization\n\t\tsummarizePrompt := \"Provide a detailed but concise summary of our conversation above. Focus on information that would be helpful for continuing the conversation, including what we did, what we're doing, which files we're working on, and what we're going to do next.\"\n\n\t\t// Create a new message with the summarize prompt\n\t\tpromptMsg := message.Message{\n\t\t\tRole: message.User,\n\t\t\tParts: []message.ContentPart{message.TextContent{Text: summarizePrompt}},\n\t\t}\n\n\t\t// Append the prompt to the messages\n\t\tmsgsWithPrompt := append(msgs, promptMsg)\n\n\t\tevent = AgentEvent{\n\t\t\tType: AgentEventTypeSummarize,\n\t\t\tProgress: \"Generating summary...\",\n\t\t}\n\n\t\ta.Publish(pubsub.CreatedEvent, event)\n\n\t\t// Send the messages to the summarize provider\n\t\tresponse, err := a.summarizeProvider.SendMessages(\n\t\t\tsummarizeCtx,\n\t\t\tmsgsWithPrompt,\n\t\t\tmake([]tools.BaseTool, 0),\n\t\t)\n\t\tif err != nil {\n\t\t\tevent = AgentEvent{\n\t\t\t\tType: AgentEventTypeError,\n\t\t\t\tError: fmt.Errorf(\"failed to summarize: %w\", err),\n\t\t\t\tDone: true,\n\t\t\t}\n\t\t\ta.Publish(pubsub.CreatedEvent, event)\n\t\t\treturn\n\t\t}\n\n\t\tsummary := strings.TrimSpace(response.Content)\n\t\tif summary == \"\" {\n\t\t\tevent = AgentEvent{\n\t\t\t\tType: AgentEventTypeError,\n\t\t\t\tError: fmt.Errorf(\"empty summary returned\"),\n\t\t\t\tDone: true,\n\t\t\t}\n\t\t\ta.Publish(pubsub.CreatedEvent, event)\n\t\t\treturn\n\t\t}\n\t\tevent = AgentEvent{\n\t\t\tType: AgentEventTypeSummarize,\n\t\t\tProgress: \"Creating new session...\",\n\t\t}\n\n\t\ta.Publish(pubsub.CreatedEvent, event)\n\t\toldSession, err := a.sessions.Get(summarizeCtx, sessionID)\n\t\tif err != nil {\n\t\t\tevent = AgentEvent{\n\t\t\t\tType: AgentEventTypeError,\n\t\t\t\tError: fmt.Errorf(\"failed to get session: %w\", err),\n\t\t\t\tDone: true,\n\t\t\t}\n\n\t\t\ta.Publish(pubsub.CreatedEvent, event)\n\t\t\treturn\n\t\t}\n\t\t// Create a message in the new session with the summary\n\t\tmsg, err := a.messages.Create(summarizeCtx, oldSession.ID, message.CreateMessageParams{\n\t\t\tRole: message.Assistant,\n\t\t\tParts: []message.ContentPart{\n\t\t\t\tmessage.TextContent{Text: summary},\n\t\t\t\tmessage.Finish{\n\t\t\t\t\tReason: message.FinishReasonEndTurn,\n\t\t\t\t\tTime: time.Now().Unix(),\n\t\t\t\t},\n\t\t\t},\n\t\t\tModel: a.summarizeProvider.Model().ID,\n\t\t})\n\t\tif err != nil {\n\t\t\tevent = AgentEvent{\n\t\t\t\tType: AgentEventTypeError,\n\t\t\t\tError: fmt.Errorf(\"failed to create summary message: %w\", err),\n\t\t\t\tDone: true,\n\t\t\t}\n\n\t\t\ta.Publish(pubsub.CreatedEvent, event)\n\t\t\treturn\n\t\t}\n\t\toldSession.SummaryMessageID = msg.ID\n\t\toldSession.CompletionTokens = response.Usage.OutputTokens\n\t\toldSession.PromptTokens = 0\n\t\tmodel := a.summarizeProvider.Model()\n\t\tusage := response.Usage\n\t\tcost := model.CostPer1MInCached/1e6*float64(usage.CacheCreationTokens) +\n\t\t\tmodel.CostPer1MOutCached/1e6*float64(usage.CacheReadTokens) +\n\t\t\tmodel.CostPer1MIn/1e6*float64(usage.InputTokens) +\n\t\t\tmodel.CostPer1MOut/1e6*float64(usage.OutputTokens)\n\t\toldSession.Cost += cost\n\t\t_, err = a.sessions.Save(summarizeCtx, oldSession)\n\t\tif err != nil {\n\t\t\tevent = AgentEvent{\n\t\t\t\tType: AgentEventTypeError,\n\t\t\t\tError: fmt.Errorf(\"failed to save session: %w\", err),\n\t\t\t\tDone: true,\n\t\t\t}\n\t\t\ta.Publish(pubsub.CreatedEvent, event)\n\t\t}\n\n\t\tevent = AgentEvent{\n\t\t\tType: AgentEventTypeSummarize,\n\t\t\tSessionID: oldSession.ID,\n\t\t\tProgress: \"Summary complete\",\n\t\t\tDone: true,\n\t\t}\n\t\ta.Publish(pubsub.CreatedEvent, event)\n\t\t// Send final success event with the new session ID\n\t}()\n\n\treturn nil\n}\n\nfunc createAgentProvider(agentName config.AgentName) (provider.Provider, error) {\n\tcfg := config.Get()\n\tagentConfig, ok := cfg.Agents[agentName]\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"agent %s not found\", agentName)\n\t}\n\tmodel, ok := models.SupportedModels[agentConfig.Model]\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"model %s not supported\", agentConfig.Model)\n\t}\n\n\tproviderCfg, ok := cfg.Providers[model.Provider]\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"provider %s not supported\", model.Provider)\n\t}\n\tif providerCfg.Disabled {\n\t\treturn nil, fmt.Errorf(\"provider %s is not enabled\", model.Provider)\n\t}\n\tmaxTokens := model.DefaultMaxTokens\n\tif agentConfig.MaxTokens > 0 {\n\t\tmaxTokens = agentConfig.MaxTokens\n\t}\n\topts := []provider.ProviderClientOption{\n\t\tprovider.WithAPIKey(providerCfg.APIKey),\n\t\tprovider.WithModel(model),\n\t\tprovider.WithSystemMessage(prompt.GetAgentPrompt(agentName, model.Provider)),\n\t\tprovider.WithMaxTokens(maxTokens),\n\t}\n\tif model.Provider == models.ProviderOpenAI || model.Provider == models.ProviderLocal && model.CanReason {\n\t\topts = append(\n\t\t\topts,\n\t\t\tprovider.WithOpenAIOptions(\n\t\t\t\tprovider.WithReasoningEffort(agentConfig.ReasoningEffort),\n\t\t\t),\n\t\t)\n\t} else if model.Provider == models.ProviderAnthropic && model.CanReason && agentName == config.AgentCoder {\n\t\topts = append(\n\t\t\topts,\n\t\t\tprovider.WithAnthropicOptions(\n\t\t\t\tprovider.WithAnthropicShouldThinkFn(provider.DefaultShouldThinkFn),\n\t\t\t),\n\t\t)\n\t}\n\tagentProvider, err := provider.NewProvider(\n\t\tmodel.Provider,\n\t\topts...,\n\t)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"could not create provider: %v\", err)\n\t}\n\n\treturn agentProvider, nil\n}\n"], ["/opencode/internal/llm/provider/gemini.go", "package provider\n\nimport (\n\t\"context\"\n\t\"encoding/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/google/uuid\"\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/llm/tools\"\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n\t\"github.com/opencode-ai/opencode/internal/message\"\n\t\"google.golang.org/genai\"\n)\n\ntype geminiOptions struct {\n\tdisableCache bool\n}\n\ntype GeminiOption func(*geminiOptions)\n\ntype geminiClient struct {\n\tproviderOptions providerClientOptions\n\toptions geminiOptions\n\tclient *genai.Client\n}\n\ntype GeminiClient ProviderClient\n\nfunc newGeminiClient(opts providerClientOptions) GeminiClient {\n\tgeminiOpts := geminiOptions{}\n\tfor _, o := range opts.geminiOptions {\n\t\to(&geminiOpts)\n\t}\n\n\tclient, err := genai.NewClient(context.Background(), &genai.ClientConfig{APIKey: opts.apiKey, Backend: genai.BackendGeminiAPI})\n\tif err != nil {\n\t\tlogging.Error(\"Failed to create Gemini client\", \"error\", err)\n\t\treturn nil\n\t}\n\n\treturn &geminiClient{\n\t\tproviderOptions: opts,\n\t\toptions: geminiOpts,\n\t\tclient: client,\n\t}\n}\n\nfunc (g *geminiClient) convertMessages(messages []message.Message) []*genai.Content {\n\tvar history []*genai.Content\n\tfor _, msg := range messages {\n\t\tswitch msg.Role {\n\t\tcase message.User:\n\t\t\tvar parts []*genai.Part\n\t\t\tparts = append(parts, &genai.Part{Text: msg.Content().String()})\n\t\t\tfor _, binaryContent := range msg.BinaryContent() {\n\t\t\t\timageFormat := strings.Split(binaryContent.MIMEType, \"/\")\n\t\t\t\tparts = append(parts, &genai.Part{InlineData: &genai.Blob{\n\t\t\t\t\tMIMEType: imageFormat[1],\n\t\t\t\t\tData: binaryContent.Data,\n\t\t\t\t}})\n\t\t\t}\n\t\t\thistory = append(history, &genai.Content{\n\t\t\t\tParts: parts,\n\t\t\t\tRole: \"user\",\n\t\t\t})\n\t\tcase message.Assistant:\n\t\t\tvar assistantParts []*genai.Part\n\n\t\t\tif msg.Content().String() != \"\" {\n\t\t\t\tassistantParts = append(assistantParts, &genai.Part{Text: msg.Content().String()})\n\t\t\t}\n\n\t\t\tif len(msg.ToolCalls()) > 0 {\n\t\t\t\tfor _, call := range msg.ToolCalls() {\n\t\t\t\t\targs, _ := parseJsonToMap(call.Input)\n\t\t\t\t\tassistantParts = append(assistantParts, &genai.Part{\n\t\t\t\t\t\tFunctionCall: &genai.FunctionCall{\n\t\t\t\t\t\t\tName: call.Name,\n\t\t\t\t\t\t\tArgs: args,\n\t\t\t\t\t\t},\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif len(assistantParts) > 0 {\n\t\t\t\thistory = append(history, &genai.Content{\n\t\t\t\t\tRole: \"model\",\n\t\t\t\t\tParts: assistantParts,\n\t\t\t\t})\n\t\t\t}\n\n\t\tcase message.Tool:\n\t\t\tfor _, result := range msg.ToolResults() {\n\t\t\t\tresponse := map[string]interface{}{\"result\": result.Content}\n\t\t\t\tparsed, err := parseJsonToMap(result.Content)\n\t\t\t\tif err == nil {\n\t\t\t\t\tresponse = parsed\n\t\t\t\t}\n\n\t\t\t\tvar toolCall message.ToolCall\n\t\t\t\tfor _, m := range messages {\n\t\t\t\t\tif m.Role == message.Assistant {\n\t\t\t\t\t\tfor _, call := range m.ToolCalls() {\n\t\t\t\t\t\t\tif call.ID == result.ToolCallID {\n\t\t\t\t\t\t\t\ttoolCall = call\n\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\thistory = append(history, &genai.Content{\n\t\t\t\t\tParts: []*genai.Part{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tFunctionResponse: &genai.FunctionResponse{\n\t\t\t\t\t\t\t\tName: toolCall.Name,\n\t\t\t\t\t\t\t\tResponse: response,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\tRole: \"function\",\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\t}\n\n\treturn history\n}\n\nfunc (g *geminiClient) convertTools(tools []tools.BaseTool) []*genai.Tool {\n\tgeminiTool := &genai.Tool{}\n\tgeminiTool.FunctionDeclarations = make([]*genai.FunctionDeclaration, 0, len(tools))\n\n\tfor _, tool := range tools {\n\t\tinfo := tool.Info()\n\t\tdeclaration := &genai.FunctionDeclaration{\n\t\t\tName: info.Name,\n\t\t\tDescription: info.Description,\n\t\t\tParameters: &genai.Schema{\n\t\t\t\tType: genai.TypeObject,\n\t\t\t\tProperties: convertSchemaProperties(info.Parameters),\n\t\t\t\tRequired: info.Required,\n\t\t\t},\n\t\t}\n\n\t\tgeminiTool.FunctionDeclarations = append(geminiTool.FunctionDeclarations, declaration)\n\t}\n\n\treturn []*genai.Tool{geminiTool}\n}\n\nfunc (g *geminiClient) finishReason(reason genai.FinishReason) message.FinishReason {\n\tswitch {\n\tcase reason == genai.FinishReasonStop:\n\t\treturn message.FinishReasonEndTurn\n\tcase reason == genai.FinishReasonMaxTokens:\n\t\treturn message.FinishReasonMaxTokens\n\tdefault:\n\t\treturn message.FinishReasonUnknown\n\t}\n}\n\nfunc (g *geminiClient) send(ctx context.Context, messages []message.Message, tools []tools.BaseTool) (*ProviderResponse, error) {\n\t// Convert messages\n\tgeminiMessages := g.convertMessages(messages)\n\n\tcfg := config.Get()\n\tif cfg.Debug {\n\t\tjsonData, _ := json.Marshal(geminiMessages)\n\t\tlogging.Debug(\"Prepared messages\", \"messages\", string(jsonData))\n\t}\n\n\thistory := geminiMessages[:len(geminiMessages)-1] // All but last message\n\tlastMsg := geminiMessages[len(geminiMessages)-1]\n\tconfig := &genai.GenerateContentConfig{\n\t\tMaxOutputTokens: int32(g.providerOptions.maxTokens),\n\t\tSystemInstruction: &genai.Content{\n\t\t\tParts: []*genai.Part{{Text: g.providerOptions.systemMessage}},\n\t\t},\n\t}\n\tif len(tools) > 0 {\n\t\tconfig.Tools = g.convertTools(tools)\n\t}\n\tchat, _ := g.client.Chats.Create(ctx, g.providerOptions.model.APIModel, config, history)\n\n\tattempts := 0\n\tfor {\n\t\tattempts++\n\t\tvar toolCalls []message.ToolCall\n\n\t\tvar lastMsgParts []genai.Part\n\t\tfor _, part := range lastMsg.Parts {\n\t\t\tlastMsgParts = append(lastMsgParts, *part)\n\t\t}\n\t\tresp, err := chat.SendMessage(ctx, lastMsgParts...)\n\t\t// If there is an error we are going to see if we can retry the call\n\t\tif err != nil {\n\t\t\tretry, after, retryErr := g.shouldRetry(attempts, err)\n\t\t\tif retryErr != nil {\n\t\t\t\treturn nil, retryErr\n\t\t\t}\n\t\t\tif retry {\n\t\t\t\tlogging.WarnPersist(fmt.Sprintf(\"Retrying due to rate limit... attempt %d of %d\", attempts, maxRetries), logging.PersistTimeArg, time.Millisecond*time.Duration(after+100))\n\t\t\t\tselect {\n\t\t\t\tcase <-ctx.Done():\n\t\t\t\t\treturn nil, ctx.Err()\n\t\t\t\tcase <-time.After(time.Duration(after) * time.Millisecond):\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn nil, retryErr\n\t\t}\n\n\t\tcontent := \"\"\n\n\t\tif len(resp.Candidates) > 0 && resp.Candidates[0].Content != nil {\n\t\t\tfor _, part := range resp.Candidates[0].Content.Parts {\n\t\t\t\tswitch {\n\t\t\t\tcase part.Text != \"\":\n\t\t\t\t\tcontent = string(part.Text)\n\t\t\t\tcase part.FunctionCall != nil:\n\t\t\t\t\tid := \"call_\" + uuid.New().String()\n\t\t\t\t\targs, _ := json.Marshal(part.FunctionCall.Args)\n\t\t\t\t\ttoolCalls = append(toolCalls, message.ToolCall{\n\t\t\t\t\t\tID: id,\n\t\t\t\t\t\tName: part.FunctionCall.Name,\n\t\t\t\t\t\tInput: string(args),\n\t\t\t\t\t\tType: \"function\",\n\t\t\t\t\t\tFinished: true,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tfinishReason := message.FinishReasonEndTurn\n\t\tif len(resp.Candidates) > 0 {\n\t\t\tfinishReason = g.finishReason(resp.Candidates[0].FinishReason)\n\t\t}\n\t\tif len(toolCalls) > 0 {\n\t\t\tfinishReason = message.FinishReasonToolUse\n\t\t}\n\n\t\treturn &ProviderResponse{\n\t\t\tContent: content,\n\t\t\tToolCalls: toolCalls,\n\t\t\tUsage: g.usage(resp),\n\t\t\tFinishReason: finishReason,\n\t\t}, nil\n\t}\n}\n\nfunc (g *geminiClient) stream(ctx context.Context, messages []message.Message, tools []tools.BaseTool) <-chan ProviderEvent {\n\t// Convert messages\n\tgeminiMessages := g.convertMessages(messages)\n\n\tcfg := config.Get()\n\tif cfg.Debug {\n\t\tjsonData, _ := json.Marshal(geminiMessages)\n\t\tlogging.Debug(\"Prepared messages\", \"messages\", string(jsonData))\n\t}\n\n\thistory := geminiMessages[:len(geminiMessages)-1] // All but last message\n\tlastMsg := geminiMessages[len(geminiMessages)-1]\n\tconfig := &genai.GenerateContentConfig{\n\t\tMaxOutputTokens: int32(g.providerOptions.maxTokens),\n\t\tSystemInstruction: &genai.Content{\n\t\t\tParts: []*genai.Part{{Text: g.providerOptions.systemMessage}},\n\t\t},\n\t}\n\tif len(tools) > 0 {\n\t\tconfig.Tools = g.convertTools(tools)\n\t}\n\tchat, _ := g.client.Chats.Create(ctx, g.providerOptions.model.APIModel, config, history)\n\n\tattempts := 0\n\teventChan := make(chan ProviderEvent)\n\n\tgo func() {\n\t\tdefer close(eventChan)\n\n\t\tfor {\n\t\t\tattempts++\n\n\t\t\tcurrentContent := \"\"\n\t\t\ttoolCalls := []message.ToolCall{}\n\t\t\tvar finalResp *genai.GenerateContentResponse\n\n\t\t\teventChan <- ProviderEvent{Type: EventContentStart}\n\n\t\t\tvar lastMsgParts []genai.Part\n\n\t\t\tfor _, part := range lastMsg.Parts {\n\t\t\t\tlastMsgParts = append(lastMsgParts, *part)\n\t\t\t}\n\t\t\tfor resp, err := range chat.SendMessageStream(ctx, lastMsgParts...) {\n\t\t\t\tif err != nil {\n\t\t\t\t\tretry, after, retryErr := g.shouldRetry(attempts, err)\n\t\t\t\t\tif retryErr != nil {\n\t\t\t\t\t\teventChan <- ProviderEvent{Type: EventError, Error: retryErr}\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\tif retry {\n\t\t\t\t\t\tlogging.WarnPersist(fmt.Sprintf(\"Retrying due to rate limit... attempt %d of %d\", attempts, maxRetries), logging.PersistTimeArg, time.Millisecond*time.Duration(after+100))\n\t\t\t\t\t\tselect {\n\t\t\t\t\t\tcase <-ctx.Done():\n\t\t\t\t\t\t\tif ctx.Err() != nil {\n\t\t\t\t\t\t\t\teventChan <- ProviderEvent{Type: EventError, Error: ctx.Err()}\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\treturn\n\t\t\t\t\t\tcase <-time.After(time.Duration(after) * time.Millisecond):\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\teventChan <- ProviderEvent{Type: EventError, Error: err}\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tfinalResp = resp\n\n\t\t\t\tif len(resp.Candidates) > 0 && resp.Candidates[0].Content != nil {\n\t\t\t\t\tfor _, part := range resp.Candidates[0].Content.Parts {\n\t\t\t\t\t\tswitch {\n\t\t\t\t\t\tcase part.Text != \"\":\n\t\t\t\t\t\t\tdelta := string(part.Text)\n\t\t\t\t\t\t\tif delta != \"\" {\n\t\t\t\t\t\t\t\teventChan <- ProviderEvent{\n\t\t\t\t\t\t\t\t\tType: EventContentDelta,\n\t\t\t\t\t\t\t\t\tContent: delta,\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tcurrentContent += delta\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\tcase part.FunctionCall != nil:\n\t\t\t\t\t\t\tid := \"call_\" + uuid.New().String()\n\t\t\t\t\t\t\targs, _ := json.Marshal(part.FunctionCall.Args)\n\t\t\t\t\t\t\tnewCall := message.ToolCall{\n\t\t\t\t\t\t\t\tID: id,\n\t\t\t\t\t\t\t\tName: part.FunctionCall.Name,\n\t\t\t\t\t\t\t\tInput: string(args),\n\t\t\t\t\t\t\t\tType: \"function\",\n\t\t\t\t\t\t\t\tFinished: true,\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tisNew := true\n\t\t\t\t\t\t\tfor _, existing := range toolCalls {\n\t\t\t\t\t\t\t\tif existing.Name == newCall.Name && existing.Input == newCall.Input {\n\t\t\t\t\t\t\t\t\tisNew = false\n\t\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif isNew {\n\t\t\t\t\t\t\t\ttoolCalls = append(toolCalls, newCall)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\teventChan <- ProviderEvent{Type: EventContentStop}\n\n\t\t\tif finalResp != nil {\n\n\t\t\t\tfinishReason := message.FinishReasonEndTurn\n\t\t\t\tif len(finalResp.Candidates) > 0 {\n\t\t\t\t\tfinishReason = g.finishReason(finalResp.Candidates[0].FinishReason)\n\t\t\t\t}\n\t\t\t\tif len(toolCalls) > 0 {\n\t\t\t\t\tfinishReason = message.FinishReasonToolUse\n\t\t\t\t}\n\t\t\t\teventChan <- ProviderEvent{\n\t\t\t\t\tType: EventComplete,\n\t\t\t\t\tResponse: &ProviderResponse{\n\t\t\t\t\t\tContent: currentContent,\n\t\t\t\t\t\tToolCalls: toolCalls,\n\t\t\t\t\t\tUsage: g.usage(finalResp),\n\t\t\t\t\t\tFinishReason: finishReason,\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\n\t\t}\n\t}()\n\n\treturn eventChan\n}\n\nfunc (g *geminiClient) shouldRetry(attempts int, err error) (bool, int64, error) {\n\t// Check if error is a rate limit error\n\tif attempts > maxRetries {\n\t\treturn false, 0, fmt.Errorf(\"maximum retry attempts reached for rate limit: %d retries\", maxRetries)\n\t}\n\n\t// Gemini doesn't have a standard error type we can check against\n\t// So we'll check the error message for rate limit indicators\n\tif errors.Is(err, io.EOF) {\n\t\treturn false, 0, err\n\t}\n\n\terrMsg := err.Error()\n\tisRateLimit := false\n\n\t// Check for common rate limit error messages\n\tif contains(errMsg, \"rate limit\", \"quota exceeded\", \"too many requests\") {\n\t\tisRateLimit = true\n\t}\n\n\tif !isRateLimit {\n\t\treturn false, 0, err\n\t}\n\n\t// Calculate backoff with jitter\n\tbackoffMs := 2000 * (1 << (attempts - 1))\n\tjitterMs := int(float64(backoffMs) * 0.2)\n\tretryMs := backoffMs + jitterMs\n\n\treturn true, int64(retryMs), nil\n}\n\nfunc (g *geminiClient) toolCalls(resp *genai.GenerateContentResponse) []message.ToolCall {\n\tvar toolCalls []message.ToolCall\n\n\tif len(resp.Candidates) > 0 && resp.Candidates[0].Content != nil {\n\t\tfor _, part := range resp.Candidates[0].Content.Parts {\n\t\t\tif part.FunctionCall != nil {\n\t\t\t\tid := \"call_\" + uuid.New().String()\n\t\t\t\targs, _ := json.Marshal(part.FunctionCall.Args)\n\t\t\t\ttoolCalls = append(toolCalls, message.ToolCall{\n\t\t\t\t\tID: id,\n\t\t\t\t\tName: part.FunctionCall.Name,\n\t\t\t\t\tInput: string(args),\n\t\t\t\t\tType: \"function\",\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\t}\n\n\treturn toolCalls\n}\n\nfunc (g *geminiClient) usage(resp *genai.GenerateContentResponse) TokenUsage {\n\tif resp == nil || resp.UsageMetadata == nil {\n\t\treturn TokenUsage{}\n\t}\n\n\treturn TokenUsage{\n\t\tInputTokens: int64(resp.UsageMetadata.PromptTokenCount),\n\t\tOutputTokens: int64(resp.UsageMetadata.CandidatesTokenCount),\n\t\tCacheCreationTokens: 0, // Not directly provided by Gemini\n\t\tCacheReadTokens: int64(resp.UsageMetadata.CachedContentTokenCount),\n\t}\n}\n\nfunc WithGeminiDisableCache() GeminiOption {\n\treturn func(options *geminiOptions) {\n\t\toptions.disableCache = true\n\t}\n}\n\n// Helper functions\nfunc parseJsonToMap(jsonStr string) (map[string]interface{}, error) {\n\tvar result map[string]interface{}\n\terr := json.Unmarshal([]byte(jsonStr), &result)\n\treturn result, err\n}\n\nfunc convertSchemaProperties(parameters map[string]interface{}) map[string]*genai.Schema {\n\tproperties := make(map[string]*genai.Schema)\n\n\tfor name, param := range parameters {\n\t\tproperties[name] = convertToSchema(param)\n\t}\n\n\treturn properties\n}\n\nfunc convertToSchema(param interface{}) *genai.Schema {\n\tschema := &genai.Schema{Type: genai.TypeString}\n\n\tparamMap, ok := param.(map[string]interface{})\n\tif !ok {\n\t\treturn schema\n\t}\n\n\tif desc, ok := paramMap[\"description\"].(string); ok {\n\t\tschema.Description = desc\n\t}\n\n\ttypeVal, hasType := paramMap[\"type\"]\n\tif !hasType {\n\t\treturn schema\n\t}\n\n\ttypeStr, ok := typeVal.(string)\n\tif !ok {\n\t\treturn schema\n\t}\n\n\tschema.Type = mapJSONTypeToGenAI(typeStr)\n\n\tswitch typeStr {\n\tcase \"array\":\n\t\tschema.Items = processArrayItems(paramMap)\n\tcase \"object\":\n\t\tif props, ok := paramMap[\"properties\"].(map[string]interface{}); ok {\n\t\t\tschema.Properties = convertSchemaProperties(props)\n\t\t}\n\t}\n\n\treturn schema\n}\n\nfunc processArrayItems(paramMap map[string]interface{}) *genai.Schema {\n\titems, ok := paramMap[\"items\"].(map[string]interface{})\n\tif !ok {\n\t\treturn nil\n\t}\n\n\treturn convertToSchema(items)\n}\n\nfunc mapJSONTypeToGenAI(jsonType string) genai.Type {\n\tswitch jsonType {\n\tcase \"string\":\n\t\treturn genai.TypeString\n\tcase \"number\":\n\t\treturn genai.TypeNumber\n\tcase \"integer\":\n\t\treturn genai.TypeInteger\n\tcase \"boolean\":\n\t\treturn genai.TypeBoolean\n\tcase \"array\":\n\t\treturn genai.TypeArray\n\tcase \"object\":\n\t\treturn genai.TypeObject\n\tdefault:\n\t\treturn genai.TypeString // Default to string for unknown types\n\t}\n}\n\nfunc contains(s string, substrs ...string) bool {\n\tfor _, substr := range substrs {\n\t\tif strings.Contains(strings.ToLower(s), strings.ToLower(substr)) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n"], ["/opencode/internal/lsp/watcher/watcher.go", "package watcher\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com/bmatcuk/doublestar/v4\"\n\t\"github.com/fsnotify/fsnotify\"\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n\t\"github.com/opencode-ai/opencode/internal/lsp\"\n\t\"github.com/opencode-ai/opencode/internal/lsp/protocol\"\n)\n\n// WorkspaceWatcher manages LSP file watching\ntype WorkspaceWatcher struct {\n\tclient *lsp.Client\n\tworkspacePath string\n\n\tdebounceTime time.Duration\n\tdebounceMap map[string]*time.Timer\n\tdebounceMu sync.Mutex\n\n\t// File watchers registered by the server\n\tregistrations []protocol.FileSystemWatcher\n\tregistrationMu sync.RWMutex\n}\n\n// NewWorkspaceWatcher creates a new workspace watcher\nfunc NewWorkspaceWatcher(client *lsp.Client) *WorkspaceWatcher {\n\treturn &WorkspaceWatcher{\n\t\tclient: client,\n\t\tdebounceTime: 300 * time.Millisecond,\n\t\tdebounceMap: make(map[string]*time.Timer),\n\t\tregistrations: []protocol.FileSystemWatcher{},\n\t}\n}\n\n// AddRegistrations adds file watchers to track\nfunc (w *WorkspaceWatcher) AddRegistrations(ctx context.Context, id string, watchers []protocol.FileSystemWatcher) {\n\tcnf := config.Get()\n\n\tlogging.Debug(\"Adding file watcher registrations\")\n\tw.registrationMu.Lock()\n\tdefer w.registrationMu.Unlock()\n\n\t// Add new watchers\n\tw.registrations = append(w.registrations, watchers...)\n\n\t// Print detailed registration information for debugging\n\tif cnf.DebugLSP {\n\t\tlogging.Debug(\"Adding file watcher registrations\",\n\t\t\t\"id\", id,\n\t\t\t\"watchers\", len(watchers),\n\t\t\t\"total\", len(w.registrations),\n\t\t)\n\n\t\tfor i, watcher := range watchers {\n\t\t\tlogging.Debug(\"Registration\", \"index\", i+1)\n\n\t\t\t// Log the GlobPattern\n\t\t\tswitch v := watcher.GlobPattern.Value.(type) {\n\t\t\tcase string:\n\t\t\t\tlogging.Debug(\"GlobPattern\", \"pattern\", v)\n\t\t\tcase protocol.RelativePattern:\n\t\t\t\tlogging.Debug(\"GlobPattern\", \"pattern\", v.Pattern)\n\n\t\t\t\t// Log BaseURI details\n\t\t\t\tswitch u := v.BaseURI.Value.(type) {\n\t\t\t\tcase string:\n\t\t\t\t\tlogging.Debug(\"BaseURI\", \"baseURI\", u)\n\t\t\t\tcase protocol.DocumentUri:\n\t\t\t\t\tlogging.Debug(\"BaseURI\", \"baseURI\", u)\n\t\t\t\tdefault:\n\t\t\t\t\tlogging.Debug(\"BaseURI\", \"baseURI\", u)\n\t\t\t\t}\n\t\t\tdefault:\n\t\t\t\tlogging.Debug(\"GlobPattern\", \"unknown type\", fmt.Sprintf(\"%T\", v))\n\t\t\t}\n\n\t\t\t// Log WatchKind\n\t\t\twatchKind := protocol.WatchKind(protocol.WatchChange | protocol.WatchCreate | protocol.WatchDelete)\n\t\t\tif watcher.Kind != nil {\n\t\t\t\twatchKind = *watcher.Kind\n\t\t\t}\n\n\t\t\tlogging.Debug(\"WatchKind\", \"kind\", watchKind)\n\t\t}\n\t}\n\n\t// Determine server type for specialized handling\n\tserverName := getServerNameFromContext(ctx)\n\tlogging.Debug(\"Server type detected\", \"serverName\", serverName)\n\n\t// Check if this server has sent file watchers\n\thasFileWatchers := len(watchers) > 0\n\n\t// For servers that need file preloading, we'll use a smart approach\n\tif shouldPreloadFiles(serverName) || !hasFileWatchers {\n\t\tgo func() {\n\t\t\tstartTime := time.Now()\n\t\t\tfilesOpened := 0\n\n\t\t\t// Determine max files to open based on server type\n\t\t\tmaxFilesToOpen := 50 // Default conservative limit\n\n\t\t\tswitch serverName {\n\t\t\tcase \"typescript\", \"typescript-language-server\", \"tsserver\", \"vtsls\":\n\t\t\t\t// TypeScript servers benefit from seeing more files\n\t\t\t\tmaxFilesToOpen = 100\n\t\t\tcase \"java\", \"jdtls\":\n\t\t\t\t// Java servers need to see many files for project model\n\t\t\t\tmaxFilesToOpen = 200\n\t\t\t}\n\n\t\t\t// First, open high-priority files\n\t\t\thighPriorityFilesOpened := w.openHighPriorityFiles(ctx, serverName)\n\t\t\tfilesOpened += highPriorityFilesOpened\n\n\t\t\tif cnf.DebugLSP {\n\t\t\t\tlogging.Debug(\"Opened high-priority files\",\n\t\t\t\t\t\"count\", highPriorityFilesOpened,\n\t\t\t\t\t\"serverName\", serverName)\n\t\t\t}\n\n\t\t\t// If we've already opened enough high-priority files, we might not need more\n\t\t\tif filesOpened >= maxFilesToOpen {\n\t\t\t\tif cnf.DebugLSP {\n\t\t\t\t\tlogging.Debug(\"Reached file limit with high-priority files\",\n\t\t\t\t\t\t\"filesOpened\", filesOpened,\n\t\t\t\t\t\t\"maxFiles\", maxFilesToOpen)\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\t// For the remaining slots, walk the directory and open matching files\n\n\t\t\terr := filepath.WalkDir(w.workspacePath, func(path string, d os.DirEntry, err error) error {\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\n\t\t\t\t// Skip directories that should be excluded\n\t\t\t\tif d.IsDir() {\n\t\t\t\t\tif path != w.workspacePath && shouldExcludeDir(path) {\n\t\t\t\t\t\tif cnf.DebugLSP {\n\t\t\t\t\t\t\tlogging.Debug(\"Skipping excluded directory\", \"path\", path)\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn filepath.SkipDir\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\t// Process files, but limit the total number\n\t\t\t\t\tif filesOpened < maxFilesToOpen {\n\t\t\t\t\t\t// Only process if it's not already open (high-priority files were opened earlier)\n\t\t\t\t\t\tif !w.client.IsFileOpen(path) {\n\t\t\t\t\t\t\tw.openMatchingFile(ctx, path)\n\t\t\t\t\t\t\tfilesOpened++\n\n\t\t\t\t\t\t\t// Add a small delay after every 10 files to prevent overwhelming the server\n\t\t\t\t\t\t\tif filesOpened%10 == 0 {\n\t\t\t\t\t\t\t\ttime.Sleep(50 * time.Millisecond)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// We've reached our limit, stop walking\n\t\t\t\t\t\treturn filepath.SkipAll\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\treturn nil\n\t\t\t})\n\n\t\t\telapsedTime := time.Since(startTime)\n\t\t\tif cnf.DebugLSP {\n\t\t\t\tlogging.Debug(\"Limited workspace scan complete\",\n\t\t\t\t\t\"filesOpened\", filesOpened,\n\t\t\t\t\t\"maxFiles\", maxFilesToOpen,\n\t\t\t\t\t\"elapsedTime\", elapsedTime.Seconds(),\n\t\t\t\t\t\"workspacePath\", w.workspacePath,\n\t\t\t\t)\n\t\t\t}\n\n\t\t\tif err != nil && cnf.DebugLSP {\n\t\t\t\tlogging.Debug(\"Error scanning workspace for files to open\", \"error\", err)\n\t\t\t}\n\t\t}()\n\t} else if cnf.DebugLSP {\n\t\tlogging.Debug(\"Using on-demand file loading for server\", \"server\", serverName)\n\t}\n}\n\n// openHighPriorityFiles opens important files for the server type\n// Returns the number of files opened\nfunc (w *WorkspaceWatcher) openHighPriorityFiles(ctx context.Context, serverName string) int {\n\tcnf := config.Get()\n\tfilesOpened := 0\n\n\t// Define patterns for high-priority files based on server type\n\tvar patterns []string\n\n\tswitch serverName {\n\tcase \"typescript\", \"typescript-language-server\", \"tsserver\", \"vtsls\":\n\t\tpatterns = []string{\n\t\t\t\"**/tsconfig.json\",\n\t\t\t\"**/package.json\",\n\t\t\t\"**/jsconfig.json\",\n\t\t\t\"**/index.ts\",\n\t\t\t\"**/index.js\",\n\t\t\t\"**/main.ts\",\n\t\t\t\"**/main.js\",\n\t\t}\n\tcase \"gopls\":\n\t\tpatterns = []string{\n\t\t\t\"**/go.mod\",\n\t\t\t\"**/go.sum\",\n\t\t\t\"**/main.go\",\n\t\t}\n\tcase \"rust-analyzer\":\n\t\tpatterns = []string{\n\t\t\t\"**/Cargo.toml\",\n\t\t\t\"**/Cargo.lock\",\n\t\t\t\"**/src/lib.rs\",\n\t\t\t\"**/src/main.rs\",\n\t\t}\n\tcase \"python\", \"pyright\", \"pylsp\":\n\t\tpatterns = []string{\n\t\t\t\"**/pyproject.toml\",\n\t\t\t\"**/setup.py\",\n\t\t\t\"**/requirements.txt\",\n\t\t\t\"**/__init__.py\",\n\t\t\t\"**/__main__.py\",\n\t\t}\n\tcase \"clangd\":\n\t\tpatterns = []string{\n\t\t\t\"**/CMakeLists.txt\",\n\t\t\t\"**/Makefile\",\n\t\t\t\"**/compile_commands.json\",\n\t\t}\n\tcase \"java\", \"jdtls\":\n\t\tpatterns = []string{\n\t\t\t\"**/pom.xml\",\n\t\t\t\"**/build.gradle\",\n\t\t\t\"**/src/main/java/**/*.java\",\n\t\t}\n\tdefault:\n\t\t// For unknown servers, use common configuration files\n\t\tpatterns = []string{\n\t\t\t\"**/package.json\",\n\t\t\t\"**/Makefile\",\n\t\t\t\"**/CMakeLists.txt\",\n\t\t\t\"**/.editorconfig\",\n\t\t}\n\t}\n\n\t// For each pattern, find and open matching files\n\tfor _, pattern := range patterns {\n\t\t// Use doublestar.Glob to find files matching the pattern (supports ** patterns)\n\t\tmatches, err := doublestar.Glob(os.DirFS(w.workspacePath), pattern)\n\t\tif err != nil {\n\t\t\tif cnf.DebugLSP {\n\t\t\t\tlogging.Debug(\"Error finding high-priority files\", \"pattern\", pattern, \"error\", err)\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\tfor _, match := range matches {\n\t\t\t// Convert relative path to absolute\n\t\t\tfullPath := filepath.Join(w.workspacePath, match)\n\n\t\t\t// Skip directories and excluded files\n\t\t\tinfo, err := os.Stat(fullPath)\n\t\t\tif err != nil || info.IsDir() || shouldExcludeFile(fullPath) {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// Open the file\n\t\t\tif err := w.client.OpenFile(ctx, fullPath); err != nil {\n\t\t\t\tif cnf.DebugLSP {\n\t\t\t\t\tlogging.Debug(\"Error opening high-priority file\", \"path\", fullPath, \"error\", err)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tfilesOpened++\n\t\t\t\tif cnf.DebugLSP {\n\t\t\t\t\tlogging.Debug(\"Opened high-priority file\", \"path\", fullPath)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Add a small delay to prevent overwhelming the server\n\t\t\ttime.Sleep(20 * time.Millisecond)\n\n\t\t\t// Limit the number of files opened per pattern\n\t\t\tif filesOpened >= 5 && (serverName != \"java\" && serverName != \"jdtls\") {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\treturn filesOpened\n}\n\n// WatchWorkspace sets up file watching for a workspace\nfunc (w *WorkspaceWatcher) WatchWorkspace(ctx context.Context, workspacePath string) {\n\tcnf := config.Get()\n\tw.workspacePath = workspacePath\n\n\t// Store the watcher in the context for later use\n\tctx = context.WithValue(ctx, \"workspaceWatcher\", w)\n\n\t// If the server name isn't already in the context, try to detect it\n\tif _, ok := ctx.Value(\"serverName\").(string); !ok {\n\t\tserverName := getServerNameFromContext(ctx)\n\t\tctx = context.WithValue(ctx, \"serverName\", serverName)\n\t}\n\n\tserverName := getServerNameFromContext(ctx)\n\tlogging.Debug(\"Starting workspace watcher\", \"workspacePath\", workspacePath, \"serverName\", serverName)\n\n\t// Register handler for file watcher registrations from the server\n\tlsp.RegisterFileWatchHandler(func(id string, watchers []protocol.FileSystemWatcher) {\n\t\tw.AddRegistrations(ctx, id, watchers)\n\t})\n\n\twatcher, err := fsnotify.NewWatcher()\n\tif err != nil {\n\t\tlogging.Error(\"Error creating watcher\", \"error\", err)\n\t}\n\tdefer watcher.Close()\n\n\t// Watch the workspace recursively\n\terr = filepath.WalkDir(workspacePath, func(path string, d os.DirEntry, err error) error {\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Skip excluded directories (except workspace root)\n\t\tif d.IsDir() && path != workspacePath {\n\t\t\tif shouldExcludeDir(path) {\n\t\t\t\tif cnf.DebugLSP {\n\t\t\t\t\tlogging.Debug(\"Skipping excluded directory\", \"path\", path)\n\t\t\t\t}\n\t\t\t\treturn filepath.SkipDir\n\t\t\t}\n\t\t}\n\n\t\t// Add directories to watcher\n\t\tif d.IsDir() {\n\t\t\terr = watcher.Add(path)\n\t\t\tif err != nil {\n\t\t\t\tlogging.Error(\"Error watching path\", \"path\", path, \"error\", err)\n\t\t\t}\n\t\t}\n\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\tlogging.Error(\"Error walking workspace\", \"error\", err)\n\t}\n\n\t// Event loop\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn\n\t\tcase event, ok := <-watcher.Events:\n\t\t\tif !ok {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\turi := fmt.Sprintf(\"file://%s\", event.Name)\n\n\t\t\t// Add new directories to the watcher\n\t\t\tif event.Op&fsnotify.Create != 0 {\n\t\t\t\tif info, err := os.Stat(event.Name); err == nil {\n\t\t\t\t\tif info.IsDir() {\n\t\t\t\t\t\t// Skip excluded directories\n\t\t\t\t\t\tif !shouldExcludeDir(event.Name) {\n\t\t\t\t\t\t\tif err := watcher.Add(event.Name); err != nil {\n\t\t\t\t\t\t\t\tlogging.Error(\"Error adding directory to watcher\", \"path\", event.Name, \"error\", err)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// For newly created files\n\t\t\t\t\t\tif !shouldExcludeFile(event.Name) {\n\t\t\t\t\t\t\tw.openMatchingFile(ctx, event.Name)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Debug logging\n\t\t\tif cnf.DebugLSP {\n\t\t\t\tmatched, kind := w.isPathWatched(event.Name)\n\t\t\t\tlogging.Debug(\"File event\",\n\t\t\t\t\t\"path\", event.Name,\n\t\t\t\t\t\"operation\", event.Op.String(),\n\t\t\t\t\t\"watched\", matched,\n\t\t\t\t\t\"kind\", kind,\n\t\t\t\t)\n\n\t\t\t}\n\n\t\t\t// Check if this path should be watched according to server registrations\n\t\t\tif watched, watchKind := w.isPathWatched(event.Name); watched {\n\t\t\t\tswitch {\n\t\t\t\tcase event.Op&fsnotify.Write != 0:\n\t\t\t\t\tif watchKind&protocol.WatchChange != 0 {\n\t\t\t\t\t\tw.debounceHandleFileEvent(ctx, uri, protocol.FileChangeType(protocol.Changed))\n\t\t\t\t\t}\n\t\t\t\tcase event.Op&fsnotify.Create != 0:\n\t\t\t\t\t// Already handled earlier in the event loop\n\t\t\t\t\t// Just send the notification if needed\n\t\t\t\t\tinfo, err := os.Stat(event.Name)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlogging.Error(\"Error getting file info\", \"path\", event.Name, \"error\", err)\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\tif !info.IsDir() && watchKind&protocol.WatchCreate != 0 {\n\t\t\t\t\t\tw.debounceHandleFileEvent(ctx, uri, protocol.FileChangeType(protocol.Created))\n\t\t\t\t\t}\n\t\t\t\tcase event.Op&fsnotify.Remove != 0:\n\t\t\t\t\tif watchKind&protocol.WatchDelete != 0 {\n\t\t\t\t\t\tw.handleFileEvent(ctx, uri, protocol.FileChangeType(protocol.Deleted))\n\t\t\t\t\t}\n\t\t\t\tcase event.Op&fsnotify.Rename != 0:\n\t\t\t\t\t// For renames, first delete\n\t\t\t\t\tif watchKind&protocol.WatchDelete != 0 {\n\t\t\t\t\t\tw.handleFileEvent(ctx, uri, protocol.FileChangeType(protocol.Deleted))\n\t\t\t\t\t}\n\n\t\t\t\t\t// Then check if the new file exists and create an event\n\t\t\t\t\tif info, err := os.Stat(event.Name); err == nil && !info.IsDir() {\n\t\t\t\t\t\tif watchKind&protocol.WatchCreate != 0 {\n\t\t\t\t\t\t\tw.debounceHandleFileEvent(ctx, uri, protocol.FileChangeType(protocol.Created))\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\tcase err, ok := <-watcher.Errors:\n\t\t\tif !ok {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tlogging.Error(\"Error watching file\", \"error\", err)\n\t\t}\n\t}\n}\n\n// isPathWatched checks if a path should be watched based on server registrations\nfunc (w *WorkspaceWatcher) isPathWatched(path string) (bool, protocol.WatchKind) {\n\tw.registrationMu.RLock()\n\tdefer w.registrationMu.RUnlock()\n\n\t// If no explicit registrations, watch everything\n\tif len(w.registrations) == 0 {\n\t\treturn true, protocol.WatchKind(protocol.WatchChange | protocol.WatchCreate | protocol.WatchDelete)\n\t}\n\n\t// Check each registration\n\tfor _, reg := range w.registrations {\n\t\tisMatch := w.matchesPattern(path, reg.GlobPattern)\n\t\tif isMatch {\n\t\t\tkind := protocol.WatchKind(protocol.WatchChange | protocol.WatchCreate | protocol.WatchDelete)\n\t\t\tif reg.Kind != nil {\n\t\t\t\tkind = *reg.Kind\n\t\t\t}\n\t\t\treturn true, kind\n\t\t}\n\t}\n\n\treturn false, 0\n}\n\n// matchesGlob handles advanced glob patterns including ** and alternatives\nfunc matchesGlob(pattern, path string) bool {\n\t// Handle file extension patterns with braces like *.{go,mod,sum}\n\tif strings.Contains(pattern, \"{\") && strings.Contains(pattern, \"}\") {\n\t\t// Extract extensions from pattern like \"*.{go,mod,sum}\"\n\t\tparts := strings.SplitN(pattern, \"{\", 2)\n\t\tif len(parts) == 2 {\n\t\t\tprefix := parts[0]\n\t\t\textPart := strings.SplitN(parts[1], \"}\", 2)\n\t\t\tif len(extPart) == 2 {\n\t\t\t\textensions := strings.Split(extPart[0], \",\")\n\t\t\t\tsuffix := extPart[1]\n\n\t\t\t\t// Check if the path matches any of the extensions\n\t\t\t\tfor _, ext := range extensions {\n\t\t\t\t\textPattern := prefix + ext + suffix\n\t\t\t\t\tisMatch := matchesSimpleGlob(extPattern, path)\n\t\t\t\t\tif isMatch {\n\t\t\t\t\t\treturn true\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t}\n\n\treturn matchesSimpleGlob(pattern, path)\n}\n\n// matchesSimpleGlob handles glob patterns with ** wildcards\nfunc matchesSimpleGlob(pattern, path string) bool {\n\t// Handle special case for **/*.ext pattern (common in LSP)\n\tif strings.HasPrefix(pattern, \"**/\") {\n\t\trest := strings.TrimPrefix(pattern, \"**/\")\n\n\t\t// If the rest is a simple file extension pattern like *.go\n\t\tif strings.HasPrefix(rest, \"*.\") {\n\t\t\text := strings.TrimPrefix(rest, \"*\")\n\t\t\tisMatch := strings.HasSuffix(path, ext)\n\t\t\treturn isMatch\n\t\t}\n\n\t\t// Otherwise, try to check if the path ends with the rest part\n\t\tisMatch := strings.HasSuffix(path, rest)\n\n\t\t// If it matches directly, great!\n\t\tif isMatch {\n\t\t\treturn true\n\t\t}\n\n\t\t// Otherwise, check if any path component matches\n\t\tpathComponents := strings.Split(path, \"/\")\n\t\tfor i := range pathComponents {\n\t\t\tsubPath := strings.Join(pathComponents[i:], \"/\")\n\t\t\tif strings.HasSuffix(subPath, rest) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\n\t\treturn false\n\t}\n\n\t// Handle other ** wildcard pattern cases\n\tif strings.Contains(pattern, \"**\") {\n\t\tparts := strings.Split(pattern, \"**\")\n\n\t\t// Validate the path starts with the first part\n\t\tif !strings.HasPrefix(path, parts[0]) && parts[0] != \"\" {\n\t\t\treturn false\n\t\t}\n\n\t\t// For patterns like \"**/*.go\", just check the suffix\n\t\tif len(parts) == 2 && parts[0] == \"\" {\n\t\t\tisMatch := strings.HasSuffix(path, parts[1])\n\t\t\treturn isMatch\n\t\t}\n\n\t\t// For other patterns, handle middle part\n\t\tremaining := strings.TrimPrefix(path, parts[0])\n\t\tif len(parts) == 2 {\n\t\t\tisMatch := strings.HasSuffix(remaining, parts[1])\n\t\t\treturn isMatch\n\t\t}\n\t}\n\n\t// Handle simple * wildcard for file extension patterns (*.go, *.sum, etc)\n\tif strings.HasPrefix(pattern, \"*.\") {\n\t\text := strings.TrimPrefix(pattern, \"*\")\n\t\tisMatch := strings.HasSuffix(path, ext)\n\t\treturn isMatch\n\t}\n\n\t// Fall back to simple matching for simpler patterns\n\tmatched, err := filepath.Match(pattern, path)\n\tif err != nil {\n\t\tlogging.Error(\"Error matching pattern\", \"pattern\", pattern, \"path\", path, \"error\", err)\n\t\treturn false\n\t}\n\n\treturn matched\n}\n\n// matchesPattern checks if a path matches the glob pattern\nfunc (w *WorkspaceWatcher) matchesPattern(path string, pattern protocol.GlobPattern) bool {\n\tpatternInfo, err := pattern.AsPattern()\n\tif err != nil {\n\t\tlogging.Error(\"Error parsing pattern\", \"pattern\", pattern, \"error\", err)\n\t\treturn false\n\t}\n\n\tbasePath := patternInfo.GetBasePath()\n\tpatternText := patternInfo.GetPattern()\n\n\tpath = filepath.ToSlash(path)\n\n\t// For simple patterns without base path\n\tif basePath == \"\" {\n\t\t// Check if the pattern matches the full path or just the file extension\n\t\tfullPathMatch := matchesGlob(patternText, path)\n\t\tbaseNameMatch := matchesGlob(patternText, filepath.Base(path))\n\n\t\treturn fullPathMatch || baseNameMatch\n\t}\n\n\t// For relative patterns\n\tbasePath = strings.TrimPrefix(basePath, \"file://\")\n\tbasePath = filepath.ToSlash(basePath)\n\n\t// Make path relative to basePath for matching\n\trelPath, err := filepath.Rel(basePath, path)\n\tif err != nil {\n\t\tlogging.Error(\"Error getting relative path\", \"path\", path, \"basePath\", basePath, \"error\", err)\n\t\treturn false\n\t}\n\trelPath = filepath.ToSlash(relPath)\n\n\tisMatch := matchesGlob(patternText, relPath)\n\n\treturn isMatch\n}\n\n// debounceHandleFileEvent handles file events with debouncing to reduce notifications\nfunc (w *WorkspaceWatcher) debounceHandleFileEvent(ctx context.Context, uri string, changeType protocol.FileChangeType) {\n\tw.debounceMu.Lock()\n\tdefer w.debounceMu.Unlock()\n\n\t// Create a unique key based on URI and change type\n\tkey := fmt.Sprintf(\"%s:%d\", uri, changeType)\n\n\t// Cancel existing timer if any\n\tif timer, exists := w.debounceMap[key]; exists {\n\t\ttimer.Stop()\n\t}\n\n\t// Create new timer\n\tw.debounceMap[key] = time.AfterFunc(w.debounceTime, func() {\n\t\tw.handleFileEvent(ctx, uri, changeType)\n\n\t\t// Cleanup timer after execution\n\t\tw.debounceMu.Lock()\n\t\tdelete(w.debounceMap, key)\n\t\tw.debounceMu.Unlock()\n\t})\n}\n\n// handleFileEvent sends file change notifications\nfunc (w *WorkspaceWatcher) handleFileEvent(ctx context.Context, uri string, changeType protocol.FileChangeType) {\n\t// If the file is open and it's a change event, use didChange notification\n\tfilePath := uri[7:] // Remove \"file://\" prefix\n\tif changeType == protocol.FileChangeType(protocol.Deleted) {\n\t\tw.client.ClearDiagnosticsForURI(protocol.DocumentUri(uri))\n\t} else if changeType == protocol.FileChangeType(protocol.Changed) && w.client.IsFileOpen(filePath) {\n\t\terr := w.client.NotifyChange(ctx, filePath)\n\t\tif err != nil {\n\t\t\tlogging.Error(\"Error notifying change\", \"error\", err)\n\t\t}\n\t\treturn\n\t}\n\n\t// Notify LSP server about the file event using didChangeWatchedFiles\n\tif err := w.notifyFileEvent(ctx, uri, changeType); err != nil {\n\t\tlogging.Error(\"Error notifying LSP server about file event\", \"error\", err)\n\t}\n}\n\n// notifyFileEvent sends a didChangeWatchedFiles notification for a file event\nfunc (w *WorkspaceWatcher) notifyFileEvent(ctx context.Context, uri string, changeType protocol.FileChangeType) error {\n\tcnf := config.Get()\n\tif cnf.DebugLSP {\n\t\tlogging.Debug(\"Notifying file event\",\n\t\t\t\"uri\", uri,\n\t\t\t\"changeType\", changeType,\n\t\t)\n\t}\n\n\tparams := protocol.DidChangeWatchedFilesParams{\n\t\tChanges: []protocol.FileEvent{\n\t\t\t{\n\t\t\t\tURI: protocol.DocumentUri(uri),\n\t\t\t\tType: changeType,\n\t\t\t},\n\t\t},\n\t}\n\n\treturn w.client.DidChangeWatchedFiles(ctx, params)\n}\n\n// getServerNameFromContext extracts the server name from the context\n// This is a best-effort function that tries to identify which LSP server we're dealing with\nfunc getServerNameFromContext(ctx context.Context) string {\n\t// First check if the server name is directly stored in the context\n\tif serverName, ok := ctx.Value(\"serverName\").(string); ok && serverName != \"\" {\n\t\treturn strings.ToLower(serverName)\n\t}\n\n\t// Otherwise, try to extract server name from the client command path\n\tif w, ok := ctx.Value(\"workspaceWatcher\").(*WorkspaceWatcher); ok && w != nil && w.client != nil && w.client.Cmd != nil {\n\t\tpath := strings.ToLower(w.client.Cmd.Path)\n\n\t\t// Extract server name from path\n\t\tif strings.Contains(path, \"typescript\") || strings.Contains(path, \"tsserver\") || strings.Contains(path, \"vtsls\") {\n\t\t\treturn \"typescript\"\n\t\t} else if strings.Contains(path, \"gopls\") {\n\t\t\treturn \"gopls\"\n\t\t} else if strings.Contains(path, \"rust-analyzer\") {\n\t\t\treturn \"rust-analyzer\"\n\t\t} else if strings.Contains(path, \"pyright\") || strings.Contains(path, \"pylsp\") || strings.Contains(path, \"python\") {\n\t\t\treturn \"python\"\n\t\t} else if strings.Contains(path, \"clangd\") {\n\t\t\treturn \"clangd\"\n\t\t} else if strings.Contains(path, \"jdtls\") || strings.Contains(path, \"java\") {\n\t\t\treturn \"java\"\n\t\t}\n\n\t\t// Return the base name as fallback\n\t\treturn filepath.Base(path)\n\t}\n\n\treturn \"unknown\"\n}\n\n// shouldPreloadFiles determines if we should preload files for a specific language server\n// Some servers work better with preloaded files, others don't need it\nfunc shouldPreloadFiles(serverName string) bool {\n\t// TypeScript/JavaScript servers typically need some files preloaded\n\t// to properly resolve imports and provide intellisense\n\tswitch serverName {\n\tcase \"typescript\", \"typescript-language-server\", \"tsserver\", \"vtsls\":\n\t\treturn true\n\tcase \"java\", \"jdtls\":\n\t\t// Java servers often need to see source files to build the project model\n\t\treturn true\n\tdefault:\n\t\t// For most servers, we'll use lazy loading by default\n\t\treturn false\n\t}\n}\n\n// Common patterns for directories and files to exclude\n// TODO: make configurable\nvar (\n\texcludedDirNames = map[string]bool{\n\t\t\".git\": true,\n\t\t\"node_modules\": true,\n\t\t\"dist\": true,\n\t\t\"build\": true,\n\t\t\"out\": true,\n\t\t\"bin\": true,\n\t\t\".idea\": true,\n\t\t\".vscode\": true,\n\t\t\".cache\": true,\n\t\t\"coverage\": true,\n\t\t\"target\": true, // Rust build output\n\t\t\"vendor\": true, // Go vendor directory\n\t}\n\n\texcludedFileExtensions = map[string]bool{\n\t\t\".swp\": true,\n\t\t\".swo\": true,\n\t\t\".tmp\": true,\n\t\t\".temp\": true,\n\t\t\".bak\": true,\n\t\t\".log\": true,\n\t\t\".o\": true, // Object files\n\t\t\".so\": true, // Shared libraries\n\t\t\".dylib\": true, // macOS shared libraries\n\t\t\".dll\": true, // Windows shared libraries\n\t\t\".a\": true, // Static libraries\n\t\t\".exe\": true, // Windows executables\n\t\t\".lock\": true, // Lock files\n\t}\n\n\t// Large binary files that shouldn't be opened\n\tlargeBinaryExtensions = map[string]bool{\n\t\t\".png\": true,\n\t\t\".jpg\": true,\n\t\t\".jpeg\": true,\n\t\t\".gif\": true,\n\t\t\".bmp\": true,\n\t\t\".ico\": true,\n\t\t\".zip\": true,\n\t\t\".tar\": true,\n\t\t\".gz\": true,\n\t\t\".rar\": true,\n\t\t\".7z\": true,\n\t\t\".pdf\": true,\n\t\t\".mp3\": true,\n\t\t\".mp4\": true,\n\t\t\".mov\": true,\n\t\t\".wav\": true,\n\t\t\".wasm\": true,\n\t}\n\n\t// Maximum file size to open (5MB)\n\tmaxFileSize int64 = 5 * 1024 * 1024\n)\n\n// shouldExcludeDir returns true if the directory should be excluded from watching/opening\nfunc shouldExcludeDir(dirPath string) bool {\n\tdirName := filepath.Base(dirPath)\n\n\t// Skip dot directories\n\tif strings.HasPrefix(dirName, \".\") {\n\t\treturn true\n\t}\n\n\t// Skip common excluded directories\n\tif excludedDirNames[dirName] {\n\t\treturn true\n\t}\n\n\treturn false\n}\n\n// shouldExcludeFile returns true if the file should be excluded from opening\nfunc shouldExcludeFile(filePath string) bool {\n\tfileName := filepath.Base(filePath)\n\tcnf := config.Get()\n\t// Skip dot files\n\tif strings.HasPrefix(fileName, \".\") {\n\t\treturn true\n\t}\n\n\t// Check file extension\n\text := strings.ToLower(filepath.Ext(filePath))\n\tif excludedFileExtensions[ext] || largeBinaryExtensions[ext] {\n\t\treturn true\n\t}\n\n\t// Skip temporary files\n\tif strings.HasSuffix(filePath, \"~\") {\n\t\treturn true\n\t}\n\n\t// Check file size\n\tinfo, err := os.Stat(filePath)\n\tif err != nil {\n\t\t// If we can't stat the file, skip it\n\t\treturn true\n\t}\n\n\t// Skip large files\n\tif info.Size() > maxFileSize {\n\t\tif cnf.DebugLSP {\n\t\t\tlogging.Debug(\"Skipping large file\",\n\t\t\t\t\"path\", filePath,\n\t\t\t\t\"size\", info.Size(),\n\t\t\t\t\"maxSize\", maxFileSize,\n\t\t\t\t\"debug\", cnf.Debug,\n\t\t\t\t\"sizeMB\", float64(info.Size())/(1024*1024),\n\t\t\t\t\"maxSizeMB\", float64(maxFileSize)/(1024*1024),\n\t\t\t)\n\t\t}\n\t\treturn true\n\t}\n\n\treturn false\n}\n\n// openMatchingFile opens a file if it matches any of the registered patterns\nfunc (w *WorkspaceWatcher) openMatchingFile(ctx context.Context, path string) {\n\tcnf := config.Get()\n\t// Skip directories\n\tinfo, err := os.Stat(path)\n\tif err != nil || info.IsDir() {\n\t\treturn\n\t}\n\n\t// Skip excluded files\n\tif shouldExcludeFile(path) {\n\t\treturn\n\t}\n\n\t// Check if this path should be watched according to server registrations\n\tif watched, _ := w.isPathWatched(path); watched {\n\t\t// Get server name for specialized handling\n\t\tserverName := getServerNameFromContext(ctx)\n\n\t\t// Check if the file is a high-priority file that should be opened immediately\n\t\t// This helps with project initialization for certain language servers\n\t\tif isHighPriorityFile(path, serverName) {\n\t\t\tif cnf.DebugLSP {\n\t\t\t\tlogging.Debug(\"Opening high-priority file\", \"path\", path, \"serverName\", serverName)\n\t\t\t}\n\t\t\tif err := w.client.OpenFile(ctx, path); err != nil && cnf.DebugLSP {\n\t\t\t\tlogging.Error(\"Error opening high-priority file\", \"path\", path, \"error\", err)\n\t\t\t}\n\t\t\treturn\n\t\t}\n\n\t\t// For non-high-priority files, we'll use different strategies based on server type\n\t\tif shouldPreloadFiles(serverName) {\n\t\t\t// For servers that benefit from preloading, open files but with limits\n\n\t\t\t// Check file size - for preloading we're more conservative\n\t\t\tif info.Size() > (1 * 1024 * 1024) { // 1MB limit for preloaded files\n\t\t\t\tif cnf.DebugLSP {\n\t\t\t\t\tlogging.Debug(\"Skipping large file for preloading\", \"path\", path, \"size\", info.Size())\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\t// Check file extension for common source files\n\t\t\text := strings.ToLower(filepath.Ext(path))\n\n\t\t\t// Only preload source files for the specific language\n\t\t\tshouldOpen := false\n\n\t\t\tswitch serverName {\n\t\t\tcase \"typescript\", \"typescript-language-server\", \"tsserver\", \"vtsls\":\n\t\t\t\tshouldOpen = ext == \".ts\" || ext == \".js\" || ext == \".tsx\" || ext == \".jsx\"\n\t\t\tcase \"gopls\":\n\t\t\t\tshouldOpen = ext == \".go\"\n\t\t\tcase \"rust-analyzer\":\n\t\t\t\tshouldOpen = ext == \".rs\"\n\t\t\tcase \"python\", \"pyright\", \"pylsp\":\n\t\t\t\tshouldOpen = ext == \".py\"\n\t\t\tcase \"clangd\":\n\t\t\t\tshouldOpen = ext == \".c\" || ext == \".cpp\" || ext == \".h\" || ext == \".hpp\"\n\t\t\tcase \"java\", \"jdtls\":\n\t\t\t\tshouldOpen = ext == \".java\"\n\t\t\tdefault:\n\t\t\t\t// For unknown servers, be conservative\n\t\t\t\tshouldOpen = false\n\t\t\t}\n\n\t\t\tif shouldOpen {\n\t\t\t\t// Don't need to check if it's already open - the client.OpenFile handles that\n\t\t\t\tif err := w.client.OpenFile(ctx, path); err != nil && cnf.DebugLSP {\n\t\t\t\t\tlogging.Error(\"Error opening file\", \"path\", path, \"error\", err)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\n// isHighPriorityFile determines if a file should be opened immediately\n// regardless of the preloading strategy\nfunc isHighPriorityFile(path string, serverName string) bool {\n\tfileName := filepath.Base(path)\n\text := filepath.Ext(path)\n\n\tswitch serverName {\n\tcase \"typescript\", \"typescript-language-server\", \"tsserver\", \"vtsls\":\n\t\t// For TypeScript, we want to open configuration files immediately\n\t\treturn fileName == \"tsconfig.json\" ||\n\t\t\tfileName == \"package.json\" ||\n\t\t\tfileName == \"jsconfig.json\" ||\n\t\t\t// Also open main entry points\n\t\t\tfileName == \"index.ts\" ||\n\t\t\tfileName == \"index.js\" ||\n\t\t\tfileName == \"main.ts\" ||\n\t\t\tfileName == \"main.js\"\n\tcase \"gopls\":\n\t\t// For Go, we want to open go.mod files immediately\n\t\treturn fileName == \"go.mod\" ||\n\t\t\tfileName == \"go.sum\" ||\n\t\t\t// Also open main.go files\n\t\t\tfileName == \"main.go\"\n\tcase \"rust-analyzer\":\n\t\t// For Rust, we want to open Cargo.toml files immediately\n\t\treturn fileName == \"Cargo.toml\" ||\n\t\t\tfileName == \"Cargo.lock\" ||\n\t\t\t// Also open lib.rs and main.rs\n\t\t\tfileName == \"lib.rs\" ||\n\t\t\tfileName == \"main.rs\"\n\tcase \"python\", \"pyright\", \"pylsp\":\n\t\t// For Python, open key project files\n\t\treturn fileName == \"pyproject.toml\" ||\n\t\t\tfileName == \"setup.py\" ||\n\t\t\tfileName == \"requirements.txt\" ||\n\t\t\tfileName == \"__init__.py\" ||\n\t\t\tfileName == \"__main__.py\"\n\tcase \"clangd\":\n\t\t// For C/C++, open key project files\n\t\treturn fileName == \"CMakeLists.txt\" ||\n\t\t\tfileName == \"Makefile\" ||\n\t\t\tfileName == \"compile_commands.json\"\n\tcase \"java\", \"jdtls\":\n\t\t// For Java, open key project files\n\t\treturn fileName == \"pom.xml\" ||\n\t\t\tfileName == \"build.gradle\" ||\n\t\t\text == \".java\" // Java servers often need to see source files\n\t}\n\n\t// For unknown servers, prioritize common configuration files\n\treturn fileName == \"package.json\" ||\n\t\tfileName == \"Makefile\" ||\n\t\tfileName == \"CMakeLists.txt\" ||\n\t\tfileName == \".editorconfig\"\n}\n"], ["/opencode/internal/lsp/util/edit.go", "package util\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"os\"\n\t\"sort\"\n\t\"strings\"\n\n\t\"github.com/opencode-ai/opencode/internal/lsp/protocol\"\n)\n\nfunc applyTextEdits(uri protocol.DocumentUri, edits []protocol.TextEdit) error {\n\tpath := strings.TrimPrefix(string(uri), \"file://\")\n\n\t// Read the file content\n\tcontent, err := os.ReadFile(path)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to read file: %w\", err)\n\t}\n\n\t// Detect line ending style\n\tvar lineEnding string\n\tif bytes.Contains(content, []byte(\"\\r\\n\")) {\n\t\tlineEnding = \"\\r\\n\"\n\t} else {\n\t\tlineEnding = \"\\n\"\n\t}\n\n\t// Track if file ends with a newline\n\tendsWithNewline := len(content) > 0 && bytes.HasSuffix(content, []byte(lineEnding))\n\n\t// Split into lines without the endings\n\tlines := strings.Split(string(content), lineEnding)\n\n\t// Check for overlapping edits\n\tfor i, edit1 := range edits {\n\t\tfor j := i + 1; j < len(edits); j++ {\n\t\t\tif rangesOverlap(edit1.Range, edits[j].Range) {\n\t\t\t\treturn fmt.Errorf(\"overlapping edits detected between edit %d and %d\", i, j)\n\t\t\t}\n\t\t}\n\t}\n\n\t// Sort edits in reverse order\n\tsortedEdits := make([]protocol.TextEdit, len(edits))\n\tcopy(sortedEdits, edits)\n\tsort.Slice(sortedEdits, func(i, j int) bool {\n\t\tif sortedEdits[i].Range.Start.Line != sortedEdits[j].Range.Start.Line {\n\t\t\treturn sortedEdits[i].Range.Start.Line > sortedEdits[j].Range.Start.Line\n\t\t}\n\t\treturn sortedEdits[i].Range.Start.Character > sortedEdits[j].Range.Start.Character\n\t})\n\n\t// Apply each edit\n\tfor _, edit := range sortedEdits {\n\t\tnewLines, err := applyTextEdit(lines, edit)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to apply edit: %w\", err)\n\t\t}\n\t\tlines = newLines\n\t}\n\n\t// Join lines with proper line endings\n\tvar newContent strings.Builder\n\tfor i, line := range lines {\n\t\tif i > 0 {\n\t\t\tnewContent.WriteString(lineEnding)\n\t\t}\n\t\tnewContent.WriteString(line)\n\t}\n\n\t// Only add a newline if the original file had one and we haven't already added it\n\tif endsWithNewline && !strings.HasSuffix(newContent.String(), lineEnding) {\n\t\tnewContent.WriteString(lineEnding)\n\t}\n\n\tif err := os.WriteFile(path, []byte(newContent.String()), 0o644); err != nil {\n\t\treturn fmt.Errorf(\"failed to write file: %w\", err)\n\t}\n\n\treturn nil\n}\n\nfunc applyTextEdit(lines []string, edit protocol.TextEdit) ([]string, error) {\n\tstartLine := int(edit.Range.Start.Line)\n\tendLine := int(edit.Range.End.Line)\n\tstartChar := int(edit.Range.Start.Character)\n\tendChar := int(edit.Range.End.Character)\n\n\t// Validate positions\n\tif startLine < 0 || startLine >= len(lines) {\n\t\treturn nil, fmt.Errorf(\"invalid start line: %d\", startLine)\n\t}\n\tif endLine < 0 || endLine >= len(lines) {\n\t\tendLine = len(lines) - 1\n\t}\n\n\t// Create result slice with initial capacity\n\tresult := make([]string, 0, len(lines))\n\n\t// Copy lines before edit\n\tresult = append(result, lines[:startLine]...)\n\n\t// Get the prefix of the start line\n\tstartLineContent := lines[startLine]\n\tif startChar < 0 || startChar > len(startLineContent) {\n\t\tstartChar = len(startLineContent)\n\t}\n\tprefix := startLineContent[:startChar]\n\n\t// Get the suffix of the end line\n\tendLineContent := lines[endLine]\n\tif endChar < 0 || endChar > len(endLineContent) {\n\t\tendChar = len(endLineContent)\n\t}\n\tsuffix := endLineContent[endChar:]\n\n\t// Handle the edit\n\tif edit.NewText == \"\" {\n\t\tif prefix+suffix != \"\" {\n\t\t\tresult = append(result, prefix+suffix)\n\t\t}\n\t} else {\n\t\t// Split new text into lines, being careful not to add extra newlines\n\t\t// newLines := strings.Split(strings.TrimRight(edit.NewText, \"\\n\"), \"\\n\")\n\t\tnewLines := strings.Split(edit.NewText, \"\\n\")\n\n\t\tif len(newLines) == 1 {\n\t\t\t// Single line change\n\t\t\tresult = append(result, prefix+newLines[0]+suffix)\n\t\t} else {\n\t\t\t// Multi-line change\n\t\t\tresult = append(result, prefix+newLines[0])\n\t\t\tresult = append(result, newLines[1:len(newLines)-1]...)\n\t\t\tresult = append(result, newLines[len(newLines)-1]+suffix)\n\t\t}\n\t}\n\n\t// Add remaining lines\n\tif endLine+1 < len(lines) {\n\t\tresult = append(result, lines[endLine+1:]...)\n\t}\n\n\treturn result, nil\n}\n\n// applyDocumentChange applies a DocumentChange (create/rename/delete operations)\nfunc applyDocumentChange(change protocol.DocumentChange) error {\n\tif change.CreateFile != nil {\n\t\tpath := strings.TrimPrefix(string(change.CreateFile.URI), \"file://\")\n\t\tif change.CreateFile.Options != nil {\n\t\t\tif change.CreateFile.Options.Overwrite {\n\t\t\t\t// Proceed with overwrite\n\t\t\t} else if change.CreateFile.Options.IgnoreIfExists {\n\t\t\t\tif _, err := os.Stat(path); err == nil {\n\t\t\t\t\treturn nil // File exists and we're ignoring it\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif err := os.WriteFile(path, []byte(\"\"), 0o644); err != nil {\n\t\t\treturn fmt.Errorf(\"failed to create file: %w\", err)\n\t\t}\n\t}\n\n\tif change.DeleteFile != nil {\n\t\tpath := strings.TrimPrefix(string(change.DeleteFile.URI), \"file://\")\n\t\tif change.DeleteFile.Options != nil && change.DeleteFile.Options.Recursive {\n\t\t\tif err := os.RemoveAll(path); err != nil {\n\t\t\t\treturn fmt.Errorf(\"failed to delete directory recursively: %w\", err)\n\t\t\t}\n\t\t} else {\n\t\t\tif err := os.Remove(path); err != nil {\n\t\t\t\treturn fmt.Errorf(\"failed to delete file: %w\", err)\n\t\t\t}\n\t\t}\n\t}\n\n\tif change.RenameFile != nil {\n\t\toldPath := strings.TrimPrefix(string(change.RenameFile.OldURI), \"file://\")\n\t\tnewPath := strings.TrimPrefix(string(change.RenameFile.NewURI), \"file://\")\n\t\tif change.RenameFile.Options != nil {\n\t\t\tif !change.RenameFile.Options.Overwrite {\n\t\t\t\tif _, err := os.Stat(newPath); err == nil {\n\t\t\t\t\treturn fmt.Errorf(\"target file already exists and overwrite is not allowed: %s\", newPath)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif err := os.Rename(oldPath, newPath); err != nil {\n\t\t\treturn fmt.Errorf(\"failed to rename file: %w\", err)\n\t\t}\n\t}\n\n\tif change.TextDocumentEdit != nil {\n\t\ttextEdits := make([]protocol.TextEdit, len(change.TextDocumentEdit.Edits))\n\t\tfor i, edit := range change.TextDocumentEdit.Edits {\n\t\t\tvar err error\n\t\t\ttextEdits[i], err = edit.AsTextEdit()\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"invalid edit type: %w\", err)\n\t\t\t}\n\t\t}\n\t\treturn applyTextEdits(change.TextDocumentEdit.TextDocument.URI, textEdits)\n\t}\n\n\treturn nil\n}\n\n// ApplyWorkspaceEdit applies the given WorkspaceEdit to the filesystem\nfunc ApplyWorkspaceEdit(edit protocol.WorkspaceEdit) error {\n\t// Handle Changes field\n\tfor uri, textEdits := range edit.Changes {\n\t\tif err := applyTextEdits(uri, textEdits); err != nil {\n\t\t\treturn fmt.Errorf(\"failed to apply text edits: %w\", err)\n\t\t}\n\t}\n\n\t// Handle DocumentChanges field\n\tfor _, change := range edit.DocumentChanges {\n\t\tif err := applyDocumentChange(change); err != nil {\n\t\t\treturn fmt.Errorf(\"failed to apply document change: %w\", err)\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc rangesOverlap(r1, r2 protocol.Range) bool {\n\tif r1.Start.Line > r2.End.Line || r2.Start.Line > r1.End.Line {\n\t\treturn false\n\t}\n\tif r1.Start.Line == r2.End.Line && r1.Start.Character > r2.End.Character {\n\t\treturn false\n\t}\n\tif r2.Start.Line == r1.End.Line && r2.Start.Character > r1.End.Character {\n\t\treturn false\n\t}\n\treturn true\n}\n"], ["/opencode/internal/llm/provider/copilot.go", "package provider\n\nimport (\n\t\"context\"\n\t\"encoding/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"net/http\"\n\t\"os\"\n\t\"time\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n\t\"github.com/openai/openai-go/shared\"\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/llm/models\"\n\ttoolsPkg \"github.com/opencode-ai/opencode/internal/llm/tools\"\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n\t\"github.com/opencode-ai/opencode/internal/message\"\n)\n\ntype copilotOptions struct {\n\treasoningEffort string\n\textraHeaders map[string]string\n\tbearerToken string\n}\n\ntype CopilotOption func(*copilotOptions)\n\ntype copilotClient struct {\n\tproviderOptions providerClientOptions\n\toptions copilotOptions\n\tclient openai.Client\n\thttpClient *http.Client\n}\n\ntype CopilotClient ProviderClient\n\n// CopilotTokenResponse represents the response from GitHub's token exchange endpoint\ntype CopilotTokenResponse struct {\n\tToken string `json:\"token\"`\n\tExpiresAt int64 `json:\"expires_at\"`\n}\n\nfunc (c *copilotClient) isAnthropicModel() bool {\n\tfor _, modelId := range models.CopilotAnthropicModels {\n\t\tif c.providerOptions.model.ID == modelId {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n// loadGitHubToken loads the GitHub OAuth token from the standard GitHub CLI/Copilot locations\n\n// exchangeGitHubToken exchanges a GitHub token for a Copilot bearer token\nfunc (c *copilotClient) exchangeGitHubToken(githubToken string) (string, error) {\n\treq, err := http.NewRequest(\"GET\", \"https://api.github.com/copilot_internal/v2/token\", nil)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed to create token exchange request: %w\", err)\n\t}\n\n\treq.Header.Set(\"Authorization\", \"Token \"+githubToken)\n\treq.Header.Set(\"User-Agent\", \"OpenCode/1.0\")\n\n\tresp, err := c.httpClient.Do(req)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed to exchange GitHub token: %w\", err)\n\t}\n\tdefer resp.Body.Close()\n\n\tif resp.StatusCode != http.StatusOK {\n\t\tbody, _ := io.ReadAll(resp.Body)\n\t\treturn \"\", fmt.Errorf(\"token exchange failed with status %d: %s\", resp.StatusCode, string(body))\n\t}\n\n\tvar tokenResp CopilotTokenResponse\n\tif err := json.NewDecoder(resp.Body).Decode(&tokenResp); err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed to decode token response: %w\", err)\n\t}\n\n\treturn tokenResp.Token, nil\n}\n\nfunc newCopilotClient(opts providerClientOptions) CopilotClient {\n\tcopilotOpts := copilotOptions{\n\t\treasoningEffort: \"medium\",\n\t}\n\t// Apply copilot-specific options\n\tfor _, o := range opts.copilotOptions {\n\t\to(&copilotOpts)\n\t}\n\n\t// Create HTTP client for token exchange\n\thttpClient := &http.Client{\n\t\tTimeout: 30 * time.Second,\n\t}\n\n\tvar bearerToken string\n\n\t// If bearer token is already provided, use it\n\tif copilotOpts.bearerToken != \"\" {\n\t\tbearerToken = copilotOpts.bearerToken\n\t} else {\n\t\t// Try to get GitHub token from multiple sources\n\t\tvar githubToken string\n\n\t\t// 1. Environment variable\n\t\tgithubToken = os.Getenv(\"GITHUB_TOKEN\")\n\n\t\t// 2. API key from options\n\t\tif githubToken == \"\" {\n\t\t\tgithubToken = opts.apiKey\n\t\t}\n\n\t\t// 3. Standard GitHub CLI/Copilot locations\n\t\tif githubToken == \"\" {\n\t\t\tvar err error\n\t\t\tgithubToken, err = config.LoadGitHubToken()\n\t\t\tif err != nil {\n\t\t\t\tlogging.Debug(\"Failed to load GitHub token from standard locations\", \"error\", err)\n\t\t\t}\n\t\t}\n\n\t\tif githubToken == \"\" {\n\t\t\tlogging.Error(\"GitHub token is required for Copilot provider. Set GITHUB_TOKEN environment variable, configure it in opencode.json, or ensure GitHub CLI/Copilot is properly authenticated.\")\n\t\t\treturn &copilotClient{\n\t\t\t\tproviderOptions: opts,\n\t\t\t\toptions: copilotOpts,\n\t\t\t\thttpClient: httpClient,\n\t\t\t}\n\t\t}\n\n\t\t// Create a temporary client for token exchange\n\t\ttempClient := &copilotClient{\n\t\t\tproviderOptions: opts,\n\t\t\toptions: copilotOpts,\n\t\t\thttpClient: httpClient,\n\t\t}\n\n\t\t// Exchange GitHub token for bearer token\n\t\tvar err error\n\t\tbearerToken, err = tempClient.exchangeGitHubToken(githubToken)\n\t\tif err != nil {\n\t\t\tlogging.Error(\"Failed to exchange GitHub token for Copilot bearer token\", \"error\", err)\n\t\t\treturn &copilotClient{\n\t\t\t\tproviderOptions: opts,\n\t\t\t\toptions: copilotOpts,\n\t\t\t\thttpClient: httpClient,\n\t\t\t}\n\t\t}\n\t}\n\n\tcopilotOpts.bearerToken = bearerToken\n\n\t// GitHub Copilot API base URL\n\tbaseURL := \"https://api.githubcopilot.com\"\n\n\topenaiClientOptions := []option.RequestOption{\n\t\toption.WithBaseURL(baseURL),\n\t\toption.WithAPIKey(bearerToken), // Use bearer token as API key\n\t}\n\n\t// Add GitHub Copilot specific headers\n\topenaiClientOptions = append(openaiClientOptions,\n\t\toption.WithHeader(\"Editor-Version\", \"OpenCode/1.0\"),\n\t\toption.WithHeader(\"Editor-Plugin-Version\", \"OpenCode/1.0\"),\n\t\toption.WithHeader(\"Copilot-Integration-Id\", \"vscode-chat\"),\n\t)\n\n\t// Add any extra headers\n\tif copilotOpts.extraHeaders != nil {\n\t\tfor key, value := range copilotOpts.extraHeaders {\n\t\t\topenaiClientOptions = append(openaiClientOptions, option.WithHeader(key, value))\n\t\t}\n\t}\n\n\tclient := openai.NewClient(openaiClientOptions...)\n\t// logging.Debug(\"Copilot client created\", \"opts\", opts, \"copilotOpts\", copilotOpts, \"model\", opts.model)\n\treturn &copilotClient{\n\t\tproviderOptions: opts,\n\t\toptions: copilotOpts,\n\t\tclient: client,\n\t\thttpClient: httpClient,\n\t}\n}\n\nfunc (c *copilotClient) convertMessages(messages []message.Message) (copilotMessages []openai.ChatCompletionMessageParamUnion) {\n\t// Add system message first\n\tcopilotMessages = append(copilotMessages, openai.SystemMessage(c.providerOptions.systemMessage))\n\n\tfor _, msg := range messages {\n\t\tswitch msg.Role {\n\t\tcase message.User:\n\t\t\tvar content []openai.ChatCompletionContentPartUnionParam\n\t\t\ttextBlock := openai.ChatCompletionContentPartTextParam{Text: msg.Content().String()}\n\t\t\tcontent = append(content, openai.ChatCompletionContentPartUnionParam{OfText: &textBlock})\n\n\t\t\tfor _, binaryContent := range msg.BinaryContent() {\n\t\t\t\timageURL := openai.ChatCompletionContentPartImageImageURLParam{URL: binaryContent.String(models.ProviderCopilot)}\n\t\t\t\timageBlock := openai.ChatCompletionContentPartImageParam{ImageURL: imageURL}\n\t\t\t\tcontent = append(content, openai.ChatCompletionContentPartUnionParam{OfImageURL: &imageBlock})\n\t\t\t}\n\n\t\t\tcopilotMessages = append(copilotMessages, openai.UserMessage(content))\n\n\t\tcase message.Assistant:\n\t\t\tassistantMsg := openai.ChatCompletionAssistantMessageParam{\n\t\t\t\tRole: \"assistant\",\n\t\t\t}\n\n\t\t\tif msg.Content().String() != \"\" {\n\t\t\t\tassistantMsg.Content = openai.ChatCompletionAssistantMessageParamContentUnion{\n\t\t\t\t\tOfString: openai.String(msg.Content().String()),\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif len(msg.ToolCalls()) > 0 {\n\t\t\t\tassistantMsg.ToolCalls = make([]openai.ChatCompletionMessageToolCallParam, len(msg.ToolCalls()))\n\t\t\t\tfor i, call := range msg.ToolCalls() {\n\t\t\t\t\tassistantMsg.ToolCalls[i] = openai.ChatCompletionMessageToolCallParam{\n\t\t\t\t\t\tID: call.ID,\n\t\t\t\t\t\tType: \"function\",\n\t\t\t\t\t\tFunction: openai.ChatCompletionMessageToolCallFunctionParam{\n\t\t\t\t\t\t\tName: call.Name,\n\t\t\t\t\t\t\tArguments: call.Input,\n\t\t\t\t\t\t},\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tcopilotMessages = append(copilotMessages, openai.ChatCompletionMessageParamUnion{\n\t\t\t\tOfAssistant: &assistantMsg,\n\t\t\t})\n\n\t\tcase message.Tool:\n\t\t\tfor _, result := range msg.ToolResults() {\n\t\t\t\tcopilotMessages = append(copilotMessages,\n\t\t\t\t\topenai.ToolMessage(result.Content, result.ToolCallID),\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn\n}\n\nfunc (c *copilotClient) convertTools(tools []toolsPkg.BaseTool) []openai.ChatCompletionToolParam {\n\tcopilotTools := make([]openai.ChatCompletionToolParam, len(tools))\n\n\tfor i, tool := range tools {\n\t\tinfo := tool.Info()\n\t\tcopilotTools[i] = openai.ChatCompletionToolParam{\n\t\t\tFunction: openai.FunctionDefinitionParam{\n\t\t\t\tName: info.Name,\n\t\t\t\tDescription: openai.String(info.Description),\n\t\t\t\tParameters: openai.FunctionParameters{\n\t\t\t\t\t\"type\": \"object\",\n\t\t\t\t\t\"properties\": info.Parameters,\n\t\t\t\t\t\"required\": info.Required,\n\t\t\t\t},\n\t\t\t},\n\t\t}\n\t}\n\n\treturn copilotTools\n}\n\nfunc (c *copilotClient) finishReason(reason string) message.FinishReason {\n\tswitch reason {\n\tcase \"stop\":\n\t\treturn message.FinishReasonEndTurn\n\tcase \"length\":\n\t\treturn message.FinishReasonMaxTokens\n\tcase \"tool_calls\":\n\t\treturn message.FinishReasonToolUse\n\tdefault:\n\t\treturn message.FinishReasonUnknown\n\t}\n}\n\nfunc (c *copilotClient) preparedParams(messages []openai.ChatCompletionMessageParamUnion, tools []openai.ChatCompletionToolParam) openai.ChatCompletionNewParams {\n\tparams := openai.ChatCompletionNewParams{\n\t\tModel: openai.ChatModel(c.providerOptions.model.APIModel),\n\t\tMessages: messages,\n\t\tTools: tools,\n\t}\n\n\tif c.providerOptions.model.CanReason == true {\n\t\tparams.MaxCompletionTokens = openai.Int(c.providerOptions.maxTokens)\n\t\tswitch c.options.reasoningEffort {\n\t\tcase \"low\":\n\t\t\tparams.ReasoningEffort = shared.ReasoningEffortLow\n\t\tcase \"medium\":\n\t\t\tparams.ReasoningEffort = shared.ReasoningEffortMedium\n\t\tcase \"high\":\n\t\t\tparams.ReasoningEffort = shared.ReasoningEffortHigh\n\t\tdefault:\n\t\t\tparams.ReasoningEffort = shared.ReasoningEffortMedium\n\t\t}\n\t} else {\n\t\tparams.MaxTokens = openai.Int(c.providerOptions.maxTokens)\n\t}\n\n\treturn params\n}\n\nfunc (c *copilotClient) send(ctx context.Context, messages []message.Message, tools []toolsPkg.BaseTool) (response *ProviderResponse, err error) {\n\tparams := c.preparedParams(c.convertMessages(messages), c.convertTools(tools))\n\tcfg := config.Get()\n\tvar sessionId string\n\trequestSeqId := (len(messages) + 1) / 2\n\tif cfg.Debug {\n\t\t// jsonData, _ := json.Marshal(params)\n\t\t// logging.Debug(\"Prepared messages\", \"messages\", string(jsonData))\n\t\tif sid, ok := ctx.Value(toolsPkg.SessionIDContextKey).(string); ok {\n\t\t\tsessionId = sid\n\t\t}\n\t\tjsonData, _ := json.Marshal(params)\n\t\tif sessionId != \"\" {\n\t\t\tfilepath := logging.WriteRequestMessageJson(sessionId, requestSeqId, params)\n\t\t\tlogging.Debug(\"Prepared messages\", \"filepath\", filepath)\n\t\t} else {\n\t\t\tlogging.Debug(\"Prepared messages\", \"messages\", string(jsonData))\n\t\t}\n\t}\n\n\tattempts := 0\n\tfor {\n\t\tattempts++\n\t\tcopilotResponse, err := c.client.Chat.Completions.New(\n\t\t\tctx,\n\t\t\tparams,\n\t\t)\n\n\t\t// If there is an error we are going to see if we can retry the call\n\t\tif err != nil {\n\t\t\tretry, after, retryErr := c.shouldRetry(attempts, err)\n\t\t\tif retryErr != nil {\n\t\t\t\treturn nil, retryErr\n\t\t\t}\n\t\t\tif retry {\n\t\t\t\tlogging.WarnPersist(fmt.Sprintf(\"Retrying due to rate limit... attempt %d of %d\", attempts, maxRetries), logging.PersistTimeArg, time.Millisecond*time.Duration(after+100))\n\t\t\t\tselect {\n\t\t\t\tcase <-ctx.Done():\n\t\t\t\t\treturn nil, ctx.Err()\n\t\t\t\tcase <-time.After(time.Duration(after) * time.Millisecond):\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn nil, retryErr\n\t\t}\n\n\t\tcontent := \"\"\n\t\tif copilotResponse.Choices[0].Message.Content != \"\" {\n\t\t\tcontent = copilotResponse.Choices[0].Message.Content\n\t\t}\n\n\t\ttoolCalls := c.toolCalls(*copilotResponse)\n\t\tfinishReason := c.finishReason(string(copilotResponse.Choices[0].FinishReason))\n\n\t\tif len(toolCalls) > 0 {\n\t\t\tfinishReason = message.FinishReasonToolUse\n\t\t}\n\n\t\treturn &ProviderResponse{\n\t\t\tContent: content,\n\t\t\tToolCalls: toolCalls,\n\t\t\tUsage: c.usage(*copilotResponse),\n\t\t\tFinishReason: finishReason,\n\t\t}, nil\n\t}\n}\n\nfunc (c *copilotClient) stream(ctx context.Context, messages []message.Message, tools []toolsPkg.BaseTool) <-chan ProviderEvent {\n\tparams := c.preparedParams(c.convertMessages(messages), c.convertTools(tools))\n\tparams.StreamOptions = openai.ChatCompletionStreamOptionsParam{\n\t\tIncludeUsage: openai.Bool(true),\n\t}\n\n\tcfg := config.Get()\n\tvar sessionId string\n\trequestSeqId := (len(messages) + 1) / 2\n\tif cfg.Debug {\n\t\tif sid, ok := ctx.Value(toolsPkg.SessionIDContextKey).(string); ok {\n\t\t\tsessionId = sid\n\t\t}\n\t\tjsonData, _ := json.Marshal(params)\n\t\tif sessionId != \"\" {\n\t\t\tfilepath := logging.WriteRequestMessageJson(sessionId, requestSeqId, params)\n\t\t\tlogging.Debug(\"Prepared messages\", \"filepath\", filepath)\n\t\t} else {\n\t\t\tlogging.Debug(\"Prepared messages\", \"messages\", string(jsonData))\n\t\t}\n\n\t}\n\n\tattempts := 0\n\teventChan := make(chan ProviderEvent)\n\n\tgo func() {\n\t\tfor {\n\t\t\tattempts++\n\t\t\tcopilotStream := c.client.Chat.Completions.NewStreaming(\n\t\t\t\tctx,\n\t\t\t\tparams,\n\t\t\t)\n\n\t\t\tacc := openai.ChatCompletionAccumulator{}\n\t\t\tcurrentContent := \"\"\n\t\t\ttoolCalls := make([]message.ToolCall, 0)\n\n\t\t\tvar currentToolCallId string\n\t\t\tvar currentToolCall openai.ChatCompletionMessageToolCall\n\t\t\tvar msgToolCalls []openai.ChatCompletionMessageToolCall\n\t\t\tfor copilotStream.Next() {\n\t\t\t\tchunk := copilotStream.Current()\n\t\t\t\tacc.AddChunk(chunk)\n\n\t\t\t\tif cfg.Debug {\n\t\t\t\t\tlogging.AppendToStreamSessionLogJson(sessionId, requestSeqId, chunk)\n\t\t\t\t}\n\n\t\t\t\tfor _, choice := range chunk.Choices {\n\t\t\t\t\tif choice.Delta.Content != \"\" {\n\t\t\t\t\t\teventChan <- ProviderEvent{\n\t\t\t\t\t\t\tType: EventContentDelta,\n\t\t\t\t\t\t\tContent: choice.Delta.Content,\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcurrentContent += choice.Delta.Content\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif c.isAnthropicModel() {\n\t\t\t\t\t// Monkeypatch adapter for Sonnet-4 multi-tool use\n\t\t\t\t\tfor _, choice := range chunk.Choices {\n\t\t\t\t\t\tif choice.Delta.ToolCalls != nil && len(choice.Delta.ToolCalls) > 0 {\n\t\t\t\t\t\t\ttoolCall := choice.Delta.ToolCalls[0]\n\t\t\t\t\t\t\t// Detect tool use start\n\t\t\t\t\t\t\tif currentToolCallId == \"\" {\n\t\t\t\t\t\t\t\tif toolCall.ID != \"\" {\n\t\t\t\t\t\t\t\t\tcurrentToolCallId = toolCall.ID\n\t\t\t\t\t\t\t\t\tcurrentToolCall = openai.ChatCompletionMessageToolCall{\n\t\t\t\t\t\t\t\t\t\tID: toolCall.ID,\n\t\t\t\t\t\t\t\t\t\tType: \"function\",\n\t\t\t\t\t\t\t\t\t\tFunction: openai.ChatCompletionMessageToolCallFunction{\n\t\t\t\t\t\t\t\t\t\t\tName: toolCall.Function.Name,\n\t\t\t\t\t\t\t\t\t\t\tArguments: toolCall.Function.Arguments,\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t// Delta tool use\n\t\t\t\t\t\t\t\tif toolCall.ID == \"\" {\n\t\t\t\t\t\t\t\t\tcurrentToolCall.Function.Arguments += toolCall.Function.Arguments\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t// Detect new tool use\n\t\t\t\t\t\t\t\t\tif toolCall.ID != currentToolCallId {\n\t\t\t\t\t\t\t\t\t\tmsgToolCalls = append(msgToolCalls, currentToolCall)\n\t\t\t\t\t\t\t\t\t\tcurrentToolCallId = toolCall.ID\n\t\t\t\t\t\t\t\t\t\tcurrentToolCall = openai.ChatCompletionMessageToolCall{\n\t\t\t\t\t\t\t\t\t\t\tID: toolCall.ID,\n\t\t\t\t\t\t\t\t\t\t\tType: \"function\",\n\t\t\t\t\t\t\t\t\t\t\tFunction: openai.ChatCompletionMessageToolCallFunction{\n\t\t\t\t\t\t\t\t\t\t\t\tName: toolCall.Function.Name,\n\t\t\t\t\t\t\t\t\t\t\t\tArguments: toolCall.Function.Arguments,\n\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif choice.FinishReason == \"tool_calls\" {\n\t\t\t\t\t\t\tmsgToolCalls = append(msgToolCalls, currentToolCall)\n\t\t\t\t\t\t\tacc.ChatCompletion.Choices[0].Message.ToolCalls = msgToolCalls\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\terr := copilotStream.Err()\n\t\t\tif err == nil || errors.Is(err, io.EOF) {\n\t\t\t\tif cfg.Debug {\n\t\t\t\t\trespFilepath := logging.WriteChatResponseJson(sessionId, requestSeqId, acc.ChatCompletion)\n\t\t\t\t\tlogging.Debug(\"Chat completion response\", \"filepath\", respFilepath)\n\t\t\t\t}\n\t\t\t\t// Stream completed successfully\n\t\t\t\tfinishReason := c.finishReason(string(acc.ChatCompletion.Choices[0].FinishReason))\n\t\t\t\tif len(acc.ChatCompletion.Choices[0].Message.ToolCalls) > 0 {\n\t\t\t\t\ttoolCalls = append(toolCalls, c.toolCalls(acc.ChatCompletion)...)\n\t\t\t\t}\n\t\t\t\tif len(toolCalls) > 0 {\n\t\t\t\t\tfinishReason = message.FinishReasonToolUse\n\t\t\t\t}\n\n\t\t\t\teventChan <- ProviderEvent{\n\t\t\t\t\tType: EventComplete,\n\t\t\t\t\tResponse: &ProviderResponse{\n\t\t\t\t\t\tContent: currentContent,\n\t\t\t\t\t\tToolCalls: toolCalls,\n\t\t\t\t\t\tUsage: c.usage(acc.ChatCompletion),\n\t\t\t\t\t\tFinishReason: finishReason,\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t\tclose(eventChan)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\t// If there is an error we are going to see if we can retry the call\n\t\t\tretry, after, retryErr := c.shouldRetry(attempts, err)\n\t\t\tif retryErr != nil {\n\t\t\t\teventChan <- ProviderEvent{Type: EventError, Error: retryErr}\n\t\t\t\tclose(eventChan)\n\t\t\t\treturn\n\t\t\t}\n\t\t\t// shouldRetry is not catching the max retries...\n\t\t\t// TODO: Figure out why\n\t\t\tif attempts > maxRetries {\n\t\t\t\tlogging.Warn(\"Maximum retry attempts reached for rate limit\", \"attempts\", attempts, \"max_retries\", maxRetries)\n\t\t\t\tretry = false\n\t\t\t}\n\t\t\tif retry {\n\t\t\t\tlogging.WarnPersist(fmt.Sprintf(\"Retrying due to rate limit... attempt %d of %d (paused for %d ms)\", attempts, maxRetries, after), logging.PersistTimeArg, time.Millisecond*time.Duration(after+100))\n\t\t\t\tselect {\n\t\t\t\tcase <-ctx.Done():\n\t\t\t\t\t// context cancelled\n\t\t\t\t\tif ctx.Err() == nil {\n\t\t\t\t\t\teventChan <- ProviderEvent{Type: EventError, Error: ctx.Err()}\n\t\t\t\t\t}\n\t\t\t\t\tclose(eventChan)\n\t\t\t\t\treturn\n\t\t\t\tcase <-time.After(time.Duration(after) * time.Millisecond):\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t\teventChan <- ProviderEvent{Type: EventError, Error: retryErr}\n\t\t\tclose(eventChan)\n\t\t\treturn\n\t\t}\n\t}()\n\n\treturn eventChan\n}\n\nfunc (c *copilotClient) shouldRetry(attempts int, err error) (bool, int64, error) {\n\tvar apierr *openai.Error\n\tif !errors.As(err, &apierr) {\n\t\treturn false, 0, err\n\t}\n\n\t// Check for token expiration (401 Unauthorized)\n\tif apierr.StatusCode == 401 {\n\t\t// Try to refresh the bearer token\n\t\tvar githubToken string\n\n\t\t// 1. Environment variable\n\t\tgithubToken = os.Getenv(\"GITHUB_TOKEN\")\n\n\t\t// 2. API key from options\n\t\tif githubToken == \"\" {\n\t\t\tgithubToken = c.providerOptions.apiKey\n\t\t}\n\n\t\t// 3. Standard GitHub CLI/Copilot locations\n\t\tif githubToken == \"\" {\n\t\t\tvar err error\n\t\t\tgithubToken, err = config.LoadGitHubToken()\n\t\t\tif err != nil {\n\t\t\t\tlogging.Debug(\"Failed to load GitHub token from standard locations during retry\", \"error\", err)\n\t\t\t}\n\t\t}\n\n\t\tif githubToken != \"\" {\n\t\t\tnewBearerToken, tokenErr := c.exchangeGitHubToken(githubToken)\n\t\t\tif tokenErr == nil {\n\t\t\t\tc.options.bearerToken = newBearerToken\n\t\t\t\t// Update the client with the new token\n\t\t\t\t// Note: This is a simplified approach. In a production system,\n\t\t\t\t// you might want to recreate the entire client with the new token\n\t\t\t\tlogging.Info(\"Refreshed Copilot bearer token\")\n\t\t\t\treturn true, 1000, nil // Retry immediately with new token\n\t\t\t}\n\t\t\tlogging.Error(\"Failed to refresh Copilot bearer token\", \"error\", tokenErr)\n\t\t}\n\t\treturn false, 0, fmt.Errorf(\"authentication failed: %w\", err)\n\t}\n\tlogging.Debug(\"Copilot API Error\", \"status\", apierr.StatusCode, \"headers\", apierr.Response.Header, \"body\", apierr.RawJSON())\n\n\tif apierr.StatusCode != 429 && apierr.StatusCode != 500 {\n\t\treturn false, 0, err\n\t}\n\n\tif apierr.StatusCode == 500 {\n\t\tlogging.Warn(\"Copilot API returned 500 error, retrying\", \"error\", err)\n\t}\n\n\tif attempts > maxRetries {\n\t\treturn false, 0, fmt.Errorf(\"maximum retry attempts reached for rate limit: %d retries\", maxRetries)\n\t}\n\n\tretryMs := 0\n\tretryAfterValues := apierr.Response.Header.Values(\"Retry-After\")\n\n\tbackoffMs := 2000 * (1 << (attempts - 1))\n\tjitterMs := int(float64(backoffMs) * 0.2)\n\tretryMs = backoffMs + jitterMs\n\tif len(retryAfterValues) > 0 {\n\t\tif _, err := fmt.Sscanf(retryAfterValues[0], \"%d\", &retryMs); err == nil {\n\t\t\tretryMs = retryMs * 1000\n\t\t}\n\t}\n\treturn true, int64(retryMs), nil\n}\n\nfunc (c *copilotClient) toolCalls(completion openai.ChatCompletion) []message.ToolCall {\n\tvar toolCalls []message.ToolCall\n\n\tif len(completion.Choices) > 0 && len(completion.Choices[0].Message.ToolCalls) > 0 {\n\t\tfor _, call := range completion.Choices[0].Message.ToolCalls {\n\t\t\ttoolCall := message.ToolCall{\n\t\t\t\tID: call.ID,\n\t\t\t\tName: call.Function.Name,\n\t\t\t\tInput: call.Function.Arguments,\n\t\t\t\tType: \"function\",\n\t\t\t\tFinished: true,\n\t\t\t}\n\t\t\ttoolCalls = append(toolCalls, toolCall)\n\t\t}\n\t}\n\n\treturn toolCalls\n}\n\nfunc (c *copilotClient) usage(completion openai.ChatCompletion) TokenUsage {\n\tcachedTokens := completion.Usage.PromptTokensDetails.CachedTokens\n\tinputTokens := completion.Usage.PromptTokens - cachedTokens\n\n\treturn TokenUsage{\n\t\tInputTokens: inputTokens,\n\t\tOutputTokens: completion.Usage.CompletionTokens,\n\t\tCacheCreationTokens: 0, // GitHub Copilot doesn't provide this directly\n\t\tCacheReadTokens: cachedTokens,\n\t}\n}\n\nfunc WithCopilotReasoningEffort(effort string) CopilotOption {\n\treturn func(options *copilotOptions) {\n\t\tdefaultReasoningEffort := \"medium\"\n\t\tswitch effort {\n\t\tcase \"low\", \"medium\", \"high\":\n\t\t\tdefaultReasoningEffort = effort\n\t\tdefault:\n\t\t\tlogging.Warn(\"Invalid reasoning effort, using default: medium\")\n\t\t}\n\t\toptions.reasoningEffort = defaultReasoningEffort\n\t}\n}\n\nfunc WithCopilotExtraHeaders(headers map[string]string) CopilotOption {\n\treturn func(options *copilotOptions) {\n\t\toptions.extraHeaders = headers\n\t}\n}\n\nfunc WithCopilotBearerToken(bearerToken string) CopilotOption {\n\treturn func(options *copilotOptions) {\n\t\toptions.bearerToken = bearerToken\n\t}\n}\n\n"], ["/opencode/internal/llm/provider/anthropic.go", "package provider\n\nimport (\n\t\"context\"\n\t\"encoding/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/anthropics/anthropic-sdk-go\"\n\t\"github.com/anthropics/anthropic-sdk-go/bedrock\"\n\t\"github.com/anthropics/anthropic-sdk-go/option\"\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/llm/models\"\n\ttoolsPkg \"github.com/opencode-ai/opencode/internal/llm/tools\"\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n\t\"github.com/opencode-ai/opencode/internal/message\"\n)\n\ntype anthropicOptions struct {\n\tuseBedrock bool\n\tdisableCache bool\n\tshouldThink func(userMessage string) bool\n}\n\ntype AnthropicOption func(*anthropicOptions)\n\ntype anthropicClient struct {\n\tproviderOptions providerClientOptions\n\toptions anthropicOptions\n\tclient anthropic.Client\n}\n\ntype AnthropicClient ProviderClient\n\nfunc newAnthropicClient(opts providerClientOptions) AnthropicClient {\n\tanthropicOpts := anthropicOptions{}\n\tfor _, o := range opts.anthropicOptions {\n\t\to(&anthropicOpts)\n\t}\n\n\tanthropicClientOptions := []option.RequestOption{}\n\tif opts.apiKey != \"\" {\n\t\tanthropicClientOptions = append(anthropicClientOptions, option.WithAPIKey(opts.apiKey))\n\t}\n\tif anthropicOpts.useBedrock {\n\t\tanthropicClientOptions = append(anthropicClientOptions, bedrock.WithLoadDefaultConfig(context.Background()))\n\t}\n\n\tclient := anthropic.NewClient(anthropicClientOptions...)\n\treturn &anthropicClient{\n\t\tproviderOptions: opts,\n\t\toptions: anthropicOpts,\n\t\tclient: client,\n\t}\n}\n\nfunc (a *anthropicClient) convertMessages(messages []message.Message) (anthropicMessages []anthropic.MessageParam) {\n\tfor i, msg := range messages {\n\t\tcache := false\n\t\tif i > len(messages)-3 {\n\t\t\tcache = true\n\t\t}\n\t\tswitch msg.Role {\n\t\tcase message.User:\n\t\t\tcontent := anthropic.NewTextBlock(msg.Content().String())\n\t\t\tif cache && !a.options.disableCache {\n\t\t\t\tcontent.OfText.CacheControl = anthropic.CacheControlEphemeralParam{\n\t\t\t\t\tType: \"ephemeral\",\n\t\t\t\t}\n\t\t\t}\n\t\t\tvar contentBlocks []anthropic.ContentBlockParamUnion\n\t\t\tcontentBlocks = append(contentBlocks, content)\n\t\t\tfor _, binaryContent := range msg.BinaryContent() {\n\t\t\t\tbase64Image := binaryContent.String(models.ProviderAnthropic)\n\t\t\t\timageBlock := anthropic.NewImageBlockBase64(binaryContent.MIMEType, base64Image)\n\t\t\t\tcontentBlocks = append(contentBlocks, imageBlock)\n\t\t\t}\n\t\t\tanthropicMessages = append(anthropicMessages, anthropic.NewUserMessage(contentBlocks...))\n\n\t\tcase message.Assistant:\n\t\t\tblocks := []anthropic.ContentBlockParamUnion{}\n\t\t\tif msg.Content().String() != \"\" {\n\t\t\t\tcontent := anthropic.NewTextBlock(msg.Content().String())\n\t\t\t\tif cache && !a.options.disableCache {\n\t\t\t\t\tcontent.OfText.CacheControl = anthropic.CacheControlEphemeralParam{\n\t\t\t\t\t\tType: \"ephemeral\",\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tblocks = append(blocks, content)\n\t\t\t}\n\n\t\t\tfor _, toolCall := range msg.ToolCalls() {\n\t\t\t\tvar inputMap map[string]any\n\t\t\t\terr := json.Unmarshal([]byte(toolCall.Input), &inputMap)\n\t\t\t\tif err != nil {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tblocks = append(blocks, anthropic.NewToolUseBlock(toolCall.ID, inputMap, toolCall.Name))\n\t\t\t}\n\n\t\t\tif len(blocks) == 0 {\n\t\t\t\tlogging.Warn(\"There is a message without content, investigate, this should not happen\")\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tanthropicMessages = append(anthropicMessages, anthropic.NewAssistantMessage(blocks...))\n\n\t\tcase message.Tool:\n\t\t\tresults := make([]anthropic.ContentBlockParamUnion, len(msg.ToolResults()))\n\t\t\tfor i, toolResult := range msg.ToolResults() {\n\t\t\t\tresults[i] = anthropic.NewToolResultBlock(toolResult.ToolCallID, toolResult.Content, toolResult.IsError)\n\t\t\t}\n\t\t\tanthropicMessages = append(anthropicMessages, anthropic.NewUserMessage(results...))\n\t\t}\n\t}\n\treturn\n}\n\nfunc (a *anthropicClient) convertTools(tools []toolsPkg.BaseTool) []anthropic.ToolUnionParam {\n\tanthropicTools := make([]anthropic.ToolUnionParam, len(tools))\n\n\tfor i, tool := range tools {\n\t\tinfo := tool.Info()\n\t\ttoolParam := anthropic.ToolParam{\n\t\t\tName: info.Name,\n\t\t\tDescription: anthropic.String(info.Description),\n\t\t\tInputSchema: anthropic.ToolInputSchemaParam{\n\t\t\t\tProperties: info.Parameters,\n\t\t\t\t// TODO: figure out how we can tell claude the required fields?\n\t\t\t},\n\t\t}\n\n\t\tif i == len(tools)-1 && !a.options.disableCache {\n\t\t\ttoolParam.CacheControl = anthropic.CacheControlEphemeralParam{\n\t\t\t\tType: \"ephemeral\",\n\t\t\t}\n\t\t}\n\n\t\tanthropicTools[i] = anthropic.ToolUnionParam{OfTool: &toolParam}\n\t}\n\n\treturn anthropicTools\n}\n\nfunc (a *anthropicClient) finishReason(reason string) message.FinishReason {\n\tswitch reason {\n\tcase \"end_turn\":\n\t\treturn message.FinishReasonEndTurn\n\tcase \"max_tokens\":\n\t\treturn message.FinishReasonMaxTokens\n\tcase \"tool_use\":\n\t\treturn message.FinishReasonToolUse\n\tcase \"stop_sequence\":\n\t\treturn message.FinishReasonEndTurn\n\tdefault:\n\t\treturn message.FinishReasonUnknown\n\t}\n}\n\nfunc (a *anthropicClient) preparedMessages(messages []anthropic.MessageParam, tools []anthropic.ToolUnionParam) anthropic.MessageNewParams {\n\tvar thinkingParam anthropic.ThinkingConfigParamUnion\n\tlastMessage := messages[len(messages)-1]\n\tisUser := lastMessage.Role == anthropic.MessageParamRoleUser\n\tmessageContent := \"\"\n\ttemperature := anthropic.Float(0)\n\tif isUser {\n\t\tfor _, m := range lastMessage.Content {\n\t\t\tif m.OfText != nil && m.OfText.Text != \"\" {\n\t\t\t\tmessageContent = m.OfText.Text\n\t\t\t}\n\t\t}\n\t\tif messageContent != \"\" && a.options.shouldThink != nil && a.options.shouldThink(messageContent) {\n\t\t\tthinkingParam = anthropic.ThinkingConfigParamOfEnabled(int64(float64(a.providerOptions.maxTokens) * 0.8))\n\t\t\ttemperature = anthropic.Float(1)\n\t\t}\n\t}\n\n\treturn anthropic.MessageNewParams{\n\t\tModel: anthropic.Model(a.providerOptions.model.APIModel),\n\t\tMaxTokens: a.providerOptions.maxTokens,\n\t\tTemperature: temperature,\n\t\tMessages: messages,\n\t\tTools: tools,\n\t\tThinking: thinkingParam,\n\t\tSystem: []anthropic.TextBlockParam{\n\t\t\t{\n\t\t\t\tText: a.providerOptions.systemMessage,\n\t\t\t\tCacheControl: anthropic.CacheControlEphemeralParam{\n\t\t\t\t\tType: \"ephemeral\",\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n}\n\nfunc (a *anthropicClient) send(ctx context.Context, messages []message.Message, tools []toolsPkg.BaseTool) (resposne *ProviderResponse, err error) {\n\tpreparedMessages := a.preparedMessages(a.convertMessages(messages), a.convertTools(tools))\n\tcfg := config.Get()\n\tif cfg.Debug {\n\t\tjsonData, _ := json.Marshal(preparedMessages)\n\t\tlogging.Debug(\"Prepared messages\", \"messages\", string(jsonData))\n\t}\n\n\tattempts := 0\n\tfor {\n\t\tattempts++\n\t\tanthropicResponse, err := a.client.Messages.New(\n\t\t\tctx,\n\t\t\tpreparedMessages,\n\t\t)\n\t\t// If there is an error we are going to see if we can retry the call\n\t\tif err != nil {\n\t\t\tlogging.Error(\"Error in Anthropic API call\", \"error\", err)\n\t\t\tretry, after, retryErr := a.shouldRetry(attempts, err)\n\t\t\tif retryErr != nil {\n\t\t\t\treturn nil, retryErr\n\t\t\t}\n\t\t\tif retry {\n\t\t\t\tlogging.WarnPersist(fmt.Sprintf(\"Retrying due to rate limit... attempt %d of %d\", attempts, maxRetries), logging.PersistTimeArg, time.Millisecond*time.Duration(after+100))\n\t\t\t\tselect {\n\t\t\t\tcase <-ctx.Done():\n\t\t\t\t\treturn nil, ctx.Err()\n\t\t\t\tcase <-time.After(time.Duration(after) * time.Millisecond):\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn nil, retryErr\n\t\t}\n\n\t\tcontent := \"\"\n\t\tfor _, block := range anthropicResponse.Content {\n\t\t\tif text, ok := block.AsAny().(anthropic.TextBlock); ok {\n\t\t\t\tcontent += text.Text\n\t\t\t}\n\t\t}\n\n\t\treturn &ProviderResponse{\n\t\t\tContent: content,\n\t\t\tToolCalls: a.toolCalls(*anthropicResponse),\n\t\t\tUsage: a.usage(*anthropicResponse),\n\t\t}, nil\n\t}\n}\n\nfunc (a *anthropicClient) stream(ctx context.Context, messages []message.Message, tools []toolsPkg.BaseTool) <-chan ProviderEvent {\n\tpreparedMessages := a.preparedMessages(a.convertMessages(messages), a.convertTools(tools))\n\tcfg := config.Get()\n\n\tvar sessionId string\n\trequestSeqId := (len(messages) + 1) / 2\n\tif cfg.Debug {\n\t\tif sid, ok := ctx.Value(toolsPkg.SessionIDContextKey).(string); ok {\n\t\t\tsessionId = sid\n\t\t}\n\t\tjsonData, _ := json.Marshal(preparedMessages)\n\t\tif sessionId != \"\" {\n\t\t\tfilepath := logging.WriteRequestMessageJson(sessionId, requestSeqId, preparedMessages)\n\t\t\tlogging.Debug(\"Prepared messages\", \"filepath\", filepath)\n\t\t} else {\n\t\t\tlogging.Debug(\"Prepared messages\", \"messages\", string(jsonData))\n\t\t}\n\n\t}\n\tattempts := 0\n\teventChan := make(chan ProviderEvent)\n\tgo func() {\n\t\tfor {\n\t\t\tattempts++\n\t\t\tanthropicStream := a.client.Messages.NewStreaming(\n\t\t\t\tctx,\n\t\t\t\tpreparedMessages,\n\t\t\t)\n\t\t\taccumulatedMessage := anthropic.Message{}\n\n\t\t\tcurrentToolCallID := \"\"\n\t\t\tfor anthropicStream.Next() {\n\t\t\t\tevent := anthropicStream.Current()\n\t\t\t\terr := accumulatedMessage.Accumulate(event)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlogging.Warn(\"Error accumulating message\", \"error\", err)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tswitch event := event.AsAny().(type) {\n\t\t\t\tcase anthropic.ContentBlockStartEvent:\n\t\t\t\t\tif event.ContentBlock.Type == \"text\" {\n\t\t\t\t\t\teventChan <- ProviderEvent{Type: EventContentStart}\n\t\t\t\t\t} else if event.ContentBlock.Type == \"tool_use\" {\n\t\t\t\t\t\tcurrentToolCallID = event.ContentBlock.ID\n\t\t\t\t\t\teventChan <- ProviderEvent{\n\t\t\t\t\t\t\tType: EventToolUseStart,\n\t\t\t\t\t\t\tToolCall: &message.ToolCall{\n\t\t\t\t\t\t\t\tID: event.ContentBlock.ID,\n\t\t\t\t\t\t\t\tName: event.ContentBlock.Name,\n\t\t\t\t\t\t\t\tFinished: false,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\tcase anthropic.ContentBlockDeltaEvent:\n\t\t\t\t\tif event.Delta.Type == \"thinking_delta\" && event.Delta.Thinking != \"\" {\n\t\t\t\t\t\teventChan <- ProviderEvent{\n\t\t\t\t\t\t\tType: EventThinkingDelta,\n\t\t\t\t\t\t\tThinking: event.Delta.Thinking,\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if event.Delta.Type == \"text_delta\" && event.Delta.Text != \"\" {\n\t\t\t\t\t\teventChan <- ProviderEvent{\n\t\t\t\t\t\t\tType: EventContentDelta,\n\t\t\t\t\t\t\tContent: event.Delta.Text,\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if event.Delta.Type == \"input_json_delta\" {\n\t\t\t\t\t\tif currentToolCallID != \"\" {\n\t\t\t\t\t\t\teventChan <- ProviderEvent{\n\t\t\t\t\t\t\t\tType: EventToolUseDelta,\n\t\t\t\t\t\t\t\tToolCall: &message.ToolCall{\n\t\t\t\t\t\t\t\t\tID: currentToolCallID,\n\t\t\t\t\t\t\t\t\tFinished: false,\n\t\t\t\t\t\t\t\t\tInput: event.Delta.JSON.PartialJSON.Raw(),\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\tcase anthropic.ContentBlockStopEvent:\n\t\t\t\t\tif currentToolCallID != \"\" {\n\t\t\t\t\t\teventChan <- ProviderEvent{\n\t\t\t\t\t\t\tType: EventToolUseStop,\n\t\t\t\t\t\t\tToolCall: &message.ToolCall{\n\t\t\t\t\t\t\t\tID: currentToolCallID,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcurrentToolCallID = \"\"\n\t\t\t\t\t} else {\n\t\t\t\t\t\teventChan <- ProviderEvent{Type: EventContentStop}\n\t\t\t\t\t}\n\n\t\t\t\tcase anthropic.MessageStopEvent:\n\t\t\t\t\tcontent := \"\"\n\t\t\t\t\tfor _, block := range accumulatedMessage.Content {\n\t\t\t\t\t\tif text, ok := block.AsAny().(anthropic.TextBlock); ok {\n\t\t\t\t\t\t\tcontent += text.Text\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\teventChan <- ProviderEvent{\n\t\t\t\t\t\tType: EventComplete,\n\t\t\t\t\t\tResponse: &ProviderResponse{\n\t\t\t\t\t\t\tContent: content,\n\t\t\t\t\t\t\tToolCalls: a.toolCalls(accumulatedMessage),\n\t\t\t\t\t\t\tUsage: a.usage(accumulatedMessage),\n\t\t\t\t\t\t\tFinishReason: a.finishReason(string(accumulatedMessage.StopReason)),\n\t\t\t\t\t\t},\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\terr := anthropicStream.Err()\n\t\t\tif err == nil || errors.Is(err, io.EOF) {\n\t\t\t\tclose(eventChan)\n\t\t\t\treturn\n\t\t\t}\n\t\t\t// If there is an error we are going to see if we can retry the call\n\t\t\tretry, after, retryErr := a.shouldRetry(attempts, err)\n\t\t\tif retryErr != nil {\n\t\t\t\teventChan <- ProviderEvent{Type: EventError, Error: retryErr}\n\t\t\t\tclose(eventChan)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif retry {\n\t\t\t\tlogging.WarnPersist(fmt.Sprintf(\"Retrying due to rate limit... attempt %d of %d\", attempts, maxRetries), logging.PersistTimeArg, time.Millisecond*time.Duration(after+100))\n\t\t\t\tselect {\n\t\t\t\tcase <-ctx.Done():\n\t\t\t\t\t// context cancelled\n\t\t\t\t\tif ctx.Err() != nil {\n\t\t\t\t\t\teventChan <- ProviderEvent{Type: EventError, Error: ctx.Err()}\n\t\t\t\t\t}\n\t\t\t\t\tclose(eventChan)\n\t\t\t\t\treturn\n\t\t\t\tcase <-time.After(time.Duration(after) * time.Millisecond):\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t\tif ctx.Err() != nil {\n\t\t\t\teventChan <- ProviderEvent{Type: EventError, Error: ctx.Err()}\n\t\t\t}\n\n\t\t\tclose(eventChan)\n\t\t\treturn\n\t\t}\n\t}()\n\treturn eventChan\n}\n\nfunc (a *anthropicClient) shouldRetry(attempts int, err error) (bool, int64, error) {\n\tvar apierr *anthropic.Error\n\tif !errors.As(err, &apierr) {\n\t\treturn false, 0, err\n\t}\n\n\tif apierr.StatusCode != 429 && apierr.StatusCode != 529 {\n\t\treturn false, 0, err\n\t}\n\n\tif attempts > maxRetries {\n\t\treturn false, 0, fmt.Errorf(\"maximum retry attempts reached for rate limit: %d retries\", maxRetries)\n\t}\n\n\tretryMs := 0\n\tretryAfterValues := apierr.Response.Header.Values(\"Retry-After\")\n\n\tbackoffMs := 2000 * (1 << (attempts - 1))\n\tjitterMs := int(float64(backoffMs) * 0.2)\n\tretryMs = backoffMs + jitterMs\n\tif len(retryAfterValues) > 0 {\n\t\tif _, err := fmt.Sscanf(retryAfterValues[0], \"%d\", &retryMs); err == nil {\n\t\t\tretryMs = retryMs * 1000\n\t\t}\n\t}\n\treturn true, int64(retryMs), nil\n}\n\nfunc (a *anthropicClient) toolCalls(msg anthropic.Message) []message.ToolCall {\n\tvar toolCalls []message.ToolCall\n\n\tfor _, block := range msg.Content {\n\t\tswitch variant := block.AsAny().(type) {\n\t\tcase anthropic.ToolUseBlock:\n\t\t\ttoolCall := message.ToolCall{\n\t\t\t\tID: variant.ID,\n\t\t\t\tName: variant.Name,\n\t\t\t\tInput: string(variant.Input),\n\t\t\t\tType: string(variant.Type),\n\t\t\t\tFinished: true,\n\t\t\t}\n\t\t\ttoolCalls = append(toolCalls, toolCall)\n\t\t}\n\t}\n\n\treturn toolCalls\n}\n\nfunc (a *anthropicClient) usage(msg anthropic.Message) TokenUsage {\n\treturn TokenUsage{\n\t\tInputTokens: msg.Usage.InputTokens,\n\t\tOutputTokens: msg.Usage.OutputTokens,\n\t\tCacheCreationTokens: msg.Usage.CacheCreationInputTokens,\n\t\tCacheReadTokens: msg.Usage.CacheReadInputTokens,\n\t}\n}\n\nfunc WithAnthropicBedrock(useBedrock bool) AnthropicOption {\n\treturn func(options *anthropicOptions) {\n\t\toptions.useBedrock = useBedrock\n\t}\n}\n\nfunc WithAnthropicDisableCache() AnthropicOption {\n\treturn func(options *anthropicOptions) {\n\t\toptions.disableCache = true\n\t}\n}\n\nfunc DefaultShouldThinkFn(s string) bool {\n\treturn strings.Contains(strings.ToLower(s), \"think\")\n}\n\nfunc WithAnthropicShouldThinkFn(fn func(string) bool) AnthropicOption {\n\treturn func(options *anthropicOptions) {\n\t\toptions.shouldThink = fn\n\t}\n}\n"], ["/opencode/cmd/root.go", "package cmd\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"os\"\n\t\"sync\"\n\t\"time\"\n\n\ttea \"github.com/charmbracelet/bubbletea\"\n\tzone \"github.com/lrstanley/bubblezone\"\n\t\"github.com/opencode-ai/opencode/internal/app\"\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/db\"\n\t\"github.com/opencode-ai/opencode/internal/format\"\n\t\"github.com/opencode-ai/opencode/internal/llm/agent\"\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n\t\"github.com/opencode-ai/opencode/internal/pubsub\"\n\t\"github.com/opencode-ai/opencode/internal/tui\"\n\t\"github.com/opencode-ai/opencode/internal/version\"\n\t\"github.com/spf13/cobra\"\n)\n\nvar rootCmd = &cobra.Command{\n\tUse: \"opencode\",\n\tShort: \"Terminal-based AI assistant for software development\",\n\tLong: `OpenCode is a powerful terminal-based AI assistant that helps with software development tasks.\nIt provides an interactive chat interface with AI capabilities, code analysis, and LSP integration\nto assist developers in writing, debugging, and understanding code directly from the terminal.`,\n\tExample: `\n # Run in interactive mode\n opencode\n\n # Run with debug logging\n opencode -d\n\n # Run with debug logging in a specific directory\n opencode -d -c /path/to/project\n\n # Print version\n opencode -v\n\n # Run a single non-interactive prompt\n opencode -p \"Explain the use of context in Go\"\n\n # Run a single non-interactive prompt with JSON output format\n opencode -p \"Explain the use of context in Go\" -f json\n `,\n\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t// If the help flag is set, show the help message\n\t\tif cmd.Flag(\"help\").Changed {\n\t\t\tcmd.Help()\n\t\t\treturn nil\n\t\t}\n\t\tif cmd.Flag(\"version\").Changed {\n\t\t\tfmt.Println(version.Version)\n\t\t\treturn nil\n\t\t}\n\n\t\t// Load the config\n\t\tdebug, _ := cmd.Flags().GetBool(\"debug\")\n\t\tcwd, _ := cmd.Flags().GetString(\"cwd\")\n\t\tprompt, _ := cmd.Flags().GetString(\"prompt\")\n\t\toutputFormat, _ := cmd.Flags().GetString(\"output-format\")\n\t\tquiet, _ := cmd.Flags().GetBool(\"quiet\")\n\n\t\t// Validate format option\n\t\tif !format.IsValid(outputFormat) {\n\t\t\treturn fmt.Errorf(\"invalid format option: %s\\n%s\", outputFormat, format.GetHelpText())\n\t\t}\n\n\t\tif cwd != \"\" {\n\t\t\terr := os.Chdir(cwd)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"failed to change directory: %v\", err)\n\t\t\t}\n\t\t}\n\t\tif cwd == \"\" {\n\t\t\tc, err := os.Getwd()\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"failed to get current working directory: %v\", err)\n\t\t\t}\n\t\t\tcwd = c\n\t\t}\n\t\t_, err := config.Load(cwd, debug)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Connect DB, this will also run migrations\n\t\tconn, err := db.Connect()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Create main context for the application\n\t\tctx, cancel := context.WithCancel(context.Background())\n\t\tdefer cancel()\n\n\t\tapp, err := app.New(ctx, conn)\n\t\tif err != nil {\n\t\t\tlogging.Error(\"Failed to create app: %v\", err)\n\t\t\treturn err\n\t\t}\n\t\t// Defer shutdown here so it runs for both interactive and non-interactive modes\n\t\tdefer app.Shutdown()\n\n\t\t// Initialize MCP tools early for both modes\n\t\tinitMCPTools(ctx, app)\n\n\t\t// Non-interactive mode\n\t\tif prompt != \"\" {\n\t\t\t// Run non-interactive flow using the App method\n\t\t\treturn app.RunNonInteractive(ctx, prompt, outputFormat, quiet)\n\t\t}\n\n\t\t// Interactive mode\n\t\t// Set up the TUI\n\t\tzone.NewGlobal()\n\t\tprogram := tea.NewProgram(\n\t\t\ttui.New(app),\n\t\t\ttea.WithAltScreen(),\n\t\t)\n\n\t\t// Setup the subscriptions, this will send services events to the TUI\n\t\tch, cancelSubs := setupSubscriptions(app, ctx)\n\n\t\t// Create a context for the TUI message handler\n\t\ttuiCtx, tuiCancel := context.WithCancel(ctx)\n\t\tvar tuiWg sync.WaitGroup\n\t\ttuiWg.Add(1)\n\n\t\t// Set up message handling for the TUI\n\t\tgo func() {\n\t\t\tdefer tuiWg.Done()\n\t\t\tdefer logging.RecoverPanic(\"TUI-message-handler\", func() {\n\t\t\t\tattemptTUIRecovery(program)\n\t\t\t})\n\n\t\t\tfor {\n\t\t\t\tselect {\n\t\t\t\tcase <-tuiCtx.Done():\n\t\t\t\t\tlogging.Info(\"TUI message handler shutting down\")\n\t\t\t\t\treturn\n\t\t\t\tcase msg, ok := <-ch:\n\t\t\t\t\tif !ok {\n\t\t\t\t\t\tlogging.Info(\"TUI message channel closed\")\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\tprogram.Send(msg)\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\n\t\t// Cleanup function for when the program exits\n\t\tcleanup := func() {\n\t\t\t// Shutdown the app\n\t\t\tapp.Shutdown()\n\n\t\t\t// Cancel subscriptions first\n\t\t\tcancelSubs()\n\n\t\t\t// Then cancel TUI message handler\n\t\t\ttuiCancel()\n\n\t\t\t// Wait for TUI message handler to finish\n\t\t\ttuiWg.Wait()\n\n\t\t\tlogging.Info(\"All goroutines cleaned up\")\n\t\t}\n\n\t\t// Run the TUI\n\t\tresult, err := program.Run()\n\t\tcleanup()\n\n\t\tif err != nil {\n\t\t\tlogging.Error(\"TUI error: %v\", err)\n\t\t\treturn fmt.Errorf(\"TUI error: %v\", err)\n\t\t}\n\n\t\tlogging.Info(\"TUI exited with result: %v\", result)\n\t\treturn nil\n\t},\n}\n\n// attemptTUIRecovery tries to recover the TUI after a panic\nfunc attemptTUIRecovery(program *tea.Program) {\n\tlogging.Info(\"Attempting to recover TUI after panic\")\n\n\t// We could try to restart the TUI or gracefully exit\n\t// For now, we'll just quit the program to avoid further issues\n\tprogram.Quit()\n}\n\nfunc initMCPTools(ctx context.Context, app *app.App) {\n\tgo func() {\n\t\tdefer logging.RecoverPanic(\"MCP-goroutine\", nil)\n\n\t\t// Create a context with timeout for the initial MCP tools fetch\n\t\tctxWithTimeout, cancel := context.WithTimeout(ctx, 30*time.Second)\n\t\tdefer cancel()\n\n\t\t// Set this up once with proper error handling\n\t\tagent.GetMcpTools(ctxWithTimeout, app.Permissions)\n\t\tlogging.Info(\"MCP message handling goroutine exiting\")\n\t}()\n}\n\nfunc setupSubscriber[T any](\n\tctx context.Context,\n\twg *sync.WaitGroup,\n\tname string,\n\tsubscriber func(context.Context) <-chan pubsub.Event[T],\n\toutputCh chan<- tea.Msg,\n) {\n\twg.Add(1)\n\tgo func() {\n\t\tdefer wg.Done()\n\t\tdefer logging.RecoverPanic(fmt.Sprintf(\"subscription-%s\", name), nil)\n\n\t\tsubCh := subscriber(ctx)\n\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase event, ok := <-subCh:\n\t\t\t\tif !ok {\n\t\t\t\t\tlogging.Info(\"subscription channel closed\", \"name\", name)\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tvar msg tea.Msg = event\n\n\t\t\t\tselect {\n\t\t\t\tcase outputCh <- msg:\n\t\t\t\tcase <-time.After(2 * time.Second):\n\t\t\t\t\tlogging.Warn(\"message dropped due to slow consumer\", \"name\", name)\n\t\t\t\tcase <-ctx.Done():\n\t\t\t\t\tlogging.Info(\"subscription cancelled\", \"name\", name)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\tcase <-ctx.Done():\n\t\t\t\tlogging.Info(\"subscription cancelled\", \"name\", name)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}()\n}\n\nfunc setupSubscriptions(app *app.App, parentCtx context.Context) (chan tea.Msg, func()) {\n\tch := make(chan tea.Msg, 100)\n\n\twg := sync.WaitGroup{}\n\tctx, cancel := context.WithCancel(parentCtx) // Inherit from parent context\n\n\tsetupSubscriber(ctx, &wg, \"logging\", logging.Subscribe, ch)\n\tsetupSubscriber(ctx, &wg, \"sessions\", app.Sessions.Subscribe, ch)\n\tsetupSubscriber(ctx, &wg, \"messages\", app.Messages.Subscribe, ch)\n\tsetupSubscriber(ctx, &wg, \"permissions\", app.Permissions.Subscribe, ch)\n\tsetupSubscriber(ctx, &wg, \"coderAgent\", app.CoderAgent.Subscribe, ch)\n\n\tcleanupFunc := func() {\n\t\tlogging.Info(\"Cancelling all subscriptions\")\n\t\tcancel() // Signal all goroutines to stop\n\n\t\twaitCh := make(chan struct{})\n\t\tgo func() {\n\t\t\tdefer logging.RecoverPanic(\"subscription-cleanup\", nil)\n\t\t\twg.Wait()\n\t\t\tclose(waitCh)\n\t\t}()\n\n\t\tselect {\n\t\tcase <-waitCh:\n\t\t\tlogging.Info(\"All subscription goroutines completed successfully\")\n\t\t\tclose(ch) // Only close after all writers are confirmed done\n\t\tcase <-time.After(5 * time.Second):\n\t\t\tlogging.Warn(\"Timed out waiting for some subscription goroutines to complete\")\n\t\t\tclose(ch)\n\t\t}\n\t}\n\treturn ch, cleanupFunc\n}\n\nfunc Execute() {\n\terr := rootCmd.Execute()\n\tif err != nil {\n\t\tos.Exit(1)\n\t}\n}\n\nfunc init() {\n\trootCmd.Flags().BoolP(\"help\", \"h\", false, \"Help\")\n\trootCmd.Flags().BoolP(\"version\", \"v\", false, \"Version\")\n\trootCmd.Flags().BoolP(\"debug\", \"d\", false, \"Debug\")\n\trootCmd.Flags().StringP(\"cwd\", \"c\", \"\", \"Current working directory\")\n\trootCmd.Flags().StringP(\"prompt\", \"p\", \"\", \"Prompt to run in non-interactive mode\")\n\n\t// Add format flag with validation logic\n\trootCmd.Flags().StringP(\"output-format\", \"f\", format.Text.String(),\n\t\t\"Output format for non-interactive mode (text, json)\")\n\n\t// Add quiet flag to hide spinner in non-interactive mode\n\trootCmd.Flags().BoolP(\"quiet\", \"q\", false, \"Hide spinner in non-interactive mode\")\n\n\t// Register custom validation for the format flag\n\trootCmd.RegisterFlagCompletionFunc(\"output-format\", func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {\n\t\treturn format.SupportedFormats, cobra.ShellCompDirectiveNoFileComp\n\t})\n}\n"], ["/opencode/internal/tui/styles/styles.go", "package styles\n\nimport (\n\t\"github.com/charmbracelet/lipgloss\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n)\n\nvar (\n\tImageBakcground = \"#212121\"\n)\n\n// Style generation functions that use the current theme\n\n// BaseStyle returns the base style with background and foreground colors\nfunc BaseStyle() lipgloss.Style {\n\tt := theme.CurrentTheme()\n\treturn lipgloss.NewStyle().\n\t\tBackground(t.Background()).\n\t\tForeground(t.Text())\n}\n\n// Regular returns a basic unstyled lipgloss.Style\nfunc Regular() lipgloss.Style {\n\treturn lipgloss.NewStyle()\n}\n\n// Bold returns a bold style\nfunc Bold() lipgloss.Style {\n\treturn Regular().Bold(true)\n}\n\n// Padded returns a style with horizontal padding\nfunc Padded() lipgloss.Style {\n\treturn Regular().Padding(0, 1)\n}\n\n// Border returns a style with a normal border\nfunc Border() lipgloss.Style {\n\tt := theme.CurrentTheme()\n\treturn Regular().\n\t\tBorder(lipgloss.NormalBorder()).\n\t\tBorderForeground(t.BorderNormal())\n}\n\n// ThickBorder returns a style with a thick border\nfunc ThickBorder() lipgloss.Style {\n\tt := theme.CurrentTheme()\n\treturn Regular().\n\t\tBorder(lipgloss.ThickBorder()).\n\t\tBorderForeground(t.BorderNormal())\n}\n\n// DoubleBorder returns a style with a double border\nfunc DoubleBorder() lipgloss.Style {\n\tt := theme.CurrentTheme()\n\treturn Regular().\n\t\tBorder(lipgloss.DoubleBorder()).\n\t\tBorderForeground(t.BorderNormal())\n}\n\n// FocusedBorder returns a style with a border using the focused border color\nfunc FocusedBorder() lipgloss.Style {\n\tt := theme.CurrentTheme()\n\treturn Regular().\n\t\tBorder(lipgloss.NormalBorder()).\n\t\tBorderForeground(t.BorderFocused())\n}\n\n// DimBorder returns a style with a border using the dim border color\nfunc DimBorder() lipgloss.Style {\n\tt := theme.CurrentTheme()\n\treturn Regular().\n\t\tBorder(lipgloss.NormalBorder()).\n\t\tBorderForeground(t.BorderDim())\n}\n\n// PrimaryColor returns the primary color from the current theme\nfunc PrimaryColor() lipgloss.AdaptiveColor {\n\treturn theme.CurrentTheme().Primary()\n}\n\n// SecondaryColor returns the secondary color from the current theme\nfunc SecondaryColor() lipgloss.AdaptiveColor {\n\treturn theme.CurrentTheme().Secondary()\n}\n\n// AccentColor returns the accent color from the current theme\nfunc AccentColor() lipgloss.AdaptiveColor {\n\treturn theme.CurrentTheme().Accent()\n}\n\n// ErrorColor returns the error color from the current theme\nfunc ErrorColor() lipgloss.AdaptiveColor {\n\treturn theme.CurrentTheme().Error()\n}\n\n// WarningColor returns the warning color from the current theme\nfunc WarningColor() lipgloss.AdaptiveColor {\n\treturn theme.CurrentTheme().Warning()\n}\n\n// SuccessColor returns the success color from the current theme\nfunc SuccessColor() lipgloss.AdaptiveColor {\n\treturn theme.CurrentTheme().Success()\n}\n\n// InfoColor returns the info color from the current theme\nfunc InfoColor() lipgloss.AdaptiveColor {\n\treturn theme.CurrentTheme().Info()\n}\n\n// TextColor returns the text color from the current theme\nfunc TextColor() lipgloss.AdaptiveColor {\n\treturn theme.CurrentTheme().Text()\n}\n\n// TextMutedColor returns the muted text color from the current theme\nfunc TextMutedColor() lipgloss.AdaptiveColor {\n\treturn theme.CurrentTheme().TextMuted()\n}\n\n// TextEmphasizedColor returns the emphasized text color from the current theme\nfunc TextEmphasizedColor() lipgloss.AdaptiveColor {\n\treturn theme.CurrentTheme().TextEmphasized()\n}\n\n// BackgroundColor returns the background color from the current theme\nfunc BackgroundColor() lipgloss.AdaptiveColor {\n\treturn theme.CurrentTheme().Background()\n}\n\n// BackgroundSecondaryColor returns the secondary background color from the current theme\nfunc BackgroundSecondaryColor() lipgloss.AdaptiveColor {\n\treturn theme.CurrentTheme().BackgroundSecondary()\n}\n\n// BackgroundDarkerColor returns the darker background color from the current theme\nfunc BackgroundDarkerColor() lipgloss.AdaptiveColor {\n\treturn theme.CurrentTheme().BackgroundDarker()\n}\n\n// BorderNormalColor returns the normal border color from the current theme\nfunc BorderNormalColor() lipgloss.AdaptiveColor {\n\treturn theme.CurrentTheme().BorderNormal()\n}\n\n// BorderFocusedColor returns the focused border color from the current theme\nfunc BorderFocusedColor() lipgloss.AdaptiveColor {\n\treturn theme.CurrentTheme().BorderFocused()\n}\n\n// BorderDimColor returns the dim border color from the current theme\nfunc BorderDimColor() lipgloss.AdaptiveColor {\n\treturn theme.CurrentTheme().BorderDim()\n}\n"], ["/opencode/internal/llm/provider/openai.go", "package provider\n\nimport (\n\t\"context\"\n\t\"encoding/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"time\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n\t\"github.com/openai/openai-go/shared\"\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/llm/models\"\n\t\"github.com/opencode-ai/opencode/internal/llm/tools\"\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n\t\"github.com/opencode-ai/opencode/internal/message\"\n)\n\ntype openaiOptions struct {\n\tbaseURL string\n\tdisableCache bool\n\treasoningEffort string\n\textraHeaders map[string]string\n}\n\ntype OpenAIOption func(*openaiOptions)\n\ntype openaiClient struct {\n\tproviderOptions providerClientOptions\n\toptions openaiOptions\n\tclient openai.Client\n}\n\ntype OpenAIClient ProviderClient\n\nfunc newOpenAIClient(opts providerClientOptions) OpenAIClient {\n\topenaiOpts := openaiOptions{\n\t\treasoningEffort: \"medium\",\n\t}\n\tfor _, o := range opts.openaiOptions {\n\t\to(&openaiOpts)\n\t}\n\n\topenaiClientOptions := []option.RequestOption{}\n\tif opts.apiKey != \"\" {\n\t\topenaiClientOptions = append(openaiClientOptions, option.WithAPIKey(opts.apiKey))\n\t}\n\tif openaiOpts.baseURL != \"\" {\n\t\topenaiClientOptions = append(openaiClientOptions, option.WithBaseURL(openaiOpts.baseURL))\n\t}\n\n\tif openaiOpts.extraHeaders != nil {\n\t\tfor key, value := range openaiOpts.extraHeaders {\n\t\t\topenaiClientOptions = append(openaiClientOptions, option.WithHeader(key, value))\n\t\t}\n\t}\n\n\tclient := openai.NewClient(openaiClientOptions...)\n\treturn &openaiClient{\n\t\tproviderOptions: opts,\n\t\toptions: openaiOpts,\n\t\tclient: client,\n\t}\n}\n\nfunc (o *openaiClient) convertMessages(messages []message.Message) (openaiMessages []openai.ChatCompletionMessageParamUnion) {\n\t// Add system message first\n\topenaiMessages = append(openaiMessages, openai.SystemMessage(o.providerOptions.systemMessage))\n\n\tfor _, msg := range messages {\n\t\tswitch msg.Role {\n\t\tcase message.User:\n\t\t\tvar content []openai.ChatCompletionContentPartUnionParam\n\t\t\ttextBlock := openai.ChatCompletionContentPartTextParam{Text: msg.Content().String()}\n\t\t\tcontent = append(content, openai.ChatCompletionContentPartUnionParam{OfText: &textBlock})\n\t\t\tfor _, binaryContent := range msg.BinaryContent() {\n\t\t\t\timageURL := openai.ChatCompletionContentPartImageImageURLParam{URL: binaryContent.String(models.ProviderOpenAI)}\n\t\t\t\timageBlock := openai.ChatCompletionContentPartImageParam{ImageURL: imageURL}\n\n\t\t\t\tcontent = append(content, openai.ChatCompletionContentPartUnionParam{OfImageURL: &imageBlock})\n\t\t\t}\n\n\t\t\topenaiMessages = append(openaiMessages, openai.UserMessage(content))\n\n\t\tcase message.Assistant:\n\t\t\tassistantMsg := openai.ChatCompletionAssistantMessageParam{\n\t\t\t\tRole: \"assistant\",\n\t\t\t}\n\n\t\t\tif msg.Content().String() != \"\" {\n\t\t\t\tassistantMsg.Content = openai.ChatCompletionAssistantMessageParamContentUnion{\n\t\t\t\t\tOfString: openai.String(msg.Content().String()),\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif len(msg.ToolCalls()) > 0 {\n\t\t\t\tassistantMsg.ToolCalls = make([]openai.ChatCompletionMessageToolCallParam, len(msg.ToolCalls()))\n\t\t\t\tfor i, call := range msg.ToolCalls() {\n\t\t\t\t\tassistantMsg.ToolCalls[i] = openai.ChatCompletionMessageToolCallParam{\n\t\t\t\t\t\tID: call.ID,\n\t\t\t\t\t\tType: \"function\",\n\t\t\t\t\t\tFunction: openai.ChatCompletionMessageToolCallFunctionParam{\n\t\t\t\t\t\t\tName: call.Name,\n\t\t\t\t\t\t\tArguments: call.Input,\n\t\t\t\t\t\t},\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\topenaiMessages = append(openaiMessages, openai.ChatCompletionMessageParamUnion{\n\t\t\t\tOfAssistant: &assistantMsg,\n\t\t\t})\n\n\t\tcase message.Tool:\n\t\t\tfor _, result := range msg.ToolResults() {\n\t\t\t\topenaiMessages = append(openaiMessages,\n\t\t\t\t\topenai.ToolMessage(result.Content, result.ToolCallID),\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn\n}\n\nfunc (o *openaiClient) convertTools(tools []tools.BaseTool) []openai.ChatCompletionToolParam {\n\topenaiTools := make([]openai.ChatCompletionToolParam, len(tools))\n\n\tfor i, tool := range tools {\n\t\tinfo := tool.Info()\n\t\topenaiTools[i] = openai.ChatCompletionToolParam{\n\t\t\tFunction: openai.FunctionDefinitionParam{\n\t\t\t\tName: info.Name,\n\t\t\t\tDescription: openai.String(info.Description),\n\t\t\t\tParameters: openai.FunctionParameters{\n\t\t\t\t\t\"type\": \"object\",\n\t\t\t\t\t\"properties\": info.Parameters,\n\t\t\t\t\t\"required\": info.Required,\n\t\t\t\t},\n\t\t\t},\n\t\t}\n\t}\n\n\treturn openaiTools\n}\n\nfunc (o *openaiClient) finishReason(reason string) message.FinishReason {\n\tswitch reason {\n\tcase \"stop\":\n\t\treturn message.FinishReasonEndTurn\n\tcase \"length\":\n\t\treturn message.FinishReasonMaxTokens\n\tcase \"tool_calls\":\n\t\treturn message.FinishReasonToolUse\n\tdefault:\n\t\treturn message.FinishReasonUnknown\n\t}\n}\n\nfunc (o *openaiClient) preparedParams(messages []openai.ChatCompletionMessageParamUnion, tools []openai.ChatCompletionToolParam) openai.ChatCompletionNewParams {\n\tparams := openai.ChatCompletionNewParams{\n\t\tModel: openai.ChatModel(o.providerOptions.model.APIModel),\n\t\tMessages: messages,\n\t\tTools: tools,\n\t}\n\n\tif o.providerOptions.model.CanReason == true {\n\t\tparams.MaxCompletionTokens = openai.Int(o.providerOptions.maxTokens)\n\t\tswitch o.options.reasoningEffort {\n\t\tcase \"low\":\n\t\t\tparams.ReasoningEffort = shared.ReasoningEffortLow\n\t\tcase \"medium\":\n\t\t\tparams.ReasoningEffort = shared.ReasoningEffortMedium\n\t\tcase \"high\":\n\t\t\tparams.ReasoningEffort = shared.ReasoningEffortHigh\n\t\tdefault:\n\t\t\tparams.ReasoningEffort = shared.ReasoningEffortMedium\n\t\t}\n\t} else {\n\t\tparams.MaxTokens = openai.Int(o.providerOptions.maxTokens)\n\t}\n\n\treturn params\n}\n\nfunc (o *openaiClient) send(ctx context.Context, messages []message.Message, tools []tools.BaseTool) (response *ProviderResponse, err error) {\n\tparams := o.preparedParams(o.convertMessages(messages), o.convertTools(tools))\n\tcfg := config.Get()\n\tif cfg.Debug {\n\t\tjsonData, _ := json.Marshal(params)\n\t\tlogging.Debug(\"Prepared messages\", \"messages\", string(jsonData))\n\t}\n\tattempts := 0\n\tfor {\n\t\tattempts++\n\t\topenaiResponse, err := o.client.Chat.Completions.New(\n\t\t\tctx,\n\t\t\tparams,\n\t\t)\n\t\t// If there is an error we are going to see if we can retry the call\n\t\tif err != nil {\n\t\t\tretry, after, retryErr := o.shouldRetry(attempts, err)\n\t\t\tif retryErr != nil {\n\t\t\t\treturn nil, retryErr\n\t\t\t}\n\t\t\tif retry {\n\t\t\t\tlogging.WarnPersist(fmt.Sprintf(\"Retrying due to rate limit... attempt %d of %d\", attempts, maxRetries), logging.PersistTimeArg, time.Millisecond*time.Duration(after+100))\n\t\t\t\tselect {\n\t\t\t\tcase <-ctx.Done():\n\t\t\t\t\treturn nil, ctx.Err()\n\t\t\t\tcase <-time.After(time.Duration(after) * time.Millisecond):\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn nil, retryErr\n\t\t}\n\n\t\tcontent := \"\"\n\t\tif openaiResponse.Choices[0].Message.Content != \"\" {\n\t\t\tcontent = openaiResponse.Choices[0].Message.Content\n\t\t}\n\n\t\ttoolCalls := o.toolCalls(*openaiResponse)\n\t\tfinishReason := o.finishReason(string(openaiResponse.Choices[0].FinishReason))\n\n\t\tif len(toolCalls) > 0 {\n\t\t\tfinishReason = message.FinishReasonToolUse\n\t\t}\n\n\t\treturn &ProviderResponse{\n\t\t\tContent: content,\n\t\t\tToolCalls: toolCalls,\n\t\t\tUsage: o.usage(*openaiResponse),\n\t\t\tFinishReason: finishReason,\n\t\t}, nil\n\t}\n}\n\nfunc (o *openaiClient) stream(ctx context.Context, messages []message.Message, tools []tools.BaseTool) <-chan ProviderEvent {\n\tparams := o.preparedParams(o.convertMessages(messages), o.convertTools(tools))\n\tparams.StreamOptions = openai.ChatCompletionStreamOptionsParam{\n\t\tIncludeUsage: openai.Bool(true),\n\t}\n\n\tcfg := config.Get()\n\tif cfg.Debug {\n\t\tjsonData, _ := json.Marshal(params)\n\t\tlogging.Debug(\"Prepared messages\", \"messages\", string(jsonData))\n\t}\n\n\tattempts := 0\n\teventChan := make(chan ProviderEvent)\n\n\tgo func() {\n\t\tfor {\n\t\t\tattempts++\n\t\t\topenaiStream := o.client.Chat.Completions.NewStreaming(\n\t\t\t\tctx,\n\t\t\t\tparams,\n\t\t\t)\n\n\t\t\tacc := openai.ChatCompletionAccumulator{}\n\t\t\tcurrentContent := \"\"\n\t\t\ttoolCalls := make([]message.ToolCall, 0)\n\n\t\t\tfor openaiStream.Next() {\n\t\t\t\tchunk := openaiStream.Current()\n\t\t\t\tacc.AddChunk(chunk)\n\n\t\t\t\tfor _, choice := range chunk.Choices {\n\t\t\t\t\tif choice.Delta.Content != \"\" {\n\t\t\t\t\t\teventChan <- ProviderEvent{\n\t\t\t\t\t\t\tType: EventContentDelta,\n\t\t\t\t\t\t\tContent: choice.Delta.Content,\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcurrentContent += choice.Delta.Content\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\terr := openaiStream.Err()\n\t\t\tif err == nil || errors.Is(err, io.EOF) {\n\t\t\t\t// Stream completed successfully\n\t\t\t\tfinishReason := o.finishReason(string(acc.ChatCompletion.Choices[0].FinishReason))\n\t\t\t\tif len(acc.ChatCompletion.Choices[0].Message.ToolCalls) > 0 {\n\t\t\t\t\ttoolCalls = append(toolCalls, o.toolCalls(acc.ChatCompletion)...)\n\t\t\t\t}\n\t\t\t\tif len(toolCalls) > 0 {\n\t\t\t\t\tfinishReason = message.FinishReasonToolUse\n\t\t\t\t}\n\n\t\t\t\teventChan <- ProviderEvent{\n\t\t\t\t\tType: EventComplete,\n\t\t\t\t\tResponse: &ProviderResponse{\n\t\t\t\t\t\tContent: currentContent,\n\t\t\t\t\t\tToolCalls: toolCalls,\n\t\t\t\t\t\tUsage: o.usage(acc.ChatCompletion),\n\t\t\t\t\t\tFinishReason: finishReason,\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t\tclose(eventChan)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\t// If there is an error we are going to see if we can retry the call\n\t\t\tretry, after, retryErr := o.shouldRetry(attempts, err)\n\t\t\tif retryErr != nil {\n\t\t\t\teventChan <- ProviderEvent{Type: EventError, Error: retryErr}\n\t\t\t\tclose(eventChan)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif retry {\n\t\t\t\tlogging.WarnPersist(fmt.Sprintf(\"Retrying due to rate limit... attempt %d of %d\", attempts, maxRetries), logging.PersistTimeArg, time.Millisecond*time.Duration(after+100))\n\t\t\t\tselect {\n\t\t\t\tcase <-ctx.Done():\n\t\t\t\t\t// context cancelled\n\t\t\t\t\tif ctx.Err() == nil {\n\t\t\t\t\t\teventChan <- ProviderEvent{Type: EventError, Error: ctx.Err()}\n\t\t\t\t\t}\n\t\t\t\t\tclose(eventChan)\n\t\t\t\t\treturn\n\t\t\t\tcase <-time.After(time.Duration(after) * time.Millisecond):\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t\teventChan <- ProviderEvent{Type: EventError, Error: retryErr}\n\t\t\tclose(eventChan)\n\t\t\treturn\n\t\t}\n\t}()\n\n\treturn eventChan\n}\n\nfunc (o *openaiClient) shouldRetry(attempts int, err error) (bool, int64, error) {\n\tvar apierr *openai.Error\n\tif !errors.As(err, &apierr) {\n\t\treturn false, 0, err\n\t}\n\n\tif apierr.StatusCode != 429 && apierr.StatusCode != 500 {\n\t\treturn false, 0, err\n\t}\n\n\tif attempts > maxRetries {\n\t\treturn false, 0, fmt.Errorf(\"maximum retry attempts reached for rate limit: %d retries\", maxRetries)\n\t}\n\n\tretryMs := 0\n\tretryAfterValues := apierr.Response.Header.Values(\"Retry-After\")\n\n\tbackoffMs := 2000 * (1 << (attempts - 1))\n\tjitterMs := int(float64(backoffMs) * 0.2)\n\tretryMs = backoffMs + jitterMs\n\tif len(retryAfterValues) > 0 {\n\t\tif _, err := fmt.Sscanf(retryAfterValues[0], \"%d\", &retryMs); err == nil {\n\t\t\tretryMs = retryMs * 1000\n\t\t}\n\t}\n\treturn true, int64(retryMs), nil\n}\n\nfunc (o *openaiClient) toolCalls(completion openai.ChatCompletion) []message.ToolCall {\n\tvar toolCalls []message.ToolCall\n\n\tif len(completion.Choices) > 0 && len(completion.Choices[0].Message.ToolCalls) > 0 {\n\t\tfor _, call := range completion.Choices[0].Message.ToolCalls {\n\t\t\ttoolCall := message.ToolCall{\n\t\t\t\tID: call.ID,\n\t\t\t\tName: call.Function.Name,\n\t\t\t\tInput: call.Function.Arguments,\n\t\t\t\tType: \"function\",\n\t\t\t\tFinished: true,\n\t\t\t}\n\t\t\ttoolCalls = append(toolCalls, toolCall)\n\t\t}\n\t}\n\n\treturn toolCalls\n}\n\nfunc (o *openaiClient) usage(completion openai.ChatCompletion) TokenUsage {\n\tcachedTokens := completion.Usage.PromptTokensDetails.CachedTokens\n\tinputTokens := completion.Usage.PromptTokens - cachedTokens\n\n\treturn TokenUsage{\n\t\tInputTokens: inputTokens,\n\t\tOutputTokens: completion.Usage.CompletionTokens,\n\t\tCacheCreationTokens: 0, // OpenAI doesn't provide this directly\n\t\tCacheReadTokens: cachedTokens,\n\t}\n}\n\nfunc WithOpenAIBaseURL(baseURL string) OpenAIOption {\n\treturn func(options *openaiOptions) {\n\t\toptions.baseURL = baseURL\n\t}\n}\n\nfunc WithOpenAIExtraHeaders(headers map[string]string) OpenAIOption {\n\treturn func(options *openaiOptions) {\n\t\toptions.extraHeaders = headers\n\t}\n}\n\nfunc WithOpenAIDisableCache() OpenAIOption {\n\treturn func(options *openaiOptions) {\n\t\toptions.disableCache = true\n\t}\n}\n\nfunc WithReasoningEffort(effort string) OpenAIOption {\n\treturn func(options *openaiOptions) {\n\t\tdefaultReasoningEffort := \"medium\"\n\t\tswitch effort {\n\t\tcase \"low\", \"medium\", \"high\":\n\t\t\tdefaultReasoningEffort = effort\n\t\tdefault:\n\t\t\tlogging.Warn(\"Invalid reasoning effort, using default: medium\")\n\t\t}\n\t\toptions.reasoningEffort = defaultReasoningEffort\n\t}\n}\n"], ["/opencode/internal/tui/styles/markdown.go", "package styles\n\nimport (\n\t\"github.com/charmbracelet/glamour\"\n\t\"github.com/charmbracelet/glamour/ansi\"\n\t\"github.com/charmbracelet/lipgloss\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n)\n\nconst defaultMargin = 1\n\n// Helper functions for style pointers\nfunc boolPtr(b bool) *bool { return &b }\nfunc stringPtr(s string) *string { return &s }\nfunc uintPtr(u uint) *uint { return &u }\n\n// returns a glamour TermRenderer configured with the current theme\nfunc GetMarkdownRenderer(width int) *glamour.TermRenderer {\n\tr, _ := glamour.NewTermRenderer(\n\t\tglamour.WithStyles(generateMarkdownStyleConfig()),\n\t\tglamour.WithWordWrap(width),\n\t)\n\treturn r\n}\n\n// creates an ansi.StyleConfig for markdown rendering\n// using adaptive colors from the provided theme.\nfunc generateMarkdownStyleConfig() ansi.StyleConfig {\n\tt := theme.CurrentTheme()\n\n\treturn ansi.StyleConfig{\n\t\tDocument: ansi.StyleBlock{\n\t\t\tStylePrimitive: ansi.StylePrimitive{\n\t\t\t\tBlockPrefix: \"\",\n\t\t\t\tBlockSuffix: \"\",\n\t\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownText())),\n\t\t\t},\n\t\t\tMargin: uintPtr(defaultMargin),\n\t\t},\n\t\tBlockQuote: ansi.StyleBlock{\n\t\t\tStylePrimitive: ansi.StylePrimitive{\n\t\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownBlockQuote())),\n\t\t\t\tItalic: boolPtr(true),\n\t\t\t\tPrefix: \"┃ \",\n\t\t\t},\n\t\t\tIndent: uintPtr(1),\n\t\t\tIndentToken: stringPtr(BaseStyle().Render(\" \")),\n\t\t},\n\t\tList: ansi.StyleList{\n\t\t\tLevelIndent: defaultMargin,\n\t\t\tStyleBlock: ansi.StyleBlock{\n\t\t\t\tIndentToken: stringPtr(BaseStyle().Render(\" \")),\n\t\t\t\tStylePrimitive: ansi.StylePrimitive{\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownText())),\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\tHeading: ansi.StyleBlock{\n\t\t\tStylePrimitive: ansi.StylePrimitive{\n\t\t\t\tBlockSuffix: \"\\n\",\n\t\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownHeading())),\n\t\t\t\tBold: boolPtr(true),\n\t\t\t},\n\t\t},\n\t\tH1: ansi.StyleBlock{\n\t\t\tStylePrimitive: ansi.StylePrimitive{\n\t\t\t\tPrefix: \"# \",\n\t\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownHeading())),\n\t\t\t\tBold: boolPtr(true),\n\t\t\t},\n\t\t},\n\t\tH2: ansi.StyleBlock{\n\t\t\tStylePrimitive: ansi.StylePrimitive{\n\t\t\t\tPrefix: \"## \",\n\t\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownHeading())),\n\t\t\t\tBold: boolPtr(true),\n\t\t\t},\n\t\t},\n\t\tH3: ansi.StyleBlock{\n\t\t\tStylePrimitive: ansi.StylePrimitive{\n\t\t\t\tPrefix: \"### \",\n\t\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownHeading())),\n\t\t\t\tBold: boolPtr(true),\n\t\t\t},\n\t\t},\n\t\tH4: ansi.StyleBlock{\n\t\t\tStylePrimitive: ansi.StylePrimitive{\n\t\t\t\tPrefix: \"#### \",\n\t\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownHeading())),\n\t\t\t\tBold: boolPtr(true),\n\t\t\t},\n\t\t},\n\t\tH5: ansi.StyleBlock{\n\t\t\tStylePrimitive: ansi.StylePrimitive{\n\t\t\t\tPrefix: \"##### \",\n\t\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownHeading())),\n\t\t\t\tBold: boolPtr(true),\n\t\t\t},\n\t\t},\n\t\tH6: ansi.StyleBlock{\n\t\t\tStylePrimitive: ansi.StylePrimitive{\n\t\t\t\tPrefix: \"###### \",\n\t\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownHeading())),\n\t\t\t\tBold: boolPtr(true),\n\t\t\t},\n\t\t},\n\t\tStrikethrough: ansi.StylePrimitive{\n\t\t\tCrossedOut: boolPtr(true),\n\t\t\tColor: stringPtr(adaptiveColorToString(t.TextMuted())),\n\t\t},\n\t\tEmph: ansi.StylePrimitive{\n\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownEmph())),\n\t\t\tItalic: boolPtr(true),\n\t\t},\n\t\tStrong: ansi.StylePrimitive{\n\t\t\tBold: boolPtr(true),\n\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownStrong())),\n\t\t},\n\t\tHorizontalRule: ansi.StylePrimitive{\n\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownHorizontalRule())),\n\t\t\tFormat: \"\\n─────────────────────────────────────────\\n\",\n\t\t},\n\t\tItem: ansi.StylePrimitive{\n\t\t\tBlockPrefix: \"• \",\n\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownListItem())),\n\t\t},\n\t\tEnumeration: ansi.StylePrimitive{\n\t\t\tBlockPrefix: \". \",\n\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownListEnumeration())),\n\t\t},\n\t\tTask: ansi.StyleTask{\n\t\t\tStylePrimitive: ansi.StylePrimitive{},\n\t\t\tTicked: \"[✓] \",\n\t\t\tUnticked: \"[ ] \",\n\t\t},\n\t\tLink: ansi.StylePrimitive{\n\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownLink())),\n\t\t\tUnderline: boolPtr(true),\n\t\t},\n\t\tLinkText: ansi.StylePrimitive{\n\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownLinkText())),\n\t\t\tBold: boolPtr(true),\n\t\t},\n\t\tImage: ansi.StylePrimitive{\n\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownImage())),\n\t\t\tUnderline: boolPtr(true),\n\t\t\tFormat: \"🖼 {{.text}}\",\n\t\t},\n\t\tImageText: ansi.StylePrimitive{\n\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownImageText())),\n\t\t\tFormat: \"{{.text}}\",\n\t\t},\n\t\tCode: ansi.StyleBlock{\n\t\t\tStylePrimitive: ansi.StylePrimitive{\n\t\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownCode())),\n\t\t\t\tPrefix: \"\",\n\t\t\t\tSuffix: \"\",\n\t\t\t},\n\t\t},\n\t\tCodeBlock: ansi.StyleCodeBlock{\n\t\t\tStyleBlock: ansi.StyleBlock{\n\t\t\t\tStylePrimitive: ansi.StylePrimitive{\n\t\t\t\t\tPrefix: \" \",\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownCodeBlock())),\n\t\t\t\t},\n\t\t\t\tMargin: uintPtr(defaultMargin),\n\t\t\t},\n\t\t\tChroma: &ansi.Chroma{\n\t\t\t\tText: ansi.StylePrimitive{\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownText())),\n\t\t\t\t},\n\t\t\t\tError: ansi.StylePrimitive{\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.Error())),\n\t\t\t\t},\n\t\t\t\tComment: ansi.StylePrimitive{\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.SyntaxComment())),\n\t\t\t\t},\n\t\t\t\tCommentPreproc: ansi.StylePrimitive{\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.SyntaxKeyword())),\n\t\t\t\t},\n\t\t\t\tKeyword: ansi.StylePrimitive{\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.SyntaxKeyword())),\n\t\t\t\t},\n\t\t\t\tKeywordReserved: ansi.StylePrimitive{\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.SyntaxKeyword())),\n\t\t\t\t},\n\t\t\t\tKeywordNamespace: ansi.StylePrimitive{\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.SyntaxKeyword())),\n\t\t\t\t},\n\t\t\t\tKeywordType: ansi.StylePrimitive{\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.SyntaxType())),\n\t\t\t\t},\n\t\t\t\tOperator: ansi.StylePrimitive{\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.SyntaxOperator())),\n\t\t\t\t},\n\t\t\t\tPunctuation: ansi.StylePrimitive{\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.SyntaxPunctuation())),\n\t\t\t\t},\n\t\t\t\tName: ansi.StylePrimitive{\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.SyntaxVariable())),\n\t\t\t\t},\n\t\t\t\tNameBuiltin: ansi.StylePrimitive{\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.SyntaxVariable())),\n\t\t\t\t},\n\t\t\t\tNameTag: ansi.StylePrimitive{\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.SyntaxKeyword())),\n\t\t\t\t},\n\t\t\t\tNameAttribute: ansi.StylePrimitive{\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.SyntaxFunction())),\n\t\t\t\t},\n\t\t\t\tNameClass: ansi.StylePrimitive{\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.SyntaxType())),\n\t\t\t\t},\n\t\t\t\tNameConstant: ansi.StylePrimitive{\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.SyntaxVariable())),\n\t\t\t\t},\n\t\t\t\tNameDecorator: ansi.StylePrimitive{\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.SyntaxFunction())),\n\t\t\t\t},\n\t\t\t\tNameFunction: ansi.StylePrimitive{\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.SyntaxFunction())),\n\t\t\t\t},\n\t\t\t\tLiteralNumber: ansi.StylePrimitive{\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.SyntaxNumber())),\n\t\t\t\t},\n\t\t\t\tLiteralString: ansi.StylePrimitive{\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.SyntaxString())),\n\t\t\t\t},\n\t\t\t\tLiteralStringEscape: ansi.StylePrimitive{\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.SyntaxKeyword())),\n\t\t\t\t},\n\t\t\t\tGenericDeleted: ansi.StylePrimitive{\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.DiffRemoved())),\n\t\t\t\t},\n\t\t\t\tGenericEmph: ansi.StylePrimitive{\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownEmph())),\n\t\t\t\t\tItalic: boolPtr(true),\n\t\t\t\t},\n\t\t\t\tGenericInserted: ansi.StylePrimitive{\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.DiffAdded())),\n\t\t\t\t},\n\t\t\t\tGenericStrong: ansi.StylePrimitive{\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownStrong())),\n\t\t\t\t\tBold: boolPtr(true),\n\t\t\t\t},\n\t\t\t\tGenericSubheading: ansi.StylePrimitive{\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownHeading())),\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\tTable: ansi.StyleTable{\n\t\t\tStyleBlock: ansi.StyleBlock{\n\t\t\t\tStylePrimitive: ansi.StylePrimitive{\n\t\t\t\t\tBlockPrefix: \"\\n\",\n\t\t\t\t\tBlockSuffix: \"\\n\",\n\t\t\t\t},\n\t\t\t},\n\t\t\tCenterSeparator: stringPtr(\"┼\"),\n\t\t\tColumnSeparator: stringPtr(\"│\"),\n\t\t\tRowSeparator: stringPtr(\"─\"),\n\t\t},\n\t\tDefinitionDescription: ansi.StylePrimitive{\n\t\t\tBlockPrefix: \"\\n ❯ \",\n\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownLinkText())),\n\t\t},\n\t\tText: ansi.StylePrimitive{\n\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownText())),\n\t\t},\n\t\tParagraph: ansi.StyleBlock{\n\t\t\tStylePrimitive: ansi.StylePrimitive{\n\t\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownText())),\n\t\t\t},\n\t\t},\n\t}\n}\n\n// adaptiveColorToString converts a lipgloss.AdaptiveColor to the appropriate\n// hex color string based on the current terminal background\nfunc adaptiveColorToString(color lipgloss.AdaptiveColor) string {\n\tif lipgloss.HasDarkBackground() {\n\t\treturn color.Dark\n\t}\n\treturn color.Light\n}\n"], ["/opencode/internal/config/config.go", "// Package config manages application configuration from various sources.\npackage config\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"log/slog\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"runtime\"\n\t\"strings\"\n\n\t\"github.com/opencode-ai/opencode/internal/llm/models\"\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n\t\"github.com/spf13/viper\"\n)\n\n// MCPType defines the type of MCP (Model Control Protocol) server.\ntype MCPType string\n\n// Supported MCP types\nconst (\n\tMCPStdio MCPType = \"stdio\"\n\tMCPSse MCPType = \"sse\"\n)\n\n// MCPServer defines the configuration for a Model Control Protocol server.\ntype MCPServer struct {\n\tCommand string `json:\"command\"`\n\tEnv []string `json:\"env\"`\n\tArgs []string `json:\"args\"`\n\tType MCPType `json:\"type\"`\n\tURL string `json:\"url\"`\n\tHeaders map[string]string `json:\"headers\"`\n}\n\ntype AgentName string\n\nconst (\n\tAgentCoder AgentName = \"coder\"\n\tAgentSummarizer AgentName = \"summarizer\"\n\tAgentTask AgentName = \"task\"\n\tAgentTitle AgentName = \"title\"\n)\n\n// Agent defines configuration for different LLM models and their token limits.\ntype Agent struct {\n\tModel models.ModelID `json:\"model\"`\n\tMaxTokens int64 `json:\"maxTokens\"`\n\tReasoningEffort string `json:\"reasoningEffort\"` // For openai models low,medium,heigh\n}\n\n// Provider defines configuration for an LLM provider.\ntype Provider struct {\n\tAPIKey string `json:\"apiKey\"`\n\tDisabled bool `json:\"disabled\"`\n}\n\n// Data defines storage configuration.\ntype Data struct {\n\tDirectory string `json:\"directory,omitempty\"`\n}\n\n// LSPConfig defines configuration for Language Server Protocol integration.\ntype LSPConfig struct {\n\tDisabled bool `json:\"enabled\"`\n\tCommand string `json:\"command\"`\n\tArgs []string `json:\"args\"`\n\tOptions any `json:\"options\"`\n}\n\n// TUIConfig defines the configuration for the Terminal User Interface.\ntype TUIConfig struct {\n\tTheme string `json:\"theme,omitempty\"`\n}\n\n// ShellConfig defines the configuration for the shell used by the bash tool.\ntype ShellConfig struct {\n\tPath string `json:\"path,omitempty\"`\n\tArgs []string `json:\"args,omitempty\"`\n}\n\n// Config is the main configuration structure for the application.\ntype Config struct {\n\tData Data `json:\"data\"`\n\tWorkingDir string `json:\"wd,omitempty\"`\n\tMCPServers map[string]MCPServer `json:\"mcpServers,omitempty\"`\n\tProviders map[models.ModelProvider]Provider `json:\"providers,omitempty\"`\n\tLSP map[string]LSPConfig `json:\"lsp,omitempty\"`\n\tAgents map[AgentName]Agent `json:\"agents,omitempty\"`\n\tDebug bool `json:\"debug,omitempty\"`\n\tDebugLSP bool `json:\"debugLSP,omitempty\"`\n\tContextPaths []string `json:\"contextPaths,omitempty\"`\n\tTUI TUIConfig `json:\"tui\"`\n\tShell ShellConfig `json:\"shell,omitempty\"`\n\tAutoCompact bool `json:\"autoCompact,omitempty\"`\n}\n\n// Application constants\nconst (\n\tdefaultDataDirectory = \".opencode\"\n\tdefaultLogLevel = \"info\"\n\tappName = \"opencode\"\n\n\tMaxTokensFallbackDefault = 4096\n)\n\nvar defaultContextPaths = []string{\n\t\".github/copilot-instructions.md\",\n\t\".cursorrules\",\n\t\".cursor/rules/\",\n\t\"CLAUDE.md\",\n\t\"CLAUDE.local.md\",\n\t\"opencode.md\",\n\t\"opencode.local.md\",\n\t\"OpenCode.md\",\n\t\"OpenCode.local.md\",\n\t\"OPENCODE.md\",\n\t\"OPENCODE.local.md\",\n}\n\n// Global configuration instance\nvar cfg *Config\n\n// Load initializes the configuration from environment variables and config files.\n// If debug is true, debug mode is enabled and log level is set to debug.\n// It returns an error if configuration loading fails.\nfunc Load(workingDir string, debug bool) (*Config, error) {\n\tif cfg != nil {\n\t\treturn cfg, nil\n\t}\n\n\tcfg = &Config{\n\t\tWorkingDir: workingDir,\n\t\tMCPServers: make(map[string]MCPServer),\n\t\tProviders: make(map[models.ModelProvider]Provider),\n\t\tLSP: make(map[string]LSPConfig),\n\t}\n\n\tconfigureViper()\n\tsetDefaults(debug)\n\n\t// Read global config\n\tif err := readConfig(viper.ReadInConfig()); err != nil {\n\t\treturn cfg, err\n\t}\n\n\t// Load and merge local config\n\tmergeLocalConfig(workingDir)\n\n\tsetProviderDefaults()\n\n\t// Apply configuration to the struct\n\tif err := viper.Unmarshal(cfg); err != nil {\n\t\treturn cfg, fmt.Errorf(\"failed to unmarshal config: %w\", err)\n\t}\n\n\tapplyDefaultValues()\n\tdefaultLevel := slog.LevelInfo\n\tif cfg.Debug {\n\t\tdefaultLevel = slog.LevelDebug\n\t}\n\tif os.Getenv(\"OPENCODE_DEV_DEBUG\") == \"true\" {\n\t\tloggingFile := fmt.Sprintf(\"%s/%s\", cfg.Data.Directory, \"debug.log\")\n\t\tmessagesPath := fmt.Sprintf(\"%s/%s\", cfg.Data.Directory, \"messages\")\n\n\t\t// if file does not exist create it\n\t\tif _, err := os.Stat(loggingFile); os.IsNotExist(err) {\n\t\t\tif err := os.MkdirAll(cfg.Data.Directory, 0o755); err != nil {\n\t\t\t\treturn cfg, fmt.Errorf(\"failed to create directory: %w\", err)\n\t\t\t}\n\t\t\tif _, err := os.Create(loggingFile); err != nil {\n\t\t\t\treturn cfg, fmt.Errorf(\"failed to create log file: %w\", err)\n\t\t\t}\n\t\t}\n\n\t\tif _, err := os.Stat(messagesPath); os.IsNotExist(err) {\n\t\t\tif err := os.MkdirAll(messagesPath, 0o756); err != nil {\n\t\t\t\treturn cfg, fmt.Errorf(\"failed to create directory: %w\", err)\n\t\t\t}\n\t\t}\n\t\tlogging.MessageDir = messagesPath\n\n\t\tsloggingFileWriter, err := os.OpenFile(loggingFile, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o666)\n\t\tif err != nil {\n\t\t\treturn cfg, fmt.Errorf(\"failed to open log file: %w\", err)\n\t\t}\n\t\t// Configure logger\n\t\tlogger := slog.New(slog.NewTextHandler(sloggingFileWriter, &slog.HandlerOptions{\n\t\t\tLevel: defaultLevel,\n\t\t}))\n\t\tslog.SetDefault(logger)\n\t} else {\n\t\t// Configure logger\n\t\tlogger := slog.New(slog.NewTextHandler(logging.NewWriter(), &slog.HandlerOptions{\n\t\t\tLevel: defaultLevel,\n\t\t}))\n\t\tslog.SetDefault(logger)\n\t}\n\n\t// Validate configuration\n\tif err := Validate(); err != nil {\n\t\treturn cfg, fmt.Errorf(\"config validation failed: %w\", err)\n\t}\n\n\tif cfg.Agents == nil {\n\t\tcfg.Agents = make(map[AgentName]Agent)\n\t}\n\n\t// Override the max tokens for title agent\n\tcfg.Agents[AgentTitle] = Agent{\n\t\tModel: cfg.Agents[AgentTitle].Model,\n\t\tMaxTokens: 80,\n\t}\n\treturn cfg, nil\n}\n\n// configureViper sets up viper's configuration paths and environment variables.\nfunc configureViper() {\n\tviper.SetConfigName(fmt.Sprintf(\".%s\", appName))\n\tviper.SetConfigType(\"json\")\n\tviper.AddConfigPath(\"$HOME\")\n\tviper.AddConfigPath(fmt.Sprintf(\"$XDG_CONFIG_HOME/%s\", appName))\n\tviper.AddConfigPath(fmt.Sprintf(\"$HOME/.config/%s\", appName))\n\tviper.SetEnvPrefix(strings.ToUpper(appName))\n\tviper.AutomaticEnv()\n}\n\n// setDefaults configures default values for configuration options.\nfunc setDefaults(debug bool) {\n\tviper.SetDefault(\"data.directory\", defaultDataDirectory)\n\tviper.SetDefault(\"contextPaths\", defaultContextPaths)\n\tviper.SetDefault(\"tui.theme\", \"opencode\")\n\tviper.SetDefault(\"autoCompact\", true)\n\n\t// Set default shell from environment or fallback to /bin/bash\n\tshellPath := os.Getenv(\"SHELL\")\n\tif shellPath == \"\" {\n\t\tshellPath = \"/bin/bash\"\n\t}\n\tviper.SetDefault(\"shell.path\", shellPath)\n\tviper.SetDefault(\"shell.args\", []string{\"-l\"})\n\n\tif debug {\n\t\tviper.SetDefault(\"debug\", true)\n\t\tviper.Set(\"log.level\", \"debug\")\n\t} else {\n\t\tviper.SetDefault(\"debug\", false)\n\t\tviper.SetDefault(\"log.level\", defaultLogLevel)\n\t}\n}\n\n// setProviderDefaults configures LLM provider defaults based on provider provided by\n// environment variables and configuration file.\nfunc setProviderDefaults() {\n\t// Set all API keys we can find in the environment\n\t// Note: Viper does not default if the json apiKey is \"\"\n\tif apiKey := os.Getenv(\"ANTHROPIC_API_KEY\"); apiKey != \"\" {\n\t\tviper.SetDefault(\"providers.anthropic.apiKey\", apiKey)\n\t}\n\tif apiKey := os.Getenv(\"OPENAI_API_KEY\"); apiKey != \"\" {\n\t\tviper.SetDefault(\"providers.openai.apiKey\", apiKey)\n\t}\n\tif apiKey := os.Getenv(\"GEMINI_API_KEY\"); apiKey != \"\" {\n\t\tviper.SetDefault(\"providers.gemini.apiKey\", apiKey)\n\t}\n\tif apiKey := os.Getenv(\"GROQ_API_KEY\"); apiKey != \"\" {\n\t\tviper.SetDefault(\"providers.groq.apiKey\", apiKey)\n\t}\n\tif apiKey := os.Getenv(\"OPENROUTER_API_KEY\"); apiKey != \"\" {\n\t\tviper.SetDefault(\"providers.openrouter.apiKey\", apiKey)\n\t}\n\tif apiKey := os.Getenv(\"XAI_API_KEY\"); apiKey != \"\" {\n\t\tviper.SetDefault(\"providers.xai.apiKey\", apiKey)\n\t}\n\tif apiKey := os.Getenv(\"AZURE_OPENAI_ENDPOINT\"); apiKey != \"\" {\n\t\t// api-key may be empty when using Entra ID credentials – that's okay\n\t\tviper.SetDefault(\"providers.azure.apiKey\", os.Getenv(\"AZURE_OPENAI_API_KEY\"))\n\t}\n\tif apiKey, err := LoadGitHubToken(); err == nil && apiKey != \"\" {\n\t\tviper.SetDefault(\"providers.copilot.apiKey\", apiKey)\n\t\tif viper.GetString(\"providers.copilot.apiKey\") == \"\" {\n\t\t\tviper.Set(\"providers.copilot.apiKey\", apiKey)\n\t\t}\n\t}\n\n\t// Use this order to set the default models\n\t// 1. Copilot\n\t// 2. Anthropic\n\t// 3. OpenAI\n\t// 4. Google Gemini\n\t// 5. Groq\n\t// 6. OpenRouter\n\t// 7. AWS Bedrock\n\t// 8. Azure\n\t// 9. Google Cloud VertexAI\n\n\t// copilot configuration\n\tif key := viper.GetString(\"providers.copilot.apiKey\"); strings.TrimSpace(key) != \"\" {\n\t\tviper.SetDefault(\"agents.coder.model\", models.CopilotGPT4o)\n\t\tviper.SetDefault(\"agents.summarizer.model\", models.CopilotGPT4o)\n\t\tviper.SetDefault(\"agents.task.model\", models.CopilotGPT4o)\n\t\tviper.SetDefault(\"agents.title.model\", models.CopilotGPT4o)\n\t\treturn\n\t}\n\n\t// Anthropic configuration\n\tif key := viper.GetString(\"providers.anthropic.apiKey\"); strings.TrimSpace(key) != \"\" {\n\t\tviper.SetDefault(\"agents.coder.model\", models.Claude4Sonnet)\n\t\tviper.SetDefault(\"agents.summarizer.model\", models.Claude4Sonnet)\n\t\tviper.SetDefault(\"agents.task.model\", models.Claude4Sonnet)\n\t\tviper.SetDefault(\"agents.title.model\", models.Claude4Sonnet)\n\t\treturn\n\t}\n\n\t// OpenAI configuration\n\tif key := viper.GetString(\"providers.openai.apiKey\"); strings.TrimSpace(key) != \"\" {\n\t\tviper.SetDefault(\"agents.coder.model\", models.GPT41)\n\t\tviper.SetDefault(\"agents.summarizer.model\", models.GPT41)\n\t\tviper.SetDefault(\"agents.task.model\", models.GPT41Mini)\n\t\tviper.SetDefault(\"agents.title.model\", models.GPT41Mini)\n\t\treturn\n\t}\n\n\t// Google Gemini configuration\n\tif key := viper.GetString(\"providers.gemini.apiKey\"); strings.TrimSpace(key) != \"\" {\n\t\tviper.SetDefault(\"agents.coder.model\", models.Gemini25)\n\t\tviper.SetDefault(\"agents.summarizer.model\", models.Gemini25)\n\t\tviper.SetDefault(\"agents.task.model\", models.Gemini25Flash)\n\t\tviper.SetDefault(\"agents.title.model\", models.Gemini25Flash)\n\t\treturn\n\t}\n\n\t// Groq configuration\n\tif key := viper.GetString(\"providers.groq.apiKey\"); strings.TrimSpace(key) != \"\" {\n\t\tviper.SetDefault(\"agents.coder.model\", models.QWENQwq)\n\t\tviper.SetDefault(\"agents.summarizer.model\", models.QWENQwq)\n\t\tviper.SetDefault(\"agents.task.model\", models.QWENQwq)\n\t\tviper.SetDefault(\"agents.title.model\", models.QWENQwq)\n\t\treturn\n\t}\n\n\t// OpenRouter configuration\n\tif key := viper.GetString(\"providers.openrouter.apiKey\"); strings.TrimSpace(key) != \"\" {\n\t\tviper.SetDefault(\"agents.coder.model\", models.OpenRouterClaude37Sonnet)\n\t\tviper.SetDefault(\"agents.summarizer.model\", models.OpenRouterClaude37Sonnet)\n\t\tviper.SetDefault(\"agents.task.model\", models.OpenRouterClaude37Sonnet)\n\t\tviper.SetDefault(\"agents.title.model\", models.OpenRouterClaude35Haiku)\n\t\treturn\n\t}\n\n\t// XAI configuration\n\tif key := viper.GetString(\"providers.xai.apiKey\"); strings.TrimSpace(key) != \"\" {\n\t\tviper.SetDefault(\"agents.coder.model\", models.XAIGrok3Beta)\n\t\tviper.SetDefault(\"agents.summarizer.model\", models.XAIGrok3Beta)\n\t\tviper.SetDefault(\"agents.task.model\", models.XAIGrok3Beta)\n\t\tviper.SetDefault(\"agents.title.model\", models.XAiGrok3MiniFastBeta)\n\t\treturn\n\t}\n\n\t// AWS Bedrock configuration\n\tif hasAWSCredentials() {\n\t\tviper.SetDefault(\"agents.coder.model\", models.BedrockClaude37Sonnet)\n\t\tviper.SetDefault(\"agents.summarizer.model\", models.BedrockClaude37Sonnet)\n\t\tviper.SetDefault(\"agents.task.model\", models.BedrockClaude37Sonnet)\n\t\tviper.SetDefault(\"agents.title.model\", models.BedrockClaude37Sonnet)\n\t\treturn\n\t}\n\n\t// Azure OpenAI configuration\n\tif os.Getenv(\"AZURE_OPENAI_ENDPOINT\") != \"\" {\n\t\tviper.SetDefault(\"agents.coder.model\", models.AzureGPT41)\n\t\tviper.SetDefault(\"agents.summarizer.model\", models.AzureGPT41)\n\t\tviper.SetDefault(\"agents.task.model\", models.AzureGPT41Mini)\n\t\tviper.SetDefault(\"agents.title.model\", models.AzureGPT41Mini)\n\t\treturn\n\t}\n\n\t// Google Cloud VertexAI configuration\n\tif hasVertexAICredentials() {\n\t\tviper.SetDefault(\"agents.coder.model\", models.VertexAIGemini25)\n\t\tviper.SetDefault(\"agents.summarizer.model\", models.VertexAIGemini25)\n\t\tviper.SetDefault(\"agents.task.model\", models.VertexAIGemini25Flash)\n\t\tviper.SetDefault(\"agents.title.model\", models.VertexAIGemini25Flash)\n\t\treturn\n\t}\n}\n\n// hasAWSCredentials checks if AWS credentials are available in the environment.\nfunc hasAWSCredentials() bool {\n\t// Check for explicit AWS credentials\n\tif os.Getenv(\"AWS_ACCESS_KEY_ID\") != \"\" && os.Getenv(\"AWS_SECRET_ACCESS_KEY\") != \"\" {\n\t\treturn true\n\t}\n\n\t// Check for AWS profile\n\tif os.Getenv(\"AWS_PROFILE\") != \"\" || os.Getenv(\"AWS_DEFAULT_PROFILE\") != \"\" {\n\t\treturn true\n\t}\n\n\t// Check for AWS region\n\tif os.Getenv(\"AWS_REGION\") != \"\" || os.Getenv(\"AWS_DEFAULT_REGION\") != \"\" {\n\t\treturn true\n\t}\n\n\t// Check if running on EC2 with instance profile\n\tif os.Getenv(\"AWS_CONTAINER_CREDENTIALS_RELATIVE_URI\") != \"\" ||\n\t\tos.Getenv(\"AWS_CONTAINER_CREDENTIALS_FULL_URI\") != \"\" {\n\t\treturn true\n\t}\n\n\treturn false\n}\n\n// hasVertexAICredentials checks if VertexAI credentials are available in the environment.\nfunc hasVertexAICredentials() bool {\n\t// Check for explicit VertexAI parameters\n\tif os.Getenv(\"VERTEXAI_PROJECT\") != \"\" && os.Getenv(\"VERTEXAI_LOCATION\") != \"\" {\n\t\treturn true\n\t}\n\t// Check for Google Cloud project and location\n\tif os.Getenv(\"GOOGLE_CLOUD_PROJECT\") != \"\" && (os.Getenv(\"GOOGLE_CLOUD_REGION\") != \"\" || os.Getenv(\"GOOGLE_CLOUD_LOCATION\") != \"\") {\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc hasCopilotCredentials() bool {\n\t// Check for explicit Copilot parameters\n\tif token, _ := LoadGitHubToken(); token != \"\" {\n\t\treturn true\n\t}\n\treturn false\n}\n\n// readConfig handles the result of reading a configuration file.\nfunc readConfig(err error) error {\n\tif err == nil {\n\t\treturn nil\n\t}\n\n\t// It's okay if the config file doesn't exist\n\tif _, ok := err.(viper.ConfigFileNotFoundError); ok {\n\t\treturn nil\n\t}\n\n\treturn fmt.Errorf(\"failed to read config: %w\", err)\n}\n\n// mergeLocalConfig loads and merges configuration from the local directory.\nfunc mergeLocalConfig(workingDir string) {\n\tlocal := viper.New()\n\tlocal.SetConfigName(fmt.Sprintf(\".%s\", appName))\n\tlocal.SetConfigType(\"json\")\n\tlocal.AddConfigPath(workingDir)\n\n\t// Merge local config if it exists\n\tif err := local.ReadInConfig(); err == nil {\n\t\tviper.MergeConfigMap(local.AllSettings())\n\t}\n}\n\n// applyDefaultValues sets default values for configuration fields that need processing.\nfunc applyDefaultValues() {\n\t// Set default MCP type if not specified\n\tfor k, v := range cfg.MCPServers {\n\t\tif v.Type == \"\" {\n\t\t\tv.Type = MCPStdio\n\t\t\tcfg.MCPServers[k] = v\n\t\t}\n\t}\n}\n\n// It validates model IDs and providers, ensuring they are supported.\nfunc validateAgent(cfg *Config, name AgentName, agent Agent) error {\n\t// Check if model exists\n\t// TODO:\tIf a copilot model is specified, but model is not found,\n\t// \t\t \tit might be new model. The https://api.githubcopilot.com/models\n\t// \t\t \tendpoint should be queried to validate if the model is supported.\n\tmodel, modelExists := models.SupportedModels[agent.Model]\n\tif !modelExists {\n\t\tlogging.Warn(\"unsupported model configured, reverting to default\",\n\t\t\t\"agent\", name,\n\t\t\t\"configured_model\", agent.Model)\n\n\t\t// Set default model based on available providers\n\t\tif setDefaultModelForAgent(name) {\n\t\t\tlogging.Info(\"set default model for agent\", \"agent\", name, \"model\", cfg.Agents[name].Model)\n\t\t} else {\n\t\t\treturn fmt.Errorf(\"no valid provider available for agent %s\", name)\n\t\t}\n\t\treturn nil\n\t}\n\n\t// Check if provider for the model is configured\n\tprovider := model.Provider\n\tproviderCfg, providerExists := cfg.Providers[provider]\n\n\tif !providerExists {\n\t\t// Provider not configured, check if we have environment variables\n\t\tapiKey := getProviderAPIKey(provider)\n\t\tif apiKey == \"\" {\n\t\t\tlogging.Warn(\"provider not configured for model, reverting to default\",\n\t\t\t\t\"agent\", name,\n\t\t\t\t\"model\", agent.Model,\n\t\t\t\t\"provider\", provider)\n\n\t\t\t// Set default model based on available providers\n\t\t\tif setDefaultModelForAgent(name) {\n\t\t\t\tlogging.Info(\"set default model for agent\", \"agent\", name, \"model\", cfg.Agents[name].Model)\n\t\t\t} else {\n\t\t\t\treturn fmt.Errorf(\"no valid provider available for agent %s\", name)\n\t\t\t}\n\t\t} else {\n\t\t\t// Add provider with API key from environment\n\t\t\tcfg.Providers[provider] = Provider{\n\t\t\t\tAPIKey: apiKey,\n\t\t\t}\n\t\t\tlogging.Info(\"added provider from environment\", \"provider\", provider)\n\t\t}\n\t} else if providerCfg.Disabled || providerCfg.APIKey == \"\" {\n\t\t// Provider is disabled or has no API key\n\t\tlogging.Warn(\"provider is disabled or has no API key, reverting to default\",\n\t\t\t\"agent\", name,\n\t\t\t\"model\", agent.Model,\n\t\t\t\"provider\", provider)\n\n\t\t// Set default model based on available providers\n\t\tif setDefaultModelForAgent(name) {\n\t\t\tlogging.Info(\"set default model for agent\", \"agent\", name, \"model\", cfg.Agents[name].Model)\n\t\t} else {\n\t\t\treturn fmt.Errorf(\"no valid provider available for agent %s\", name)\n\t\t}\n\t}\n\n\t// Validate max tokens\n\tif agent.MaxTokens <= 0 {\n\t\tlogging.Warn(\"invalid max tokens, setting to default\",\n\t\t\t\"agent\", name,\n\t\t\t\"model\", agent.Model,\n\t\t\t\"max_tokens\", agent.MaxTokens)\n\n\t\t// Update the agent with default max tokens\n\t\tupdatedAgent := cfg.Agents[name]\n\t\tif model.DefaultMaxTokens > 0 {\n\t\t\tupdatedAgent.MaxTokens = model.DefaultMaxTokens\n\t\t} else {\n\t\t\tupdatedAgent.MaxTokens = MaxTokensFallbackDefault\n\t\t}\n\t\tcfg.Agents[name] = updatedAgent\n\t} else if model.ContextWindow > 0 && agent.MaxTokens > model.ContextWindow/2 {\n\t\t// Ensure max tokens doesn't exceed half the context window (reasonable limit)\n\t\tlogging.Warn(\"max tokens exceeds half the context window, adjusting\",\n\t\t\t\"agent\", name,\n\t\t\t\"model\", agent.Model,\n\t\t\t\"max_tokens\", agent.MaxTokens,\n\t\t\t\"context_window\", model.ContextWindow)\n\n\t\t// Update the agent with adjusted max tokens\n\t\tupdatedAgent := cfg.Agents[name]\n\t\tupdatedAgent.MaxTokens = model.ContextWindow / 2\n\t\tcfg.Agents[name] = updatedAgent\n\t}\n\n\t// Validate reasoning effort for models that support reasoning\n\tif model.CanReason && provider == models.ProviderOpenAI || provider == models.ProviderLocal {\n\t\tif agent.ReasoningEffort == \"\" {\n\t\t\t// Set default reasoning effort for models that support it\n\t\t\tlogging.Info(\"setting default reasoning effort for model that supports reasoning\",\n\t\t\t\t\"agent\", name,\n\t\t\t\t\"model\", agent.Model)\n\n\t\t\t// Update the agent with default reasoning effort\n\t\t\tupdatedAgent := cfg.Agents[name]\n\t\t\tupdatedAgent.ReasoningEffort = \"medium\"\n\t\t\tcfg.Agents[name] = updatedAgent\n\t\t} else {\n\t\t\t// Check if reasoning effort is valid (low, medium, high)\n\t\t\teffort := strings.ToLower(agent.ReasoningEffort)\n\t\t\tif effort != \"low\" && effort != \"medium\" && effort != \"high\" {\n\t\t\t\tlogging.Warn(\"invalid reasoning effort, setting to medium\",\n\t\t\t\t\t\"agent\", name,\n\t\t\t\t\t\"model\", agent.Model,\n\t\t\t\t\t\"reasoning_effort\", agent.ReasoningEffort)\n\n\t\t\t\t// Update the agent with valid reasoning effort\n\t\t\t\tupdatedAgent := cfg.Agents[name]\n\t\t\t\tupdatedAgent.ReasoningEffort = \"medium\"\n\t\t\t\tcfg.Agents[name] = updatedAgent\n\t\t\t}\n\t\t}\n\t} else if !model.CanReason && agent.ReasoningEffort != \"\" {\n\t\t// Model doesn't support reasoning but reasoning effort is set\n\t\tlogging.Warn(\"model doesn't support reasoning but reasoning effort is set, ignoring\",\n\t\t\t\"agent\", name,\n\t\t\t\"model\", agent.Model,\n\t\t\t\"reasoning_effort\", agent.ReasoningEffort)\n\n\t\t// Update the agent to remove reasoning effort\n\t\tupdatedAgent := cfg.Agents[name]\n\t\tupdatedAgent.ReasoningEffort = \"\"\n\t\tcfg.Agents[name] = updatedAgent\n\t}\n\n\treturn nil\n}\n\n// Validate checks if the configuration is valid and applies defaults where needed.\nfunc Validate() error {\n\tif cfg == nil {\n\t\treturn fmt.Errorf(\"config not loaded\")\n\t}\n\n\t// Validate agent models\n\tfor name, agent := range cfg.Agents {\n\t\tif err := validateAgent(cfg, name, agent); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// Validate providers\n\tfor provider, providerCfg := range cfg.Providers {\n\t\tif providerCfg.APIKey == \"\" && !providerCfg.Disabled {\n\t\t\tfmt.Printf(\"provider has no API key, marking as disabled %s\", provider)\n\t\t\tlogging.Warn(\"provider has no API key, marking as disabled\", \"provider\", provider)\n\t\t\tproviderCfg.Disabled = true\n\t\t\tcfg.Providers[provider] = providerCfg\n\t\t}\n\t}\n\n\t// Validate LSP configurations\n\tfor language, lspConfig := range cfg.LSP {\n\t\tif lspConfig.Command == \"\" && !lspConfig.Disabled {\n\t\t\tlogging.Warn(\"LSP configuration has no command, marking as disabled\", \"language\", language)\n\t\t\tlspConfig.Disabled = true\n\t\t\tcfg.LSP[language] = lspConfig\n\t\t}\n\t}\n\n\treturn nil\n}\n\n// getProviderAPIKey gets the API key for a provider from environment variables\nfunc getProviderAPIKey(provider models.ModelProvider) string {\n\tswitch provider {\n\tcase models.ProviderAnthropic:\n\t\treturn os.Getenv(\"ANTHROPIC_API_KEY\")\n\tcase models.ProviderOpenAI:\n\t\treturn os.Getenv(\"OPENAI_API_KEY\")\n\tcase models.ProviderGemini:\n\t\treturn os.Getenv(\"GEMINI_API_KEY\")\n\tcase models.ProviderGROQ:\n\t\treturn os.Getenv(\"GROQ_API_KEY\")\n\tcase models.ProviderAzure:\n\t\treturn os.Getenv(\"AZURE_OPENAI_API_KEY\")\n\tcase models.ProviderOpenRouter:\n\t\treturn os.Getenv(\"OPENROUTER_API_KEY\")\n\tcase models.ProviderBedrock:\n\t\tif hasAWSCredentials() {\n\t\t\treturn \"aws-credentials-available\"\n\t\t}\n\tcase models.ProviderVertexAI:\n\t\tif hasVertexAICredentials() {\n\t\t\treturn \"vertex-ai-credentials-available\"\n\t\t}\n\t}\n\treturn \"\"\n}\n\n// setDefaultModelForAgent sets a default model for an agent based on available providers\nfunc setDefaultModelForAgent(agent AgentName) bool {\n\tif hasCopilotCredentials() {\n\t\tmaxTokens := int64(5000)\n\t\tif agent == AgentTitle {\n\t\t\tmaxTokens = 80\n\t\t}\n\n\t\tcfg.Agents[agent] = Agent{\n\t\t\tModel: models.CopilotGPT4o,\n\t\t\tMaxTokens: maxTokens,\n\t\t}\n\t\treturn true\n\t}\n\t// Check providers in order of preference\n\tif apiKey := os.Getenv(\"ANTHROPIC_API_KEY\"); apiKey != \"\" {\n\t\tmaxTokens := int64(5000)\n\t\tif agent == AgentTitle {\n\t\t\tmaxTokens = 80\n\t\t}\n\t\tcfg.Agents[agent] = Agent{\n\t\t\tModel: models.Claude37Sonnet,\n\t\t\tMaxTokens: maxTokens,\n\t\t}\n\t\treturn true\n\t}\n\n\tif apiKey := os.Getenv(\"OPENAI_API_KEY\"); apiKey != \"\" {\n\t\tvar model models.ModelID\n\t\tmaxTokens := int64(5000)\n\t\treasoningEffort := \"\"\n\n\t\tswitch agent {\n\t\tcase AgentTitle:\n\t\t\tmodel = models.GPT41Mini\n\t\t\tmaxTokens = 80\n\t\tcase AgentTask:\n\t\t\tmodel = models.GPT41Mini\n\t\tdefault:\n\t\t\tmodel = models.GPT41\n\t\t}\n\n\t\t// Check if model supports reasoning\n\t\tif modelInfo, ok := models.SupportedModels[model]; ok && modelInfo.CanReason {\n\t\t\treasoningEffort = \"medium\"\n\t\t}\n\n\t\tcfg.Agents[agent] = Agent{\n\t\t\tModel: model,\n\t\t\tMaxTokens: maxTokens,\n\t\t\tReasoningEffort: reasoningEffort,\n\t\t}\n\t\treturn true\n\t}\n\n\tif apiKey := os.Getenv(\"OPENROUTER_API_KEY\"); apiKey != \"\" {\n\t\tvar model models.ModelID\n\t\tmaxTokens := int64(5000)\n\t\treasoningEffort := \"\"\n\n\t\tswitch agent {\n\t\tcase AgentTitle:\n\t\t\tmodel = models.OpenRouterClaude35Haiku\n\t\t\tmaxTokens = 80\n\t\tcase AgentTask:\n\t\t\tmodel = models.OpenRouterClaude37Sonnet\n\t\tdefault:\n\t\t\tmodel = models.OpenRouterClaude37Sonnet\n\t\t}\n\n\t\t// Check if model supports reasoning\n\t\tif modelInfo, ok := models.SupportedModels[model]; ok && modelInfo.CanReason {\n\t\t\treasoningEffort = \"medium\"\n\t\t}\n\n\t\tcfg.Agents[agent] = Agent{\n\t\t\tModel: model,\n\t\t\tMaxTokens: maxTokens,\n\t\t\tReasoningEffort: reasoningEffort,\n\t\t}\n\t\treturn true\n\t}\n\n\tif apiKey := os.Getenv(\"GEMINI_API_KEY\"); apiKey != \"\" {\n\t\tvar model models.ModelID\n\t\tmaxTokens := int64(5000)\n\n\t\tif agent == AgentTitle {\n\t\t\tmodel = models.Gemini25Flash\n\t\t\tmaxTokens = 80\n\t\t} else {\n\t\t\tmodel = models.Gemini25\n\t\t}\n\n\t\tcfg.Agents[agent] = Agent{\n\t\t\tModel: model,\n\t\t\tMaxTokens: maxTokens,\n\t\t}\n\t\treturn true\n\t}\n\n\tif apiKey := os.Getenv(\"GROQ_API_KEY\"); apiKey != \"\" {\n\t\tmaxTokens := int64(5000)\n\t\tif agent == AgentTitle {\n\t\t\tmaxTokens = 80\n\t\t}\n\n\t\tcfg.Agents[agent] = Agent{\n\t\t\tModel: models.QWENQwq,\n\t\t\tMaxTokens: maxTokens,\n\t\t}\n\t\treturn true\n\t}\n\n\tif hasAWSCredentials() {\n\t\tmaxTokens := int64(5000)\n\t\tif agent == AgentTitle {\n\t\t\tmaxTokens = 80\n\t\t}\n\n\t\tcfg.Agents[agent] = Agent{\n\t\t\tModel: models.BedrockClaude37Sonnet,\n\t\t\tMaxTokens: maxTokens,\n\t\t\tReasoningEffort: \"medium\", // Claude models support reasoning\n\t\t}\n\t\treturn true\n\t}\n\n\tif hasVertexAICredentials() {\n\t\tvar model models.ModelID\n\t\tmaxTokens := int64(5000)\n\n\t\tif agent == AgentTitle {\n\t\t\tmodel = models.VertexAIGemini25Flash\n\t\t\tmaxTokens = 80\n\t\t} else {\n\t\t\tmodel = models.VertexAIGemini25\n\t\t}\n\n\t\tcfg.Agents[agent] = Agent{\n\t\t\tModel: model,\n\t\t\tMaxTokens: maxTokens,\n\t\t}\n\t\treturn true\n\t}\n\n\treturn false\n}\n\nfunc updateCfgFile(updateCfg func(config *Config)) error {\n\tif cfg == nil {\n\t\treturn fmt.Errorf(\"config not loaded\")\n\t}\n\n\t// Get the config file path\n\tconfigFile := viper.ConfigFileUsed()\n\tvar configData []byte\n\tif configFile == \"\" {\n\t\thomeDir, err := os.UserHomeDir()\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to get home directory: %w\", err)\n\t\t}\n\t\tconfigFile = filepath.Join(homeDir, fmt.Sprintf(\".%s.json\", appName))\n\t\tlogging.Info(\"config file not found, creating new one\", \"path\", configFile)\n\t\tconfigData = []byte(`{}`)\n\t} else {\n\t\t// Read the existing config file\n\t\tdata, err := os.ReadFile(configFile)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to read config file: %w\", err)\n\t\t}\n\t\tconfigData = data\n\t}\n\n\t// Parse the JSON\n\tvar userCfg *Config\n\tif err := json.Unmarshal(configData, &userCfg); err != nil {\n\t\treturn fmt.Errorf(\"failed to parse config file: %w\", err)\n\t}\n\n\tupdateCfg(userCfg)\n\n\t// Write the updated config back to file\n\tupdatedData, err := json.MarshalIndent(userCfg, \"\", \" \")\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to marshal config: %w\", err)\n\t}\n\n\tif err := os.WriteFile(configFile, updatedData, 0o644); err != nil {\n\t\treturn fmt.Errorf(\"failed to write config file: %w\", err)\n\t}\n\n\treturn nil\n}\n\n// Get returns the current configuration.\n// It's safe to call this function multiple times.\nfunc Get() *Config {\n\treturn cfg\n}\n\n// WorkingDirectory returns the current working directory from the configuration.\nfunc WorkingDirectory() string {\n\tif cfg == nil {\n\t\tpanic(\"config not loaded\")\n\t}\n\treturn cfg.WorkingDir\n}\n\nfunc UpdateAgentModel(agentName AgentName, modelID models.ModelID) error {\n\tif cfg == nil {\n\t\tpanic(\"config not loaded\")\n\t}\n\n\texistingAgentCfg := cfg.Agents[agentName]\n\n\tmodel, ok := models.SupportedModels[modelID]\n\tif !ok {\n\t\treturn fmt.Errorf(\"model %s not supported\", modelID)\n\t}\n\n\tmaxTokens := existingAgentCfg.MaxTokens\n\tif model.DefaultMaxTokens > 0 {\n\t\tmaxTokens = model.DefaultMaxTokens\n\t}\n\n\tnewAgentCfg := Agent{\n\t\tModel: modelID,\n\t\tMaxTokens: maxTokens,\n\t\tReasoningEffort: existingAgentCfg.ReasoningEffort,\n\t}\n\tcfg.Agents[agentName] = newAgentCfg\n\n\tif err := validateAgent(cfg, agentName, newAgentCfg); err != nil {\n\t\t// revert config update on failure\n\t\tcfg.Agents[agentName] = existingAgentCfg\n\t\treturn fmt.Errorf(\"failed to update agent model: %w\", err)\n\t}\n\n\treturn updateCfgFile(func(config *Config) {\n\t\tif config.Agents == nil {\n\t\t\tconfig.Agents = make(map[AgentName]Agent)\n\t\t}\n\t\tconfig.Agents[agentName] = newAgentCfg\n\t})\n}\n\n// UpdateTheme updates the theme in the configuration and writes it to the config file.\nfunc UpdateTheme(themeName string) error {\n\tif cfg == nil {\n\t\treturn fmt.Errorf(\"config not loaded\")\n\t}\n\n\t// Update the in-memory config\n\tcfg.TUI.Theme = themeName\n\n\t// Update the file config\n\treturn updateCfgFile(func(config *Config) {\n\t\tconfig.TUI.Theme = themeName\n\t})\n}\n\n// Tries to load Github token from all possible locations\nfunc LoadGitHubToken() (string, error) {\n\t// First check environment variable\n\tif token := os.Getenv(\"GITHUB_TOKEN\"); token != \"\" {\n\t\treturn token, nil\n\t}\n\n\t// Get config directory\n\tvar configDir string\n\tif xdgConfig := os.Getenv(\"XDG_CONFIG_HOME\"); xdgConfig != \"\" {\n\t\tconfigDir = xdgConfig\n\t} else if runtime.GOOS == \"windows\" {\n\t\tif localAppData := os.Getenv(\"LOCALAPPDATA\"); localAppData != \"\" {\n\t\t\tconfigDir = localAppData\n\t\t} else {\n\t\t\tconfigDir = filepath.Join(os.Getenv(\"HOME\"), \"AppData\", \"Local\")\n\t\t}\n\t} else {\n\t\tconfigDir = filepath.Join(os.Getenv(\"HOME\"), \".config\")\n\t}\n\n\t// Try both hosts.json and apps.json files\n\tfilePaths := []string{\n\t\tfilepath.Join(configDir, \"github-copilot\", \"hosts.json\"),\n\t\tfilepath.Join(configDir, \"github-copilot\", \"apps.json\"),\n\t}\n\n\tfor _, filePath := range filePaths {\n\t\tdata, err := os.ReadFile(filePath)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tvar config map[string]map[string]interface{}\n\t\tif err := json.Unmarshal(data, &config); err != nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tfor key, value := range config {\n\t\t\tif strings.Contains(key, \"github.com\") {\n\t\t\t\tif oauthToken, ok := value[\"oauth_token\"].(string); ok {\n\t\t\t\t\treturn oauthToken, nil\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn \"\", fmt.Errorf(\"GitHub token not found in standard locations\")\n}\n"], ["/opencode/internal/lsp/client.go", "package lsp\n\nimport (\n\t\"bufio\"\n\t\"context\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"os/exec\"\n\t\"path/filepath\"\n\t\"strings\"\n\t\"sync\"\n\t\"sync/atomic\"\n\t\"time\"\n\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n\t\"github.com/opencode-ai/opencode/internal/lsp/protocol\"\n)\n\ntype Client struct {\n\tCmd *exec.Cmd\n\tstdin io.WriteCloser\n\tstdout *bufio.Reader\n\tstderr io.ReadCloser\n\n\t// Request ID counter\n\tnextID atomic.Int32\n\n\t// Response handlers\n\thandlers map[int32]chan *Message\n\thandlersMu sync.RWMutex\n\n\t// Server request handlers\n\tserverRequestHandlers map[string]ServerRequestHandler\n\tserverHandlersMu sync.RWMutex\n\n\t// Notification handlers\n\tnotificationHandlers map[string]NotificationHandler\n\tnotificationMu sync.RWMutex\n\n\t// Diagnostic cache\n\tdiagnostics map[protocol.DocumentUri][]protocol.Diagnostic\n\tdiagnosticsMu sync.RWMutex\n\n\t// Files are currently opened by the LSP\n\topenFiles map[string]*OpenFileInfo\n\topenFilesMu sync.RWMutex\n\n\t// Server state\n\tserverState atomic.Value\n}\n\nfunc NewClient(ctx context.Context, command string, args ...string) (*Client, error) {\n\tcmd := exec.CommandContext(ctx, command, args...)\n\t// Copy env\n\tcmd.Env = os.Environ()\n\n\tstdin, err := cmd.StdinPipe()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to create stdin pipe: %w\", err)\n\t}\n\n\tstdout, err := cmd.StdoutPipe()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to create stdout pipe: %w\", err)\n\t}\n\n\tstderr, err := cmd.StderrPipe()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to create stderr pipe: %w\", err)\n\t}\n\n\tclient := &Client{\n\t\tCmd: cmd,\n\t\tstdin: stdin,\n\t\tstdout: bufio.NewReader(stdout),\n\t\tstderr: stderr,\n\t\thandlers: make(map[int32]chan *Message),\n\t\tnotificationHandlers: make(map[string]NotificationHandler),\n\t\tserverRequestHandlers: make(map[string]ServerRequestHandler),\n\t\tdiagnostics: make(map[protocol.DocumentUri][]protocol.Diagnostic),\n\t\topenFiles: make(map[string]*OpenFileInfo),\n\t}\n\n\t// Initialize server state\n\tclient.serverState.Store(StateStarting)\n\n\t// Start the LSP server process\n\tif err := cmd.Start(); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to start LSP server: %w\", err)\n\t}\n\n\t// Handle stderr in a separate goroutine\n\tgo func() {\n\t\tscanner := bufio.NewScanner(stderr)\n\t\tfor scanner.Scan() {\n\t\t\tfmt.Fprintf(os.Stderr, \"LSP Server: %s\\n\", scanner.Text())\n\t\t}\n\t\tif err := scanner.Err(); err != nil {\n\t\t\tfmt.Fprintf(os.Stderr, \"Error reading stderr: %v\\n\", err)\n\t\t}\n\t}()\n\n\t// Start message handling loop\n\tgo func() {\n\t\tdefer logging.RecoverPanic(\"LSP-message-handler\", func() {\n\t\t\tlogging.ErrorPersist(\"LSP message handler crashed, LSP functionality may be impaired\")\n\t\t})\n\t\tclient.handleMessages()\n\t}()\n\n\treturn client, nil\n}\n\nfunc (c *Client) RegisterNotificationHandler(method string, handler NotificationHandler) {\n\tc.notificationMu.Lock()\n\tdefer c.notificationMu.Unlock()\n\tc.notificationHandlers[method] = handler\n}\n\nfunc (c *Client) RegisterServerRequestHandler(method string, handler ServerRequestHandler) {\n\tc.serverHandlersMu.Lock()\n\tdefer c.serverHandlersMu.Unlock()\n\tc.serverRequestHandlers[method] = handler\n}\n\nfunc (c *Client) InitializeLSPClient(ctx context.Context, workspaceDir string) (*protocol.InitializeResult, error) {\n\tinitParams := &protocol.InitializeParams{\n\t\tWorkspaceFoldersInitializeParams: protocol.WorkspaceFoldersInitializeParams{\n\t\t\tWorkspaceFolders: []protocol.WorkspaceFolder{\n\t\t\t\t{\n\t\t\t\t\tURI: protocol.URI(\"file://\" + workspaceDir),\n\t\t\t\t\tName: workspaceDir,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\n\t\tXInitializeParams: protocol.XInitializeParams{\n\t\t\tProcessID: int32(os.Getpid()),\n\t\t\tClientInfo: &protocol.ClientInfo{\n\t\t\t\tName: \"mcp-language-server\",\n\t\t\t\tVersion: \"0.1.0\",\n\t\t\t},\n\t\t\tRootPath: workspaceDir,\n\t\t\tRootURI: protocol.DocumentUri(\"file://\" + workspaceDir),\n\t\t\tCapabilities: protocol.ClientCapabilities{\n\t\t\t\tWorkspace: protocol.WorkspaceClientCapabilities{\n\t\t\t\t\tConfiguration: true,\n\t\t\t\t\tDidChangeConfiguration: protocol.DidChangeConfigurationClientCapabilities{\n\t\t\t\t\t\tDynamicRegistration: true,\n\t\t\t\t\t},\n\t\t\t\t\tDidChangeWatchedFiles: protocol.DidChangeWatchedFilesClientCapabilities{\n\t\t\t\t\t\tDynamicRegistration: true,\n\t\t\t\t\t\tRelativePatternSupport: true,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tTextDocument: protocol.TextDocumentClientCapabilities{\n\t\t\t\t\tSynchronization: &protocol.TextDocumentSyncClientCapabilities{\n\t\t\t\t\t\tDynamicRegistration: true,\n\t\t\t\t\t\tDidSave: true,\n\t\t\t\t\t},\n\t\t\t\t\tCompletion: protocol.CompletionClientCapabilities{\n\t\t\t\t\t\tCompletionItem: protocol.ClientCompletionItemOptions{},\n\t\t\t\t\t},\n\t\t\t\t\tCodeLens: &protocol.CodeLensClientCapabilities{\n\t\t\t\t\t\tDynamicRegistration: true,\n\t\t\t\t\t},\n\t\t\t\t\tDocumentSymbol: protocol.DocumentSymbolClientCapabilities{},\n\t\t\t\t\tCodeAction: protocol.CodeActionClientCapabilities{\n\t\t\t\t\t\tCodeActionLiteralSupport: protocol.ClientCodeActionLiteralOptions{\n\t\t\t\t\t\t\tCodeActionKind: protocol.ClientCodeActionKindOptions{\n\t\t\t\t\t\t\t\tValueSet: []protocol.CodeActionKind{},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\tPublishDiagnostics: protocol.PublishDiagnosticsClientCapabilities{\n\t\t\t\t\t\tVersionSupport: true,\n\t\t\t\t\t},\n\t\t\t\t\tSemanticTokens: protocol.SemanticTokensClientCapabilities{\n\t\t\t\t\t\tRequests: protocol.ClientSemanticTokensRequestOptions{\n\t\t\t\t\t\t\tRange: &protocol.Or_ClientSemanticTokensRequestOptions_range{},\n\t\t\t\t\t\t\tFull: &protocol.Or_ClientSemanticTokensRequestOptions_full{},\n\t\t\t\t\t\t},\n\t\t\t\t\t\tTokenTypes: []string{},\n\t\t\t\t\t\tTokenModifiers: []string{},\n\t\t\t\t\t\tFormats: []protocol.TokenFormat{},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tWindow: protocol.WindowClientCapabilities{},\n\t\t\t},\n\t\t\tInitializationOptions: map[string]any{\n\t\t\t\t\"codelenses\": map[string]bool{\n\t\t\t\t\t\"generate\": true,\n\t\t\t\t\t\"regenerate_cgo\": true,\n\t\t\t\t\t\"test\": true,\n\t\t\t\t\t\"tidy\": true,\n\t\t\t\t\t\"upgrade_dependency\": true,\n\t\t\t\t\t\"vendor\": true,\n\t\t\t\t\t\"vulncheck\": false,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\tvar result protocol.InitializeResult\n\tif err := c.Call(ctx, \"initialize\", initParams, &result); err != nil {\n\t\treturn nil, fmt.Errorf(\"initialize failed: %w\", err)\n\t}\n\n\tif err := c.Notify(ctx, \"initialized\", struct{}{}); err != nil {\n\t\treturn nil, fmt.Errorf(\"initialized notification failed: %w\", err)\n\t}\n\n\t// Register handlers\n\tc.RegisterServerRequestHandler(\"workspace/applyEdit\", HandleApplyEdit)\n\tc.RegisterServerRequestHandler(\"workspace/configuration\", HandleWorkspaceConfiguration)\n\tc.RegisterServerRequestHandler(\"client/registerCapability\", HandleRegisterCapability)\n\tc.RegisterNotificationHandler(\"window/showMessage\", HandleServerMessage)\n\tc.RegisterNotificationHandler(\"textDocument/publishDiagnostics\",\n\t\tfunc(params json.RawMessage) { HandleDiagnostics(c, params) })\n\n\t// Notify the LSP server\n\terr := c.Initialized(ctx, protocol.InitializedParams{})\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"initialization failed: %w\", err)\n\t}\n\n\treturn &result, nil\n}\n\nfunc (c *Client) Close() error {\n\t// Try to close all open files first\n\tctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)\n\tdefer cancel()\n\n\t// Attempt to close files but continue shutdown regardless\n\tc.CloseAllFiles(ctx)\n\n\t// Close stdin to signal the server\n\tif err := c.stdin.Close(); err != nil {\n\t\treturn fmt.Errorf(\"failed to close stdin: %w\", err)\n\t}\n\n\t// Use a channel to handle the Wait with timeout\n\tdone := make(chan error, 1)\n\tgo func() {\n\t\tdone <- c.Cmd.Wait()\n\t}()\n\n\t// Wait for process to exit with timeout\n\tselect {\n\tcase err := <-done:\n\t\treturn err\n\tcase <-time.After(2 * time.Second):\n\t\t// If we timeout, try to kill the process\n\t\tif err := c.Cmd.Process.Kill(); err != nil {\n\t\t\treturn fmt.Errorf(\"failed to kill process: %w\", err)\n\t\t}\n\t\treturn fmt.Errorf(\"process killed after timeout\")\n\t}\n}\n\ntype ServerState int\n\nconst (\n\tStateStarting ServerState = iota\n\tStateReady\n\tStateError\n)\n\n// GetServerState returns the current state of the LSP server\nfunc (c *Client) GetServerState() ServerState {\n\tif val := c.serverState.Load(); val != nil {\n\t\treturn val.(ServerState)\n\t}\n\treturn StateStarting\n}\n\n// SetServerState sets the current state of the LSP server\nfunc (c *Client) SetServerState(state ServerState) {\n\tc.serverState.Store(state)\n}\n\n// WaitForServerReady waits for the server to be ready by polling the server\n// with a simple request until it responds successfully or times out\nfunc (c *Client) WaitForServerReady(ctx context.Context) error {\n\tcnf := config.Get()\n\n\t// Set initial state\n\tc.SetServerState(StateStarting)\n\n\t// Create a context with timeout\n\tctx, cancel := context.WithTimeout(ctx, 30*time.Second)\n\tdefer cancel()\n\n\t// Try to ping the server with a simple request\n\tticker := time.NewTicker(500 * time.Millisecond)\n\tdefer ticker.Stop()\n\n\tif cnf.DebugLSP {\n\t\tlogging.Debug(\"Waiting for LSP server to be ready...\")\n\t}\n\n\t// Determine server type for specialized initialization\n\tserverType := c.detectServerType()\n\n\t// For TypeScript-like servers, we need to open some key files first\n\tif serverType == ServerTypeTypeScript {\n\t\tif cnf.DebugLSP {\n\t\t\tlogging.Debug(\"TypeScript-like server detected, opening key configuration files\")\n\t\t}\n\t\tc.openKeyConfigFiles(ctx)\n\t}\n\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\tc.SetServerState(StateError)\n\t\t\treturn fmt.Errorf(\"timeout waiting for LSP server to be ready\")\n\t\tcase <-ticker.C:\n\t\t\t// Try a ping method appropriate for this server type\n\t\t\terr := c.pingServerByType(ctx, serverType)\n\t\t\tif err == nil {\n\t\t\t\t// Server responded successfully\n\t\t\t\tc.SetServerState(StateReady)\n\t\t\t\tif cnf.DebugLSP {\n\t\t\t\t\tlogging.Debug(\"LSP server is ready\")\n\t\t\t\t}\n\t\t\t\treturn nil\n\t\t\t} else {\n\t\t\t\tlogging.Debug(\"LSP server not ready yet\", \"error\", err, \"serverType\", serverType)\n\t\t\t}\n\n\t\t\tif cnf.DebugLSP {\n\t\t\t\tlogging.Debug(\"LSP server not ready yet\", \"error\", err, \"serverType\", serverType)\n\t\t\t}\n\t\t}\n\t}\n}\n\n// ServerType represents the type of LSP server\ntype ServerType int\n\nconst (\n\tServerTypeUnknown ServerType = iota\n\tServerTypeGo\n\tServerTypeTypeScript\n\tServerTypeRust\n\tServerTypePython\n\tServerTypeGeneric\n)\n\n// detectServerType tries to determine what type of LSP server we're dealing with\nfunc (c *Client) detectServerType() ServerType {\n\tif c.Cmd == nil {\n\t\treturn ServerTypeUnknown\n\t}\n\n\tcmdPath := strings.ToLower(c.Cmd.Path)\n\n\tswitch {\n\tcase strings.Contains(cmdPath, \"gopls\"):\n\t\treturn ServerTypeGo\n\tcase strings.Contains(cmdPath, \"typescript\") || strings.Contains(cmdPath, \"vtsls\") || strings.Contains(cmdPath, \"tsserver\"):\n\t\treturn ServerTypeTypeScript\n\tcase strings.Contains(cmdPath, \"rust-analyzer\"):\n\t\treturn ServerTypeRust\n\tcase strings.Contains(cmdPath, \"pyright\") || strings.Contains(cmdPath, \"pylsp\") || strings.Contains(cmdPath, \"python\"):\n\t\treturn ServerTypePython\n\tdefault:\n\t\treturn ServerTypeGeneric\n\t}\n}\n\n// openKeyConfigFiles opens important configuration files that help initialize the server\nfunc (c *Client) openKeyConfigFiles(ctx context.Context) {\n\tworkDir := config.WorkingDirectory()\n\tserverType := c.detectServerType()\n\n\tvar filesToOpen []string\n\n\tswitch serverType {\n\tcase ServerTypeTypeScript:\n\t\t// TypeScript servers need these config files to properly initialize\n\t\tfilesToOpen = []string{\n\t\t\tfilepath.Join(workDir, \"tsconfig.json\"),\n\t\t\tfilepath.Join(workDir, \"package.json\"),\n\t\t\tfilepath.Join(workDir, \"jsconfig.json\"),\n\t\t}\n\n\t\t// Also find and open a few TypeScript files to help the server initialize\n\t\tc.openTypeScriptFiles(ctx, workDir)\n\tcase ServerTypeGo:\n\t\tfilesToOpen = []string{\n\t\t\tfilepath.Join(workDir, \"go.mod\"),\n\t\t\tfilepath.Join(workDir, \"go.sum\"),\n\t\t}\n\tcase ServerTypeRust:\n\t\tfilesToOpen = []string{\n\t\t\tfilepath.Join(workDir, \"Cargo.toml\"),\n\t\t\tfilepath.Join(workDir, \"Cargo.lock\"),\n\t\t}\n\t}\n\n\t// Try to open each file, ignoring errors if they don't exist\n\tfor _, file := range filesToOpen {\n\t\tif _, err := os.Stat(file); err == nil {\n\t\t\t// File exists, try to open it\n\t\t\tif err := c.OpenFile(ctx, file); err != nil {\n\t\t\t\tlogging.Debug(\"Failed to open key config file\", \"file\", file, \"error\", err)\n\t\t\t} else {\n\t\t\t\tlogging.Debug(\"Opened key config file for initialization\", \"file\", file)\n\t\t\t}\n\t\t}\n\t}\n}\n\n// pingServerByType sends a ping request appropriate for the server type\nfunc (c *Client) pingServerByType(ctx context.Context, serverType ServerType) error {\n\tswitch serverType {\n\tcase ServerTypeTypeScript:\n\t\t// For TypeScript, try a document symbol request on an open file\n\t\treturn c.pingTypeScriptServer(ctx)\n\tcase ServerTypeGo:\n\t\t// For Go, workspace/symbol works well\n\t\treturn c.pingWithWorkspaceSymbol(ctx)\n\tcase ServerTypeRust:\n\t\t// For Rust, workspace/symbol works well\n\t\treturn c.pingWithWorkspaceSymbol(ctx)\n\tdefault:\n\t\t// Default ping method\n\t\treturn c.pingWithWorkspaceSymbol(ctx)\n\t}\n}\n\n// pingTypeScriptServer tries to ping a TypeScript server with appropriate methods\nfunc (c *Client) pingTypeScriptServer(ctx context.Context) error {\n\t// First try workspace/symbol which works for many servers\n\tif err := c.pingWithWorkspaceSymbol(ctx); err == nil {\n\t\treturn nil\n\t}\n\n\t// If that fails, try to find an open file and request document symbols\n\tc.openFilesMu.RLock()\n\tdefer c.openFilesMu.RUnlock()\n\n\t// If we have any open files, try to get document symbols for one\n\tfor uri := range c.openFiles {\n\t\tfilePath := strings.TrimPrefix(uri, \"file://\")\n\t\tif strings.HasSuffix(filePath, \".ts\") || strings.HasSuffix(filePath, \".js\") ||\n\t\t\tstrings.HasSuffix(filePath, \".tsx\") || strings.HasSuffix(filePath, \".jsx\") {\n\t\t\tvar symbols []protocol.DocumentSymbol\n\t\t\terr := c.Call(ctx, \"textDocument/documentSymbol\", protocol.DocumentSymbolParams{\n\t\t\t\tTextDocument: protocol.TextDocumentIdentifier{\n\t\t\t\t\tURI: protocol.DocumentUri(uri),\n\t\t\t\t},\n\t\t\t}, &symbols)\n\t\t\tif err == nil {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\t}\n\n\t// If we have no open TypeScript files, try to find and open one\n\tworkDir := config.WorkingDirectory()\n\terr := filepath.WalkDir(workDir, func(path string, d os.DirEntry, err error) error {\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Skip directories and non-TypeScript files\n\t\tif d.IsDir() {\n\t\t\treturn nil\n\t\t}\n\n\t\text := filepath.Ext(path)\n\t\tif ext == \".ts\" || ext == \".js\" || ext == \".tsx\" || ext == \".jsx\" {\n\t\t\t// Found a TypeScript file, try to open it\n\t\t\tif err := c.OpenFile(ctx, path); err == nil {\n\t\t\t\t// Successfully opened, stop walking\n\t\t\t\treturn filepath.SkipAll\n\t\t\t}\n\t\t}\n\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\tlogging.Debug(\"Error walking directory for TypeScript files\", \"error\", err)\n\t}\n\n\t// Final fallback - just try a generic capability\n\treturn c.pingWithServerCapabilities(ctx)\n}\n\n// openTypeScriptFiles finds and opens TypeScript files to help initialize the server\nfunc (c *Client) openTypeScriptFiles(ctx context.Context, workDir string) {\n\tcnf := config.Get()\n\tfilesOpened := 0\n\tmaxFilesToOpen := 5 // Limit to a reasonable number of files\n\n\t// Find and open TypeScript files\n\terr := filepath.WalkDir(workDir, func(path string, d os.DirEntry, err error) error {\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Skip directories and non-TypeScript files\n\t\tif d.IsDir() {\n\t\t\t// Skip common directories to avoid wasting time\n\t\t\tif shouldSkipDir(path) {\n\t\t\t\treturn filepath.SkipDir\n\t\t\t}\n\t\t\treturn nil\n\t\t}\n\n\t\t// Check if we've opened enough files\n\t\tif filesOpened >= maxFilesToOpen {\n\t\t\treturn filepath.SkipAll\n\t\t}\n\n\t\t// Check file extension\n\t\text := filepath.Ext(path)\n\t\tif ext == \".ts\" || ext == \".tsx\" || ext == \".js\" || ext == \".jsx\" {\n\t\t\t// Try to open the file\n\t\t\tif err := c.OpenFile(ctx, path); err == nil {\n\t\t\t\tfilesOpened++\n\t\t\t\tif cnf.DebugLSP {\n\t\t\t\t\tlogging.Debug(\"Opened TypeScript file for initialization\", \"file\", path)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn nil\n\t})\n\n\tif err != nil && cnf.DebugLSP {\n\t\tlogging.Debug(\"Error walking directory for TypeScript files\", \"error\", err)\n\t}\n\n\tif cnf.DebugLSP {\n\t\tlogging.Debug(\"Opened TypeScript files for initialization\", \"count\", filesOpened)\n\t}\n}\n\n// shouldSkipDir returns true if the directory should be skipped during file search\nfunc shouldSkipDir(path string) bool {\n\tdirName := filepath.Base(path)\n\n\t// Skip hidden directories\n\tif strings.HasPrefix(dirName, \".\") {\n\t\treturn true\n\t}\n\n\t// Skip common directories that won't contain relevant source files\n\tskipDirs := map[string]bool{\n\t\t\"node_modules\": true,\n\t\t\"dist\": true,\n\t\t\"build\": true,\n\t\t\"coverage\": true,\n\t\t\"vendor\": true,\n\t\t\"target\": true,\n\t}\n\n\treturn skipDirs[dirName]\n}\n\n// pingWithWorkspaceSymbol tries a workspace/symbol request\nfunc (c *Client) pingWithWorkspaceSymbol(ctx context.Context) error {\n\tvar result []protocol.SymbolInformation\n\treturn c.Call(ctx, \"workspace/symbol\", protocol.WorkspaceSymbolParams{\n\t\tQuery: \"\",\n\t}, &result)\n}\n\n// pingWithServerCapabilities tries to get server capabilities\nfunc (c *Client) pingWithServerCapabilities(ctx context.Context) error {\n\t// This is a very lightweight request that should work for most servers\n\treturn c.Notify(ctx, \"$/cancelRequest\", struct{ ID int }{ID: -1})\n}\n\ntype OpenFileInfo struct {\n\tVersion int32\n\tURI protocol.DocumentUri\n}\n\nfunc (c *Client) OpenFile(ctx context.Context, filepath string) error {\n\turi := fmt.Sprintf(\"file://%s\", filepath)\n\n\tc.openFilesMu.Lock()\n\tif _, exists := c.openFiles[uri]; exists {\n\t\tc.openFilesMu.Unlock()\n\t\treturn nil // Already open\n\t}\n\tc.openFilesMu.Unlock()\n\n\t// Skip files that do not exist or cannot be read\n\tcontent, err := os.ReadFile(filepath)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error reading file: %w\", err)\n\t}\n\n\tparams := protocol.DidOpenTextDocumentParams{\n\t\tTextDocument: protocol.TextDocumentItem{\n\t\t\tURI: protocol.DocumentUri(uri),\n\t\t\tLanguageID: DetectLanguageID(uri),\n\t\t\tVersion: 1,\n\t\t\tText: string(content),\n\t\t},\n\t}\n\n\tif err := c.Notify(ctx, \"textDocument/didOpen\", params); err != nil {\n\t\treturn err\n\t}\n\n\tc.openFilesMu.Lock()\n\tc.openFiles[uri] = &OpenFileInfo{\n\t\tVersion: 1,\n\t\tURI: protocol.DocumentUri(uri),\n\t}\n\tc.openFilesMu.Unlock()\n\n\treturn nil\n}\n\nfunc (c *Client) NotifyChange(ctx context.Context, filepath string) error {\n\turi := fmt.Sprintf(\"file://%s\", filepath)\n\n\tcontent, err := os.ReadFile(filepath)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error reading file: %w\", err)\n\t}\n\n\tc.openFilesMu.Lock()\n\tfileInfo, isOpen := c.openFiles[uri]\n\tif !isOpen {\n\t\tc.openFilesMu.Unlock()\n\t\treturn fmt.Errorf(\"cannot notify change for unopened file: %s\", filepath)\n\t}\n\n\t// Increment version\n\tfileInfo.Version++\n\tversion := fileInfo.Version\n\tc.openFilesMu.Unlock()\n\n\tparams := protocol.DidChangeTextDocumentParams{\n\t\tTextDocument: protocol.VersionedTextDocumentIdentifier{\n\t\t\tTextDocumentIdentifier: protocol.TextDocumentIdentifier{\n\t\t\t\tURI: protocol.DocumentUri(uri),\n\t\t\t},\n\t\t\tVersion: version,\n\t\t},\n\t\tContentChanges: []protocol.TextDocumentContentChangeEvent{\n\t\t\t{\n\t\t\t\tValue: protocol.TextDocumentContentChangeWholeDocument{\n\t\t\t\t\tText: string(content),\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\treturn c.Notify(ctx, \"textDocument/didChange\", params)\n}\n\nfunc (c *Client) CloseFile(ctx context.Context, filepath string) error {\n\tcnf := config.Get()\n\turi := fmt.Sprintf(\"file://%s\", filepath)\n\n\tc.openFilesMu.Lock()\n\tif _, exists := c.openFiles[uri]; !exists {\n\t\tc.openFilesMu.Unlock()\n\t\treturn nil // Already closed\n\t}\n\tc.openFilesMu.Unlock()\n\n\tparams := protocol.DidCloseTextDocumentParams{\n\t\tTextDocument: protocol.TextDocumentIdentifier{\n\t\t\tURI: protocol.DocumentUri(uri),\n\t\t},\n\t}\n\n\tif cnf.DebugLSP {\n\t\tlogging.Debug(\"Closing file\", \"file\", filepath)\n\t}\n\tif err := c.Notify(ctx, \"textDocument/didClose\", params); err != nil {\n\t\treturn err\n\t}\n\n\tc.openFilesMu.Lock()\n\tdelete(c.openFiles, uri)\n\tc.openFilesMu.Unlock()\n\n\treturn nil\n}\n\nfunc (c *Client) IsFileOpen(filepath string) bool {\n\turi := fmt.Sprintf(\"file://%s\", filepath)\n\tc.openFilesMu.RLock()\n\tdefer c.openFilesMu.RUnlock()\n\t_, exists := c.openFiles[uri]\n\treturn exists\n}\n\n// CloseAllFiles closes all currently open files\nfunc (c *Client) CloseAllFiles(ctx context.Context) {\n\tcnf := config.Get()\n\tc.openFilesMu.Lock()\n\tfilesToClose := make([]string, 0, len(c.openFiles))\n\n\t// First collect all URIs that need to be closed\n\tfor uri := range c.openFiles {\n\t\t// Convert URI back to file path by trimming \"file://\" prefix\n\t\tfilePath := strings.TrimPrefix(uri, \"file://\")\n\t\tfilesToClose = append(filesToClose, filePath)\n\t}\n\tc.openFilesMu.Unlock()\n\n\t// Then close them all\n\tfor _, filePath := range filesToClose {\n\t\terr := c.CloseFile(ctx, filePath)\n\t\tif err != nil && cnf.DebugLSP {\n\t\t\tlogging.Warn(\"Error closing file\", \"file\", filePath, \"error\", err)\n\t\t}\n\t}\n\n\tif cnf.DebugLSP {\n\t\tlogging.Debug(\"Closed all files\", \"files\", filesToClose)\n\t}\n}\n\nfunc (c *Client) GetFileDiagnostics(uri protocol.DocumentUri) []protocol.Diagnostic {\n\tc.diagnosticsMu.RLock()\n\tdefer c.diagnosticsMu.RUnlock()\n\n\treturn c.diagnostics[uri]\n}\n\n// GetDiagnostics returns all diagnostics for all files\nfunc (c *Client) GetDiagnostics() map[protocol.DocumentUri][]protocol.Diagnostic {\n\treturn c.diagnostics\n}\n\n// OpenFileOnDemand opens a file only if it's not already open\n// This is used for lazy-loading files when they're actually needed\nfunc (c *Client) OpenFileOnDemand(ctx context.Context, filepath string) error {\n\t// Check if the file is already open\n\tif c.IsFileOpen(filepath) {\n\t\treturn nil\n\t}\n\n\t// Open the file\n\treturn c.OpenFile(ctx, filepath)\n}\n\n// GetDiagnosticsForFile ensures a file is open and returns its diagnostics\n// This is useful for on-demand diagnostics when using lazy loading\nfunc (c *Client) GetDiagnosticsForFile(ctx context.Context, filepath string) ([]protocol.Diagnostic, error) {\n\turi := fmt.Sprintf(\"file://%s\", filepath)\n\tdocumentUri := protocol.DocumentUri(uri)\n\n\t// Make sure the file is open\n\tif !c.IsFileOpen(filepath) {\n\t\tif err := c.OpenFile(ctx, filepath); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to open file for diagnostics: %w\", err)\n\t\t}\n\n\t\t// Give the LSP server a moment to process the file\n\t\ttime.Sleep(100 * time.Millisecond)\n\t}\n\n\t// Get diagnostics\n\tc.diagnosticsMu.RLock()\n\tdiagnostics := c.diagnostics[documentUri]\n\tc.diagnosticsMu.RUnlock()\n\n\treturn diagnostics, nil\n}\n\n// ClearDiagnosticsForURI removes diagnostics for a specific URI from the cache\nfunc (c *Client) ClearDiagnosticsForURI(uri protocol.DocumentUri) {\n\tc.diagnosticsMu.Lock()\n\tdefer c.diagnosticsMu.Unlock()\n\tdelete(c.diagnostics, uri)\n}\n"], ["/opencode/internal/completions/files-folders.go", "package completions\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"os/exec\"\n\t\"path/filepath\"\n\n\t\"github.com/lithammer/fuzzysearch/fuzzy\"\n\t\"github.com/opencode-ai/opencode/internal/fileutil\"\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n\t\"github.com/opencode-ai/opencode/internal/tui/components/dialog\"\n)\n\ntype filesAndFoldersContextGroup struct {\n\tprefix string\n}\n\nfunc (cg *filesAndFoldersContextGroup) GetId() string {\n\treturn cg.prefix\n}\n\nfunc (cg *filesAndFoldersContextGroup) GetEntry() dialog.CompletionItemI {\n\treturn dialog.NewCompletionItem(dialog.CompletionItem{\n\t\tTitle: \"Files & Folders\",\n\t\tValue: \"files\",\n\t})\n}\n\nfunc processNullTerminatedOutput(outputBytes []byte) []string {\n\tif len(outputBytes) > 0 && outputBytes[len(outputBytes)-1] == 0 {\n\t\toutputBytes = outputBytes[:len(outputBytes)-1]\n\t}\n\n\tif len(outputBytes) == 0 {\n\t\treturn []string{}\n\t}\n\n\tsplit := bytes.Split(outputBytes, []byte{0})\n\tmatches := make([]string, 0, len(split))\n\n\tfor _, p := range split {\n\t\tif len(p) == 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\tpath := string(p)\n\t\tpath = filepath.Join(\".\", path)\n\n\t\tif !fileutil.SkipHidden(path) {\n\t\t\tmatches = append(matches, path)\n\t\t}\n\t}\n\n\treturn matches\n}\n\nfunc (cg *filesAndFoldersContextGroup) getFiles(query string) ([]string, error) {\n\tcmdRg := fileutil.GetRgCmd(\"\") // No glob pattern for this use case\n\tcmdFzf := fileutil.GetFzfCmd(query)\n\n\tvar matches []string\n\t// Case 1: Both rg and fzf available\n\tif cmdRg != nil && cmdFzf != nil {\n\t\trgPipe, err := cmdRg.StdoutPipe()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to get rg stdout pipe: %w\", err)\n\t\t}\n\t\tdefer rgPipe.Close()\n\n\t\tcmdFzf.Stdin = rgPipe\n\t\tvar fzfOut bytes.Buffer\n\t\tvar fzfErr bytes.Buffer\n\t\tcmdFzf.Stdout = &fzfOut\n\t\tcmdFzf.Stderr = &fzfErr\n\n\t\tif err := cmdFzf.Start(); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to start fzf: %w\", err)\n\t\t}\n\n\t\terrRg := cmdRg.Run()\n\t\terrFzf := cmdFzf.Wait()\n\n\t\tif errRg != nil {\n\t\t\tlogging.Warn(fmt.Sprintf(\"rg command failed during pipe: %v\", errRg))\n\t\t}\n\n\t\tif errFzf != nil {\n\t\t\tif exitErr, ok := errFzf.(*exec.ExitError); ok && exitErr.ExitCode() == 1 {\n\t\t\t\treturn []string{}, nil // No matches from fzf\n\t\t\t}\n\t\t\treturn nil, fmt.Errorf(\"fzf command failed: %w\\nStderr: %s\", errFzf, fzfErr.String())\n\t\t}\n\n\t\tmatches = processNullTerminatedOutput(fzfOut.Bytes())\n\n\t\t// Case 2: Only rg available\n\t} else if cmdRg != nil {\n\t\tlogging.Debug(\"Using Ripgrep with fuzzy match fallback for file completions\")\n\t\tvar rgOut bytes.Buffer\n\t\tvar rgErr bytes.Buffer\n\t\tcmdRg.Stdout = &rgOut\n\t\tcmdRg.Stderr = &rgErr\n\n\t\tif err := cmdRg.Run(); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"rg command failed: %w\\nStderr: %s\", err, rgErr.String())\n\t\t}\n\n\t\tallFiles := processNullTerminatedOutput(rgOut.Bytes())\n\t\tmatches = fuzzy.Find(query, allFiles)\n\n\t\t// Case 3: Only fzf available\n\t} else if cmdFzf != nil {\n\t\tlogging.Debug(\"Using FZF with doublestar fallback for file completions\")\n\t\tfiles, _, err := fileutil.GlobWithDoublestar(\"**/*\", \".\", 0)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to list files for fzf: %w\", err)\n\t\t}\n\n\t\tallFiles := make([]string, 0, len(files))\n\t\tfor _, file := range files {\n\t\t\tif !fileutil.SkipHidden(file) {\n\t\t\t\tallFiles = append(allFiles, file)\n\t\t\t}\n\t\t}\n\n\t\tvar fzfIn bytes.Buffer\n\t\tfor _, file := range allFiles {\n\t\t\tfzfIn.WriteString(file)\n\t\t\tfzfIn.WriteByte(0)\n\t\t}\n\n\t\tcmdFzf.Stdin = &fzfIn\n\t\tvar fzfOut bytes.Buffer\n\t\tvar fzfErr bytes.Buffer\n\t\tcmdFzf.Stdout = &fzfOut\n\t\tcmdFzf.Stderr = &fzfErr\n\n\t\tif err := cmdFzf.Run(); err != nil {\n\t\t\tif exitErr, ok := err.(*exec.ExitError); ok && exitErr.ExitCode() == 1 {\n\t\t\t\treturn []string{}, nil\n\t\t\t}\n\t\t\treturn nil, fmt.Errorf(\"fzf command failed: %w\\nStderr: %s\", err, fzfErr.String())\n\t\t}\n\n\t\tmatches = processNullTerminatedOutput(fzfOut.Bytes())\n\n\t\t// Case 4: Fallback to doublestar with fuzzy match\n\t} else {\n\t\tlogging.Debug(\"Using doublestar with fuzzy match for file completions\")\n\t\tallFiles, _, err := fileutil.GlobWithDoublestar(\"**/*\", \".\", 0)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to glob files: %w\", err)\n\t\t}\n\n\t\tfilteredFiles := make([]string, 0, len(allFiles))\n\t\tfor _, file := range allFiles {\n\t\t\tif !fileutil.SkipHidden(file) {\n\t\t\t\tfilteredFiles = append(filteredFiles, file)\n\t\t\t}\n\t\t}\n\n\t\tmatches = fuzzy.Find(query, filteredFiles)\n\t}\n\n\treturn matches, nil\n}\n\nfunc (cg *filesAndFoldersContextGroup) GetChildEntries(query string) ([]dialog.CompletionItemI, error) {\n\tmatches, err := cg.getFiles(query)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\titems := make([]dialog.CompletionItemI, 0, len(matches))\n\tfor _, file := range matches {\n\t\titem := dialog.NewCompletionItem(dialog.CompletionItem{\n\t\t\tTitle: file,\n\t\t\tValue: file,\n\t\t})\n\t\titems = append(items, item)\n\t}\n\n\treturn items, nil\n}\n\nfunc NewFileAndFolderContextGroup() dialog.CompletionProvider {\n\treturn &filesAndFoldersContextGroup{\n\t\tprefix: \"file\",\n\t}\n}\n"], ["/opencode/internal/fileutil/fileutil.go", "package fileutil\n\nimport (\n\t\"fmt\"\n\t\"io/fs\"\n\t\"os\"\n\t\"os/exec\"\n\t\"path/filepath\"\n\t\"sort\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/bmatcuk/doublestar/v4\"\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n)\n\nvar (\n\trgPath string\n\tfzfPath string\n)\n\nfunc init() {\n\tvar err error\n\trgPath, err = exec.LookPath(\"rg\")\n\tif err != nil {\n\t\tlogging.Warn(\"Ripgrep (rg) not found in $PATH. Some features might be limited or slower.\")\n\t\trgPath = \"\"\n\t}\n\tfzfPath, err = exec.LookPath(\"fzf\")\n\tif err != nil {\n\t\tlogging.Warn(\"FZF not found in $PATH. Some features might be limited or slower.\")\n\t\tfzfPath = \"\"\n\t}\n}\n\nfunc GetRgCmd(globPattern string) *exec.Cmd {\n\tif rgPath == \"\" {\n\t\treturn nil\n\t}\n\trgArgs := []string{\n\t\t\"--files\",\n\t\t\"-L\",\n\t\t\"--null\",\n\t}\n\tif globPattern != \"\" {\n\t\tif !filepath.IsAbs(globPattern) && !strings.HasPrefix(globPattern, \"/\") {\n\t\t\tglobPattern = \"/\" + globPattern\n\t\t}\n\t\trgArgs = append(rgArgs, \"--glob\", globPattern)\n\t}\n\tcmd := exec.Command(rgPath, rgArgs...)\n\tcmd.Dir = \".\"\n\treturn cmd\n}\n\nfunc GetFzfCmd(query string) *exec.Cmd {\n\tif fzfPath == \"\" {\n\t\treturn nil\n\t}\n\tfzfArgs := []string{\n\t\t\"--filter\",\n\t\tquery,\n\t\t\"--read0\",\n\t\t\"--print0\",\n\t}\n\tcmd := exec.Command(fzfPath, fzfArgs...)\n\tcmd.Dir = \".\"\n\treturn cmd\n}\n\ntype FileInfo struct {\n\tPath string\n\tModTime time.Time\n}\n\nfunc SkipHidden(path string) bool {\n\t// Check for hidden files (starting with a dot)\n\tbase := filepath.Base(path)\n\tif base != \".\" && strings.HasPrefix(base, \".\") {\n\t\treturn true\n\t}\n\n\tcommonIgnoredDirs := map[string]bool{\n\t\t\".opencode\": true,\n\t\t\"node_modules\": true,\n\t\t\"vendor\": true,\n\t\t\"dist\": true,\n\t\t\"build\": true,\n\t\t\"target\": true,\n\t\t\".git\": true,\n\t\t\".idea\": true,\n\t\t\".vscode\": true,\n\t\t\"__pycache__\": true,\n\t\t\"bin\": true,\n\t\t\"obj\": true,\n\t\t\"out\": true,\n\t\t\"coverage\": true,\n\t\t\"tmp\": true,\n\t\t\"temp\": true,\n\t\t\"logs\": true,\n\t\t\"generated\": true,\n\t\t\"bower_components\": true,\n\t\t\"jspm_packages\": true,\n\t}\n\n\tparts := strings.Split(path, string(os.PathSeparator))\n\tfor _, part := range parts {\n\t\tif commonIgnoredDirs[part] {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc GlobWithDoublestar(pattern, searchPath string, limit int) ([]string, bool, error) {\n\tfsys := os.DirFS(searchPath)\n\trelPattern := strings.TrimPrefix(pattern, \"/\")\n\tvar matches []FileInfo\n\n\terr := doublestar.GlobWalk(fsys, relPattern, func(path string, d fs.DirEntry) error {\n\t\tif d.IsDir() {\n\t\t\treturn nil\n\t\t}\n\t\tif SkipHidden(path) {\n\t\t\treturn nil\n\t\t}\n\t\tinfo, err := d.Info()\n\t\tif err != nil {\n\t\t\treturn nil\n\t\t}\n\t\tabsPath := path\n\t\tif !strings.HasPrefix(absPath, searchPath) && searchPath != \".\" {\n\t\t\tabsPath = filepath.Join(searchPath, absPath)\n\t\t} else if !strings.HasPrefix(absPath, \"/\") && searchPath == \".\" {\n\t\t\tabsPath = filepath.Join(searchPath, absPath) // Ensure relative paths are joined correctly\n\t\t}\n\n\t\tmatches = append(matches, FileInfo{Path: absPath, ModTime: info.ModTime()})\n\t\tif limit > 0 && len(matches) >= limit*2 {\n\t\t\treturn fs.SkipAll\n\t\t}\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\treturn nil, false, fmt.Errorf(\"glob walk error: %w\", err)\n\t}\n\n\tsort.Slice(matches, func(i, j int) bool {\n\t\treturn matches[i].ModTime.After(matches[j].ModTime)\n\t})\n\n\ttruncated := false\n\tif limit > 0 && len(matches) > limit {\n\t\tmatches = matches[:limit]\n\t\ttruncated = true\n\t}\n\n\tresults := make([]string, len(matches))\n\tfor i, m := range matches {\n\t\tresults[i] = m.Path\n\t}\n\treturn results, truncated, nil\n}\n"], ["/opencode/internal/tui/components/dialog/custom_commands.go", "package dialog\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"regexp\"\n\t\"strings\"\n\n\ttea \"github.com/charmbracelet/bubbletea\"\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/tui/util\"\n)\n\n// Command prefix constants\nconst (\n\tUserCommandPrefix = \"user:\"\n\tProjectCommandPrefix = \"project:\"\n)\n\n// namedArgPattern is a regex pattern to find named arguments in the format $NAME\nvar namedArgPattern = regexp.MustCompile(`\\$([A-Z][A-Z0-9_]*)`)\n\n// LoadCustomCommands loads custom commands from both XDG_CONFIG_HOME and project data directory\nfunc LoadCustomCommands() ([]Command, error) {\n\tcfg := config.Get()\n\tif cfg == nil {\n\t\treturn nil, fmt.Errorf(\"config not loaded\")\n\t}\n\n\tvar commands []Command\n\n\t// Load user commands from XDG_CONFIG_HOME/opencode/commands\n\txdgConfigHome := os.Getenv(\"XDG_CONFIG_HOME\")\n\tif xdgConfigHome == \"\" {\n\t\t// Default to ~/.config if XDG_CONFIG_HOME is not set\n\t\thome, err := os.UserHomeDir()\n\t\tif err == nil {\n\t\t\txdgConfigHome = filepath.Join(home, \".config\")\n\t\t}\n\t}\n\n\tif xdgConfigHome != \"\" {\n\t\tuserCommandsDir := filepath.Join(xdgConfigHome, \"opencode\", \"commands\")\n\t\tuserCommands, err := loadCommandsFromDir(userCommandsDir, UserCommandPrefix)\n\t\tif err != nil {\n\t\t\t// Log error but continue - we'll still try to load other commands\n\t\t\tfmt.Printf(\"Warning: failed to load user commands from XDG_CONFIG_HOME: %v\\n\", err)\n\t\t} else {\n\t\t\tcommands = append(commands, userCommands...)\n\t\t}\n\t}\n\n\t// Load commands from $HOME/.opencode/commands\n\thome, err := os.UserHomeDir()\n\tif err == nil {\n\t\thomeCommandsDir := filepath.Join(home, \".opencode\", \"commands\")\n\t\thomeCommands, err := loadCommandsFromDir(homeCommandsDir, UserCommandPrefix)\n\t\tif err != nil {\n\t\t\t// Log error but continue - we'll still try to load other commands\n\t\t\tfmt.Printf(\"Warning: failed to load home commands: %v\\n\", err)\n\t\t} else {\n\t\t\tcommands = append(commands, homeCommands...)\n\t\t}\n\t}\n\n\t// Load project commands from data directory\n\tprojectCommandsDir := filepath.Join(cfg.Data.Directory, \"commands\")\n\tprojectCommands, err := loadCommandsFromDir(projectCommandsDir, ProjectCommandPrefix)\n\tif err != nil {\n\t\t// Log error but return what we have so far\n\t\tfmt.Printf(\"Warning: failed to load project commands: %v\\n\", err)\n\t} else {\n\t\tcommands = append(commands, projectCommands...)\n\t}\n\n\treturn commands, nil\n}\n\n// loadCommandsFromDir loads commands from a specific directory with the given prefix\nfunc loadCommandsFromDir(commandsDir string, prefix string) ([]Command, error) {\n\t// Check if the commands directory exists\n\tif _, err := os.Stat(commandsDir); os.IsNotExist(err) {\n\t\t// Create the commands directory if it doesn't exist\n\t\tif err := os.MkdirAll(commandsDir, 0755); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to create commands directory %s: %w\", commandsDir, err)\n\t\t}\n\t\t// Return empty list since we just created the directory\n\t\treturn []Command{}, nil\n\t}\n\n\tvar commands []Command\n\n\t// Walk through the commands directory and load all .md files\n\terr := filepath.Walk(commandsDir, func(path string, info os.FileInfo, err error) error {\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Skip directories\n\t\tif info.IsDir() {\n\t\t\treturn nil\n\t\t}\n\n\t\t// Only process markdown files\n\t\tif !strings.HasSuffix(strings.ToLower(info.Name()), \".md\") {\n\t\t\treturn nil\n\t\t}\n\n\t\t// Read the file content\n\t\tcontent, err := os.ReadFile(path)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to read command file %s: %w\", path, err)\n\t\t}\n\n\t\t// Get the command ID from the file name without the .md extension\n\t\tcommandID := strings.TrimSuffix(info.Name(), filepath.Ext(info.Name()))\n\n\t\t// Get relative path from commands directory\n\t\trelPath, err := filepath.Rel(commandsDir, path)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to get relative path for %s: %w\", path, err)\n\t\t}\n\n\t\t// Create the command ID from the relative path\n\t\t// Replace directory separators with colons\n\t\tcommandIDPath := strings.ReplaceAll(filepath.Dir(relPath), string(filepath.Separator), \":\")\n\t\tif commandIDPath != \".\" {\n\t\t\tcommandID = commandIDPath + \":\" + commandID\n\t\t}\n\n\t\t// Create a command\n\t\tcommand := Command{\n\t\t\tID: prefix + commandID,\n\t\t\tTitle: prefix + commandID,\n\t\t\tDescription: fmt.Sprintf(\"Custom command from %s\", relPath),\n\t\t\tHandler: func(cmd Command) tea.Cmd {\n\t\t\t\tcommandContent := string(content)\n\n\t\t\t\t// Check for named arguments\n\t\t\t\tmatches := namedArgPattern.FindAllStringSubmatch(commandContent, -1)\n\t\t\t\tif len(matches) > 0 {\n\t\t\t\t\t// Extract unique argument names\n\t\t\t\t\targNames := make([]string, 0)\n\t\t\t\t\targMap := make(map[string]bool)\n\n\t\t\t\t\tfor _, match := range matches {\n\t\t\t\t\t\targName := match[1] // Group 1 is the name without $\n\t\t\t\t\t\tif !argMap[argName] {\n\t\t\t\t\t\t\targMap[argName] = true\n\t\t\t\t\t\t\targNames = append(argNames, argName)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\t// Show multi-arguments dialog for all named arguments\n\t\t\t\t\treturn util.CmdHandler(ShowMultiArgumentsDialogMsg{\n\t\t\t\t\t\tCommandID: cmd.ID,\n\t\t\t\t\t\tContent: commandContent,\n\t\t\t\t\t\tArgNames: argNames,\n\t\t\t\t\t})\n\t\t\t\t}\n\n\t\t\t\t// No arguments needed, run command directly\n\t\t\t\treturn util.CmdHandler(CommandRunCustomMsg{\n\t\t\t\t\tContent: commandContent,\n\t\t\t\t\tArgs: nil, // No arguments\n\t\t\t\t})\n\t\t\t},\n\t\t}\n\n\t\tcommands = append(commands, command)\n\t\treturn nil\n\t})\n\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to load custom commands from %s: %w\", commandsDir, err)\n\t}\n\n\treturn commands, nil\n}\n\n// CommandRunCustomMsg is sent when a custom command is executed\ntype CommandRunCustomMsg struct {\n\tContent string\n\tArgs map[string]string // Map of argument names to values\n}\n"], ["/opencode/internal/lsp/protocol/uri.go", "// Copyright 2023 The Go Authors. All rights reserved.\n// Use of this source code is governed by a BSD-style\n// license that can be found in the LICENSE file.\n\npackage protocol\n\n// This file declares URI, DocumentUri, and its methods.\n//\n// For the LSP definition of these types, see\n// https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#uri\n\nimport (\n\t\"fmt\"\n\t\"net/url\"\n\t\"path/filepath\"\n\t\"strings\"\n\t\"unicode\"\n)\n\n// A DocumentUri is the URI of a client editor document.\n//\n// According to the LSP specification:\n//\n//\tCare should be taken to handle encoding in URIs. For\n//\texample, some clients (such as VS Code) may encode colons\n//\tin drive letters while others do not. The URIs below are\n//\tboth valid, but clients and servers should be consistent\n//\twith the form they use themselves to ensure the other party\n//\tdoesn’t interpret them as distinct URIs. Clients and\n//\tservers should not assume that each other are encoding the\n//\tsame way (for example a client encoding colons in drive\n//\tletters cannot assume server responses will have encoded\n//\tcolons). The same applies to casing of drive letters - one\n//\tparty should not assume the other party will return paths\n//\twith drive letters cased the same as it.\n//\n//\tfile:///c:/project/readme.md\n//\tfile:///C%3A/project/readme.md\n//\n// This is done during JSON unmarshalling;\n// see [DocumentUri.UnmarshalText] for details.\ntype DocumentUri string\n\n// A URI is an arbitrary URL (e.g. https), not necessarily a file.\ntype URI = string\n\n// UnmarshalText implements decoding of DocumentUri values.\n//\n// In particular, it implements a systematic correction of various odd\n// features of the definition of DocumentUri in the LSP spec that\n// appear to be workarounds for bugs in VS Code. For example, it may\n// URI-encode the URI itself, so that colon becomes %3A, and it may\n// send file://foo.go URIs that have two slashes (not three) and no\n// hostname.\n//\n// We use UnmarshalText, not UnmarshalJSON, because it is called even\n// for non-addressable values such as keys and values of map[K]V,\n// where there is no pointer of type *K or *V on which to call\n// UnmarshalJSON. (See Go issue #28189 for more detail.)\n//\n// Non-empty DocumentUris are valid \"file\"-scheme URIs.\n// The empty DocumentUri is valid.\nfunc (uri *DocumentUri) UnmarshalText(data []byte) (err error) {\n\t*uri, err = ParseDocumentUri(string(data))\n\treturn\n}\n\n// Path returns the file path for the given URI.\n//\n// DocumentUri(\"\").Path() returns the empty string.\n//\n// Path panics if called on a URI that is not a valid filename.\nfunc (uri DocumentUri) Path() string {\n\tfilename, err := filename(uri)\n\tif err != nil {\n\t\t// e.g. ParseRequestURI failed.\n\t\t//\n\t\t// This can only affect DocumentUris created by\n\t\t// direct string manipulation; all DocumentUris\n\t\t// received from the client pass through\n\t\t// ParseRequestURI, which ensures validity.\n\t\tpanic(err)\n\t}\n\treturn filepath.FromSlash(filename)\n}\n\n// Dir returns the URI for the directory containing the receiver.\nfunc (uri DocumentUri) Dir() DocumentUri {\n\t// This function could be more efficiently implemented by avoiding any call\n\t// to Path(), but at least consolidates URI manipulation.\n\treturn URIFromPath(uri.DirPath())\n}\n\n// DirPath returns the file path to the directory containing this URI, which\n// must be a file URI.\nfunc (uri DocumentUri) DirPath() string {\n\treturn filepath.Dir(uri.Path())\n}\n\nfunc filename(uri DocumentUri) (string, error) {\n\tif uri == \"\" {\n\t\treturn \"\", nil\n\t}\n\n\t// This conservative check for the common case\n\t// of a simple non-empty absolute POSIX filename\n\t// avoids the allocation of a net.URL.\n\tif strings.HasPrefix(string(uri), \"file:///\") {\n\t\trest := string(uri)[len(\"file://\"):] // leave one slash\n\t\tfor i := range len(rest) {\n\t\t\tb := rest[i]\n\t\t\t// Reject these cases:\n\t\t\tif b < ' ' || b == 0x7f || // control character\n\t\t\t\tb == '%' || b == '+' || // URI escape\n\t\t\t\tb == ':' || // Windows drive letter\n\t\t\t\tb == '@' || b == '&' || b == '?' { // authority or query\n\t\t\t\tgoto slow\n\t\t\t}\n\t\t}\n\t\treturn rest, nil\n\t}\nslow:\n\n\tu, err := url.ParseRequestURI(string(uri))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tif u.Scheme != fileScheme {\n\t\treturn \"\", fmt.Errorf(\"only file URIs are supported, got %q from %q\", u.Scheme, uri)\n\t}\n\t// If the URI is a Windows URI, we trim the leading \"/\" and uppercase\n\t// the drive letter, which will never be case sensitive.\n\tif isWindowsDriveURIPath(u.Path) {\n\t\tu.Path = strings.ToUpper(string(u.Path[1])) + u.Path[2:]\n\t}\n\n\treturn u.Path, nil\n}\n\n// ParseDocumentUri interprets a string as a DocumentUri, applying VS\n// Code workarounds; see [DocumentUri.UnmarshalText] for details.\nfunc ParseDocumentUri(s string) (DocumentUri, error) {\n\tif s == \"\" {\n\t\treturn \"\", nil\n\t}\n\n\tif !strings.HasPrefix(s, \"file://\") {\n\t\treturn \"\", fmt.Errorf(\"DocumentUri scheme is not 'file': %s\", s)\n\t}\n\n\t// VS Code sends URLs with only two slashes,\n\t// which are invalid. golang/go#39789.\n\tif !strings.HasPrefix(s, \"file:///\") {\n\t\ts = \"file:///\" + s[len(\"file://\"):]\n\t}\n\n\t// Even though the input is a URI, it may not be in canonical form. VS Code\n\t// in particular over-escapes :, @, etc. Unescape and re-encode to canonicalize.\n\tpath, err := url.PathUnescape(s[len(\"file://\"):])\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t// File URIs from Windows may have lowercase drive letters.\n\t// Since drive letters are guaranteed to be case insensitive,\n\t// we change them to uppercase to remain consistent.\n\t// For example, file:///c:/x/y/z becomes file:///C:/x/y/z.\n\tif isWindowsDriveURIPath(path) {\n\t\tpath = path[:1] + strings.ToUpper(string(path[1])) + path[2:]\n\t}\n\tu := url.URL{Scheme: fileScheme, Path: path}\n\treturn DocumentUri(u.String()), nil\n}\n\n// URIFromPath returns DocumentUri for the supplied file path.\n// Given \"\", it returns \"\".\nfunc URIFromPath(path string) DocumentUri {\n\tif path == \"\" {\n\t\treturn \"\"\n\t}\n\tif !isWindowsDrivePath(path) {\n\t\tif abs, err := filepath.Abs(path); err == nil {\n\t\t\tpath = abs\n\t\t}\n\t}\n\t// Check the file path again, in case it became absolute.\n\tif isWindowsDrivePath(path) {\n\t\tpath = \"/\" + strings.ToUpper(string(path[0])) + path[1:]\n\t}\n\tpath = filepath.ToSlash(path)\n\tu := url.URL{\n\t\tScheme: fileScheme,\n\t\tPath: path,\n\t}\n\treturn DocumentUri(u.String())\n}\n\nconst fileScheme = \"file\"\n\n// isWindowsDrivePath returns true if the file path is of the form used by\n// Windows. We check if the path begins with a drive letter, followed by a \":\".\n// For example: C:/x/y/z.\nfunc isWindowsDrivePath(path string) bool {\n\tif len(path) < 3 {\n\t\treturn false\n\t}\n\treturn unicode.IsLetter(rune(path[0])) && path[1] == ':'\n}\n\n// isWindowsDriveURIPath returns true if the file URI is of the format used by\n// Windows URIs. The url.Parse package does not specially handle Windows paths\n// (see golang/go#6027), so we check if the URI path has a drive prefix (e.g. \"/C:\").\nfunc isWindowsDriveURIPath(uri string) bool {\n\tif len(uri) < 4 {\n\t\treturn false\n\t}\n\treturn uri[0] == '/' && unicode.IsLetter(rune(uri[1])) && uri[2] == ':'\n}\n"], ["/opencode/internal/llm/prompt/prompt.go", "package prompt\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"strings\"\n\t\"sync\"\n\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/llm/models\"\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n)\n\nfunc GetAgentPrompt(agentName config.AgentName, provider models.ModelProvider) string {\n\tbasePrompt := \"\"\n\tswitch agentName {\n\tcase config.AgentCoder:\n\t\tbasePrompt = CoderPrompt(provider)\n\tcase config.AgentTitle:\n\t\tbasePrompt = TitlePrompt(provider)\n\tcase config.AgentTask:\n\t\tbasePrompt = TaskPrompt(provider)\n\tcase config.AgentSummarizer:\n\t\tbasePrompt = SummarizerPrompt(provider)\n\tdefault:\n\t\tbasePrompt = \"You are a helpful assistant\"\n\t}\n\n\tif agentName == config.AgentCoder || agentName == config.AgentTask {\n\t\t// Add context from project-specific instruction files if they exist\n\t\tcontextContent := getContextFromPaths()\n\t\tlogging.Debug(\"Context content\", \"Context\", contextContent)\n\t\tif contextContent != \"\" {\n\t\t\treturn fmt.Sprintf(\"%s\\n\\n# Project-Specific Context\\n Make sure to follow the instructions in the context below\\n%s\", basePrompt, contextContent)\n\t\t}\n\t}\n\treturn basePrompt\n}\n\nvar (\n\tonceContext sync.Once\n\tcontextContent string\n)\n\nfunc getContextFromPaths() string {\n\tonceContext.Do(func() {\n\t\tvar (\n\t\t\tcfg = config.Get()\n\t\t\tworkDir = cfg.WorkingDir\n\t\t\tcontextPaths = cfg.ContextPaths\n\t\t)\n\n\t\tcontextContent = processContextPaths(workDir, contextPaths)\n\t})\n\n\treturn contextContent\n}\n\nfunc processContextPaths(workDir string, paths []string) string {\n\tvar (\n\t\twg sync.WaitGroup\n\t\tresultCh = make(chan string)\n\t)\n\n\t// Track processed files to avoid duplicates\n\tprocessedFiles := make(map[string]bool)\n\tvar processedMutex sync.Mutex\n\n\tfor _, path := range paths {\n\t\twg.Add(1)\n\t\tgo func(p string) {\n\t\t\tdefer wg.Done()\n\n\t\t\tif strings.HasSuffix(p, \"/\") {\n\t\t\t\tfilepath.WalkDir(filepath.Join(workDir, p), func(path string, d os.DirEntry, err error) error {\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn err\n\t\t\t\t\t}\n\t\t\t\t\tif !d.IsDir() {\n\t\t\t\t\t\t// Check if we've already processed this file (case-insensitive)\n\t\t\t\t\t\tprocessedMutex.Lock()\n\t\t\t\t\t\tlowerPath := strings.ToLower(path)\n\t\t\t\t\t\tif !processedFiles[lowerPath] {\n\t\t\t\t\t\t\tprocessedFiles[lowerPath] = true\n\t\t\t\t\t\t\tprocessedMutex.Unlock()\n\n\t\t\t\t\t\t\tif result := processFile(path); result != \"\" {\n\t\t\t\t\t\t\t\tresultCh <- result\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tprocessedMutex.Unlock()\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\treturn nil\n\t\t\t\t})\n\t\t\t} else {\n\t\t\t\tfullPath := filepath.Join(workDir, p)\n\n\t\t\t\t// Check if we've already processed this file (case-insensitive)\n\t\t\t\tprocessedMutex.Lock()\n\t\t\t\tlowerPath := strings.ToLower(fullPath)\n\t\t\t\tif !processedFiles[lowerPath] {\n\t\t\t\t\tprocessedFiles[lowerPath] = true\n\t\t\t\t\tprocessedMutex.Unlock()\n\n\t\t\t\t\tresult := processFile(fullPath)\n\t\t\t\t\tif result != \"\" {\n\t\t\t\t\t\tresultCh <- result\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tprocessedMutex.Unlock()\n\t\t\t\t}\n\t\t\t}\n\t\t}(path)\n\t}\n\n\tgo func() {\n\t\twg.Wait()\n\t\tclose(resultCh)\n\t}()\n\n\tresults := make([]string, 0)\n\tfor result := range resultCh {\n\t\tresults = append(results, result)\n\t}\n\n\treturn strings.Join(results, \"\\n\")\n}\n\nfunc processFile(filePath string) string {\n\tcontent, err := os.ReadFile(filePath)\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\treturn \"# From:\" + filePath + \"\\n\" + string(content)\n}\n"], ["/opencode/internal/llm/agent/mcp-tools.go", "package agent\n\nimport (\n\t\"context\"\n\t\"encoding/json\"\n\t\"fmt\"\n\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/llm/tools\"\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n\t\"github.com/opencode-ai/opencode/internal/permission\"\n\t\"github.com/opencode-ai/opencode/internal/version\"\n\n\t\"github.com/mark3labs/mcp-go/client\"\n\t\"github.com/mark3labs/mcp-go/mcp\"\n)\n\ntype mcpTool struct {\n\tmcpName string\n\ttool mcp.Tool\n\tmcpConfig config.MCPServer\n\tpermissions permission.Service\n}\n\ntype MCPClient interface {\n\tInitialize(\n\t\tctx context.Context,\n\t\trequest mcp.InitializeRequest,\n\t) (*mcp.InitializeResult, error)\n\tListTools(ctx context.Context, request mcp.ListToolsRequest) (*mcp.ListToolsResult, error)\n\tCallTool(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error)\n\tClose() error\n}\n\nfunc (b *mcpTool) Info() tools.ToolInfo {\n\trequired := b.tool.InputSchema.Required\n\tif required == nil {\n\t\trequired = make([]string, 0)\n\t}\n\treturn tools.ToolInfo{\n\t\tName: fmt.Sprintf(\"%s_%s\", b.mcpName, b.tool.Name),\n\t\tDescription: b.tool.Description,\n\t\tParameters: b.tool.InputSchema.Properties,\n\t\tRequired: required,\n\t}\n}\n\nfunc runTool(ctx context.Context, c MCPClient, toolName string, input string) (tools.ToolResponse, error) {\n\tdefer c.Close()\n\tinitRequest := mcp.InitializeRequest{}\n\tinitRequest.Params.ProtocolVersion = mcp.LATEST_PROTOCOL_VERSION\n\tinitRequest.Params.ClientInfo = mcp.Implementation{\n\t\tName: \"OpenCode\",\n\t\tVersion: version.Version,\n\t}\n\n\t_, err := c.Initialize(ctx, initRequest)\n\tif err != nil {\n\t\treturn tools.NewTextErrorResponse(err.Error()), nil\n\t}\n\n\ttoolRequest := mcp.CallToolRequest{}\n\ttoolRequest.Params.Name = toolName\n\tvar args map[string]any\n\tif err = json.Unmarshal([]byte(input), &args); err != nil {\n\t\treturn tools.NewTextErrorResponse(fmt.Sprintf(\"error parsing parameters: %s\", err)), nil\n\t}\n\ttoolRequest.Params.Arguments = args\n\tresult, err := c.CallTool(ctx, toolRequest)\n\tif err != nil {\n\t\treturn tools.NewTextErrorResponse(err.Error()), nil\n\t}\n\n\toutput := \"\"\n\tfor _, v := range result.Content {\n\t\tif v, ok := v.(mcp.TextContent); ok {\n\t\t\toutput = v.Text\n\t\t} else {\n\t\t\toutput = fmt.Sprintf(\"%v\", v)\n\t\t}\n\t}\n\n\treturn tools.NewTextResponse(output), nil\n}\n\nfunc (b *mcpTool) Run(ctx context.Context, params tools.ToolCall) (tools.ToolResponse, error) {\n\tsessionID, messageID := tools.GetContextValues(ctx)\n\tif sessionID == \"\" || messageID == \"\" {\n\t\treturn tools.ToolResponse{}, fmt.Errorf(\"session ID and message ID are required for creating a new file\")\n\t}\n\tpermissionDescription := fmt.Sprintf(\"execute %s with the following parameters: %s\", b.Info().Name, params.Input)\n\tp := b.permissions.Request(\n\t\tpermission.CreatePermissionRequest{\n\t\t\tSessionID: sessionID,\n\t\t\tPath: config.WorkingDirectory(),\n\t\t\tToolName: b.Info().Name,\n\t\t\tAction: \"execute\",\n\t\t\tDescription: permissionDescription,\n\t\t\tParams: params.Input,\n\t\t},\n\t)\n\tif !p {\n\t\treturn tools.NewTextErrorResponse(\"permission denied\"), nil\n\t}\n\n\tswitch b.mcpConfig.Type {\n\tcase config.MCPStdio:\n\t\tc, err := client.NewStdioMCPClient(\n\t\t\tb.mcpConfig.Command,\n\t\t\tb.mcpConfig.Env,\n\t\t\tb.mcpConfig.Args...,\n\t\t)\n\t\tif err != nil {\n\t\t\treturn tools.NewTextErrorResponse(err.Error()), nil\n\t\t}\n\t\treturn runTool(ctx, c, b.tool.Name, params.Input)\n\tcase config.MCPSse:\n\t\tc, err := client.NewSSEMCPClient(\n\t\t\tb.mcpConfig.URL,\n\t\t\tclient.WithHeaders(b.mcpConfig.Headers),\n\t\t)\n\t\tif err != nil {\n\t\t\treturn tools.NewTextErrorResponse(err.Error()), nil\n\t\t}\n\t\treturn runTool(ctx, c, b.tool.Name, params.Input)\n\t}\n\n\treturn tools.NewTextErrorResponse(\"invalid mcp type\"), nil\n}\n\nfunc NewMcpTool(name string, tool mcp.Tool, permissions permission.Service, mcpConfig config.MCPServer) tools.BaseTool {\n\treturn &mcpTool{\n\t\tmcpName: name,\n\t\ttool: tool,\n\t\tmcpConfig: mcpConfig,\n\t\tpermissions: permissions,\n\t}\n}\n\nvar mcpTools []tools.BaseTool\n\nfunc getTools(ctx context.Context, name string, m config.MCPServer, permissions permission.Service, c MCPClient) []tools.BaseTool {\n\tvar stdioTools []tools.BaseTool\n\tinitRequest := mcp.InitializeRequest{}\n\tinitRequest.Params.ProtocolVersion = mcp.LATEST_PROTOCOL_VERSION\n\tinitRequest.Params.ClientInfo = mcp.Implementation{\n\t\tName: \"OpenCode\",\n\t\tVersion: version.Version,\n\t}\n\n\t_, err := c.Initialize(ctx, initRequest)\n\tif err != nil {\n\t\tlogging.Error(\"error initializing mcp client\", \"error\", err)\n\t\treturn stdioTools\n\t}\n\ttoolsRequest := mcp.ListToolsRequest{}\n\ttools, err := c.ListTools(ctx, toolsRequest)\n\tif err != nil {\n\t\tlogging.Error(\"error listing tools\", \"error\", err)\n\t\treturn stdioTools\n\t}\n\tfor _, t := range tools.Tools {\n\t\tstdioTools = append(stdioTools, NewMcpTool(name, t, permissions, m))\n\t}\n\tdefer c.Close()\n\treturn stdioTools\n}\n\nfunc GetMcpTools(ctx context.Context, permissions permission.Service) []tools.BaseTool {\n\tif len(mcpTools) > 0 {\n\t\treturn mcpTools\n\t}\n\tfor name, m := range config.Get().MCPServers {\n\t\tswitch m.Type {\n\t\tcase config.MCPStdio:\n\t\t\tc, err := client.NewStdioMCPClient(\n\t\t\t\tm.Command,\n\t\t\t\tm.Env,\n\t\t\t\tm.Args...,\n\t\t\t)\n\t\t\tif err != nil {\n\t\t\t\tlogging.Error(\"error creating mcp client\", \"error\", err)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tmcpTools = append(mcpTools, getTools(ctx, name, m, permissions, c)...)\n\t\tcase config.MCPSse:\n\t\t\tc, err := client.NewSSEMCPClient(\n\t\t\t\tm.URL,\n\t\t\t\tclient.WithHeaders(m.Headers),\n\t\t\t)\n\t\t\tif err != nil {\n\t\t\t\tlogging.Error(\"error creating mcp client\", \"error\", err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tmcpTools = append(mcpTools, getTools(ctx, name, m, permissions, c)...)\n\t\t}\n\t}\n\n\treturn mcpTools\n}\n"], ["/opencode/internal/llm/models/local.go", "package models\n\nimport (\n\t\"cmp\"\n\t\"encoding/json\"\n\t\"net/http\"\n\t\"net/url\"\n\t\"os\"\n\t\"regexp\"\n\t\"strings\"\n\t\"unicode\"\n\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n\t\"github.com/spf13/viper\"\n)\n\nconst (\n\tProviderLocal ModelProvider = \"local\"\n\n\tlocalModelsPath = \"v1/models\"\n\tlmStudioBetaModelsPath = \"api/v0/models\"\n)\n\nfunc init() {\n\tif endpoint := os.Getenv(\"LOCAL_ENDPOINT\"); endpoint != \"\" {\n\t\tlocalEndpoint, err := url.Parse(endpoint)\n\t\tif err != nil {\n\t\t\tlogging.Debug(\"Failed to parse local endpoint\",\n\t\t\t\t\"error\", err,\n\t\t\t\t\"endpoint\", endpoint,\n\t\t\t)\n\t\t\treturn\n\t\t}\n\n\t\tload := func(url *url.URL, path string) []localModel {\n\t\t\turl.Path = path\n\t\t\treturn listLocalModels(url.String())\n\t\t}\n\n\t\tmodels := load(localEndpoint, lmStudioBetaModelsPath)\n\n\t\tif len(models) == 0 {\n\t\t\tmodels = load(localEndpoint, localModelsPath)\n\t\t}\n\n\t\tif len(models) == 0 {\n\t\t\tlogging.Debug(\"No local models found\",\n\t\t\t\t\"endpoint\", endpoint,\n\t\t\t)\n\t\t\treturn\n\t\t}\n\n\t\tloadLocalModels(models)\n\n\t\tviper.SetDefault(\"providers.local.apiKey\", \"dummy\")\n\t\tProviderPopularity[ProviderLocal] = 0\n\t}\n}\n\ntype localModelList struct {\n\tData []localModel `json:\"data\"`\n}\n\ntype localModel struct {\n\tID string `json:\"id\"`\n\tObject string `json:\"object\"`\n\tType string `json:\"type\"`\n\tPublisher string `json:\"publisher\"`\n\tArch string `json:\"arch\"`\n\tCompatibilityType string `json:\"compatibility_type\"`\n\tQuantization string `json:\"quantization\"`\n\tState string `json:\"state\"`\n\tMaxContextLength int64 `json:\"max_context_length\"`\n\tLoadedContextLength int64 `json:\"loaded_context_length\"`\n}\n\nfunc listLocalModels(modelsEndpoint string) []localModel {\n\tres, err := http.Get(modelsEndpoint)\n\tif err != nil {\n\t\tlogging.Debug(\"Failed to list local models\",\n\t\t\t\"error\", err,\n\t\t\t\"endpoint\", modelsEndpoint,\n\t\t)\n\t\treturn []localModel{}\n\t}\n\tdefer res.Body.Close()\n\n\tif res.StatusCode != http.StatusOK {\n\t\tlogging.Debug(\"Failed to list local models\",\n\t\t\t\"status\", res.StatusCode,\n\t\t\t\"endpoint\", modelsEndpoint,\n\t\t)\n\t\treturn []localModel{}\n\t}\n\n\tvar modelList localModelList\n\tif err = json.NewDecoder(res.Body).Decode(&modelList); err != nil {\n\t\tlogging.Debug(\"Failed to list local models\",\n\t\t\t\"error\", err,\n\t\t\t\"endpoint\", modelsEndpoint,\n\t\t)\n\t\treturn []localModel{}\n\t}\n\n\tvar supportedModels []localModel\n\tfor _, model := range modelList.Data {\n\t\tif strings.HasSuffix(modelsEndpoint, lmStudioBetaModelsPath) {\n\t\t\tif model.Object != \"model\" || model.Type != \"llm\" {\n\t\t\t\tlogging.Debug(\"Skipping unsupported LMStudio model\",\n\t\t\t\t\t\"endpoint\", modelsEndpoint,\n\t\t\t\t\t\"id\", model.ID,\n\t\t\t\t\t\"object\", model.Object,\n\t\t\t\t\t\"type\", model.Type,\n\t\t\t\t)\n\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\n\t\tsupportedModels = append(supportedModels, model)\n\t}\n\n\treturn supportedModels\n}\n\nfunc loadLocalModels(models []localModel) {\n\tfor i, m := range models {\n\t\tmodel := convertLocalModel(m)\n\t\tSupportedModels[model.ID] = model\n\n\t\tif i == 0 || m.State == \"loaded\" {\n\t\t\tviper.SetDefault(\"agents.coder.model\", model.ID)\n\t\t\tviper.SetDefault(\"agents.summarizer.model\", model.ID)\n\t\t\tviper.SetDefault(\"agents.task.model\", model.ID)\n\t\t\tviper.SetDefault(\"agents.title.model\", model.ID)\n\t\t}\n\t}\n}\n\nfunc convertLocalModel(model localModel) Model {\n\treturn Model{\n\t\tID: ModelID(\"local.\" + model.ID),\n\t\tName: friendlyModelName(model.ID),\n\t\tProvider: ProviderLocal,\n\t\tAPIModel: model.ID,\n\t\tContextWindow: cmp.Or(model.LoadedContextLength, 4096),\n\t\tDefaultMaxTokens: cmp.Or(model.LoadedContextLength, 4096),\n\t\tCanReason: true,\n\t\tSupportsAttachments: true,\n\t}\n}\n\nvar modelInfoRegex = regexp.MustCompile(`(?i)^([a-z0-9]+)(?:[-_]?([rv]?\\d[\\.\\d]*))?(?:[-_]?([a-z]+))?.*`)\n\nfunc friendlyModelName(modelID string) string {\n\tmainID := modelID\n\ttag := \"\"\n\n\tif slash := strings.LastIndex(mainID, \"/\"); slash != -1 {\n\t\tmainID = mainID[slash+1:]\n\t}\n\n\tif at := strings.Index(modelID, \"@\"); at != -1 {\n\t\tmainID = modelID[:at]\n\t\ttag = modelID[at+1:]\n\t}\n\n\tmatch := modelInfoRegex.FindStringSubmatch(mainID)\n\tif match == nil {\n\t\treturn modelID\n\t}\n\n\tcapitalize := func(s string) string {\n\t\tif s == \"\" {\n\t\t\treturn \"\"\n\t\t}\n\t\trunes := []rune(s)\n\t\trunes[0] = unicode.ToUpper(runes[0])\n\t\treturn string(runes)\n\t}\n\n\tfamily := capitalize(match[1])\n\tversion := \"\"\n\tlabel := \"\"\n\n\tif len(match) > 2 && match[2] != \"\" {\n\t\tversion = strings.ToUpper(match[2])\n\t}\n\n\tif len(match) > 3 && match[3] != \"\" {\n\t\tlabel = capitalize(match[3])\n\t}\n\n\tvar parts []string\n\tif family != \"\" {\n\t\tparts = append(parts, family)\n\t}\n\tif version != \"\" {\n\t\tparts = append(parts, version)\n\t}\n\tif label != \"\" {\n\t\tparts = append(parts, label)\n\t}\n\tif tag != \"\" {\n\t\tparts = append(parts, tag)\n\t}\n\n\treturn strings.Join(parts, \" \")\n}\n"], ["/opencode/internal/message/content.go", "package message\n\nimport (\n\t\"encoding/base64\"\n\t\"slices\"\n\t\"time\"\n\n\t\"github.com/opencode-ai/opencode/internal/llm/models\"\n)\n\ntype MessageRole string\n\nconst (\n\tAssistant MessageRole = \"assistant\"\n\tUser MessageRole = \"user\"\n\tSystem MessageRole = \"system\"\n\tTool MessageRole = \"tool\"\n)\n\ntype FinishReason string\n\nconst (\n\tFinishReasonEndTurn FinishReason = \"end_turn\"\n\tFinishReasonMaxTokens FinishReason = \"max_tokens\"\n\tFinishReasonToolUse FinishReason = \"tool_use\"\n\tFinishReasonCanceled FinishReason = \"canceled\"\n\tFinishReasonError FinishReason = \"error\"\n\tFinishReasonPermissionDenied FinishReason = \"permission_denied\"\n\n\t// Should never happen\n\tFinishReasonUnknown FinishReason = \"unknown\"\n)\n\ntype ContentPart interface {\n\tisPart()\n}\n\ntype ReasoningContent struct {\n\tThinking string `json:\"thinking\"`\n}\n\nfunc (tc ReasoningContent) String() string {\n\treturn tc.Thinking\n}\nfunc (ReasoningContent) isPart() {}\n\ntype TextContent struct {\n\tText string `json:\"text\"`\n}\n\nfunc (tc TextContent) String() string {\n\treturn tc.Text\n}\n\nfunc (TextContent) isPart() {}\n\ntype ImageURLContent struct {\n\tURL string `json:\"url\"`\n\tDetail string `json:\"detail,omitempty\"`\n}\n\nfunc (iuc ImageURLContent) String() string {\n\treturn iuc.URL\n}\n\nfunc (ImageURLContent) isPart() {}\n\ntype BinaryContent struct {\n\tPath string\n\tMIMEType string\n\tData []byte\n}\n\nfunc (bc BinaryContent) String(provider models.ModelProvider) string {\n\tbase64Encoded := base64.StdEncoding.EncodeToString(bc.Data)\n\tif provider == models.ProviderOpenAI {\n\t\treturn \"data:\" + bc.MIMEType + \";base64,\" + base64Encoded\n\t}\n\treturn base64Encoded\n}\n\nfunc (BinaryContent) isPart() {}\n\ntype ToolCall struct {\n\tID string `json:\"id\"`\n\tName string `json:\"name\"`\n\tInput string `json:\"input\"`\n\tType string `json:\"type\"`\n\tFinished bool `json:\"finished\"`\n}\n\nfunc (ToolCall) isPart() {}\n\ntype ToolResult struct {\n\tToolCallID string `json:\"tool_call_id\"`\n\tName string `json:\"name\"`\n\tContent string `json:\"content\"`\n\tMetadata string `json:\"metadata\"`\n\tIsError bool `json:\"is_error\"`\n}\n\nfunc (ToolResult) isPart() {}\n\ntype Finish struct {\n\tReason FinishReason `json:\"reason\"`\n\tTime int64 `json:\"time\"`\n}\n\nfunc (Finish) isPart() {}\n\ntype Message struct {\n\tID string\n\tRole MessageRole\n\tSessionID string\n\tParts []ContentPart\n\tModel models.ModelID\n\tCreatedAt int64\n\tUpdatedAt int64\n}\n\nfunc (m *Message) Content() TextContent {\n\tfor _, part := range m.Parts {\n\t\tif c, ok := part.(TextContent); ok {\n\t\t\treturn c\n\t\t}\n\t}\n\treturn TextContent{}\n}\n\nfunc (m *Message) ReasoningContent() ReasoningContent {\n\tfor _, part := range m.Parts {\n\t\tif c, ok := part.(ReasoningContent); ok {\n\t\t\treturn c\n\t\t}\n\t}\n\treturn ReasoningContent{}\n}\n\nfunc (m *Message) ImageURLContent() []ImageURLContent {\n\timageURLContents := make([]ImageURLContent, 0)\n\tfor _, part := range m.Parts {\n\t\tif c, ok := part.(ImageURLContent); ok {\n\t\t\timageURLContents = append(imageURLContents, c)\n\t\t}\n\t}\n\treturn imageURLContents\n}\n\nfunc (m *Message) BinaryContent() []BinaryContent {\n\tbinaryContents := make([]BinaryContent, 0)\n\tfor _, part := range m.Parts {\n\t\tif c, ok := part.(BinaryContent); ok {\n\t\t\tbinaryContents = append(binaryContents, c)\n\t\t}\n\t}\n\treturn binaryContents\n}\n\nfunc (m *Message) ToolCalls() []ToolCall {\n\ttoolCalls := make([]ToolCall, 0)\n\tfor _, part := range m.Parts {\n\t\tif c, ok := part.(ToolCall); ok {\n\t\t\ttoolCalls = append(toolCalls, c)\n\t\t}\n\t}\n\treturn toolCalls\n}\n\nfunc (m *Message) ToolResults() []ToolResult {\n\ttoolResults := make([]ToolResult, 0)\n\tfor _, part := range m.Parts {\n\t\tif c, ok := part.(ToolResult); ok {\n\t\t\ttoolResults = append(toolResults, c)\n\t\t}\n\t}\n\treturn toolResults\n}\n\nfunc (m *Message) IsFinished() bool {\n\tfor _, part := range m.Parts {\n\t\tif _, ok := part.(Finish); ok {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc (m *Message) FinishPart() *Finish {\n\tfor _, part := range m.Parts {\n\t\tif c, ok := part.(Finish); ok {\n\t\t\treturn &c\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (m *Message) FinishReason() FinishReason {\n\tfor _, part := range m.Parts {\n\t\tif c, ok := part.(Finish); ok {\n\t\t\treturn c.Reason\n\t\t}\n\t}\n\treturn \"\"\n}\n\nfunc (m *Message) IsThinking() bool {\n\tif m.ReasoningContent().Thinking != \"\" && m.Content().Text == \"\" && !m.IsFinished() {\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc (m *Message) AppendContent(delta string) {\n\tfound := false\n\tfor i, part := range m.Parts {\n\t\tif c, ok := part.(TextContent); ok {\n\t\t\tm.Parts[i] = TextContent{Text: c.Text + delta}\n\t\t\tfound = true\n\t\t}\n\t}\n\tif !found {\n\t\tm.Parts = append(m.Parts, TextContent{Text: delta})\n\t}\n}\n\nfunc (m *Message) AppendReasoningContent(delta string) {\n\tfound := false\n\tfor i, part := range m.Parts {\n\t\tif c, ok := part.(ReasoningContent); ok {\n\t\t\tm.Parts[i] = ReasoningContent{Thinking: c.Thinking + delta}\n\t\t\tfound = true\n\t\t}\n\t}\n\tif !found {\n\t\tm.Parts = append(m.Parts, ReasoningContent{Thinking: delta})\n\t}\n}\n\nfunc (m *Message) FinishToolCall(toolCallID string) {\n\tfor i, part := range m.Parts {\n\t\tif c, ok := part.(ToolCall); ok {\n\t\t\tif c.ID == toolCallID {\n\t\t\t\tm.Parts[i] = ToolCall{\n\t\t\t\t\tID: c.ID,\n\t\t\t\t\tName: c.Name,\n\t\t\t\t\tInput: c.Input,\n\t\t\t\t\tType: c.Type,\n\t\t\t\t\tFinished: true,\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc (m *Message) AppendToolCallInput(toolCallID string, inputDelta string) {\n\tfor i, part := range m.Parts {\n\t\tif c, ok := part.(ToolCall); ok {\n\t\t\tif c.ID == toolCallID {\n\t\t\t\tm.Parts[i] = ToolCall{\n\t\t\t\t\tID: c.ID,\n\t\t\t\t\tName: c.Name,\n\t\t\t\t\tInput: c.Input + inputDelta,\n\t\t\t\t\tType: c.Type,\n\t\t\t\t\tFinished: c.Finished,\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc (m *Message) AddToolCall(tc ToolCall) {\n\tfor i, part := range m.Parts {\n\t\tif c, ok := part.(ToolCall); ok {\n\t\t\tif c.ID == tc.ID {\n\t\t\t\tm.Parts[i] = tc\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\tm.Parts = append(m.Parts, tc)\n}\n\nfunc (m *Message) SetToolCalls(tc []ToolCall) {\n\t// remove any existing tool call part it could have multiple\n\tparts := make([]ContentPart, 0)\n\tfor _, part := range m.Parts {\n\t\tif _, ok := part.(ToolCall); ok {\n\t\t\tcontinue\n\t\t}\n\t\tparts = append(parts, part)\n\t}\n\tm.Parts = parts\n\tfor _, toolCall := range tc {\n\t\tm.Parts = append(m.Parts, toolCall)\n\t}\n}\n\nfunc (m *Message) AddToolResult(tr ToolResult) {\n\tm.Parts = append(m.Parts, tr)\n}\n\nfunc (m *Message) SetToolResults(tr []ToolResult) {\n\tfor _, toolResult := range tr {\n\t\tm.Parts = append(m.Parts, toolResult)\n\t}\n}\n\nfunc (m *Message) AddFinish(reason FinishReason) {\n\t// remove any existing finish part\n\tfor i, part := range m.Parts {\n\t\tif _, ok := part.(Finish); ok {\n\t\t\tm.Parts = slices.Delete(m.Parts, i, i+1)\n\t\t\tbreak\n\t\t}\n\t}\n\tm.Parts = append(m.Parts, Finish{Reason: reason, Time: time.Now().Unix()})\n}\n\nfunc (m *Message) AddImageURL(url, detail string) {\n\tm.Parts = append(m.Parts, ImageURLContent{URL: url, Detail: detail})\n}\n\nfunc (m *Message) AddBinary(mimeType string, data []byte) {\n\tm.Parts = append(m.Parts, BinaryContent{MIMEType: mimeType, Data: data})\n}\n"], ["/opencode/internal/llm/prompt/coder.go", "package prompt\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"runtime\"\n\t\"time\"\n\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/llm/models\"\n\t\"github.com/opencode-ai/opencode/internal/llm/tools\"\n)\n\nfunc CoderPrompt(provider models.ModelProvider) string {\n\tbasePrompt := baseAnthropicCoderPrompt\n\tswitch provider {\n\tcase models.ProviderOpenAI:\n\t\tbasePrompt = baseOpenAICoderPrompt\n\t}\n\tenvInfo := getEnvironmentInfo()\n\n\treturn fmt.Sprintf(\"%s\\n\\n%s\\n%s\", basePrompt, envInfo, lspInformation())\n}\n\nconst baseOpenAICoderPrompt = `\nYou are operating as and within the OpenCode CLI, a terminal-based agentic coding assistant built by OpenAI. It wraps OpenAI models to enable natural language interaction with a local codebase. You are expected to be precise, safe, and helpful.\n\nYou can:\n- Receive user prompts, project context, and files.\n- Stream responses and emit function calls (e.g., shell commands, code edits).\n- Apply patches, run commands, and manage user approvals based on policy.\n- Work inside a sandboxed, git-backed workspace with rollback support.\n- Log telemetry so sessions can be replayed or inspected later.\n- More details on your functionality are available at \"opencode --help\"\n\n\nYou are an agent - please keep going until the user's query is completely resolved, before ending your turn and yielding back to the user. Only terminate your turn when you are sure that the problem is solved. If you are not sure about file content or codebase structure pertaining to the user's request, use your tools to read files and gather the relevant information: do NOT guess or make up an answer.\n\nPlease resolve the user's task by editing and testing the code files in your current code execution session. You are a deployed coding agent. Your session allows for you to modify and run code. The repo(s) are already cloned in your working directory, and you must fully solve the problem for your answer to be considered correct.\n\nYou MUST adhere to the following criteria when executing the task:\n- Working on the repo(s) in the current environment is allowed, even if they are proprietary.\n- Analyzing code for vulnerabilities is allowed.\n- Showing user code and tool call details is allowed.\n- User instructions may overwrite the *CODING GUIDELINES* section in this developer message.\n- If completing the user's task requires writing or modifying files:\n - Your code and final answer should follow these *CODING GUIDELINES*:\n - Fix the problem at the root cause rather than applying surface-level patches, when possible.\n - Avoid unneeded complexity in your solution.\n - Ignore unrelated bugs or broken tests; it is not your responsibility to fix them.\n - Update documentation as necessary.\n - Keep changes consistent with the style of the existing codebase. Changes should be minimal and focused on the task.\n - Use \"git log\" and \"git blame\" to search the history of the codebase if additional context is required; internet access is disabled.\n - NEVER add copyright or license headers unless specifically requested.\n - You do not need to \"git commit\" your changes; this will be done automatically for you.\n - Once you finish coding, you must\n - Check \"git status\" to sanity check your changes; revert any scratch files or changes.\n - Remove all inline comments you added as much as possible, even if they look normal. Check using \"git diff\". Inline comments must be generally avoided, unless active maintainers of the repo, after long careful study of the code and the issue, will still misinterpret the code without the comments.\n - Check if you accidentally add copyright or license headers. If so, remove them.\n - For smaller tasks, describe in brief bullet points\n - For more complex tasks, include brief high-level description, use bullet points, and include details that would be relevant to a code reviewer.\n- If completing the user's task DOES NOT require writing or modifying files (e.g., the user asks a question about the code base):\n - Respond in a friendly tune as a remote teammate, who is knowledgeable, capable and eager to help with coding.\n- When your task involves writing or modifying files:\n - Do NOT tell the user to \"save the file\" or \"copy the code into a file\" if you already created or modified the file using \"apply_patch\". Instead, reference the file as already saved.\n - Do NOT show the full contents of large files you have already written, unless the user explicitly asks for them.\n- When doing things with paths, always use use the full path, if the working directory is /abc/xyz and you want to edit the file abc.go in the working dir refer to it as /abc/xyz/abc.go.\n- If you send a path not including the working dir, the working dir will be prepended to it.\n- Remember the user does not see the full output of tools\n`\n\nconst baseAnthropicCoderPrompt = `You are OpenCode, an interactive CLI tool that helps users with software engineering tasks. Use the instructions below and the tools available to you to assist the user.\n\nIMPORTANT: Before you begin work, think about what the code you're editing is supposed to do based on the filenames directory structure.\n\n# Memory\nIf the current working directory contains a file called OpenCode.md, it will be automatically added to your context. This file serves multiple purposes:\n1. Storing frequently used bash commands (build, test, lint, etc.) so you can use them without searching each time\n2. Recording the user's code style preferences (naming conventions, preferred libraries, etc.)\n3. Maintaining useful information about the codebase structure and organization\n\nWhen you spend time searching for commands to typecheck, lint, build, or test, you should ask the user if it's okay to add those commands to OpenCode.md. Similarly, when learning about code style preferences or important codebase information, ask if it's okay to add that to OpenCode.md so you can remember it for next time.\n\n# Tone and style\nYou should be concise, direct, and to the point. When you run a non-trivial bash command, you should explain what the command does and why you are running it, to make sure the user understands what you are doing (this is especially important when you are running a command that will make changes to the user's system).\nRemember that your output will be displayed on a command line interface. Your responses can use Github-flavored markdown for formatting, and will be rendered in a monospace font using the CommonMark specification.\nOutput text to communicate with the user; all text you output outside of tool use is displayed to the user. Only use tools to complete tasks. Never use tools like Bash or code comments as means to communicate with the user during the session.\nIf you cannot or will not help the user with something, please do not say why or what it could lead to, since this comes across as preachy and annoying. Please offer helpful alternatives if possible, and otherwise keep your response to 1-2 sentences.\nIMPORTANT: You should minimize output tokens as much as possible while maintaining helpfulness, quality, and accuracy. Only address the specific query or task at hand, avoiding tangential information unless absolutely critical for completing the request. If you can answer in 1-3 sentences or a short paragraph, please do.\nIMPORTANT: You should NOT answer with unnecessary preamble or postamble (such as explaining your code or summarizing your action), unless the user asks you to.\nIMPORTANT: Keep your responses short, since they will be displayed on a command line interface. You MUST answer concisely with fewer than 4 lines (not including tool use or code generation), unless user asks for detail. Answer the user's question directly, without elaboration, explanation, or details. One word answers are best. Avoid introductions, conclusions, and explanations. You MUST avoid text before/after your response, such as \"The answer is .\", \"Here is the content of the file...\" or \"Based on the information provided, the answer is...\" or \"Here is what I will do next...\". Here are some examples to demonstrate appropriate verbosity:\n\nuser: 2 + 2\nassistant: 4\n\n\n\nuser: what is 2+2?\nassistant: 4\n\n\n\nuser: is 11 a prime number?\nassistant: true\n\n\n\nuser: what command should I run to list files in the current directory?\nassistant: ls\n\n\n\nuser: what command should I run to watch files in the current directory?\nassistant: [use the ls tool to list the files in the current directory, then read docs/commands in the relevant file to find out how to watch files]\nnpm run dev\n\n\n\nuser: How many golf balls fit inside a jetta?\nassistant: 150000\n\n\n\nuser: what files are in the directory src/?\nassistant: [runs ls and sees foo.c, bar.c, baz.c]\nuser: which file contains the implementation of foo?\nassistant: src/foo.c\n\n\n\nuser: write tests for new feature\nassistant: [uses grep and glob search tools to find where similar tests are defined, uses concurrent read file tool use blocks in one tool call to read relevant files at the same time, uses edit/patch file tool to write new tests]\n\n\n# Proactiveness\nYou are allowed to be proactive, but only when the user asks you to do something. You should strive to strike a balance between:\n1. Doing the right thing when asked, including taking actions and follow-up actions\n2. Not surprising the user with actions you take without asking\nFor example, if the user asks you how to approach something, you should do your best to answer their question first, and not immediately jump into taking actions.\n3. Do not add additional code explanation summary unless requested by the user. After working on a file, just stop, rather than providing an explanation of what you did.\n\n# Following conventions\nWhen making changes to files, first understand the file's code conventions. Mimic code style, use existing libraries and utilities, and follow existing patterns.\n- NEVER assume that a given library is available, even if it is well known. Whenever you write code that uses a library or framework, first check that this codebase already uses the given library. For example, you might look at neighboring files, or check the package.json (or cargo.toml, and so on depending on the language).\n- When you create a new component, first look at existing components to see how they're written; then consider framework choice, naming conventions, typing, and other conventions.\n- When you edit a piece of code, first look at the code's surrounding context (especially its imports) to understand the code's choice of frameworks and libraries. Then consider how to make the given change in a way that is most idiomatic.\n- Always follow security best practices. Never introduce code that exposes or logs secrets and keys. Never commit secrets or keys to the repository.\n\n# Code style\n- Do not add comments to the code you write, unless the user asks you to, or the code is complex and requires additional context.\n\n# Doing tasks\nThe user will primarily request you perform software engineering tasks. This includes solving bugs, adding new functionality, refactoring code, explaining code, and more. For these tasks the following steps are recommended:\n1. Use the available search tools to understand the codebase and the user's query. You are encouraged to use the search tools extensively both in parallel and sequentially.\n2. Implement the solution using all tools available to you\n3. Verify the solution if possible with tests. NEVER assume specific test framework or test script. Check the README or search codebase to determine the testing approach.\n4. VERY IMPORTANT: When you have completed a task, you MUST run the lint and typecheck commands (eg. npm run lint, npm run typecheck, ruff, etc.) if they were provided to you to ensure your code is correct. If you are unable to find the correct command, ask the user for the command to run and if they supply it, proactively suggest writing it to opencode.md so that you will know to run it next time.\n\nNEVER commit changes unless the user explicitly asks you to. It is VERY IMPORTANT to only commit when explicitly asked, otherwise the user will feel that you are being too proactive.\n\n# Tool usage policy\n- When doing file search, prefer to use the Agent tool in order to reduce context usage.\n- If you intend to call multiple tools and there are no dependencies between the calls, make all of the independent calls in the same function_calls block.\n- IMPORTANT: The user does not see the full output of the tool responses, so if you need the output of the tool for the response make sure to summarize it for the user.\n\nYou MUST answer concisely with fewer than 4 lines of text (not including tool use or code generation), unless user asks for detail.`\n\nfunc getEnvironmentInfo() string {\n\tcwd := config.WorkingDirectory()\n\tisGit := isGitRepo(cwd)\n\tplatform := runtime.GOOS\n\tdate := time.Now().Format(\"1/2/2006\")\n\tls := tools.NewLsTool()\n\tr, _ := ls.Run(context.Background(), tools.ToolCall{\n\t\tInput: `{\"path\":\".\"}`,\n\t})\n\treturn fmt.Sprintf(`Here is useful information about the environment you are running in:\n\nWorking directory: %s\nIs directory a git repo: %s\nPlatform: %s\nToday's date: %s\n\n\n%s\n\n\t\t`, cwd, boolToYesNo(isGit), platform, date, r.Content)\n}\n\nfunc isGitRepo(dir string) bool {\n\t_, err := os.Stat(filepath.Join(dir, \".git\"))\n\treturn err == nil\n}\n\nfunc lspInformation() string {\n\tcfg := config.Get()\n\thasLSP := false\n\tfor _, v := range cfg.LSP {\n\t\tif !v.Disabled {\n\t\t\thasLSP = true\n\t\t\tbreak\n\t\t}\n\t}\n\tif !hasLSP {\n\t\treturn \"\"\n\t}\n\treturn `# LSP Information\nTools that support it will also include useful diagnostics such as linting and typechecking.\n- These diagnostics will be automatically enabled when you run the tool, and will be displayed in the output at the bottom within the and tags.\n- Take necessary actions to fix the issues.\n- You should ignore diagnostics of files that you did not change or are not related or caused by your changes unless the user explicitly asks you to fix them.\n`\n}\n\nfunc boolToYesNo(b bool) string {\n\tif b {\n\t\treturn \"Yes\"\n\t}\n\treturn \"No\"\n}\n"], ["/opencode/internal/tui/layout/layout.go", "package layout\n\nimport (\n\t\"reflect\"\n\n\t\"github.com/charmbracelet/bubbles/key\"\n\ttea \"github.com/charmbracelet/bubbletea\"\n)\n\ntype Focusable interface {\n\tFocus() tea.Cmd\n\tBlur() tea.Cmd\n\tIsFocused() bool\n}\n\ntype Sizeable interface {\n\tSetSize(width, height int) tea.Cmd\n\tGetSize() (int, int)\n}\n\ntype Bindings interface {\n\tBindingKeys() []key.Binding\n}\n\nfunc KeyMapToSlice(t any) (bindings []key.Binding) {\n\ttyp := reflect.TypeOf(t)\n\tif typ.Kind() != reflect.Struct {\n\t\treturn nil\n\t}\n\tfor i := range typ.NumField() {\n\t\tv := reflect.ValueOf(t).Field(i)\n\t\tbindings = append(bindings, v.Interface().(key.Binding))\n\t}\n\treturn\n}\n"], ["/opencode/internal/logging/writer.go", "package logging\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"fmt\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com/go-logfmt/logfmt\"\n\t\"github.com/opencode-ai/opencode/internal/pubsub\"\n)\n\nconst (\n\tpersistKeyArg = \"$_persist\"\n\tPersistTimeArg = \"$_persist_time\"\n)\n\ntype LogData struct {\n\tmessages []LogMessage\n\t*pubsub.Broker[LogMessage]\n\tlock sync.Mutex\n}\n\nfunc (l *LogData) Add(msg LogMessage) {\n\tl.lock.Lock()\n\tdefer l.lock.Unlock()\n\tl.messages = append(l.messages, msg)\n\tl.Publish(pubsub.CreatedEvent, msg)\n}\n\nfunc (l *LogData) List() []LogMessage {\n\tl.lock.Lock()\n\tdefer l.lock.Unlock()\n\treturn l.messages\n}\n\nvar defaultLogData = &LogData{\n\tmessages: make([]LogMessage, 0),\n\tBroker: pubsub.NewBroker[LogMessage](),\n}\n\ntype writer struct{}\n\nfunc (w *writer) Write(p []byte) (int, error) {\n\td := logfmt.NewDecoder(bytes.NewReader(p))\n\n\tfor d.ScanRecord() {\n\t\tmsg := LogMessage{\n\t\t\tID: fmt.Sprintf(\"%d\", time.Now().UnixNano()),\n\t\t\tTime: time.Now(),\n\t\t}\n\t\tfor d.ScanKeyval() {\n\t\t\tswitch string(d.Key()) {\n\t\t\tcase \"time\":\n\t\t\t\tparsed, err := time.Parse(time.RFC3339, string(d.Value()))\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn 0, fmt.Errorf(\"parsing time: %w\", err)\n\t\t\t\t}\n\t\t\t\tmsg.Time = parsed\n\t\t\tcase \"level\":\n\t\t\t\tmsg.Level = strings.ToLower(string(d.Value()))\n\t\t\tcase \"msg\":\n\t\t\t\tmsg.Message = string(d.Value())\n\t\t\tdefault:\n\t\t\t\tif string(d.Key()) == persistKeyArg {\n\t\t\t\t\tmsg.Persist = true\n\t\t\t\t} else if string(d.Key()) == PersistTimeArg {\n\t\t\t\t\tparsed, err := time.ParseDuration(string(d.Value()))\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tmsg.PersistTime = parsed\n\t\t\t\t} else {\n\t\t\t\t\tmsg.Attributes = append(msg.Attributes, Attr{\n\t\t\t\t\t\tKey: string(d.Key()),\n\t\t\t\t\t\tValue: string(d.Value()),\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tdefaultLogData.Add(msg)\n\t}\n\tif d.Err() != nil {\n\t\treturn 0, d.Err()\n\t}\n\treturn len(p), nil\n}\n\nfunc NewWriter() *writer {\n\tw := &writer{}\n\treturn w\n}\n\nfunc Subscribe(ctx context.Context) <-chan pubsub.Event[LogMessage] {\n\treturn defaultLogData.Subscribe(ctx)\n}\n\nfunc List() []LogMessage {\n\treturn defaultLogData.List()\n}\n"], ["/opencode/internal/app/app.go", "package app\n\nimport (\n\t\"context\"\n\t\"database/sql\"\n\t\"errors\"\n\t\"fmt\"\n\t\"maps\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/db\"\n\t\"github.com/opencode-ai/opencode/internal/format\"\n\t\"github.com/opencode-ai/opencode/internal/history\"\n\t\"github.com/opencode-ai/opencode/internal/llm/agent\"\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n\t\"github.com/opencode-ai/opencode/internal/lsp\"\n\t\"github.com/opencode-ai/opencode/internal/message\"\n\t\"github.com/opencode-ai/opencode/internal/permission\"\n\t\"github.com/opencode-ai/opencode/internal/session\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n)\n\ntype App struct {\n\tSessions session.Service\n\tMessages message.Service\n\tHistory history.Service\n\tPermissions permission.Service\n\n\tCoderAgent agent.Service\n\n\tLSPClients map[string]*lsp.Client\n\n\tclientsMutex sync.RWMutex\n\n\twatcherCancelFuncs []context.CancelFunc\n\tcancelFuncsMutex sync.Mutex\n\twatcherWG sync.WaitGroup\n}\n\nfunc New(ctx context.Context, conn *sql.DB) (*App, error) {\n\tq := db.New(conn)\n\tsessions := session.NewService(q)\n\tmessages := message.NewService(q)\n\tfiles := history.NewService(q, conn)\n\n\tapp := &App{\n\t\tSessions: sessions,\n\t\tMessages: messages,\n\t\tHistory: files,\n\t\tPermissions: permission.NewPermissionService(),\n\t\tLSPClients: make(map[string]*lsp.Client),\n\t}\n\n\t// Initialize theme based on configuration\n\tapp.initTheme()\n\n\t// Initialize LSP clients in the background\n\tgo app.initLSPClients(ctx)\n\n\tvar err error\n\tapp.CoderAgent, err = agent.NewAgent(\n\t\tconfig.AgentCoder,\n\t\tapp.Sessions,\n\t\tapp.Messages,\n\t\tagent.CoderAgentTools(\n\t\t\tapp.Permissions,\n\t\t\tapp.Sessions,\n\t\t\tapp.Messages,\n\t\t\tapp.History,\n\t\t\tapp.LSPClients,\n\t\t),\n\t)\n\tif err != nil {\n\t\tlogging.Error(\"Failed to create coder agent\", err)\n\t\treturn nil, err\n\t}\n\n\treturn app, nil\n}\n\n// initTheme sets the application theme based on the configuration\nfunc (app *App) initTheme() {\n\tcfg := config.Get()\n\tif cfg == nil || cfg.TUI.Theme == \"\" {\n\t\treturn // Use default theme\n\t}\n\n\t// Try to set the theme from config\n\terr := theme.SetTheme(cfg.TUI.Theme)\n\tif err != nil {\n\t\tlogging.Warn(\"Failed to set theme from config, using default theme\", \"theme\", cfg.TUI.Theme, \"error\", err)\n\t} else {\n\t\tlogging.Debug(\"Set theme from config\", \"theme\", cfg.TUI.Theme)\n\t}\n}\n\n// RunNonInteractive handles the execution flow when a prompt is provided via CLI flag.\nfunc (a *App) RunNonInteractive(ctx context.Context, prompt string, outputFormat string, quiet bool) error {\n\tlogging.Info(\"Running in non-interactive mode\")\n\n\t// Start spinner if not in quiet mode\n\tvar spinner *format.Spinner\n\tif !quiet {\n\t\tspinner = format.NewSpinner(\"Thinking...\")\n\t\tspinner.Start()\n\t\tdefer spinner.Stop()\n\t}\n\n\tconst maxPromptLengthForTitle = 100\n\ttitlePrefix := \"Non-interactive: \"\n\tvar titleSuffix string\n\n\tif len(prompt) > maxPromptLengthForTitle {\n\t\ttitleSuffix = prompt[:maxPromptLengthForTitle] + \"...\"\n\t} else {\n\t\ttitleSuffix = prompt\n\t}\n\ttitle := titlePrefix + titleSuffix\n\n\tsess, err := a.Sessions.Create(ctx, title)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to create session for non-interactive mode: %w\", err)\n\t}\n\tlogging.Info(\"Created session for non-interactive run\", \"session_id\", sess.ID)\n\n\t// Automatically approve all permission requests for this non-interactive session\n\ta.Permissions.AutoApproveSession(sess.ID)\n\n\tdone, err := a.CoderAgent.Run(ctx, sess.ID, prompt)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to start agent processing stream: %w\", err)\n\t}\n\n\tresult := <-done\n\tif result.Error != nil {\n\t\tif errors.Is(result.Error, context.Canceled) || errors.Is(result.Error, agent.ErrRequestCancelled) {\n\t\t\tlogging.Info(\"Agent processing cancelled\", \"session_id\", sess.ID)\n\t\t\treturn nil\n\t\t}\n\t\treturn fmt.Errorf(\"agent processing failed: %w\", result.Error)\n\t}\n\n\t// Stop spinner before printing output\n\tif !quiet && spinner != nil {\n\t\tspinner.Stop()\n\t}\n\n\t// Get the text content from the response\n\tcontent := \"No content available\"\n\tif result.Message.Content().String() != \"\" {\n\t\tcontent = result.Message.Content().String()\n\t}\n\n\tfmt.Println(format.FormatOutput(content, outputFormat))\n\n\tlogging.Info(\"Non-interactive run completed\", \"session_id\", sess.ID)\n\n\treturn nil\n}\n\n// Shutdown performs a clean shutdown of the application\nfunc (app *App) Shutdown() {\n\t// Cancel all watcher goroutines\n\tapp.cancelFuncsMutex.Lock()\n\tfor _, cancel := range app.watcherCancelFuncs {\n\t\tcancel()\n\t}\n\tapp.cancelFuncsMutex.Unlock()\n\tapp.watcherWG.Wait()\n\n\t// Perform additional cleanup for LSP clients\n\tapp.clientsMutex.RLock()\n\tclients := make(map[string]*lsp.Client, len(app.LSPClients))\n\tmaps.Copy(clients, app.LSPClients)\n\tapp.clientsMutex.RUnlock()\n\n\tfor name, client := range clients {\n\t\tshutdownCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)\n\t\tif err := client.Shutdown(shutdownCtx); err != nil {\n\t\t\tlogging.Error(\"Failed to shutdown LSP client\", \"name\", name, \"error\", err)\n\t\t}\n\t\tcancel()\n\t}\n}\n"], ["/opencode/internal/tui/theme/dracula.go", "package theme\n\nimport (\n\t\"github.com/charmbracelet/lipgloss\"\n)\n\n// DraculaTheme implements the Theme interface with Dracula colors.\n// It provides both dark and light variants, though Dracula is primarily a dark theme.\ntype DraculaTheme struct {\n\tBaseTheme\n}\n\n// NewDraculaTheme creates a new instance of the Dracula theme.\nfunc NewDraculaTheme() *DraculaTheme {\n\t// Dracula color palette\n\t// Official colors from https://draculatheme.com/\n\tdarkBackground := \"#282a36\"\n\tdarkCurrentLine := \"#44475a\"\n\tdarkSelection := \"#44475a\"\n\tdarkForeground := \"#f8f8f2\"\n\tdarkComment := \"#6272a4\"\n\tdarkCyan := \"#8be9fd\"\n\tdarkGreen := \"#50fa7b\"\n\tdarkOrange := \"#ffb86c\"\n\tdarkPink := \"#ff79c6\"\n\tdarkPurple := \"#bd93f9\"\n\tdarkRed := \"#ff5555\"\n\tdarkYellow := \"#f1fa8c\"\n\tdarkBorder := \"#44475a\"\n\n\t// Light mode approximation (Dracula is primarily a dark theme)\n\tlightBackground := \"#f8f8f2\"\n\tlightCurrentLine := \"#e6e6e6\"\n\tlightSelection := \"#d8d8d8\"\n\tlightForeground := \"#282a36\"\n\tlightComment := \"#6272a4\"\n\tlightCyan := \"#0097a7\"\n\tlightGreen := \"#388e3c\"\n\tlightOrange := \"#f57c00\"\n\tlightPink := \"#d81b60\"\n\tlightPurple := \"#7e57c2\"\n\tlightRed := \"#e53935\"\n\tlightYellow := \"#fbc02d\"\n\tlightBorder := \"#d8d8d8\"\n\n\ttheme := &DraculaTheme{}\n\n\t// Base colors\n\ttheme.PrimaryColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPurple,\n\t\tLight: lightPurple,\n\t}\n\ttheme.SecondaryColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPink,\n\t\tLight: lightPink,\n\t}\n\ttheme.AccentColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\n\t// Status colors\n\ttheme.ErrorColor = lipgloss.AdaptiveColor{\n\t\tDark: darkRed,\n\t\tLight: lightRed,\n\t}\n\ttheme.WarningColor = lipgloss.AdaptiveColor{\n\t\tDark: darkOrange,\n\t\tLight: lightOrange,\n\t}\n\ttheme.SuccessColor = lipgloss.AdaptiveColor{\n\t\tDark: darkGreen,\n\t\tLight: lightGreen,\n\t}\n\ttheme.InfoColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\n\t// Text colors\n\ttheme.TextColor = lipgloss.AdaptiveColor{\n\t\tDark: darkForeground,\n\t\tLight: lightForeground,\n\t}\n\ttheme.TextMutedColor = lipgloss.AdaptiveColor{\n\t\tDark: darkComment,\n\t\tLight: lightComment,\n\t}\n\ttheme.TextEmphasizedColor = lipgloss.AdaptiveColor{\n\t\tDark: darkYellow,\n\t\tLight: lightYellow,\n\t}\n\n\t// Background colors\n\ttheme.BackgroundColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBackground,\n\t\tLight: lightBackground,\n\t}\n\ttheme.BackgroundSecondaryColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCurrentLine,\n\t\tLight: lightCurrentLine,\n\t}\n\ttheme.BackgroundDarkerColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#21222c\", // Slightly darker than background\n\t\tLight: \"#ffffff\", // Slightly lighter than background\n\t}\n\n\t// Border colors\n\ttheme.BorderNormalColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBorder,\n\t\tLight: lightBorder,\n\t}\n\ttheme.BorderFocusedColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPurple,\n\t\tLight: lightPurple,\n\t}\n\ttheme.BorderDimColor = lipgloss.AdaptiveColor{\n\t\tDark: darkSelection,\n\t\tLight: lightSelection,\n\t}\n\n\t// Diff view colors\n\ttheme.DiffAddedColor = lipgloss.AdaptiveColor{\n\t\tDark: darkGreen,\n\t\tLight: lightGreen,\n\t}\n\ttheme.DiffRemovedColor = lipgloss.AdaptiveColor{\n\t\tDark: darkRed,\n\t\tLight: lightRed,\n\t}\n\ttheme.DiffContextColor = lipgloss.AdaptiveColor{\n\t\tDark: darkComment,\n\t\tLight: lightComment,\n\t}\n\ttheme.DiffHunkHeaderColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPurple,\n\t\tLight: lightPurple,\n\t}\n\ttheme.DiffHighlightAddedColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#50fa7b\",\n\t\tLight: \"#a5d6a7\",\n\t}\n\ttheme.DiffHighlightRemovedColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#ff5555\",\n\t\tLight: \"#ef9a9a\",\n\t}\n\ttheme.DiffAddedBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#2c3b2c\",\n\t\tLight: \"#e8f5e9\",\n\t}\n\ttheme.DiffRemovedBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#3b2c2c\",\n\t\tLight: \"#ffebee\",\n\t}\n\ttheme.DiffContextBgColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBackground,\n\t\tLight: lightBackground,\n\t}\n\ttheme.DiffLineNumberColor = lipgloss.AdaptiveColor{\n\t\tDark: darkComment,\n\t\tLight: lightComment,\n\t}\n\ttheme.DiffAddedLineNumberBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#253025\",\n\t\tLight: \"#c8e6c9\",\n\t}\n\ttheme.DiffRemovedLineNumberBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#302525\",\n\t\tLight: \"#ffcdd2\",\n\t}\n\n\t// Markdown colors\n\ttheme.MarkdownTextColor = lipgloss.AdaptiveColor{\n\t\tDark: darkForeground,\n\t\tLight: lightForeground,\n\t}\n\ttheme.MarkdownHeadingColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPink,\n\t\tLight: lightPink,\n\t}\n\ttheme.MarkdownLinkColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPurple,\n\t\tLight: lightPurple,\n\t}\n\ttheme.MarkdownLinkTextColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.MarkdownCodeColor = lipgloss.AdaptiveColor{\n\t\tDark: darkGreen,\n\t\tLight: lightGreen,\n\t}\n\ttheme.MarkdownBlockQuoteColor = lipgloss.AdaptiveColor{\n\t\tDark: darkYellow,\n\t\tLight: lightYellow,\n\t}\n\ttheme.MarkdownEmphColor = lipgloss.AdaptiveColor{\n\t\tDark: darkYellow,\n\t\tLight: lightYellow,\n\t}\n\ttheme.MarkdownStrongColor = lipgloss.AdaptiveColor{\n\t\tDark: darkOrange,\n\t\tLight: lightOrange,\n\t}\n\ttheme.MarkdownHorizontalRuleColor = lipgloss.AdaptiveColor{\n\t\tDark: darkComment,\n\t\tLight: lightComment,\n\t}\n\ttheme.MarkdownListItemColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPurple,\n\t\tLight: lightPurple,\n\t}\n\ttheme.MarkdownListEnumerationColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.MarkdownImageColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPurple,\n\t\tLight: lightPurple,\n\t}\n\ttheme.MarkdownImageTextColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.MarkdownCodeBlockColor = lipgloss.AdaptiveColor{\n\t\tDark: darkForeground,\n\t\tLight: lightForeground,\n\t}\n\n\t// Syntax highlighting colors\n\ttheme.SyntaxCommentColor = lipgloss.AdaptiveColor{\n\t\tDark: darkComment,\n\t\tLight: lightComment,\n\t}\n\ttheme.SyntaxKeywordColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPink,\n\t\tLight: lightPink,\n\t}\n\ttheme.SyntaxFunctionColor = lipgloss.AdaptiveColor{\n\t\tDark: darkGreen,\n\t\tLight: lightGreen,\n\t}\n\ttheme.SyntaxVariableColor = lipgloss.AdaptiveColor{\n\t\tDark: darkOrange,\n\t\tLight: lightOrange,\n\t}\n\ttheme.SyntaxStringColor = lipgloss.AdaptiveColor{\n\t\tDark: darkYellow,\n\t\tLight: lightYellow,\n\t}\n\ttheme.SyntaxNumberColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPurple,\n\t\tLight: lightPurple,\n\t}\n\ttheme.SyntaxTypeColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.SyntaxOperatorColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPink,\n\t\tLight: lightPink,\n\t}\n\ttheme.SyntaxPunctuationColor = lipgloss.AdaptiveColor{\n\t\tDark: darkForeground,\n\t\tLight: lightForeground,\n\t}\n\n\treturn theme\n}\n\nfunc init() {\n\t// Register the Dracula theme with the theme manager\n\tRegisterTheme(\"dracula\", NewDraculaTheme())\n}"], ["/opencode/internal/tui/theme/monokai.go", "package theme\n\nimport (\n\t\"github.com/charmbracelet/lipgloss\"\n)\n\n// MonokaiProTheme implements the Theme interface with Monokai Pro colors.\n// It provides both dark and light variants.\ntype MonokaiProTheme struct {\n\tBaseTheme\n}\n\n// NewMonokaiProTheme creates a new instance of the Monokai Pro theme.\nfunc NewMonokaiProTheme() *MonokaiProTheme {\n\t// Monokai Pro color palette (dark mode)\n\tdarkBackground := \"#2d2a2e\"\n\tdarkCurrentLine := \"#403e41\"\n\tdarkSelection := \"#5b595c\"\n\tdarkForeground := \"#fcfcfa\"\n\tdarkComment := \"#727072\"\n\tdarkRed := \"#ff6188\"\n\tdarkOrange := \"#fc9867\"\n\tdarkYellow := \"#ffd866\"\n\tdarkGreen := \"#a9dc76\"\n\tdarkCyan := \"#78dce8\"\n\tdarkBlue := \"#ab9df2\"\n\tdarkPurple := \"#ab9df2\"\n\tdarkBorder := \"#403e41\"\n\n\t// Light mode colors (adapted from dark)\n\tlightBackground := \"#fafafa\"\n\tlightCurrentLine := \"#f0f0f0\"\n\tlightSelection := \"#e5e5e6\"\n\tlightForeground := \"#2d2a2e\"\n\tlightComment := \"#939293\"\n\tlightRed := \"#f92672\"\n\tlightOrange := \"#fd971f\"\n\tlightYellow := \"#e6db74\"\n\tlightGreen := \"#9bca65\"\n\tlightCyan := \"#66d9ef\"\n\tlightBlue := \"#7e75db\"\n\tlightPurple := \"#ae81ff\"\n\tlightBorder := \"#d3d3d3\"\n\n\ttheme := &MonokaiProTheme{}\n\n\t// Base colors\n\ttheme.PrimaryColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.SecondaryColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPurple,\n\t\tLight: lightPurple,\n\t}\n\ttheme.AccentColor = lipgloss.AdaptiveColor{\n\t\tDark: darkOrange,\n\t\tLight: lightOrange,\n\t}\n\n\t// Status colors\n\ttheme.ErrorColor = lipgloss.AdaptiveColor{\n\t\tDark: darkRed,\n\t\tLight: lightRed,\n\t}\n\ttheme.WarningColor = lipgloss.AdaptiveColor{\n\t\tDark: darkOrange,\n\t\tLight: lightOrange,\n\t}\n\ttheme.SuccessColor = lipgloss.AdaptiveColor{\n\t\tDark: darkGreen,\n\t\tLight: lightGreen,\n\t}\n\ttheme.InfoColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBlue,\n\t\tLight: lightBlue,\n\t}\n\n\t// Text colors\n\ttheme.TextColor = lipgloss.AdaptiveColor{\n\t\tDark: darkForeground,\n\t\tLight: lightForeground,\n\t}\n\ttheme.TextMutedColor = lipgloss.AdaptiveColor{\n\t\tDark: darkComment,\n\t\tLight: lightComment,\n\t}\n\ttheme.TextEmphasizedColor = lipgloss.AdaptiveColor{\n\t\tDark: darkYellow,\n\t\tLight: lightYellow,\n\t}\n\n\t// Background colors\n\ttheme.BackgroundColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBackground,\n\t\tLight: lightBackground,\n\t}\n\ttheme.BackgroundSecondaryColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCurrentLine,\n\t\tLight: lightCurrentLine,\n\t}\n\ttheme.BackgroundDarkerColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#221f22\", // Slightly darker than background\n\t\tLight: \"#ffffff\", // Slightly lighter than background\n\t}\n\n\t// Border colors\n\ttheme.BorderNormalColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBorder,\n\t\tLight: lightBorder,\n\t}\n\ttheme.BorderFocusedColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.BorderDimColor = lipgloss.AdaptiveColor{\n\t\tDark: darkSelection,\n\t\tLight: lightSelection,\n\t}\n\n\t// Diff view colors\n\ttheme.DiffAddedColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#a9dc76\",\n\t\tLight: \"#9bca65\",\n\t}\n\ttheme.DiffRemovedColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#ff6188\",\n\t\tLight: \"#f92672\",\n\t}\n\ttheme.DiffContextColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#a0a0a0\",\n\t\tLight: \"#757575\",\n\t}\n\ttheme.DiffHunkHeaderColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#a0a0a0\",\n\t\tLight: \"#757575\",\n\t}\n\ttheme.DiffHighlightAddedColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#c2e7a9\",\n\t\tLight: \"#c5e0b4\",\n\t}\n\ttheme.DiffHighlightRemovedColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#ff8ca6\",\n\t\tLight: \"#ffb3c8\",\n\t}\n\ttheme.DiffAddedBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#3a4a35\",\n\t\tLight: \"#e8f5e9\",\n\t}\n\ttheme.DiffRemovedBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#4a3439\",\n\t\tLight: \"#ffebee\",\n\t}\n\ttheme.DiffContextBgColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBackground,\n\t\tLight: lightBackground,\n\t}\n\ttheme.DiffLineNumberColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#888888\",\n\t\tLight: \"#9e9e9e\",\n\t}\n\ttheme.DiffAddedLineNumberBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#2d3a28\",\n\t\tLight: \"#c8e6c9\",\n\t}\n\ttheme.DiffRemovedLineNumberBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#3d2a2e\",\n\t\tLight: \"#ffcdd2\",\n\t}\n\n\t// Markdown colors\n\ttheme.MarkdownTextColor = lipgloss.AdaptiveColor{\n\t\tDark: darkForeground,\n\t\tLight: lightForeground,\n\t}\n\ttheme.MarkdownHeadingColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPurple,\n\t\tLight: lightPurple,\n\t}\n\ttheme.MarkdownLinkColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.MarkdownLinkTextColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBlue,\n\t\tLight: lightBlue,\n\t}\n\ttheme.MarkdownCodeColor = lipgloss.AdaptiveColor{\n\t\tDark: darkGreen,\n\t\tLight: lightGreen,\n\t}\n\ttheme.MarkdownBlockQuoteColor = lipgloss.AdaptiveColor{\n\t\tDark: darkYellow,\n\t\tLight: lightYellow,\n\t}\n\ttheme.MarkdownEmphColor = lipgloss.AdaptiveColor{\n\t\tDark: darkYellow,\n\t\tLight: lightYellow,\n\t}\n\ttheme.MarkdownStrongColor = lipgloss.AdaptiveColor{\n\t\tDark: darkOrange,\n\t\tLight: lightOrange,\n\t}\n\ttheme.MarkdownHorizontalRuleColor = lipgloss.AdaptiveColor{\n\t\tDark: darkComment,\n\t\tLight: lightComment,\n\t}\n\ttheme.MarkdownListItemColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.MarkdownListEnumerationColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBlue,\n\t\tLight: lightBlue,\n\t}\n\ttheme.MarkdownImageColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.MarkdownImageTextColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBlue,\n\t\tLight: lightBlue,\n\t}\n\ttheme.MarkdownCodeBlockColor = lipgloss.AdaptiveColor{\n\t\tDark: darkForeground,\n\t\tLight: lightForeground,\n\t}\n\n\t// Syntax highlighting colors\n\ttheme.SyntaxCommentColor = lipgloss.AdaptiveColor{\n\t\tDark: darkComment,\n\t\tLight: lightComment,\n\t}\n\ttheme.SyntaxKeywordColor = lipgloss.AdaptiveColor{\n\t\tDark: darkRed,\n\t\tLight: lightRed,\n\t}\n\ttheme.SyntaxFunctionColor = lipgloss.AdaptiveColor{\n\t\tDark: darkGreen,\n\t\tLight: lightGreen,\n\t}\n\ttheme.SyntaxVariableColor = lipgloss.AdaptiveColor{\n\t\tDark: darkForeground,\n\t\tLight: lightForeground,\n\t}\n\ttheme.SyntaxStringColor = lipgloss.AdaptiveColor{\n\t\tDark: darkYellow,\n\t\tLight: lightYellow,\n\t}\n\ttheme.SyntaxNumberColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPurple,\n\t\tLight: lightPurple,\n\t}\n\ttheme.SyntaxTypeColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBlue,\n\t\tLight: lightBlue,\n\t}\n\ttheme.SyntaxOperatorColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.SyntaxPunctuationColor = lipgloss.AdaptiveColor{\n\t\tDark: darkForeground,\n\t\tLight: lightForeground,\n\t}\n\n\treturn theme\n}\n\nfunc init() {\n\t// Register the Monokai Pro theme with the theme manager\n\tRegisterTheme(\"monokai\", NewMonokaiProTheme())\n}"], ["/opencode/internal/tui/theme/opencode.go", "package theme\n\nimport (\n\t\"github.com/charmbracelet/lipgloss\"\n)\n\n// OpenCodeTheme implements the Theme interface with OpenCode brand colors.\n// It provides both dark and light variants.\ntype OpenCodeTheme struct {\n\tBaseTheme\n}\n\n// NewOpenCodeTheme creates a new instance of the OpenCode theme.\nfunc NewOpenCodeTheme() *OpenCodeTheme {\n\t// OpenCode color palette\n\t// Dark mode colors\n\tdarkBackground := \"#212121\"\n\tdarkCurrentLine := \"#252525\"\n\tdarkSelection := \"#303030\"\n\tdarkForeground := \"#e0e0e0\"\n\tdarkComment := \"#6a6a6a\"\n\tdarkPrimary := \"#fab283\" // Primary orange/gold\n\tdarkSecondary := \"#5c9cf5\" // Secondary blue\n\tdarkAccent := \"#9d7cd8\" // Accent purple\n\tdarkRed := \"#e06c75\" // Error red\n\tdarkOrange := \"#f5a742\" // Warning orange\n\tdarkGreen := \"#7fd88f\" // Success green\n\tdarkCyan := \"#56b6c2\" // Info cyan\n\tdarkYellow := \"#e5c07b\" // Emphasized text\n\tdarkBorder := \"#4b4c5c\" // Border color\n\n\t// Light mode colors\n\tlightBackground := \"#f8f8f8\"\n\tlightCurrentLine := \"#f0f0f0\"\n\tlightSelection := \"#e5e5e6\"\n\tlightForeground := \"#2a2a2a\"\n\tlightComment := \"#8a8a8a\"\n\tlightPrimary := \"#3b7dd8\" // Primary blue\n\tlightSecondary := \"#7b5bb6\" // Secondary purple\n\tlightAccent := \"#d68c27\" // Accent orange/gold\n\tlightRed := \"#d1383d\" // Error red\n\tlightOrange := \"#d68c27\" // Warning orange\n\tlightGreen := \"#3d9a57\" // Success green\n\tlightCyan := \"#318795\" // Info cyan\n\tlightYellow := \"#b0851f\" // Emphasized text\n\tlightBorder := \"#d3d3d3\" // Border color\n\n\ttheme := &OpenCodeTheme{}\n\n\t// Base colors\n\ttheme.PrimaryColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPrimary,\n\t\tLight: lightPrimary,\n\t}\n\ttheme.SecondaryColor = lipgloss.AdaptiveColor{\n\t\tDark: darkSecondary,\n\t\tLight: lightSecondary,\n\t}\n\ttheme.AccentColor = lipgloss.AdaptiveColor{\n\t\tDark: darkAccent,\n\t\tLight: lightAccent,\n\t}\n\n\t// Status colors\n\ttheme.ErrorColor = lipgloss.AdaptiveColor{\n\t\tDark: darkRed,\n\t\tLight: lightRed,\n\t}\n\ttheme.WarningColor = lipgloss.AdaptiveColor{\n\t\tDark: darkOrange,\n\t\tLight: lightOrange,\n\t}\n\ttheme.SuccessColor = lipgloss.AdaptiveColor{\n\t\tDark: darkGreen,\n\t\tLight: lightGreen,\n\t}\n\ttheme.InfoColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\n\t// Text colors\n\ttheme.TextColor = lipgloss.AdaptiveColor{\n\t\tDark: darkForeground,\n\t\tLight: lightForeground,\n\t}\n\ttheme.TextMutedColor = lipgloss.AdaptiveColor{\n\t\tDark: darkComment,\n\t\tLight: lightComment,\n\t}\n\ttheme.TextEmphasizedColor = lipgloss.AdaptiveColor{\n\t\tDark: darkYellow,\n\t\tLight: lightYellow,\n\t}\n\n\t// Background colors\n\ttheme.BackgroundColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBackground,\n\t\tLight: lightBackground,\n\t}\n\ttheme.BackgroundSecondaryColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCurrentLine,\n\t\tLight: lightCurrentLine,\n\t}\n\ttheme.BackgroundDarkerColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#121212\", // Slightly darker than background\n\t\tLight: \"#ffffff\", // Slightly lighter than background\n\t}\n\n\t// Border colors\n\ttheme.BorderNormalColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBorder,\n\t\tLight: lightBorder,\n\t}\n\ttheme.BorderFocusedColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPrimary,\n\t\tLight: lightPrimary,\n\t}\n\ttheme.BorderDimColor = lipgloss.AdaptiveColor{\n\t\tDark: darkSelection,\n\t\tLight: lightSelection,\n\t}\n\n\t// Diff view colors\n\ttheme.DiffAddedColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#478247\",\n\t\tLight: \"#2E7D32\",\n\t}\n\ttheme.DiffRemovedColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#7C4444\",\n\t\tLight: \"#C62828\",\n\t}\n\ttheme.DiffContextColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#a0a0a0\",\n\t\tLight: \"#757575\",\n\t}\n\ttheme.DiffHunkHeaderColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#a0a0a0\",\n\t\tLight: \"#757575\",\n\t}\n\ttheme.DiffHighlightAddedColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#DAFADA\",\n\t\tLight: \"#A5D6A7\",\n\t}\n\ttheme.DiffHighlightRemovedColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#FADADD\",\n\t\tLight: \"#EF9A9A\",\n\t}\n\ttheme.DiffAddedBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#303A30\",\n\t\tLight: \"#E8F5E9\",\n\t}\n\ttheme.DiffRemovedBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#3A3030\",\n\t\tLight: \"#FFEBEE\",\n\t}\n\ttheme.DiffContextBgColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBackground,\n\t\tLight: lightBackground,\n\t}\n\ttheme.DiffLineNumberColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#888888\",\n\t\tLight: \"#9E9E9E\",\n\t}\n\ttheme.DiffAddedLineNumberBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#293229\",\n\t\tLight: \"#C8E6C9\",\n\t}\n\ttheme.DiffRemovedLineNumberBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#332929\",\n\t\tLight: \"#FFCDD2\",\n\t}\n\n\t// Markdown colors\n\ttheme.MarkdownTextColor = lipgloss.AdaptiveColor{\n\t\tDark: darkForeground,\n\t\tLight: lightForeground,\n\t}\n\ttheme.MarkdownHeadingColor = lipgloss.AdaptiveColor{\n\t\tDark: darkSecondary,\n\t\tLight: lightSecondary,\n\t}\n\ttheme.MarkdownLinkColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPrimary,\n\t\tLight: lightPrimary,\n\t}\n\ttheme.MarkdownLinkTextColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.MarkdownCodeColor = lipgloss.AdaptiveColor{\n\t\tDark: darkGreen,\n\t\tLight: lightGreen,\n\t}\n\ttheme.MarkdownBlockQuoteColor = lipgloss.AdaptiveColor{\n\t\tDark: darkYellow,\n\t\tLight: lightYellow,\n\t}\n\ttheme.MarkdownEmphColor = lipgloss.AdaptiveColor{\n\t\tDark: darkYellow,\n\t\tLight: lightYellow,\n\t}\n\ttheme.MarkdownStrongColor = lipgloss.AdaptiveColor{\n\t\tDark: darkAccent,\n\t\tLight: lightAccent,\n\t}\n\ttheme.MarkdownHorizontalRuleColor = lipgloss.AdaptiveColor{\n\t\tDark: darkComment,\n\t\tLight: lightComment,\n\t}\n\ttheme.MarkdownListItemColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPrimary,\n\t\tLight: lightPrimary,\n\t}\n\ttheme.MarkdownListEnumerationColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.MarkdownImageColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPrimary,\n\t\tLight: lightPrimary,\n\t}\n\ttheme.MarkdownImageTextColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.MarkdownCodeBlockColor = lipgloss.AdaptiveColor{\n\t\tDark: darkForeground,\n\t\tLight: lightForeground,\n\t}\n\n\t// Syntax highlighting colors\n\ttheme.SyntaxCommentColor = lipgloss.AdaptiveColor{\n\t\tDark: darkComment,\n\t\tLight: lightComment,\n\t}\n\ttheme.SyntaxKeywordColor = lipgloss.AdaptiveColor{\n\t\tDark: darkSecondary,\n\t\tLight: lightSecondary,\n\t}\n\ttheme.SyntaxFunctionColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPrimary,\n\t\tLight: lightPrimary,\n\t}\n\ttheme.SyntaxVariableColor = lipgloss.AdaptiveColor{\n\t\tDark: darkRed,\n\t\tLight: lightRed,\n\t}\n\ttheme.SyntaxStringColor = lipgloss.AdaptiveColor{\n\t\tDark: darkGreen,\n\t\tLight: lightGreen,\n\t}\n\ttheme.SyntaxNumberColor = lipgloss.AdaptiveColor{\n\t\tDark: darkAccent,\n\t\tLight: lightAccent,\n\t}\n\ttheme.SyntaxTypeColor = lipgloss.AdaptiveColor{\n\t\tDark: darkYellow,\n\t\tLight: lightYellow,\n\t}\n\ttheme.SyntaxOperatorColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.SyntaxPunctuationColor = lipgloss.AdaptiveColor{\n\t\tDark: darkForeground,\n\t\tLight: lightForeground,\n\t}\n\n\treturn theme\n}\n\nfunc init() {\n\t// Register the OpenCode theme with the theme manager\n\tRegisterTheme(\"opencode\", NewOpenCodeTheme())\n}\n\n"], ["/opencode/internal/tui/theme/tron.go", "package theme\n\nimport (\n\t\"github.com/charmbracelet/lipgloss\"\n)\n\n// TronTheme implements the Theme interface with Tron-inspired colors.\n// It provides both dark and light variants, though Tron is primarily a dark theme.\ntype TronTheme struct {\n\tBaseTheme\n}\n\n// NewTronTheme creates a new instance of the Tron theme.\nfunc NewTronTheme() *TronTheme {\n\t// Tron color palette\n\t// Inspired by the Tron movie's neon aesthetic\n\tdarkBackground := \"#0c141f\"\n\tdarkCurrentLine := \"#1a2633\"\n\tdarkSelection := \"#1a2633\"\n\tdarkForeground := \"#caf0ff\"\n\tdarkComment := \"#4d6b87\"\n\tdarkCyan := \"#00d9ff\"\n\tdarkBlue := \"#007fff\"\n\tdarkOrange := \"#ff9000\"\n\tdarkPink := \"#ff00a0\"\n\tdarkPurple := \"#b73fff\"\n\tdarkRed := \"#ff3333\"\n\tdarkYellow := \"#ffcc00\"\n\tdarkGreen := \"#00ff8f\"\n\tdarkBorder := \"#1a2633\"\n\n\t// Light mode approximation\n\tlightBackground := \"#f0f8ff\"\n\tlightCurrentLine := \"#e0f0ff\"\n\tlightSelection := \"#d0e8ff\"\n\tlightForeground := \"#0c141f\"\n\tlightComment := \"#4d6b87\"\n\tlightCyan := \"#0097b3\"\n\tlightBlue := \"#0066cc\"\n\tlightOrange := \"#cc7300\"\n\tlightPink := \"#cc0080\"\n\tlightPurple := \"#9932cc\"\n\tlightRed := \"#cc2929\"\n\tlightYellow := \"#cc9900\"\n\tlightGreen := \"#00cc72\"\n\tlightBorder := \"#d0e8ff\"\n\n\ttheme := &TronTheme{}\n\n\t// Base colors\n\ttheme.PrimaryColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.SecondaryColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBlue,\n\t\tLight: lightBlue,\n\t}\n\ttheme.AccentColor = lipgloss.AdaptiveColor{\n\t\tDark: darkOrange,\n\t\tLight: lightOrange,\n\t}\n\n\t// Status colors\n\ttheme.ErrorColor = lipgloss.AdaptiveColor{\n\t\tDark: darkRed,\n\t\tLight: lightRed,\n\t}\n\ttheme.WarningColor = lipgloss.AdaptiveColor{\n\t\tDark: darkOrange,\n\t\tLight: lightOrange,\n\t}\n\ttheme.SuccessColor = lipgloss.AdaptiveColor{\n\t\tDark: darkGreen,\n\t\tLight: lightGreen,\n\t}\n\ttheme.InfoColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\n\t// Text colors\n\ttheme.TextColor = lipgloss.AdaptiveColor{\n\t\tDark: darkForeground,\n\t\tLight: lightForeground,\n\t}\n\ttheme.TextMutedColor = lipgloss.AdaptiveColor{\n\t\tDark: darkComment,\n\t\tLight: lightComment,\n\t}\n\ttheme.TextEmphasizedColor = lipgloss.AdaptiveColor{\n\t\tDark: darkYellow,\n\t\tLight: lightYellow,\n\t}\n\n\t// Background colors\n\ttheme.BackgroundColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBackground,\n\t\tLight: lightBackground,\n\t}\n\ttheme.BackgroundSecondaryColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCurrentLine,\n\t\tLight: lightCurrentLine,\n\t}\n\ttheme.BackgroundDarkerColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#070d14\", // Slightly darker than background\n\t\tLight: \"#ffffff\", // Slightly lighter than background\n\t}\n\n\t// Border colors\n\ttheme.BorderNormalColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBorder,\n\t\tLight: lightBorder,\n\t}\n\ttheme.BorderFocusedColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.BorderDimColor = lipgloss.AdaptiveColor{\n\t\tDark: darkSelection,\n\t\tLight: lightSelection,\n\t}\n\n\t// Diff view colors\n\ttheme.DiffAddedColor = lipgloss.AdaptiveColor{\n\t\tDark: darkGreen,\n\t\tLight: lightGreen,\n\t}\n\ttheme.DiffRemovedColor = lipgloss.AdaptiveColor{\n\t\tDark: darkRed,\n\t\tLight: lightRed,\n\t}\n\ttheme.DiffContextColor = lipgloss.AdaptiveColor{\n\t\tDark: darkComment,\n\t\tLight: lightComment,\n\t}\n\ttheme.DiffHunkHeaderColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBlue,\n\t\tLight: lightBlue,\n\t}\n\ttheme.DiffHighlightAddedColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#00ff8f\",\n\t\tLight: \"#a5d6a7\",\n\t}\n\ttheme.DiffHighlightRemovedColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#ff3333\",\n\t\tLight: \"#ef9a9a\",\n\t}\n\ttheme.DiffAddedBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#0a2a1a\",\n\t\tLight: \"#e8f5e9\",\n\t}\n\ttheme.DiffRemovedBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#2a0a0a\",\n\t\tLight: \"#ffebee\",\n\t}\n\ttheme.DiffContextBgColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBackground,\n\t\tLight: lightBackground,\n\t}\n\ttheme.DiffLineNumberColor = lipgloss.AdaptiveColor{\n\t\tDark: darkComment,\n\t\tLight: lightComment,\n\t}\n\ttheme.DiffAddedLineNumberBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#082015\",\n\t\tLight: \"#c8e6c9\",\n\t}\n\ttheme.DiffRemovedLineNumberBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#200808\",\n\t\tLight: \"#ffcdd2\",\n\t}\n\n\t// Markdown colors\n\ttheme.MarkdownTextColor = lipgloss.AdaptiveColor{\n\t\tDark: darkForeground,\n\t\tLight: lightForeground,\n\t}\n\ttheme.MarkdownHeadingColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.MarkdownLinkColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBlue,\n\t\tLight: lightBlue,\n\t}\n\ttheme.MarkdownLinkTextColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.MarkdownCodeColor = lipgloss.AdaptiveColor{\n\t\tDark: darkGreen,\n\t\tLight: lightGreen,\n\t}\n\ttheme.MarkdownBlockQuoteColor = lipgloss.AdaptiveColor{\n\t\tDark: darkYellow,\n\t\tLight: lightYellow,\n\t}\n\ttheme.MarkdownEmphColor = lipgloss.AdaptiveColor{\n\t\tDark: darkYellow,\n\t\tLight: lightYellow,\n\t}\n\ttheme.MarkdownStrongColor = lipgloss.AdaptiveColor{\n\t\tDark: darkOrange,\n\t\tLight: lightOrange,\n\t}\n\ttheme.MarkdownHorizontalRuleColor = lipgloss.AdaptiveColor{\n\t\tDark: darkComment,\n\t\tLight: lightComment,\n\t}\n\ttheme.MarkdownListItemColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBlue,\n\t\tLight: lightBlue,\n\t}\n\ttheme.MarkdownListEnumerationColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.MarkdownImageColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBlue,\n\t\tLight: lightBlue,\n\t}\n\ttheme.MarkdownImageTextColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.MarkdownCodeBlockColor = lipgloss.AdaptiveColor{\n\t\tDark: darkForeground,\n\t\tLight: lightForeground,\n\t}\n\n\t// Syntax highlighting colors\n\ttheme.SyntaxCommentColor = lipgloss.AdaptiveColor{\n\t\tDark: darkComment,\n\t\tLight: lightComment,\n\t}\n\ttheme.SyntaxKeywordColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.SyntaxFunctionColor = lipgloss.AdaptiveColor{\n\t\tDark: darkGreen,\n\t\tLight: lightGreen,\n\t}\n\ttheme.SyntaxVariableColor = lipgloss.AdaptiveColor{\n\t\tDark: darkOrange,\n\t\tLight: lightOrange,\n\t}\n\ttheme.SyntaxStringColor = lipgloss.AdaptiveColor{\n\t\tDark: darkYellow,\n\t\tLight: lightYellow,\n\t}\n\ttheme.SyntaxNumberColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBlue,\n\t\tLight: lightBlue,\n\t}\n\ttheme.SyntaxTypeColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPurple,\n\t\tLight: lightPurple,\n\t}\n\ttheme.SyntaxOperatorColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPink,\n\t\tLight: lightPink,\n\t}\n\ttheme.SyntaxPunctuationColor = lipgloss.AdaptiveColor{\n\t\tDark: darkForeground,\n\t\tLight: lightForeground,\n\t}\n\n\treturn theme\n}\n\nfunc init() {\n\t// Register the Tron theme with the theme manager\n\tRegisterTheme(\"tron\", NewTronTheme())\n}"], ["/opencode/internal/history/file.go", "package history\n\nimport (\n\t\"context\"\n\t\"database/sql\"\n\t\"fmt\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/google/uuid\"\n\t\"github.com/opencode-ai/opencode/internal/db\"\n\t\"github.com/opencode-ai/opencode/internal/pubsub\"\n)\n\nconst (\n\tInitialVersion = \"initial\"\n)\n\ntype File struct {\n\tID string\n\tSessionID string\n\tPath string\n\tContent string\n\tVersion string\n\tCreatedAt int64\n\tUpdatedAt int64\n}\n\ntype Service interface {\n\tpubsub.Suscriber[File]\n\tCreate(ctx context.Context, sessionID, path, content string) (File, error)\n\tCreateVersion(ctx context.Context, sessionID, path, content string) (File, error)\n\tGet(ctx context.Context, id string) (File, error)\n\tGetByPathAndSession(ctx context.Context, path, sessionID string) (File, error)\n\tListBySession(ctx context.Context, sessionID string) ([]File, error)\n\tListLatestSessionFiles(ctx context.Context, sessionID string) ([]File, error)\n\tUpdate(ctx context.Context, file File) (File, error)\n\tDelete(ctx context.Context, id string) error\n\tDeleteSessionFiles(ctx context.Context, sessionID string) error\n}\n\ntype service struct {\n\t*pubsub.Broker[File]\n\tdb *sql.DB\n\tq *db.Queries\n}\n\nfunc NewService(q *db.Queries, db *sql.DB) Service {\n\treturn &service{\n\t\tBroker: pubsub.NewBroker[File](),\n\t\tq: q,\n\t\tdb: db,\n\t}\n}\n\nfunc (s *service) Create(ctx context.Context, sessionID, path, content string) (File, error) {\n\treturn s.createWithVersion(ctx, sessionID, path, content, InitialVersion)\n}\n\nfunc (s *service) CreateVersion(ctx context.Context, sessionID, path, content string) (File, error) {\n\t// Get the latest version for this path\n\tfiles, err := s.q.ListFilesByPath(ctx, path)\n\tif err != nil {\n\t\treturn File{}, err\n\t}\n\n\tif len(files) == 0 {\n\t\t// No previous versions, create initial\n\t\treturn s.Create(ctx, sessionID, path, content)\n\t}\n\n\t// Get the latest version\n\tlatestFile := files[0] // Files are ordered by created_at DESC\n\tlatestVersion := latestFile.Version\n\n\t// Generate the next version\n\tvar nextVersion string\n\tif latestVersion == InitialVersion {\n\t\tnextVersion = \"v1\"\n\t} else if strings.HasPrefix(latestVersion, \"v\") {\n\t\tversionNum, err := strconv.Atoi(latestVersion[1:])\n\t\tif err != nil {\n\t\t\t// If we can't parse the version, just use a timestamp-based version\n\t\t\tnextVersion = fmt.Sprintf(\"v%d\", latestFile.CreatedAt)\n\t\t} else {\n\t\t\tnextVersion = fmt.Sprintf(\"v%d\", versionNum+1)\n\t\t}\n\t} else {\n\t\t// If the version format is unexpected, use a timestamp-based version\n\t\tnextVersion = fmt.Sprintf(\"v%d\", latestFile.CreatedAt)\n\t}\n\n\treturn s.createWithVersion(ctx, sessionID, path, content, nextVersion)\n}\n\nfunc (s *service) createWithVersion(ctx context.Context, sessionID, path, content, version string) (File, error) {\n\t// Maximum number of retries for transaction conflicts\n\tconst maxRetries = 3\n\tvar file File\n\tvar err error\n\n\t// Retry loop for transaction conflicts\n\tfor attempt := range maxRetries {\n\t\t// Start a transaction\n\t\ttx, txErr := s.db.Begin()\n\t\tif txErr != nil {\n\t\t\treturn File{}, fmt.Errorf(\"failed to begin transaction: %w\", txErr)\n\t\t}\n\n\t\t// Create a new queries instance with the transaction\n\t\tqtx := s.q.WithTx(tx)\n\n\t\t// Try to create the file within the transaction\n\t\tdbFile, txErr := qtx.CreateFile(ctx, db.CreateFileParams{\n\t\t\tID: uuid.New().String(),\n\t\t\tSessionID: sessionID,\n\t\t\tPath: path,\n\t\t\tContent: content,\n\t\t\tVersion: version,\n\t\t})\n\t\tif txErr != nil {\n\t\t\t// Rollback the transaction\n\t\t\ttx.Rollback()\n\n\t\t\t// Check if this is a uniqueness constraint violation\n\t\t\tif strings.Contains(txErr.Error(), \"UNIQUE constraint failed\") {\n\t\t\t\tif attempt < maxRetries-1 {\n\t\t\t\t\t// If we have retries left, generate a new version and try again\n\t\t\t\t\tif strings.HasPrefix(version, \"v\") {\n\t\t\t\t\t\tversionNum, parseErr := strconv.Atoi(version[1:])\n\t\t\t\t\t\tif parseErr == nil {\n\t\t\t\t\t\t\tversion = fmt.Sprintf(\"v%d\", versionNum+1)\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t// If we can't parse the version, use a timestamp-based version\n\t\t\t\t\tversion = fmt.Sprintf(\"v%d\", time.Now().Unix())\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn File{}, txErr\n\t\t}\n\n\t\t// Commit the transaction\n\t\tif txErr = tx.Commit(); txErr != nil {\n\t\t\treturn File{}, fmt.Errorf(\"failed to commit transaction: %w\", txErr)\n\t\t}\n\n\t\tfile = s.fromDBItem(dbFile)\n\t\ts.Publish(pubsub.CreatedEvent, file)\n\t\treturn file, nil\n\t}\n\n\treturn file, err\n}\n\nfunc (s *service) Get(ctx context.Context, id string) (File, error) {\n\tdbFile, err := s.q.GetFile(ctx, id)\n\tif err != nil {\n\t\treturn File{}, err\n\t}\n\treturn s.fromDBItem(dbFile), nil\n}\n\nfunc (s *service) GetByPathAndSession(ctx context.Context, path, sessionID string) (File, error) {\n\tdbFile, err := s.q.GetFileByPathAndSession(ctx, db.GetFileByPathAndSessionParams{\n\t\tPath: path,\n\t\tSessionID: sessionID,\n\t})\n\tif err != nil {\n\t\treturn File{}, err\n\t}\n\treturn s.fromDBItem(dbFile), nil\n}\n\nfunc (s *service) ListBySession(ctx context.Context, sessionID string) ([]File, error) {\n\tdbFiles, err := s.q.ListFilesBySession(ctx, sessionID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfiles := make([]File, len(dbFiles))\n\tfor i, dbFile := range dbFiles {\n\t\tfiles[i] = s.fromDBItem(dbFile)\n\t}\n\treturn files, nil\n}\n\nfunc (s *service) ListLatestSessionFiles(ctx context.Context, sessionID string) ([]File, error) {\n\tdbFiles, err := s.q.ListLatestSessionFiles(ctx, sessionID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfiles := make([]File, len(dbFiles))\n\tfor i, dbFile := range dbFiles {\n\t\tfiles[i] = s.fromDBItem(dbFile)\n\t}\n\treturn files, nil\n}\n\nfunc (s *service) Update(ctx context.Context, file File) (File, error) {\n\tdbFile, err := s.q.UpdateFile(ctx, db.UpdateFileParams{\n\t\tID: file.ID,\n\t\tContent: file.Content,\n\t\tVersion: file.Version,\n\t})\n\tif err != nil {\n\t\treturn File{}, err\n\t}\n\tupdatedFile := s.fromDBItem(dbFile)\n\ts.Publish(pubsub.UpdatedEvent, updatedFile)\n\treturn updatedFile, nil\n}\n\nfunc (s *service) Delete(ctx context.Context, id string) error {\n\tfile, err := s.Get(ctx, id)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = s.q.DeleteFile(ctx, id)\n\tif err != nil {\n\t\treturn err\n\t}\n\ts.Publish(pubsub.DeletedEvent, file)\n\treturn nil\n}\n\nfunc (s *service) DeleteSessionFiles(ctx context.Context, sessionID string) error {\n\tfiles, err := s.ListBySession(ctx, sessionID)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor _, file := range files {\n\t\terr = s.Delete(ctx, file.ID)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (s *service) fromDBItem(item db.File) File {\n\treturn File{\n\t\tID: item.ID,\n\t\tSessionID: item.SessionID,\n\t\tPath: item.Path,\n\t\tContent: item.Content,\n\t\tVersion: item.Version,\n\t\tCreatedAt: item.CreatedAt,\n\t\tUpdatedAt: item.UpdatedAt,\n\t}\n}\n"], ["/opencode/internal/tui/theme/tokyonight.go", "package theme\n\nimport (\n\t\"github.com/charmbracelet/lipgloss\"\n)\n\n// TokyoNightTheme implements the Theme interface with Tokyo Night colors.\n// It provides both dark and light variants.\ntype TokyoNightTheme struct {\n\tBaseTheme\n}\n\n// NewTokyoNightTheme creates a new instance of the Tokyo Night theme.\nfunc NewTokyoNightTheme() *TokyoNightTheme {\n\t// Tokyo Night color palette\n\t// Dark mode colors\n\tdarkBackground := \"#222436\"\n\tdarkCurrentLine := \"#1e2030\"\n\tdarkSelection := \"#2f334d\"\n\tdarkForeground := \"#c8d3f5\"\n\tdarkComment := \"#636da6\"\n\tdarkRed := \"#ff757f\"\n\tdarkOrange := \"#ff966c\"\n\tdarkYellow := \"#ffc777\"\n\tdarkGreen := \"#c3e88d\"\n\tdarkCyan := \"#86e1fc\"\n\tdarkBlue := \"#82aaff\"\n\tdarkPurple := \"#c099ff\"\n\tdarkBorder := \"#3b4261\"\n\n\t// Light mode colors (Tokyo Night Day)\n\tlightBackground := \"#e1e2e7\"\n\tlightCurrentLine := \"#d5d6db\"\n\tlightSelection := \"#c8c9ce\"\n\tlightForeground := \"#3760bf\"\n\tlightComment := \"#848cb5\"\n\tlightRed := \"#f52a65\"\n\tlightOrange := \"#b15c00\"\n\tlightYellow := \"#8c6c3e\"\n\tlightGreen := \"#587539\"\n\tlightCyan := \"#007197\"\n\tlightBlue := \"#2e7de9\"\n\tlightPurple := \"#9854f1\"\n\tlightBorder := \"#a8aecb\"\n\n\ttheme := &TokyoNightTheme{}\n\n\t// Base colors\n\ttheme.PrimaryColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBlue,\n\t\tLight: lightBlue,\n\t}\n\ttheme.SecondaryColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPurple,\n\t\tLight: lightPurple,\n\t}\n\ttheme.AccentColor = lipgloss.AdaptiveColor{\n\t\tDark: darkOrange,\n\t\tLight: lightOrange,\n\t}\n\n\t// Status colors\n\ttheme.ErrorColor = lipgloss.AdaptiveColor{\n\t\tDark: darkRed,\n\t\tLight: lightRed,\n\t}\n\ttheme.WarningColor = lipgloss.AdaptiveColor{\n\t\tDark: darkOrange,\n\t\tLight: lightOrange,\n\t}\n\ttheme.SuccessColor = lipgloss.AdaptiveColor{\n\t\tDark: darkGreen,\n\t\tLight: lightGreen,\n\t}\n\ttheme.InfoColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBlue,\n\t\tLight: lightBlue,\n\t}\n\n\t// Text colors\n\ttheme.TextColor = lipgloss.AdaptiveColor{\n\t\tDark: darkForeground,\n\t\tLight: lightForeground,\n\t}\n\ttheme.TextMutedColor = lipgloss.AdaptiveColor{\n\t\tDark: darkComment,\n\t\tLight: lightComment,\n\t}\n\ttheme.TextEmphasizedColor = lipgloss.AdaptiveColor{\n\t\tDark: darkYellow,\n\t\tLight: lightYellow,\n\t}\n\n\t// Background colors\n\ttheme.BackgroundColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBackground,\n\t\tLight: lightBackground,\n\t}\n\ttheme.BackgroundSecondaryColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCurrentLine,\n\t\tLight: lightCurrentLine,\n\t}\n\ttheme.BackgroundDarkerColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#191B29\", // Darker background from palette\n\t\tLight: \"#f0f0f5\", // Slightly lighter than background\n\t}\n\n\t// Border colors\n\ttheme.BorderNormalColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBorder,\n\t\tLight: lightBorder,\n\t}\n\ttheme.BorderFocusedColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBlue,\n\t\tLight: lightBlue,\n\t}\n\ttheme.BorderDimColor = lipgloss.AdaptiveColor{\n\t\tDark: darkSelection,\n\t\tLight: lightSelection,\n\t}\n\n\t// Diff view colors\n\ttheme.DiffAddedColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#4fd6be\", // teal from palette\n\t\tLight: \"#1e725c\",\n\t}\n\ttheme.DiffRemovedColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#c53b53\", // red1 from palette\n\t\tLight: \"#c53b53\",\n\t}\n\ttheme.DiffContextColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#828bb8\", // fg_dark from palette\n\t\tLight: \"#7086b5\",\n\t}\n\ttheme.DiffHunkHeaderColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#828bb8\", // fg_dark from palette\n\t\tLight: \"#7086b5\",\n\t}\n\ttheme.DiffHighlightAddedColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#b8db87\", // git.add from palette\n\t\tLight: \"#4db380\",\n\t}\n\ttheme.DiffHighlightRemovedColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#e26a75\", // git.delete from palette\n\t\tLight: \"#f52a65\",\n\t}\n\ttheme.DiffAddedBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#20303b\",\n\t\tLight: \"#d5e5d5\",\n\t}\n\ttheme.DiffRemovedBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#37222c\",\n\t\tLight: \"#f7d8db\",\n\t}\n\ttheme.DiffContextBgColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBackground,\n\t\tLight: lightBackground,\n\t}\n\ttheme.DiffLineNumberColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#545c7e\", // dark3 from palette\n\t\tLight: \"#848cb5\",\n\t}\n\ttheme.DiffAddedLineNumberBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#1b2b34\",\n\t\tLight: \"#c5d5c5\",\n\t}\n\ttheme.DiffRemovedLineNumberBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#2d1f26\",\n\t\tLight: \"#e7c8cb\",\n\t}\n\n\t// Markdown colors\n\ttheme.MarkdownTextColor = lipgloss.AdaptiveColor{\n\t\tDark: darkForeground,\n\t\tLight: lightForeground,\n\t}\n\ttheme.MarkdownHeadingColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPurple,\n\t\tLight: lightPurple,\n\t}\n\ttheme.MarkdownLinkColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBlue,\n\t\tLight: lightBlue,\n\t}\n\ttheme.MarkdownLinkTextColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.MarkdownCodeColor = lipgloss.AdaptiveColor{\n\t\tDark: darkGreen,\n\t\tLight: lightGreen,\n\t}\n\ttheme.MarkdownBlockQuoteColor = lipgloss.AdaptiveColor{\n\t\tDark: darkYellow,\n\t\tLight: lightYellow,\n\t}\n\ttheme.MarkdownEmphColor = lipgloss.AdaptiveColor{\n\t\tDark: darkYellow,\n\t\tLight: lightYellow,\n\t}\n\ttheme.MarkdownStrongColor = lipgloss.AdaptiveColor{\n\t\tDark: darkOrange,\n\t\tLight: lightOrange,\n\t}\n\ttheme.MarkdownHorizontalRuleColor = lipgloss.AdaptiveColor{\n\t\tDark: darkComment,\n\t\tLight: lightComment,\n\t}\n\ttheme.MarkdownListItemColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBlue,\n\t\tLight: lightBlue,\n\t}\n\ttheme.MarkdownListEnumerationColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.MarkdownImageColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBlue,\n\t\tLight: lightBlue,\n\t}\n\ttheme.MarkdownImageTextColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.MarkdownCodeBlockColor = lipgloss.AdaptiveColor{\n\t\tDark: darkForeground,\n\t\tLight: lightForeground,\n\t}\n\n\t// Syntax highlighting colors\n\ttheme.SyntaxCommentColor = lipgloss.AdaptiveColor{\n\t\tDark: darkComment,\n\t\tLight: lightComment,\n\t}\n\ttheme.SyntaxKeywordColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPurple,\n\t\tLight: lightPurple,\n\t}\n\ttheme.SyntaxFunctionColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBlue,\n\t\tLight: lightBlue,\n\t}\n\ttheme.SyntaxVariableColor = lipgloss.AdaptiveColor{\n\t\tDark: darkRed,\n\t\tLight: lightRed,\n\t}\n\ttheme.SyntaxStringColor = lipgloss.AdaptiveColor{\n\t\tDark: darkGreen,\n\t\tLight: lightGreen,\n\t}\n\ttheme.SyntaxNumberColor = lipgloss.AdaptiveColor{\n\t\tDark: darkOrange,\n\t\tLight: lightOrange,\n\t}\n\ttheme.SyntaxTypeColor = lipgloss.AdaptiveColor{\n\t\tDark: darkYellow,\n\t\tLight: lightYellow,\n\t}\n\ttheme.SyntaxOperatorColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.SyntaxPunctuationColor = lipgloss.AdaptiveColor{\n\t\tDark: darkForeground,\n\t\tLight: lightForeground,\n\t}\n\n\treturn theme\n}\n\nfunc init() {\n\t// Register the Tokyo Night theme with the theme manager\n\tRegisterTheme(\"tokyonight\", NewTokyoNightTheme())\n}"], ["/opencode/internal/tui/theme/onedark.go", "package theme\n\nimport (\n\t\"github.com/charmbracelet/lipgloss\"\n)\n\n// OneDarkTheme implements the Theme interface with Atom's One Dark colors.\n// It provides both dark and light variants.\ntype OneDarkTheme struct {\n\tBaseTheme\n}\n\n// NewOneDarkTheme creates a new instance of the One Dark theme.\nfunc NewOneDarkTheme() *OneDarkTheme {\n\t// One Dark color palette\n\t// Dark mode colors from Atom One Dark\n\tdarkBackground := \"#282c34\"\n\tdarkCurrentLine := \"#2c313c\"\n\tdarkSelection := \"#3e4451\"\n\tdarkForeground := \"#abb2bf\"\n\tdarkComment := \"#5c6370\"\n\tdarkRed := \"#e06c75\"\n\tdarkOrange := \"#d19a66\"\n\tdarkYellow := \"#e5c07b\"\n\tdarkGreen := \"#98c379\"\n\tdarkCyan := \"#56b6c2\"\n\tdarkBlue := \"#61afef\"\n\tdarkPurple := \"#c678dd\"\n\tdarkBorder := \"#3b4048\"\n\n\t// Light mode colors from Atom One Light\n\tlightBackground := \"#fafafa\"\n\tlightCurrentLine := \"#f0f0f0\"\n\tlightSelection := \"#e5e5e6\"\n\tlightForeground := \"#383a42\"\n\tlightComment := \"#a0a1a7\"\n\tlightRed := \"#e45649\"\n\tlightOrange := \"#da8548\"\n\tlightYellow := \"#c18401\"\n\tlightGreen := \"#50a14f\"\n\tlightCyan := \"#0184bc\"\n\tlightBlue := \"#4078f2\"\n\tlightPurple := \"#a626a4\"\n\tlightBorder := \"#d3d3d3\"\n\n\ttheme := &OneDarkTheme{}\n\n\t// Base colors\n\ttheme.PrimaryColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBlue,\n\t\tLight: lightBlue,\n\t}\n\ttheme.SecondaryColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPurple,\n\t\tLight: lightPurple,\n\t}\n\ttheme.AccentColor = lipgloss.AdaptiveColor{\n\t\tDark: darkOrange,\n\t\tLight: lightOrange,\n\t}\n\n\t// Status colors\n\ttheme.ErrorColor = lipgloss.AdaptiveColor{\n\t\tDark: darkRed,\n\t\tLight: lightRed,\n\t}\n\ttheme.WarningColor = lipgloss.AdaptiveColor{\n\t\tDark: darkOrange,\n\t\tLight: lightOrange,\n\t}\n\ttheme.SuccessColor = lipgloss.AdaptiveColor{\n\t\tDark: darkGreen,\n\t\tLight: lightGreen,\n\t}\n\ttheme.InfoColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBlue,\n\t\tLight: lightBlue,\n\t}\n\n\t// Text colors\n\ttheme.TextColor = lipgloss.AdaptiveColor{\n\t\tDark: darkForeground,\n\t\tLight: lightForeground,\n\t}\n\ttheme.TextMutedColor = lipgloss.AdaptiveColor{\n\t\tDark: darkComment,\n\t\tLight: lightComment,\n\t}\n\ttheme.TextEmphasizedColor = lipgloss.AdaptiveColor{\n\t\tDark: darkYellow,\n\t\tLight: lightYellow,\n\t}\n\n\t// Background colors\n\ttheme.BackgroundColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBackground,\n\t\tLight: lightBackground,\n\t}\n\ttheme.BackgroundSecondaryColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCurrentLine,\n\t\tLight: lightCurrentLine,\n\t}\n\ttheme.BackgroundDarkerColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#21252b\", // Slightly darker than background\n\t\tLight: \"#ffffff\", // Slightly lighter than background\n\t}\n\n\t// Border colors\n\ttheme.BorderNormalColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBorder,\n\t\tLight: lightBorder,\n\t}\n\ttheme.BorderFocusedColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBlue,\n\t\tLight: lightBlue,\n\t}\n\ttheme.BorderDimColor = lipgloss.AdaptiveColor{\n\t\tDark: darkSelection,\n\t\tLight: lightSelection,\n\t}\n\n\t// Diff view colors\n\ttheme.DiffAddedColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#478247\",\n\t\tLight: \"#2E7D32\",\n\t}\n\ttheme.DiffRemovedColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#7C4444\",\n\t\tLight: \"#C62828\",\n\t}\n\ttheme.DiffContextColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#a0a0a0\",\n\t\tLight: \"#757575\",\n\t}\n\ttheme.DiffHunkHeaderColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#a0a0a0\",\n\t\tLight: \"#757575\",\n\t}\n\ttheme.DiffHighlightAddedColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#DAFADA\",\n\t\tLight: \"#A5D6A7\",\n\t}\n\ttheme.DiffHighlightRemovedColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#FADADD\",\n\t\tLight: \"#EF9A9A\",\n\t}\n\ttheme.DiffAddedBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#303A30\",\n\t\tLight: \"#E8F5E9\",\n\t}\n\ttheme.DiffRemovedBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#3A3030\",\n\t\tLight: \"#FFEBEE\",\n\t}\n\ttheme.DiffContextBgColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBackground,\n\t\tLight: lightBackground,\n\t}\n\ttheme.DiffLineNumberColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#888888\",\n\t\tLight: \"#9E9E9E\",\n\t}\n\ttheme.DiffAddedLineNumberBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#293229\",\n\t\tLight: \"#C8E6C9\",\n\t}\n\ttheme.DiffRemovedLineNumberBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#332929\",\n\t\tLight: \"#FFCDD2\",\n\t}\n\n\t// Markdown colors\n\ttheme.MarkdownTextColor = lipgloss.AdaptiveColor{\n\t\tDark: darkForeground,\n\t\tLight: lightForeground,\n\t}\n\ttheme.MarkdownHeadingColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPurple,\n\t\tLight: lightPurple,\n\t}\n\ttheme.MarkdownLinkColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBlue,\n\t\tLight: lightBlue,\n\t}\n\ttheme.MarkdownLinkTextColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.MarkdownCodeColor = lipgloss.AdaptiveColor{\n\t\tDark: darkGreen,\n\t\tLight: lightGreen,\n\t}\n\ttheme.MarkdownBlockQuoteColor = lipgloss.AdaptiveColor{\n\t\tDark: darkYellow,\n\t\tLight: lightYellow,\n\t}\n\ttheme.MarkdownEmphColor = lipgloss.AdaptiveColor{\n\t\tDark: darkYellow,\n\t\tLight: lightYellow,\n\t}\n\ttheme.MarkdownStrongColor = lipgloss.AdaptiveColor{\n\t\tDark: darkOrange,\n\t\tLight: lightOrange,\n\t}\n\ttheme.MarkdownHorizontalRuleColor = lipgloss.AdaptiveColor{\n\t\tDark: darkComment,\n\t\tLight: lightComment,\n\t}\n\ttheme.MarkdownListItemColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBlue,\n\t\tLight: lightBlue,\n\t}\n\ttheme.MarkdownListEnumerationColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.MarkdownImageColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBlue,\n\t\tLight: lightBlue,\n\t}\n\ttheme.MarkdownImageTextColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.MarkdownCodeBlockColor = lipgloss.AdaptiveColor{\n\t\tDark: darkForeground,\n\t\tLight: lightForeground,\n\t}\n\n\t// Syntax highlighting colors\n\ttheme.SyntaxCommentColor = lipgloss.AdaptiveColor{\n\t\tDark: darkComment,\n\t\tLight: lightComment,\n\t}\n\ttheme.SyntaxKeywordColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPurple,\n\t\tLight: lightPurple,\n\t}\n\ttheme.SyntaxFunctionColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBlue,\n\t\tLight: lightBlue,\n\t}\n\ttheme.SyntaxVariableColor = lipgloss.AdaptiveColor{\n\t\tDark: darkRed,\n\t\tLight: lightRed,\n\t}\n\ttheme.SyntaxStringColor = lipgloss.AdaptiveColor{\n\t\tDark: darkGreen,\n\t\tLight: lightGreen,\n\t}\n\ttheme.SyntaxNumberColor = lipgloss.AdaptiveColor{\n\t\tDark: darkOrange,\n\t\tLight: lightOrange,\n\t}\n\ttheme.SyntaxTypeColor = lipgloss.AdaptiveColor{\n\t\tDark: darkYellow,\n\t\tLight: lightYellow,\n\t}\n\ttheme.SyntaxOperatorColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.SyntaxPunctuationColor = lipgloss.AdaptiveColor{\n\t\tDark: darkForeground,\n\t\tLight: lightForeground,\n\t}\n\n\treturn theme\n}\n\nfunc init() {\n\t// Register the One Dark theme with the theme manager\n\tRegisterTheme(\"onedark\", NewOneDarkTheme())\n}"], ["/opencode/internal/message/message.go", "package message\n\nimport (\n\t\"context\"\n\t\"database/sql\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com/google/uuid\"\n\t\"github.com/opencode-ai/opencode/internal/db\"\n\t\"github.com/opencode-ai/opencode/internal/llm/models\"\n\t\"github.com/opencode-ai/opencode/internal/pubsub\"\n)\n\ntype CreateMessageParams struct {\n\tRole MessageRole\n\tParts []ContentPart\n\tModel models.ModelID\n}\n\ntype Service interface {\n\tpubsub.Suscriber[Message]\n\tCreate(ctx context.Context, sessionID string, params CreateMessageParams) (Message, error)\n\tUpdate(ctx context.Context, message Message) error\n\tGet(ctx context.Context, id string) (Message, error)\n\tList(ctx context.Context, sessionID string) ([]Message, error)\n\tDelete(ctx context.Context, id string) error\n\tDeleteSessionMessages(ctx context.Context, sessionID string) error\n}\n\ntype service struct {\n\t*pubsub.Broker[Message]\n\tq db.Querier\n}\n\nfunc NewService(q db.Querier) Service {\n\treturn &service{\n\t\tBroker: pubsub.NewBroker[Message](),\n\t\tq: q,\n\t}\n}\n\nfunc (s *service) Delete(ctx context.Context, id string) error {\n\tmessage, err := s.Get(ctx, id)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = s.q.DeleteMessage(ctx, message.ID)\n\tif err != nil {\n\t\treturn err\n\t}\n\ts.Publish(pubsub.DeletedEvent, message)\n\treturn nil\n}\n\nfunc (s *service) Create(ctx context.Context, sessionID string, params CreateMessageParams) (Message, error) {\n\tif params.Role != Assistant {\n\t\tparams.Parts = append(params.Parts, Finish{\n\t\t\tReason: \"stop\",\n\t\t})\n\t}\n\tpartsJSON, err := marshallParts(params.Parts)\n\tif err != nil {\n\t\treturn Message{}, err\n\t}\n\tdbMessage, err := s.q.CreateMessage(ctx, db.CreateMessageParams{\n\t\tID: uuid.New().String(),\n\t\tSessionID: sessionID,\n\t\tRole: string(params.Role),\n\t\tParts: string(partsJSON),\n\t\tModel: sql.NullString{String: string(params.Model), Valid: true},\n\t})\n\tif err != nil {\n\t\treturn Message{}, err\n\t}\n\tmessage, err := s.fromDBItem(dbMessage)\n\tif err != nil {\n\t\treturn Message{}, err\n\t}\n\ts.Publish(pubsub.CreatedEvent, message)\n\treturn message, nil\n}\n\nfunc (s *service) DeleteSessionMessages(ctx context.Context, sessionID string) error {\n\tmessages, err := s.List(ctx, sessionID)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor _, message := range messages {\n\t\tif message.SessionID == sessionID {\n\t\t\terr = s.Delete(ctx, message.ID)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (s *service) Update(ctx context.Context, message Message) error {\n\tparts, err := marshallParts(message.Parts)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfinishedAt := sql.NullInt64{}\n\tif f := message.FinishPart(); f != nil {\n\t\tfinishedAt.Int64 = f.Time\n\t\tfinishedAt.Valid = true\n\t}\n\terr = s.q.UpdateMessage(ctx, db.UpdateMessageParams{\n\t\tID: message.ID,\n\t\tParts: string(parts),\n\t\tFinishedAt: finishedAt,\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\tmessage.UpdatedAt = time.Now().Unix()\n\ts.Publish(pubsub.UpdatedEvent, message)\n\treturn nil\n}\n\nfunc (s *service) Get(ctx context.Context, id string) (Message, error) {\n\tdbMessage, err := s.q.GetMessage(ctx, id)\n\tif err != nil {\n\t\treturn Message{}, err\n\t}\n\treturn s.fromDBItem(dbMessage)\n}\n\nfunc (s *service) List(ctx context.Context, sessionID string) ([]Message, error) {\n\tdbMessages, err := s.q.ListMessagesBySession(ctx, sessionID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tmessages := make([]Message, len(dbMessages))\n\tfor i, dbMessage := range dbMessages {\n\t\tmessages[i], err = s.fromDBItem(dbMessage)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn messages, nil\n}\n\nfunc (s *service) fromDBItem(item db.Message) (Message, error) {\n\tparts, err := unmarshallParts([]byte(item.Parts))\n\tif err != nil {\n\t\treturn Message{}, err\n\t}\n\treturn Message{\n\t\tID: item.ID,\n\t\tSessionID: item.SessionID,\n\t\tRole: MessageRole(item.Role),\n\t\tParts: parts,\n\t\tModel: models.ModelID(item.Model.String),\n\t\tCreatedAt: item.CreatedAt,\n\t\tUpdatedAt: item.UpdatedAt,\n\t}, nil\n}\n\ntype partType string\n\nconst (\n\treasoningType partType = \"reasoning\"\n\ttextType partType = \"text\"\n\timageURLType partType = \"image_url\"\n\tbinaryType partType = \"binary\"\n\ttoolCallType partType = \"tool_call\"\n\ttoolResultType partType = \"tool_result\"\n\tfinishType partType = \"finish\"\n)\n\ntype partWrapper struct {\n\tType partType `json:\"type\"`\n\tData ContentPart `json:\"data\"`\n}\n\nfunc marshallParts(parts []ContentPart) ([]byte, error) {\n\twrappedParts := make([]partWrapper, len(parts))\n\n\tfor i, part := range parts {\n\t\tvar typ partType\n\n\t\tswitch part.(type) {\n\t\tcase ReasoningContent:\n\t\t\ttyp = reasoningType\n\t\tcase TextContent:\n\t\t\ttyp = textType\n\t\tcase ImageURLContent:\n\t\t\ttyp = imageURLType\n\t\tcase BinaryContent:\n\t\t\ttyp = binaryType\n\t\tcase ToolCall:\n\t\t\ttyp = toolCallType\n\t\tcase ToolResult:\n\t\t\ttyp = toolResultType\n\t\tcase Finish:\n\t\t\ttyp = finishType\n\t\tdefault:\n\t\t\treturn nil, fmt.Errorf(\"unknown part type: %T\", part)\n\t\t}\n\n\t\twrappedParts[i] = partWrapper{\n\t\t\tType: typ,\n\t\t\tData: part,\n\t\t}\n\t}\n\treturn json.Marshal(wrappedParts)\n}\n\nfunc unmarshallParts(data []byte) ([]ContentPart, error) {\n\ttemp := []json.RawMessage{}\n\n\tif err := json.Unmarshal(data, &temp); err != nil {\n\t\treturn nil, err\n\t}\n\n\tparts := make([]ContentPart, 0)\n\n\tfor _, rawPart := range temp {\n\t\tvar wrapper struct {\n\t\t\tType partType `json:\"type\"`\n\t\t\tData json.RawMessage `json:\"data\"`\n\t\t}\n\n\t\tif err := json.Unmarshal(rawPart, &wrapper); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tswitch wrapper.Type {\n\t\tcase reasoningType:\n\t\t\tpart := ReasoningContent{}\n\t\t\tif err := json.Unmarshal(wrapper.Data, &part); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tparts = append(parts, part)\n\t\tcase textType:\n\t\t\tpart := TextContent{}\n\t\t\tif err := json.Unmarshal(wrapper.Data, &part); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tparts = append(parts, part)\n\t\tcase imageURLType:\n\t\t\tpart := ImageURLContent{}\n\t\t\tif err := json.Unmarshal(wrapper.Data, &part); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\tcase binaryType:\n\t\t\tpart := BinaryContent{}\n\t\t\tif err := json.Unmarshal(wrapper.Data, &part); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tparts = append(parts, part)\n\t\tcase toolCallType:\n\t\t\tpart := ToolCall{}\n\t\t\tif err := json.Unmarshal(wrapper.Data, &part); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tparts = append(parts, part)\n\t\tcase toolResultType:\n\t\t\tpart := ToolResult{}\n\t\t\tif err := json.Unmarshal(wrapper.Data, &part); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tparts = append(parts, part)\n\t\tcase finishType:\n\t\t\tpart := Finish{}\n\t\t\tif err := json.Unmarshal(wrapper.Data, &part); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tparts = append(parts, part)\n\t\tdefault:\n\t\t\treturn nil, fmt.Errorf(\"unknown part type: %s\", wrapper.Type)\n\t\t}\n\n\t}\n\n\treturn parts, nil\n}\n"], ["/opencode/internal/llm/provider/provider.go", "package provider\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"os\"\n\n\t\"github.com/opencode-ai/opencode/internal/llm/models\"\n\t\"github.com/opencode-ai/opencode/internal/llm/tools\"\n\t\"github.com/opencode-ai/opencode/internal/message\"\n)\n\ntype EventType string\n\nconst maxRetries = 8\n\nconst (\n\tEventContentStart EventType = \"content_start\"\n\tEventToolUseStart EventType = \"tool_use_start\"\n\tEventToolUseDelta EventType = \"tool_use_delta\"\n\tEventToolUseStop EventType = \"tool_use_stop\"\n\tEventContentDelta EventType = \"content_delta\"\n\tEventThinkingDelta EventType = \"thinking_delta\"\n\tEventContentStop EventType = \"content_stop\"\n\tEventComplete EventType = \"complete\"\n\tEventError EventType = \"error\"\n\tEventWarning EventType = \"warning\"\n)\n\ntype TokenUsage struct {\n\tInputTokens int64\n\tOutputTokens int64\n\tCacheCreationTokens int64\n\tCacheReadTokens int64\n}\n\ntype ProviderResponse struct {\n\tContent string\n\tToolCalls []message.ToolCall\n\tUsage TokenUsage\n\tFinishReason message.FinishReason\n}\n\ntype ProviderEvent struct {\n\tType EventType\n\n\tContent string\n\tThinking string\n\tResponse *ProviderResponse\n\tToolCall *message.ToolCall\n\tError error\n}\ntype Provider interface {\n\tSendMessages(ctx context.Context, messages []message.Message, tools []tools.BaseTool) (*ProviderResponse, error)\n\n\tStreamResponse(ctx context.Context, messages []message.Message, tools []tools.BaseTool) <-chan ProviderEvent\n\n\tModel() models.Model\n}\n\ntype providerClientOptions struct {\n\tapiKey string\n\tmodel models.Model\n\tmaxTokens int64\n\tsystemMessage string\n\n\tanthropicOptions []AnthropicOption\n\topenaiOptions []OpenAIOption\n\tgeminiOptions []GeminiOption\n\tbedrockOptions []BedrockOption\n\tcopilotOptions []CopilotOption\n}\n\ntype ProviderClientOption func(*providerClientOptions)\n\ntype ProviderClient interface {\n\tsend(ctx context.Context, messages []message.Message, tools []tools.BaseTool) (*ProviderResponse, error)\n\tstream(ctx context.Context, messages []message.Message, tools []tools.BaseTool) <-chan ProviderEvent\n}\n\ntype baseProvider[C ProviderClient] struct {\n\toptions providerClientOptions\n\tclient C\n}\n\nfunc NewProvider(providerName models.ModelProvider, opts ...ProviderClientOption) (Provider, error) {\n\tclientOptions := providerClientOptions{}\n\tfor _, o := range opts {\n\t\to(&clientOptions)\n\t}\n\tswitch providerName {\n\tcase models.ProviderCopilot:\n\t\treturn &baseProvider[CopilotClient]{\n\t\t\toptions: clientOptions,\n\t\t\tclient: newCopilotClient(clientOptions),\n\t\t}, nil\n\tcase models.ProviderAnthropic:\n\t\treturn &baseProvider[AnthropicClient]{\n\t\t\toptions: clientOptions,\n\t\t\tclient: newAnthropicClient(clientOptions),\n\t\t}, nil\n\tcase models.ProviderOpenAI:\n\t\treturn &baseProvider[OpenAIClient]{\n\t\t\toptions: clientOptions,\n\t\t\tclient: newOpenAIClient(clientOptions),\n\t\t}, nil\n\tcase models.ProviderGemini:\n\t\treturn &baseProvider[GeminiClient]{\n\t\t\toptions: clientOptions,\n\t\t\tclient: newGeminiClient(clientOptions),\n\t\t}, nil\n\tcase models.ProviderBedrock:\n\t\treturn &baseProvider[BedrockClient]{\n\t\t\toptions: clientOptions,\n\t\t\tclient: newBedrockClient(clientOptions),\n\t\t}, nil\n\tcase models.ProviderGROQ:\n\t\tclientOptions.openaiOptions = append(clientOptions.openaiOptions,\n\t\t\tWithOpenAIBaseURL(\"https://api.groq.com/openai/v1\"),\n\t\t)\n\t\treturn &baseProvider[OpenAIClient]{\n\t\t\toptions: clientOptions,\n\t\t\tclient: newOpenAIClient(clientOptions),\n\t\t}, nil\n\tcase models.ProviderAzure:\n\t\treturn &baseProvider[AzureClient]{\n\t\t\toptions: clientOptions,\n\t\t\tclient: newAzureClient(clientOptions),\n\t\t}, nil\n\tcase models.ProviderVertexAI:\n\t\treturn &baseProvider[VertexAIClient]{\n\t\t\toptions: clientOptions,\n\t\t\tclient: newVertexAIClient(clientOptions),\n\t\t}, nil\n\tcase models.ProviderOpenRouter:\n\t\tclientOptions.openaiOptions = append(clientOptions.openaiOptions,\n\t\t\tWithOpenAIBaseURL(\"https://openrouter.ai/api/v1\"),\n\t\t\tWithOpenAIExtraHeaders(map[string]string{\n\t\t\t\t\"HTTP-Referer\": \"opencode.ai\",\n\t\t\t\t\"X-Title\": \"OpenCode\",\n\t\t\t}),\n\t\t)\n\t\treturn &baseProvider[OpenAIClient]{\n\t\t\toptions: clientOptions,\n\t\t\tclient: newOpenAIClient(clientOptions),\n\t\t}, nil\n\tcase models.ProviderXAI:\n\t\tclientOptions.openaiOptions = append(clientOptions.openaiOptions,\n\t\t\tWithOpenAIBaseURL(\"https://api.x.ai/v1\"),\n\t\t)\n\t\treturn &baseProvider[OpenAIClient]{\n\t\t\toptions: clientOptions,\n\t\t\tclient: newOpenAIClient(clientOptions),\n\t\t}, nil\n\tcase models.ProviderLocal:\n\t\tclientOptions.openaiOptions = append(clientOptions.openaiOptions,\n\t\t\tWithOpenAIBaseURL(os.Getenv(\"LOCAL_ENDPOINT\")),\n\t\t)\n\t\treturn &baseProvider[OpenAIClient]{\n\t\t\toptions: clientOptions,\n\t\t\tclient: newOpenAIClient(clientOptions),\n\t\t}, nil\n\tcase models.ProviderMock:\n\t\t// TODO: implement mock client for test\n\t\tpanic(\"not implemented\")\n\t}\n\treturn nil, fmt.Errorf(\"provider not supported: %s\", providerName)\n}\n\nfunc (p *baseProvider[C]) cleanMessages(messages []message.Message) (cleaned []message.Message) {\n\tfor _, msg := range messages {\n\t\t// The message has no content\n\t\tif len(msg.Parts) == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tcleaned = append(cleaned, msg)\n\t}\n\treturn\n}\n\nfunc (p *baseProvider[C]) SendMessages(ctx context.Context, messages []message.Message, tools []tools.BaseTool) (*ProviderResponse, error) {\n\tmessages = p.cleanMessages(messages)\n\treturn p.client.send(ctx, messages, tools)\n}\n\nfunc (p *baseProvider[C]) Model() models.Model {\n\treturn p.options.model\n}\n\nfunc (p *baseProvider[C]) StreamResponse(ctx context.Context, messages []message.Message, tools []tools.BaseTool) <-chan ProviderEvent {\n\tmessages = p.cleanMessages(messages)\n\treturn p.client.stream(ctx, messages, tools)\n}\n\nfunc WithAPIKey(apiKey string) ProviderClientOption {\n\treturn func(options *providerClientOptions) {\n\t\toptions.apiKey = apiKey\n\t}\n}\n\nfunc WithModel(model models.Model) ProviderClientOption {\n\treturn func(options *providerClientOptions) {\n\t\toptions.model = model\n\t}\n}\n\nfunc WithMaxTokens(maxTokens int64) ProviderClientOption {\n\treturn func(options *providerClientOptions) {\n\t\toptions.maxTokens = maxTokens\n\t}\n}\n\nfunc WithSystemMessage(systemMessage string) ProviderClientOption {\n\treturn func(options *providerClientOptions) {\n\t\toptions.systemMessage = systemMessage\n\t}\n}\n\nfunc WithAnthropicOptions(anthropicOptions ...AnthropicOption) ProviderClientOption {\n\treturn func(options *providerClientOptions) {\n\t\toptions.anthropicOptions = anthropicOptions\n\t}\n}\n\nfunc WithOpenAIOptions(openaiOptions ...OpenAIOption) ProviderClientOption {\n\treturn func(options *providerClientOptions) {\n\t\toptions.openaiOptions = openaiOptions\n\t}\n}\n\nfunc WithGeminiOptions(geminiOptions ...GeminiOption) ProviderClientOption {\n\treturn func(options *providerClientOptions) {\n\t\toptions.geminiOptions = geminiOptions\n\t}\n}\n\nfunc WithBedrockOptions(bedrockOptions ...BedrockOption) ProviderClientOption {\n\treturn func(options *providerClientOptions) {\n\t\toptions.bedrockOptions = bedrockOptions\n\t}\n}\n\nfunc WithCopilotOptions(copilotOptions ...CopilotOption) ProviderClientOption {\n\treturn func(options *providerClientOptions) {\n\t\toptions.copilotOptions = copilotOptions\n\t}\n}\n"], ["/opencode/internal/lsp/transport.go", "package lsp\n\nimport (\n\t\"bufio\"\n\t\"context\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"strings\"\n\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n)\n\n// Write writes an LSP message to the given writer\nfunc WriteMessage(w io.Writer, msg *Message) error {\n\tdata, err := json.Marshal(msg)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to marshal message: %w\", err)\n\t}\n\tcnf := config.Get()\n\n\tif cnf.DebugLSP {\n\t\tlogging.Debug(\"Sending message to server\", \"method\", msg.Method, \"id\", msg.ID)\n\t}\n\n\t_, err = fmt.Fprintf(w, \"Content-Length: %d\\r\\n\\r\\n\", len(data))\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to write header: %w\", err)\n\t}\n\n\t_, err = w.Write(data)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to write message: %w\", err)\n\t}\n\n\treturn nil\n}\n\n// ReadMessage reads a single LSP message from the given reader\nfunc ReadMessage(r *bufio.Reader) (*Message, error) {\n\tcnf := config.Get()\n\t// Read headers\n\tvar contentLength int\n\tfor {\n\t\tline, err := r.ReadString('\\n')\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to read header: %w\", err)\n\t\t}\n\t\tline = strings.TrimSpace(line)\n\n\t\tif cnf.DebugLSP {\n\t\t\tlogging.Debug(\"Received header\", \"line\", line)\n\t\t}\n\n\t\tif line == \"\" {\n\t\t\tbreak // End of headers\n\t\t}\n\n\t\tif strings.HasPrefix(line, \"Content-Length: \") {\n\t\t\t_, err := fmt.Sscanf(line, \"Content-Length: %d\", &contentLength)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"invalid Content-Length: %w\", err)\n\t\t\t}\n\t\t}\n\t}\n\n\tif cnf.DebugLSP {\n\t\tlogging.Debug(\"Content-Length\", \"length\", contentLength)\n\t}\n\n\t// Read content\n\tcontent := make([]byte, contentLength)\n\t_, err := io.ReadFull(r, content)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to read content: %w\", err)\n\t}\n\n\tif cnf.DebugLSP {\n\t\tlogging.Debug(\"Received content\", \"content\", string(content))\n\t}\n\n\t// Parse message\n\tvar msg Message\n\tif err := json.Unmarshal(content, &msg); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to unmarshal message: %w\", err)\n\t}\n\n\treturn &msg, nil\n}\n\n// handleMessages reads and dispatches messages in a loop\nfunc (c *Client) handleMessages() {\n\tcnf := config.Get()\n\tfor {\n\t\tmsg, err := ReadMessage(c.stdout)\n\t\tif err != nil {\n\t\t\tif cnf.DebugLSP {\n\t\t\t\tlogging.Error(\"Error reading message\", \"error\", err)\n\t\t\t}\n\t\t\treturn\n\t\t}\n\n\t\t// Handle server->client request (has both Method and ID)\n\t\tif msg.Method != \"\" && msg.ID != 0 {\n\t\t\tif cnf.DebugLSP {\n\t\t\t\tlogging.Debug(\"Received request from server\", \"method\", msg.Method, \"id\", msg.ID)\n\t\t\t}\n\n\t\t\tresponse := &Message{\n\t\t\t\tJSONRPC: \"2.0\",\n\t\t\t\tID: msg.ID,\n\t\t\t}\n\n\t\t\t// Look up handler for this method\n\t\t\tc.serverHandlersMu.RLock()\n\t\t\thandler, ok := c.serverRequestHandlers[msg.Method]\n\t\t\tc.serverHandlersMu.RUnlock()\n\n\t\t\tif ok {\n\t\t\t\tresult, err := handler(msg.Params)\n\t\t\t\tif err != nil {\n\t\t\t\t\tresponse.Error = &ResponseError{\n\t\t\t\t\t\tCode: -32603,\n\t\t\t\t\t\tMessage: err.Error(),\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\trawJSON, err := json.Marshal(result)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tresponse.Error = &ResponseError{\n\t\t\t\t\t\t\tCode: -32603,\n\t\t\t\t\t\t\tMessage: fmt.Sprintf(\"failed to marshal response: %v\", err),\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tresponse.Result = rawJSON\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tresponse.Error = &ResponseError{\n\t\t\t\t\tCode: -32601,\n\t\t\t\t\tMessage: fmt.Sprintf(\"method not found: %s\", msg.Method),\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Send response back to server\n\t\t\tif err := WriteMessage(c.stdin, response); err != nil {\n\t\t\t\tlogging.Error(\"Error sending response to server\", \"error\", err)\n\t\t\t}\n\n\t\t\tcontinue\n\t\t}\n\n\t\t// Handle notification (has Method but no ID)\n\t\tif msg.Method != \"\" && msg.ID == 0 {\n\t\t\tc.notificationMu.RLock()\n\t\t\thandler, ok := c.notificationHandlers[msg.Method]\n\t\t\tc.notificationMu.RUnlock()\n\n\t\t\tif ok {\n\t\t\t\tif cnf.DebugLSP {\n\t\t\t\t\tlogging.Debug(\"Handling notification\", \"method\", msg.Method)\n\t\t\t\t}\n\t\t\t\tgo handler(msg.Params)\n\t\t\t} else if cnf.DebugLSP {\n\t\t\t\tlogging.Debug(\"No handler for notification\", \"method\", msg.Method)\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\t// Handle response to our request (has ID but no Method)\n\t\tif msg.ID != 0 && msg.Method == \"\" {\n\t\t\tc.handlersMu.RLock()\n\t\t\tch, ok := c.handlers[msg.ID]\n\t\t\tc.handlersMu.RUnlock()\n\n\t\t\tif ok {\n\t\t\t\tif cnf.DebugLSP {\n\t\t\t\t\tlogging.Debug(\"Received response for request\", \"id\", msg.ID)\n\t\t\t\t}\n\t\t\t\tch <- msg\n\t\t\t\tclose(ch)\n\t\t\t} else if cnf.DebugLSP {\n\t\t\t\tlogging.Debug(\"No handler for response\", \"id\", msg.ID)\n\t\t\t}\n\t\t}\n\t}\n}\n\n// Call makes a request and waits for the response\nfunc (c *Client) Call(ctx context.Context, method string, params any, result any) error {\n\tcnf := config.Get()\n\tid := c.nextID.Add(1)\n\n\tif cnf.DebugLSP {\n\t\tlogging.Debug(\"Making call\", \"method\", method, \"id\", id)\n\t}\n\n\tmsg, err := NewRequest(id, method, params)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to create request: %w\", err)\n\t}\n\n\t// Create response channel\n\tch := make(chan *Message, 1)\n\tc.handlersMu.Lock()\n\tc.handlers[id] = ch\n\tc.handlersMu.Unlock()\n\n\tdefer func() {\n\t\tc.handlersMu.Lock()\n\t\tdelete(c.handlers, id)\n\t\tc.handlersMu.Unlock()\n\t}()\n\n\t// Send request\n\tif err := WriteMessage(c.stdin, msg); err != nil {\n\t\treturn fmt.Errorf(\"failed to send request: %w\", err)\n\t}\n\n\tif cnf.DebugLSP {\n\t\tlogging.Debug(\"Request sent\", \"method\", method, \"id\", id)\n\t}\n\n\t// Wait for response\n\tresp := <-ch\n\n\tif cnf.DebugLSP {\n\t\tlogging.Debug(\"Received response\", \"id\", id)\n\t}\n\n\tif resp.Error != nil {\n\t\treturn fmt.Errorf(\"request failed: %s (code: %d)\", resp.Error.Message, resp.Error.Code)\n\t}\n\n\tif result != nil {\n\t\t// If result is a json.RawMessage, just copy the raw bytes\n\t\tif rawMsg, ok := result.(*json.RawMessage); ok {\n\t\t\t*rawMsg = resp.Result\n\t\t\treturn nil\n\t\t}\n\t\t// Otherwise unmarshal into the provided type\n\t\tif err := json.Unmarshal(resp.Result, result); err != nil {\n\t\t\treturn fmt.Errorf(\"failed to unmarshal result: %w\", err)\n\t\t}\n\t}\n\n\treturn nil\n}\n\n// Notify sends a notification (a request without an ID that doesn't expect a response)\nfunc (c *Client) Notify(ctx context.Context, method string, params any) error {\n\tcnf := config.Get()\n\tif cnf.DebugLSP {\n\t\tlogging.Debug(\"Sending notification\", \"method\", method)\n\t}\n\n\tmsg, err := NewNotification(method, params)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to create notification: %w\", err)\n\t}\n\n\tif err := WriteMessage(c.stdin, msg); err != nil {\n\t\treturn fmt.Errorf(\"failed to send notification: %w\", err)\n\t}\n\n\treturn nil\n}\n\ntype (\n\tNotificationHandler func(params json.RawMessage)\n\tServerRequestHandler func(params json.RawMessage) (any, error)\n)\n"], ["/opencode/internal/tui/theme/catppuccin.go", "package theme\n\nimport (\n\tcatppuccin \"github.com/catppuccin/go\"\n\t\"github.com/charmbracelet/lipgloss\"\n)\n\n// CatppuccinTheme implements the Theme interface with Catppuccin colors.\n// It provides both dark (Mocha) and light (Latte) variants.\ntype CatppuccinTheme struct {\n\tBaseTheme\n}\n\n// NewCatppuccinTheme creates a new instance of the Catppuccin theme.\nfunc NewCatppuccinTheme() *CatppuccinTheme {\n\t// Get the Catppuccin palettes\n\tmocha := catppuccin.Mocha\n\tlatte := catppuccin.Latte\n\n\ttheme := &CatppuccinTheme{}\n\n\t// Base colors\n\ttheme.PrimaryColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Blue().Hex,\n\t\tLight: latte.Blue().Hex,\n\t}\n\ttheme.SecondaryColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Mauve().Hex,\n\t\tLight: latte.Mauve().Hex,\n\t}\n\ttheme.AccentColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Peach().Hex,\n\t\tLight: latte.Peach().Hex,\n\t}\n\n\t// Status colors\n\ttheme.ErrorColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Red().Hex,\n\t\tLight: latte.Red().Hex,\n\t}\n\ttheme.WarningColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Peach().Hex,\n\t\tLight: latte.Peach().Hex,\n\t}\n\ttheme.SuccessColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Green().Hex,\n\t\tLight: latte.Green().Hex,\n\t}\n\ttheme.InfoColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Blue().Hex,\n\t\tLight: latte.Blue().Hex,\n\t}\n\n\t// Text colors\n\ttheme.TextColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Text().Hex,\n\t\tLight: latte.Text().Hex,\n\t}\n\ttheme.TextMutedColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Subtext0().Hex,\n\t\tLight: latte.Subtext0().Hex,\n\t}\n\ttheme.TextEmphasizedColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Lavender().Hex,\n\t\tLight: latte.Lavender().Hex,\n\t}\n\n\t// Background colors\n\ttheme.BackgroundColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#212121\", // From existing styles\n\t\tLight: \"#EEEEEE\", // Light equivalent\n\t}\n\ttheme.BackgroundSecondaryColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#2c2c2c\", // From existing styles\n\t\tLight: \"#E0E0E0\", // Light equivalent\n\t}\n\ttheme.BackgroundDarkerColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#181818\", // From existing styles\n\t\tLight: \"#F5F5F5\", // Light equivalent\n\t}\n\n\t// Border colors\n\ttheme.BorderNormalColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#4b4c5c\", // From existing styles\n\t\tLight: \"#BDBDBD\", // Light equivalent\n\t}\n\ttheme.BorderFocusedColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Blue().Hex,\n\t\tLight: latte.Blue().Hex,\n\t}\n\ttheme.BorderDimColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Surface0().Hex,\n\t\tLight: latte.Surface0().Hex,\n\t}\n\n\t// Diff view colors\n\ttheme.DiffAddedColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#478247\", // From existing diff.go\n\t\tLight: \"#2E7D32\", // Light equivalent\n\t}\n\ttheme.DiffRemovedColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#7C4444\", // From existing diff.go\n\t\tLight: \"#C62828\", // Light equivalent\n\t}\n\ttheme.DiffContextColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#a0a0a0\", // From existing diff.go\n\t\tLight: \"#757575\", // Light equivalent\n\t}\n\ttheme.DiffHunkHeaderColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#a0a0a0\", // From existing diff.go\n\t\tLight: \"#757575\", // Light equivalent\n\t}\n\ttheme.DiffHighlightAddedColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#DAFADA\", // From existing diff.go\n\t\tLight: \"#A5D6A7\", // Light equivalent\n\t}\n\ttheme.DiffHighlightRemovedColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#FADADD\", // From existing diff.go\n\t\tLight: \"#EF9A9A\", // Light equivalent\n\t}\n\ttheme.DiffAddedBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#303A30\", // From existing diff.go\n\t\tLight: \"#E8F5E9\", // Light equivalent\n\t}\n\ttheme.DiffRemovedBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#3A3030\", // From existing diff.go\n\t\tLight: \"#FFEBEE\", // Light equivalent\n\t}\n\ttheme.DiffContextBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#212121\", // From existing diff.go\n\t\tLight: \"#F5F5F5\", // Light equivalent\n\t}\n\ttheme.DiffLineNumberColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#888888\", // From existing diff.go\n\t\tLight: \"#9E9E9E\", // Light equivalent\n\t}\n\ttheme.DiffAddedLineNumberBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#293229\", // From existing diff.go\n\t\tLight: \"#C8E6C9\", // Light equivalent\n\t}\n\ttheme.DiffRemovedLineNumberBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#332929\", // From existing diff.go\n\t\tLight: \"#FFCDD2\", // Light equivalent\n\t}\n\n\t// Markdown colors\n\ttheme.MarkdownTextColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Text().Hex,\n\t\tLight: latte.Text().Hex,\n\t}\n\ttheme.MarkdownHeadingColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Mauve().Hex,\n\t\tLight: latte.Mauve().Hex,\n\t}\n\ttheme.MarkdownLinkColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Sky().Hex,\n\t\tLight: latte.Sky().Hex,\n\t}\n\ttheme.MarkdownLinkTextColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Pink().Hex,\n\t\tLight: latte.Pink().Hex,\n\t}\n\ttheme.MarkdownCodeColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Green().Hex,\n\t\tLight: latte.Green().Hex,\n\t}\n\ttheme.MarkdownBlockQuoteColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Yellow().Hex,\n\t\tLight: latte.Yellow().Hex,\n\t}\n\ttheme.MarkdownEmphColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Yellow().Hex,\n\t\tLight: latte.Yellow().Hex,\n\t}\n\ttheme.MarkdownStrongColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Peach().Hex,\n\t\tLight: latte.Peach().Hex,\n\t}\n\ttheme.MarkdownHorizontalRuleColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Overlay0().Hex,\n\t\tLight: latte.Overlay0().Hex,\n\t}\n\ttheme.MarkdownListItemColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Blue().Hex,\n\t\tLight: latte.Blue().Hex,\n\t}\n\ttheme.MarkdownListEnumerationColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Sky().Hex,\n\t\tLight: latte.Sky().Hex,\n\t}\n\ttheme.MarkdownImageColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Sapphire().Hex,\n\t\tLight: latte.Sapphire().Hex,\n\t}\n\ttheme.MarkdownImageTextColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Pink().Hex,\n\t\tLight: latte.Pink().Hex,\n\t}\n\ttheme.MarkdownCodeBlockColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Text().Hex,\n\t\tLight: latte.Text().Hex,\n\t}\n\n\t// Syntax highlighting colors\n\ttheme.SyntaxCommentColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Overlay1().Hex,\n\t\tLight: latte.Overlay1().Hex,\n\t}\n\ttheme.SyntaxKeywordColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Pink().Hex,\n\t\tLight: latte.Pink().Hex,\n\t}\n\ttheme.SyntaxFunctionColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Green().Hex,\n\t\tLight: latte.Green().Hex,\n\t}\n\ttheme.SyntaxVariableColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Sky().Hex,\n\t\tLight: latte.Sky().Hex,\n\t}\n\ttheme.SyntaxStringColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Yellow().Hex,\n\t\tLight: latte.Yellow().Hex,\n\t}\n\ttheme.SyntaxNumberColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Teal().Hex,\n\t\tLight: latte.Teal().Hex,\n\t}\n\ttheme.SyntaxTypeColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Sky().Hex,\n\t\tLight: latte.Sky().Hex,\n\t}\n\ttheme.SyntaxOperatorColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Pink().Hex,\n\t\tLight: latte.Pink().Hex,\n\t}\n\ttheme.SyntaxPunctuationColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Text().Hex,\n\t\tLight: latte.Text().Hex,\n\t}\n\n\treturn theme\n}\n\nfunc init() {\n\t// Register the Catppuccin theme with the theme manager\n\tRegisterTheme(\"catppuccin\", NewCatppuccinTheme())\n}"], ["/opencode/internal/format/spinner.go", "package format\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"os\"\n\n\t\"github.com/charmbracelet/bubbles/spinner\"\n\ttea \"github.com/charmbracelet/bubbletea\"\n)\n\n// Spinner wraps the bubbles spinner for non-interactive mode\ntype Spinner struct {\n\tmodel spinner.Model\n\tdone chan struct{}\n\tprog *tea.Program\n\tctx context.Context\n\tcancel context.CancelFunc\n}\n\n// spinnerModel is the tea.Model for the spinner\ntype spinnerModel struct {\n\tspinner spinner.Model\n\tmessage string\n\tquitting bool\n}\n\nfunc (m spinnerModel) Init() tea.Cmd {\n\treturn m.spinner.Tick\n}\n\nfunc (m spinnerModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {\n\tswitch msg := msg.(type) {\n\tcase tea.KeyMsg:\n\t\tm.quitting = true\n\t\treturn m, tea.Quit\n\tcase spinner.TickMsg:\n\t\tvar cmd tea.Cmd\n\t\tm.spinner, cmd = m.spinner.Update(msg)\n\t\treturn m, cmd\n\tcase quitMsg:\n\t\tm.quitting = true\n\t\treturn m, tea.Quit\n\tdefault:\n\t\treturn m, nil\n\t}\n}\n\nfunc (m spinnerModel) View() string {\n\tif m.quitting {\n\t\treturn \"\"\n\t}\n\treturn fmt.Sprintf(\"%s %s\", m.spinner.View(), m.message)\n}\n\n// quitMsg is sent when we want to quit the spinner\ntype quitMsg struct{}\n\n// NewSpinner creates a new spinner with the given message\nfunc NewSpinner(message string) *Spinner {\n\ts := spinner.New()\n\ts.Spinner = spinner.Dot\n\ts.Style = s.Style.Foreground(s.Style.GetForeground())\n\n\tctx, cancel := context.WithCancel(context.Background())\n\n\tmodel := spinnerModel{\n\t\tspinner: s,\n\t\tmessage: message,\n\t}\n\n\tprog := tea.NewProgram(model, tea.WithOutput(os.Stderr), tea.WithoutCatchPanics())\n\n\treturn &Spinner{\n\t\tmodel: s,\n\t\tdone: make(chan struct{}),\n\t\tprog: prog,\n\t\tctx: ctx,\n\t\tcancel: cancel,\n\t}\n}\n\n// Start begins the spinner animation\nfunc (s *Spinner) Start() {\n\tgo func() {\n\t\tdefer close(s.done)\n\t\tgo func() {\n\t\t\t<-s.ctx.Done()\n\t\t\ts.prog.Send(quitMsg{})\n\t\t}()\n\t\t_, err := s.prog.Run()\n\t\tif err != nil {\n\t\t\tfmt.Fprintf(os.Stderr, \"Error running spinner: %v\\n\", err)\n\t\t}\n\t}()\n}\n\n// Stop ends the spinner animation\nfunc (s *Spinner) Stop() {\n\ts.cancel()\n\t<-s.done\n}\n"], ["/opencode/internal/tui/theme/manager.go", "package theme\n\nimport (\n\t\"fmt\"\n\t\"slices\"\n\t\"strings\"\n\t\"sync\"\n\n\t\"github.com/alecthomas/chroma/v2/styles\"\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n)\n\n// Manager handles theme registration, selection, and retrieval.\n// It maintains a registry of available themes and tracks the currently active theme.\ntype Manager struct {\n\tthemes map[string]Theme\n\tcurrentName string\n\tmu sync.RWMutex\n}\n\n// Global instance of the theme manager\nvar globalManager = &Manager{\n\tthemes: make(map[string]Theme),\n\tcurrentName: \"\",\n}\n\n// RegisterTheme adds a new theme to the registry.\n// If this is the first theme registered, it becomes the default.\nfunc RegisterTheme(name string, theme Theme) {\n\tglobalManager.mu.Lock()\n\tdefer globalManager.mu.Unlock()\n\n\tglobalManager.themes[name] = theme\n\n\t// If this is the first theme, make it the default\n\tif globalManager.currentName == \"\" {\n\t\tglobalManager.currentName = name\n\t}\n}\n\n// SetTheme changes the active theme to the one with the specified name.\n// Returns an error if the theme doesn't exist.\nfunc SetTheme(name string) error {\n\tglobalManager.mu.Lock()\n\tdefer globalManager.mu.Unlock()\n\n\tdelete(styles.Registry, \"charm\")\n\tif _, exists := globalManager.themes[name]; !exists {\n\t\treturn fmt.Errorf(\"theme '%s' not found\", name)\n\t}\n\n\tglobalManager.currentName = name\n\n\t// Update the config file using viper\n\tif err := updateConfigTheme(name); err != nil {\n\t\t// Log the error but don't fail the theme change\n\t\tlogging.Warn(\"Warning: Failed to update config file with new theme\", \"err\", err)\n\t}\n\n\treturn nil\n}\n\n// CurrentTheme returns the currently active theme.\n// If no theme is set, it returns nil.\nfunc CurrentTheme() Theme {\n\tglobalManager.mu.RLock()\n\tdefer globalManager.mu.RUnlock()\n\n\tif globalManager.currentName == \"\" {\n\t\treturn nil\n\t}\n\n\treturn globalManager.themes[globalManager.currentName]\n}\n\n// CurrentThemeName returns the name of the currently active theme.\nfunc CurrentThemeName() string {\n\tglobalManager.mu.RLock()\n\tdefer globalManager.mu.RUnlock()\n\n\treturn globalManager.currentName\n}\n\n// AvailableThemes returns a list of all registered theme names.\nfunc AvailableThemes() []string {\n\tglobalManager.mu.RLock()\n\tdefer globalManager.mu.RUnlock()\n\n\tnames := make([]string, 0, len(globalManager.themes))\n\tfor name := range globalManager.themes {\n\t\tnames = append(names, name)\n\t}\n\tslices.SortFunc(names, func(a, b string) int {\n\t\tif a == \"opencode\" {\n\t\t\treturn -1\n\t\t} else if b == \"opencode\" {\n\t\t\treturn 1\n\t\t}\n\t\treturn strings.Compare(a, b)\n\t})\n\treturn names\n}\n\n// GetTheme returns a specific theme by name.\n// Returns nil if the theme doesn't exist.\nfunc GetTheme(name string) Theme {\n\tglobalManager.mu.RLock()\n\tdefer globalManager.mu.RUnlock()\n\n\treturn globalManager.themes[name]\n}\n\n// updateConfigTheme updates the theme setting in the configuration file\nfunc updateConfigTheme(themeName string) error {\n\t// Use the config package to update the theme\n\treturn config.UpdateTheme(themeName)\n}\n"], ["/opencode/internal/tui/theme/flexoki.go", "package theme\n\nimport (\n\t\"github.com/charmbracelet/lipgloss\"\n)\n\n// Flexoki color palette constants\nconst (\n\t// Base colors\n\tflexokiPaper = \"#FFFCF0\" // Paper (lightest)\n\tflexokiBase50 = \"#F2F0E5\" // bg-2 (light)\n\tflexokiBase100 = \"#E6E4D9\" // ui (light)\n\tflexokiBase150 = \"#DAD8CE\" // ui-2 (light)\n\tflexokiBase200 = \"#CECDC3\" // ui-3 (light)\n\tflexokiBase300 = \"#B7B5AC\" // tx-3 (light)\n\tflexokiBase500 = \"#878580\" // tx-2 (light)\n\tflexokiBase600 = \"#6F6E69\" // tx (light)\n\tflexokiBase700 = \"#575653\" // tx-3 (dark)\n\tflexokiBase800 = \"#403E3C\" // ui-3 (dark)\n\tflexokiBase850 = \"#343331\" // ui-2 (dark)\n\tflexokiBase900 = \"#282726\" // ui (dark)\n\tflexokiBase950 = \"#1C1B1A\" // bg-2 (dark)\n\tflexokiBlack = \"#100F0F\" // bg (darkest)\n\n\t// Accent colors - Light theme (600)\n\tflexokiRed600 = \"#AF3029\"\n\tflexokiOrange600 = \"#BC5215\"\n\tflexokiYellow600 = \"#AD8301\"\n\tflexokiGreen600 = \"#66800B\"\n\tflexokiCyan600 = \"#24837B\"\n\tflexokiBlue600 = \"#205EA6\"\n\tflexokiPurple600 = \"#5E409D\"\n\tflexokiMagenta600 = \"#A02F6F\"\n\n\t// Accent colors - Dark theme (400)\n\tflexokiRed400 = \"#D14D41\"\n\tflexokiOrange400 = \"#DA702C\"\n\tflexokiYellow400 = \"#D0A215\"\n\tflexokiGreen400 = \"#879A39\"\n\tflexokiCyan400 = \"#3AA99F\"\n\tflexokiBlue400 = \"#4385BE\"\n\tflexokiPurple400 = \"#8B7EC8\"\n\tflexokiMagenta400 = \"#CE5D97\"\n)\n\n// FlexokiTheme implements the Theme interface with Flexoki colors.\n// It provides both dark and light variants.\ntype FlexokiTheme struct {\n\tBaseTheme\n}\n\n// NewFlexokiTheme creates a new instance of the Flexoki theme.\nfunc NewFlexokiTheme() *FlexokiTheme {\n\ttheme := &FlexokiTheme{}\n\n\t// Base colors\n\ttheme.PrimaryColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiBlue400,\n\t\tLight: flexokiBlue600,\n\t}\n\ttheme.SecondaryColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiPurple400,\n\t\tLight: flexokiPurple600,\n\t}\n\ttheme.AccentColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiOrange400,\n\t\tLight: flexokiOrange600,\n\t}\n\n\t// Status colors\n\ttheme.ErrorColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiRed400,\n\t\tLight: flexokiRed600,\n\t}\n\ttheme.WarningColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiYellow400,\n\t\tLight: flexokiYellow600,\n\t}\n\ttheme.SuccessColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiGreen400,\n\t\tLight: flexokiGreen600,\n\t}\n\ttheme.InfoColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiCyan400,\n\t\tLight: flexokiCyan600,\n\t}\n\n\t// Text colors\n\ttheme.TextColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiBase300,\n\t\tLight: flexokiBase600,\n\t}\n\ttheme.TextMutedColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiBase700,\n\t\tLight: flexokiBase500,\n\t}\n\ttheme.TextEmphasizedColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiYellow400,\n\t\tLight: flexokiYellow600,\n\t}\n\n\t// Background colors\n\ttheme.BackgroundColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiBlack,\n\t\tLight: flexokiPaper,\n\t}\n\ttheme.BackgroundSecondaryColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiBase950,\n\t\tLight: flexokiBase50,\n\t}\n\ttheme.BackgroundDarkerColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiBase900,\n\t\tLight: flexokiBase100,\n\t}\n\n\t// Border colors\n\ttheme.BorderNormalColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiBase900,\n\t\tLight: flexokiBase100,\n\t}\n\ttheme.BorderFocusedColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiBlue400,\n\t\tLight: flexokiBlue600,\n\t}\n\ttheme.BorderDimColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiBase850,\n\t\tLight: flexokiBase150,\n\t}\n\n\t// Diff view colors\n\ttheme.DiffAddedColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiGreen400,\n\t\tLight: flexokiGreen600,\n\t}\n\ttheme.DiffRemovedColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiRed400,\n\t\tLight: flexokiRed600,\n\t}\n\ttheme.DiffContextColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiBase700,\n\t\tLight: flexokiBase500,\n\t}\n\ttheme.DiffHunkHeaderColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiBase700,\n\t\tLight: flexokiBase500,\n\t}\n\ttheme.DiffHighlightAddedColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiGreen400,\n\t\tLight: flexokiGreen600,\n\t}\n\ttheme.DiffHighlightRemovedColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiRed400,\n\t\tLight: flexokiRed600,\n\t}\n\ttheme.DiffAddedBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#1D2419\", // Darker green background\n\t\tLight: \"#EFF2E2\", // Light green background\n\t}\n\ttheme.DiffRemovedBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#241919\", // Darker red background\n\t\tLight: \"#F2E2E2\", // Light red background\n\t}\n\ttheme.DiffContextBgColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiBlack,\n\t\tLight: flexokiPaper,\n\t}\n\ttheme.DiffLineNumberColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiBase700,\n\t\tLight: flexokiBase500,\n\t}\n\ttheme.DiffAddedLineNumberBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#1A2017\", // Slightly darker green\n\t\tLight: \"#E5EBD9\", // Light green\n\t}\n\ttheme.DiffRemovedLineNumberBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#201717\", // Slightly darker red\n\t\tLight: \"#EBD9D9\", // Light red\n\t}\n\n\t// Markdown colors\n\ttheme.MarkdownTextColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiBase300,\n\t\tLight: flexokiBase600,\n\t}\n\ttheme.MarkdownHeadingColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiYellow400,\n\t\tLight: flexokiYellow600,\n\t}\n\ttheme.MarkdownLinkColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiCyan400,\n\t\tLight: flexokiCyan600,\n\t}\n\ttheme.MarkdownLinkTextColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiMagenta400,\n\t\tLight: flexokiMagenta600,\n\t}\n\ttheme.MarkdownCodeColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiGreen400,\n\t\tLight: flexokiGreen600,\n\t}\n\ttheme.MarkdownBlockQuoteColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiCyan400,\n\t\tLight: flexokiCyan600,\n\t}\n\ttheme.MarkdownEmphColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiYellow400,\n\t\tLight: flexokiYellow600,\n\t}\n\ttheme.MarkdownStrongColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiOrange400,\n\t\tLight: flexokiOrange600,\n\t}\n\ttheme.MarkdownHorizontalRuleColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiBase800,\n\t\tLight: flexokiBase200,\n\t}\n\ttheme.MarkdownListItemColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiBlue400,\n\t\tLight: flexokiBlue600,\n\t}\n\ttheme.MarkdownListEnumerationColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiBlue400,\n\t\tLight: flexokiBlue600,\n\t}\n\ttheme.MarkdownImageColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiPurple400,\n\t\tLight: flexokiPurple600,\n\t}\n\ttheme.MarkdownImageTextColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiMagenta400,\n\t\tLight: flexokiMagenta600,\n\t}\n\ttheme.MarkdownCodeBlockColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiBase300,\n\t\tLight: flexokiBase600,\n\t}\n\n\t// Syntax highlighting colors (based on Flexoki's mappings)\n\ttheme.SyntaxCommentColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiBase700, // tx-3\n\t\tLight: flexokiBase300, // tx-3\n\t}\n\ttheme.SyntaxKeywordColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiGreen400, // gr\n\t\tLight: flexokiGreen600, // gr\n\t}\n\ttheme.SyntaxFunctionColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiOrange400, // or\n\t\tLight: flexokiOrange600, // or\n\t}\n\ttheme.SyntaxVariableColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiBlue400, // bl\n\t\tLight: flexokiBlue600, // bl\n\t}\n\ttheme.SyntaxStringColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiCyan400, // cy\n\t\tLight: flexokiCyan600, // cy\n\t}\n\ttheme.SyntaxNumberColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiPurple400, // pu\n\t\tLight: flexokiPurple600, // pu\n\t}\n\ttheme.SyntaxTypeColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiYellow400, // ye\n\t\tLight: flexokiYellow600, // ye\n\t}\n\ttheme.SyntaxOperatorColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiBase500, // tx-2\n\t\tLight: flexokiBase500, // tx-2\n\t}\n\ttheme.SyntaxPunctuationColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiBase500, // tx-2\n\t\tLight: flexokiBase500, // tx-2\n\t}\n\n\treturn theme\n}\n\nfunc init() {\n\t// Register the Flexoki theme with the theme manager\n\tRegisterTheme(\"flexoki\", NewFlexokiTheme())\n}"], ["/opencode/internal/llm/agent/agent-tool.go", "package agent\n\nimport (\n\t\"context\"\n\t\"encoding/json\"\n\t\"fmt\"\n\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/llm/tools\"\n\t\"github.com/opencode-ai/opencode/internal/lsp\"\n\t\"github.com/opencode-ai/opencode/internal/message\"\n\t\"github.com/opencode-ai/opencode/internal/session\"\n)\n\ntype agentTool struct {\n\tsessions session.Service\n\tmessages message.Service\n\tlspClients map[string]*lsp.Client\n}\n\nconst (\n\tAgentToolName = \"agent\"\n)\n\ntype AgentParams struct {\n\tPrompt string `json:\"prompt\"`\n}\n\nfunc (b *agentTool) Info() tools.ToolInfo {\n\treturn tools.ToolInfo{\n\t\tName: AgentToolName,\n\t\tDescription: \"Launch a new agent that has access to the following tools: GlobTool, GrepTool, LS, View. When you are searching for a keyword or file and are not confident that you will find the right match on the first try, use the Agent tool to perform the search for you. For example:\\n\\n- If you are searching for a keyword like \\\"config\\\" or \\\"logger\\\", or for questions like \\\"which file does X?\\\", the Agent tool is strongly recommended\\n- If you want to read a specific file path, use the View or GlobTool tool instead of the Agent tool, to find the match more quickly\\n- If you are searching for a specific class definition like \\\"class Foo\\\", use the GlobTool tool instead, to find the match more quickly\\n\\nUsage notes:\\n1. Launch multiple agents concurrently whenever possible, to maximize performance; to do that, use a single message with multiple tool uses\\n2. When the agent is done, it will return a single message back to you. The result returned by the agent is not visible to the user. To show the user the result, you should send a text message back to the user with a concise summary of the result.\\n3. Each agent invocation is stateless. You will not be able to send additional messages to the agent, nor will the agent be able to communicate with you outside of its final report. Therefore, your prompt should contain a highly detailed task description for the agent to perform autonomously and you should specify exactly what information the agent should return back to you in its final and only message to you.\\n4. The agent's outputs should generally be trusted\\n5. IMPORTANT: The agent can not use Bash, Replace, Edit, so can not modify files. If you want to use these tools, use them directly instead of going through the agent.\",\n\t\tParameters: map[string]any{\n\t\t\t\"prompt\": map[string]any{\n\t\t\t\t\"type\": \"string\",\n\t\t\t\t\"description\": \"The task for the agent to perform\",\n\t\t\t},\n\t\t},\n\t\tRequired: []string{\"prompt\"},\n\t}\n}\n\nfunc (b *agentTool) Run(ctx context.Context, call tools.ToolCall) (tools.ToolResponse, error) {\n\tvar params AgentParams\n\tif err := json.Unmarshal([]byte(call.Input), ¶ms); err != nil {\n\t\treturn tools.NewTextErrorResponse(fmt.Sprintf(\"error parsing parameters: %s\", err)), nil\n\t}\n\tif params.Prompt == \"\" {\n\t\treturn tools.NewTextErrorResponse(\"prompt is required\"), nil\n\t}\n\n\tsessionID, messageID := tools.GetContextValues(ctx)\n\tif sessionID == \"\" || messageID == \"\" {\n\t\treturn tools.ToolResponse{}, fmt.Errorf(\"session_id and message_id are required\")\n\t}\n\n\tagent, err := NewAgent(config.AgentTask, b.sessions, b.messages, TaskAgentTools(b.lspClients))\n\tif err != nil {\n\t\treturn tools.ToolResponse{}, fmt.Errorf(\"error creating agent: %s\", err)\n\t}\n\n\tsession, err := b.sessions.CreateTaskSession(ctx, call.ID, sessionID, \"New Agent Session\")\n\tif err != nil {\n\t\treturn tools.ToolResponse{}, fmt.Errorf(\"error creating session: %s\", err)\n\t}\n\n\tdone, err := agent.Run(ctx, session.ID, params.Prompt)\n\tif err != nil {\n\t\treturn tools.ToolResponse{}, fmt.Errorf(\"error generating agent: %s\", err)\n\t}\n\tresult := <-done\n\tif result.Error != nil {\n\t\treturn tools.ToolResponse{}, fmt.Errorf(\"error generating agent: %s\", result.Error)\n\t}\n\n\tresponse := result.Message\n\tif response.Role != message.Assistant {\n\t\treturn tools.NewTextErrorResponse(\"no response\"), nil\n\t}\n\n\tupdatedSession, err := b.sessions.Get(ctx, session.ID)\n\tif err != nil {\n\t\treturn tools.ToolResponse{}, fmt.Errorf(\"error getting session: %s\", err)\n\t}\n\tparentSession, err := b.sessions.Get(ctx, sessionID)\n\tif err != nil {\n\t\treturn tools.ToolResponse{}, fmt.Errorf(\"error getting parent session: %s\", err)\n\t}\n\n\tparentSession.Cost += updatedSession.Cost\n\n\t_, err = b.sessions.Save(ctx, parentSession)\n\tif err != nil {\n\t\treturn tools.ToolResponse{}, fmt.Errorf(\"error saving parent session: %s\", err)\n\t}\n\treturn tools.NewTextResponse(response.Content().String()), nil\n}\n\nfunc NewAgentTool(\n\tSessions session.Service,\n\tMessages message.Service,\n\tLspClients map[string]*lsp.Client,\n) tools.BaseTool {\n\treturn &agentTool{\n\t\tsessions: Sessions,\n\t\tmessages: Messages,\n\t\tlspClients: LspClients,\n\t}\n}\n"], ["/opencode/internal/lsp/protocol/interface.go", "package protocol\n\nimport \"fmt\"\n\n// TextEditResult is an interface for types that represent workspace symbols\ntype WorkspaceSymbolResult interface {\n\tGetName() string\n\tGetLocation() Location\n\tisWorkspaceSymbol() // marker method\n}\n\nfunc (ws *WorkspaceSymbol) GetName() string { return ws.Name }\nfunc (ws *WorkspaceSymbol) GetLocation() Location {\n\tswitch v := ws.Location.Value.(type) {\n\tcase Location:\n\t\treturn v\n\tcase LocationUriOnly:\n\t\treturn Location{URI: v.URI}\n\t}\n\treturn Location{}\n}\nfunc (ws *WorkspaceSymbol) isWorkspaceSymbol() {}\n\nfunc (si *SymbolInformation) GetName() string { return si.Name }\nfunc (si *SymbolInformation) GetLocation() Location { return si.Location }\nfunc (si *SymbolInformation) isWorkspaceSymbol() {}\n\n// Results converts the Value to a slice of WorkspaceSymbolResult\nfunc (r Or_Result_workspace_symbol) Results() ([]WorkspaceSymbolResult, error) {\n\tif r.Value == nil {\n\t\treturn make([]WorkspaceSymbolResult, 0), nil\n\t}\n\tswitch v := r.Value.(type) {\n\tcase []WorkspaceSymbol:\n\t\tresults := make([]WorkspaceSymbolResult, len(v))\n\t\tfor i := range v {\n\t\t\tresults[i] = &v[i]\n\t\t}\n\t\treturn results, nil\n\tcase []SymbolInformation:\n\t\tresults := make([]WorkspaceSymbolResult, len(v))\n\t\tfor i := range v {\n\t\t\tresults[i] = &v[i]\n\t\t}\n\t\treturn results, nil\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"unknown symbol type: %T\", r.Value)\n\t}\n}\n\n// TextEditResult is an interface for types that represent document symbols\ntype DocumentSymbolResult interface {\n\tGetRange() Range\n\tGetName() string\n\tisDocumentSymbol() // marker method\n}\n\nfunc (ds *DocumentSymbol) GetRange() Range { return ds.Range }\nfunc (ds *DocumentSymbol) GetName() string { return ds.Name }\nfunc (ds *DocumentSymbol) isDocumentSymbol() {}\n\nfunc (si *SymbolInformation) GetRange() Range { return si.Location.Range }\n\n// Note: SymbolInformation already has GetName() implemented above\nfunc (si *SymbolInformation) isDocumentSymbol() {}\n\n// Results converts the Value to a slice of DocumentSymbolResult\nfunc (r Or_Result_textDocument_documentSymbol) Results() ([]DocumentSymbolResult, error) {\n\tif r.Value == nil {\n\t\treturn make([]DocumentSymbolResult, 0), nil\n\t}\n\tswitch v := r.Value.(type) {\n\tcase []DocumentSymbol:\n\t\tresults := make([]DocumentSymbolResult, len(v))\n\t\tfor i := range v {\n\t\t\tresults[i] = &v[i]\n\t\t}\n\t\treturn results, nil\n\tcase []SymbolInformation:\n\t\tresults := make([]DocumentSymbolResult, len(v))\n\t\tfor i := range v {\n\t\t\tresults[i] = &v[i]\n\t\t}\n\t\treturn results, nil\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"unknown document symbol type: %T\", v)\n\t}\n}\n\n// TextEditResult is an interface for types that can be used as text edits\ntype TextEditResult interface {\n\tGetRange() Range\n\tGetNewText() string\n\tisTextEdit() // marker method\n}\n\nfunc (te *TextEdit) GetRange() Range { return te.Range }\nfunc (te *TextEdit) GetNewText() string { return te.NewText }\nfunc (te *TextEdit) isTextEdit() {}\n\n// Convert Or_TextDocumentEdit_edits_Elem to TextEdit\nfunc (e Or_TextDocumentEdit_edits_Elem) AsTextEdit() (TextEdit, error) {\n\tif e.Value == nil {\n\t\treturn TextEdit{}, fmt.Errorf(\"nil text edit\")\n\t}\n\tswitch v := e.Value.(type) {\n\tcase TextEdit:\n\t\treturn v, nil\n\tcase AnnotatedTextEdit:\n\t\treturn TextEdit{\n\t\t\tRange: v.Range,\n\t\t\tNewText: v.NewText,\n\t\t}, nil\n\tdefault:\n\t\treturn TextEdit{}, fmt.Errorf(\"unknown text edit type: %T\", e.Value)\n\t}\n}\n"], ["/opencode/internal/tui/theme/gruvbox.go", "package theme\n\nimport (\n\t\"github.com/charmbracelet/lipgloss\"\n)\n\n// Gruvbox color palette constants\nconst (\n\t// Dark theme colors\n\tgruvboxDarkBg0 = \"#282828\"\n\tgruvboxDarkBg0Soft = \"#32302f\"\n\tgruvboxDarkBg1 = \"#3c3836\"\n\tgruvboxDarkBg2 = \"#504945\"\n\tgruvboxDarkBg3 = \"#665c54\"\n\tgruvboxDarkBg4 = \"#7c6f64\"\n\tgruvboxDarkFg0 = \"#fbf1c7\"\n\tgruvboxDarkFg1 = \"#ebdbb2\"\n\tgruvboxDarkFg2 = \"#d5c4a1\"\n\tgruvboxDarkFg3 = \"#bdae93\"\n\tgruvboxDarkFg4 = \"#a89984\"\n\tgruvboxDarkGray = \"#928374\"\n\tgruvboxDarkRed = \"#cc241d\"\n\tgruvboxDarkRedBright = \"#fb4934\"\n\tgruvboxDarkGreen = \"#98971a\"\n\tgruvboxDarkGreenBright = \"#b8bb26\"\n\tgruvboxDarkYellow = \"#d79921\"\n\tgruvboxDarkYellowBright = \"#fabd2f\"\n\tgruvboxDarkBlue = \"#458588\"\n\tgruvboxDarkBlueBright = \"#83a598\"\n\tgruvboxDarkPurple = \"#b16286\"\n\tgruvboxDarkPurpleBright = \"#d3869b\"\n\tgruvboxDarkAqua = \"#689d6a\"\n\tgruvboxDarkAquaBright = \"#8ec07c\"\n\tgruvboxDarkOrange = \"#d65d0e\"\n\tgruvboxDarkOrangeBright = \"#fe8019\"\n\n\t// Light theme colors\n\tgruvboxLightBg0 = \"#fbf1c7\"\n\tgruvboxLightBg0Soft = \"#f2e5bc\"\n\tgruvboxLightBg1 = \"#ebdbb2\"\n\tgruvboxLightBg2 = \"#d5c4a1\"\n\tgruvboxLightBg3 = \"#bdae93\"\n\tgruvboxLightBg4 = \"#a89984\"\n\tgruvboxLightFg0 = \"#282828\"\n\tgruvboxLightFg1 = \"#3c3836\"\n\tgruvboxLightFg2 = \"#504945\"\n\tgruvboxLightFg3 = \"#665c54\"\n\tgruvboxLightFg4 = \"#7c6f64\"\n\tgruvboxLightGray = \"#928374\"\n\tgruvboxLightRed = \"#9d0006\"\n\tgruvboxLightRedBright = \"#cc241d\"\n\tgruvboxLightGreen = \"#79740e\"\n\tgruvboxLightGreenBright = \"#98971a\"\n\tgruvboxLightYellow = \"#b57614\"\n\tgruvboxLightYellowBright = \"#d79921\"\n\tgruvboxLightBlue = \"#076678\"\n\tgruvboxLightBlueBright = \"#458588\"\n\tgruvboxLightPurple = \"#8f3f71\"\n\tgruvboxLightPurpleBright = \"#b16286\"\n\tgruvboxLightAqua = \"#427b58\"\n\tgruvboxLightAquaBright = \"#689d6a\"\n\tgruvboxLightOrange = \"#af3a03\"\n\tgruvboxLightOrangeBright = \"#d65d0e\"\n)\n\n// GruvboxTheme implements the Theme interface with Gruvbox colors.\n// It provides both dark and light variants.\ntype GruvboxTheme struct {\n\tBaseTheme\n}\n\n// NewGruvboxTheme creates a new instance of the Gruvbox theme.\nfunc NewGruvboxTheme() *GruvboxTheme {\n\ttheme := &GruvboxTheme{}\n\n\t// Base colors\n\ttheme.PrimaryColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkBlueBright,\n\t\tLight: gruvboxLightBlueBright,\n\t}\n\ttheme.SecondaryColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkPurpleBright,\n\t\tLight: gruvboxLightPurpleBright,\n\t}\n\ttheme.AccentColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkOrangeBright,\n\t\tLight: gruvboxLightOrangeBright,\n\t}\n\n\t// Status colors\n\ttheme.ErrorColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkRedBright,\n\t\tLight: gruvboxLightRedBright,\n\t}\n\ttheme.WarningColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkYellowBright,\n\t\tLight: gruvboxLightYellowBright,\n\t}\n\ttheme.SuccessColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkGreenBright,\n\t\tLight: gruvboxLightGreenBright,\n\t}\n\ttheme.InfoColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkBlueBright,\n\t\tLight: gruvboxLightBlueBright,\n\t}\n\n\t// Text colors\n\ttheme.TextColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkFg1,\n\t\tLight: gruvboxLightFg1,\n\t}\n\ttheme.TextMutedColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkFg4,\n\t\tLight: gruvboxLightFg4,\n\t}\n\ttheme.TextEmphasizedColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkYellowBright,\n\t\tLight: gruvboxLightYellowBright,\n\t}\n\n\t// Background colors\n\ttheme.BackgroundColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkBg0,\n\t\tLight: gruvboxLightBg0,\n\t}\n\ttheme.BackgroundSecondaryColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkBg1,\n\t\tLight: gruvboxLightBg1,\n\t}\n\ttheme.BackgroundDarkerColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkBg0Soft,\n\t\tLight: gruvboxLightBg0Soft,\n\t}\n\n\t// Border colors\n\ttheme.BorderNormalColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkBg2,\n\t\tLight: gruvboxLightBg2,\n\t}\n\ttheme.BorderFocusedColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkBlueBright,\n\t\tLight: gruvboxLightBlueBright,\n\t}\n\ttheme.BorderDimColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkBg1,\n\t\tLight: gruvboxLightBg1,\n\t}\n\n\t// Diff view colors\n\ttheme.DiffAddedColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkGreenBright,\n\t\tLight: gruvboxLightGreenBright,\n\t}\n\ttheme.DiffRemovedColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkRedBright,\n\t\tLight: gruvboxLightRedBright,\n\t}\n\ttheme.DiffContextColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkFg4,\n\t\tLight: gruvboxLightFg4,\n\t}\n\ttheme.DiffHunkHeaderColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkFg3,\n\t\tLight: gruvboxLightFg3,\n\t}\n\ttheme.DiffHighlightAddedColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkGreenBright,\n\t\tLight: gruvboxLightGreenBright,\n\t}\n\ttheme.DiffHighlightRemovedColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkRedBright,\n\t\tLight: gruvboxLightRedBright,\n\t}\n\ttheme.DiffAddedBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#3C4C3C\", // Darker green background\n\t\tLight: \"#E8F5E9\", // Light green background\n\t}\n\ttheme.DiffRemovedBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#4C3C3C\", // Darker red background\n\t\tLight: \"#FFEBEE\", // Light red background\n\t}\n\ttheme.DiffContextBgColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkBg0,\n\t\tLight: gruvboxLightBg0,\n\t}\n\ttheme.DiffLineNumberColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkFg4,\n\t\tLight: gruvboxLightFg4,\n\t}\n\ttheme.DiffAddedLineNumberBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#32432F\", // Slightly darker green\n\t\tLight: \"#C8E6C9\", // Light green\n\t}\n\ttheme.DiffRemovedLineNumberBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#43322F\", // Slightly darker red\n\t\tLight: \"#FFCDD2\", // Light red\n\t}\n\n\t// Markdown colors\n\ttheme.MarkdownTextColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkFg1,\n\t\tLight: gruvboxLightFg1,\n\t}\n\ttheme.MarkdownHeadingColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkYellowBright,\n\t\tLight: gruvboxLightYellowBright,\n\t}\n\ttheme.MarkdownLinkColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkBlueBright,\n\t\tLight: gruvboxLightBlueBright,\n\t}\n\ttheme.MarkdownLinkTextColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkAquaBright,\n\t\tLight: gruvboxLightAquaBright,\n\t}\n\ttheme.MarkdownCodeColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkGreenBright,\n\t\tLight: gruvboxLightGreenBright,\n\t}\n\ttheme.MarkdownBlockQuoteColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkAquaBright,\n\t\tLight: gruvboxLightAquaBright,\n\t}\n\ttheme.MarkdownEmphColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkYellowBright,\n\t\tLight: gruvboxLightYellowBright,\n\t}\n\ttheme.MarkdownStrongColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkOrangeBright,\n\t\tLight: gruvboxLightOrangeBright,\n\t}\n\ttheme.MarkdownHorizontalRuleColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkBg3,\n\t\tLight: gruvboxLightBg3,\n\t}\n\ttheme.MarkdownListItemColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkBlueBright,\n\t\tLight: gruvboxLightBlueBright,\n\t}\n\ttheme.MarkdownListEnumerationColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkBlueBright,\n\t\tLight: gruvboxLightBlueBright,\n\t}\n\ttheme.MarkdownImageColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkPurpleBright,\n\t\tLight: gruvboxLightPurpleBright,\n\t}\n\ttheme.MarkdownImageTextColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkAquaBright,\n\t\tLight: gruvboxLightAquaBright,\n\t}\n\ttheme.MarkdownCodeBlockColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkFg1,\n\t\tLight: gruvboxLightFg1,\n\t}\n\n\t// Syntax highlighting colors\n\ttheme.SyntaxCommentColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkGray,\n\t\tLight: gruvboxLightGray,\n\t}\n\ttheme.SyntaxKeywordColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkRedBright,\n\t\tLight: gruvboxLightRedBright,\n\t}\n\ttheme.SyntaxFunctionColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkGreenBright,\n\t\tLight: gruvboxLightGreenBright,\n\t}\n\ttheme.SyntaxVariableColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkBlueBright,\n\t\tLight: gruvboxLightBlueBright,\n\t}\n\ttheme.SyntaxStringColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkYellowBright,\n\t\tLight: gruvboxLightYellowBright,\n\t}\n\ttheme.SyntaxNumberColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkPurpleBright,\n\t\tLight: gruvboxLightPurpleBright,\n\t}\n\ttheme.SyntaxTypeColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkYellow,\n\t\tLight: gruvboxLightYellow,\n\t}\n\ttheme.SyntaxOperatorColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkAquaBright,\n\t\tLight: gruvboxLightAquaBright,\n\t}\n\ttheme.SyntaxPunctuationColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkFg1,\n\t\tLight: gruvboxLightFg1,\n\t}\n\n\treturn theme\n}\n\nfunc init() {\n\t// Register the Gruvbox theme with the theme manager\n\tRegisterTheme(\"gruvbox\", NewGruvboxTheme())\n}"], ["/opencode/internal/pubsub/broker.go", "package pubsub\n\nimport (\n\t\"context\"\n\t\"sync\"\n)\n\nconst bufferSize = 64\n\ntype Broker[T any] struct {\n\tsubs map[chan Event[T]]struct{}\n\tmu sync.RWMutex\n\tdone chan struct{}\n\tsubCount int\n\tmaxEvents int\n}\n\nfunc NewBroker[T any]() *Broker[T] {\n\treturn NewBrokerWithOptions[T](bufferSize, 1000)\n}\n\nfunc NewBrokerWithOptions[T any](channelBufferSize, maxEvents int) *Broker[T] {\n\tb := &Broker[T]{\n\t\tsubs: make(map[chan Event[T]]struct{}),\n\t\tdone: make(chan struct{}),\n\t\tsubCount: 0,\n\t\tmaxEvents: maxEvents,\n\t}\n\treturn b\n}\n\nfunc (b *Broker[T]) Shutdown() {\n\tselect {\n\tcase <-b.done: // Already closed\n\t\treturn\n\tdefault:\n\t\tclose(b.done)\n\t}\n\n\tb.mu.Lock()\n\tdefer b.mu.Unlock()\n\n\tfor ch := range b.subs {\n\t\tdelete(b.subs, ch)\n\t\tclose(ch)\n\t}\n\n\tb.subCount = 0\n}\n\nfunc (b *Broker[T]) Subscribe(ctx context.Context) <-chan Event[T] {\n\tb.mu.Lock()\n\tdefer b.mu.Unlock()\n\n\tselect {\n\tcase <-b.done:\n\t\tch := make(chan Event[T])\n\t\tclose(ch)\n\t\treturn ch\n\tdefault:\n\t}\n\n\tsub := make(chan Event[T], bufferSize)\n\tb.subs[sub] = struct{}{}\n\tb.subCount++\n\n\tgo func() {\n\t\t<-ctx.Done()\n\n\t\tb.mu.Lock()\n\t\tdefer b.mu.Unlock()\n\n\t\tselect {\n\t\tcase <-b.done:\n\t\t\treturn\n\t\tdefault:\n\t\t}\n\n\t\tdelete(b.subs, sub)\n\t\tclose(sub)\n\t\tb.subCount--\n\t}()\n\n\treturn sub\n}\n\nfunc (b *Broker[T]) GetSubscriberCount() int {\n\tb.mu.RLock()\n\tdefer b.mu.RUnlock()\n\treturn b.subCount\n}\n\nfunc (b *Broker[T]) Publish(t EventType, payload T) {\n\tb.mu.RLock()\n\tselect {\n\tcase <-b.done:\n\t\tb.mu.RUnlock()\n\t\treturn\n\tdefault:\n\t}\n\n\tsubscribers := make([]chan Event[T], 0, len(b.subs))\n\tfor sub := range b.subs {\n\t\tsubscribers = append(subscribers, sub)\n\t}\n\tb.mu.RUnlock()\n\n\tevent := Event[T]{Type: t, Payload: payload}\n\n\tfor _, sub := range subscribers {\n\t\tselect {\n\t\tcase sub <- event:\n\t\tdefault:\n\t\t}\n\t}\n}\n"], ["/opencode/internal/tui/theme/theme.go", "package theme\n\nimport (\n\t\"github.com/charmbracelet/lipgloss\"\n)\n\n// Theme defines the interface for all UI themes in the application.\n// All colors must be defined as lipgloss.AdaptiveColor to support\n// both light and dark terminal backgrounds.\ntype Theme interface {\n\t// Base colors\n\tPrimary() lipgloss.AdaptiveColor\n\tSecondary() lipgloss.AdaptiveColor\n\tAccent() lipgloss.AdaptiveColor\n\n\t// Status colors\n\tError() lipgloss.AdaptiveColor\n\tWarning() lipgloss.AdaptiveColor\n\tSuccess() lipgloss.AdaptiveColor\n\tInfo() lipgloss.AdaptiveColor\n\n\t// Text colors\n\tText() lipgloss.AdaptiveColor\n\tTextMuted() lipgloss.AdaptiveColor\n\tTextEmphasized() lipgloss.AdaptiveColor\n\n\t// Background colors\n\tBackground() lipgloss.AdaptiveColor\n\tBackgroundSecondary() lipgloss.AdaptiveColor\n\tBackgroundDarker() lipgloss.AdaptiveColor\n\n\t// Border colors\n\tBorderNormal() lipgloss.AdaptiveColor\n\tBorderFocused() lipgloss.AdaptiveColor\n\tBorderDim() lipgloss.AdaptiveColor\n\n\t// Diff view colors\n\tDiffAdded() lipgloss.AdaptiveColor\n\tDiffRemoved() lipgloss.AdaptiveColor\n\tDiffContext() lipgloss.AdaptiveColor\n\tDiffHunkHeader() lipgloss.AdaptiveColor\n\tDiffHighlightAdded() lipgloss.AdaptiveColor\n\tDiffHighlightRemoved() lipgloss.AdaptiveColor\n\tDiffAddedBg() lipgloss.AdaptiveColor\n\tDiffRemovedBg() lipgloss.AdaptiveColor\n\tDiffContextBg() lipgloss.AdaptiveColor\n\tDiffLineNumber() lipgloss.AdaptiveColor\n\tDiffAddedLineNumberBg() lipgloss.AdaptiveColor\n\tDiffRemovedLineNumberBg() lipgloss.AdaptiveColor\n\n\t// Markdown colors\n\tMarkdownText() lipgloss.AdaptiveColor\n\tMarkdownHeading() lipgloss.AdaptiveColor\n\tMarkdownLink() lipgloss.AdaptiveColor\n\tMarkdownLinkText() lipgloss.AdaptiveColor\n\tMarkdownCode() lipgloss.AdaptiveColor\n\tMarkdownBlockQuote() lipgloss.AdaptiveColor\n\tMarkdownEmph() lipgloss.AdaptiveColor\n\tMarkdownStrong() lipgloss.AdaptiveColor\n\tMarkdownHorizontalRule() lipgloss.AdaptiveColor\n\tMarkdownListItem() lipgloss.AdaptiveColor\n\tMarkdownListEnumeration() lipgloss.AdaptiveColor\n\tMarkdownImage() lipgloss.AdaptiveColor\n\tMarkdownImageText() lipgloss.AdaptiveColor\n\tMarkdownCodeBlock() lipgloss.AdaptiveColor\n\n\t// Syntax highlighting colors\n\tSyntaxComment() lipgloss.AdaptiveColor\n\tSyntaxKeyword() lipgloss.AdaptiveColor\n\tSyntaxFunction() lipgloss.AdaptiveColor\n\tSyntaxVariable() lipgloss.AdaptiveColor\n\tSyntaxString() lipgloss.AdaptiveColor\n\tSyntaxNumber() lipgloss.AdaptiveColor\n\tSyntaxType() lipgloss.AdaptiveColor\n\tSyntaxOperator() lipgloss.AdaptiveColor\n\tSyntaxPunctuation() lipgloss.AdaptiveColor\n}\n\n// BaseTheme provides a default implementation of the Theme interface\n// that can be embedded in concrete theme implementations.\ntype BaseTheme struct {\n\t// Base colors\n\tPrimaryColor lipgloss.AdaptiveColor\n\tSecondaryColor lipgloss.AdaptiveColor\n\tAccentColor lipgloss.AdaptiveColor\n\n\t// Status colors\n\tErrorColor lipgloss.AdaptiveColor\n\tWarningColor lipgloss.AdaptiveColor\n\tSuccessColor lipgloss.AdaptiveColor\n\tInfoColor lipgloss.AdaptiveColor\n\n\t// Text colors\n\tTextColor lipgloss.AdaptiveColor\n\tTextMutedColor lipgloss.AdaptiveColor\n\tTextEmphasizedColor lipgloss.AdaptiveColor\n\n\t// Background colors\n\tBackgroundColor lipgloss.AdaptiveColor\n\tBackgroundSecondaryColor lipgloss.AdaptiveColor\n\tBackgroundDarkerColor lipgloss.AdaptiveColor\n\n\t// Border colors\n\tBorderNormalColor lipgloss.AdaptiveColor\n\tBorderFocusedColor lipgloss.AdaptiveColor\n\tBorderDimColor lipgloss.AdaptiveColor\n\n\t// Diff view colors\n\tDiffAddedColor lipgloss.AdaptiveColor\n\tDiffRemovedColor lipgloss.AdaptiveColor\n\tDiffContextColor lipgloss.AdaptiveColor\n\tDiffHunkHeaderColor lipgloss.AdaptiveColor\n\tDiffHighlightAddedColor lipgloss.AdaptiveColor\n\tDiffHighlightRemovedColor lipgloss.AdaptiveColor\n\tDiffAddedBgColor lipgloss.AdaptiveColor\n\tDiffRemovedBgColor lipgloss.AdaptiveColor\n\tDiffContextBgColor lipgloss.AdaptiveColor\n\tDiffLineNumberColor lipgloss.AdaptiveColor\n\tDiffAddedLineNumberBgColor lipgloss.AdaptiveColor\n\tDiffRemovedLineNumberBgColor lipgloss.AdaptiveColor\n\n\t// Markdown colors\n\tMarkdownTextColor lipgloss.AdaptiveColor\n\tMarkdownHeadingColor lipgloss.AdaptiveColor\n\tMarkdownLinkColor lipgloss.AdaptiveColor\n\tMarkdownLinkTextColor lipgloss.AdaptiveColor\n\tMarkdownCodeColor lipgloss.AdaptiveColor\n\tMarkdownBlockQuoteColor lipgloss.AdaptiveColor\n\tMarkdownEmphColor lipgloss.AdaptiveColor\n\tMarkdownStrongColor lipgloss.AdaptiveColor\n\tMarkdownHorizontalRuleColor lipgloss.AdaptiveColor\n\tMarkdownListItemColor lipgloss.AdaptiveColor\n\tMarkdownListEnumerationColor lipgloss.AdaptiveColor\n\tMarkdownImageColor lipgloss.AdaptiveColor\n\tMarkdownImageTextColor lipgloss.AdaptiveColor\n\tMarkdownCodeBlockColor lipgloss.AdaptiveColor\n\n\t// Syntax highlighting colors\n\tSyntaxCommentColor lipgloss.AdaptiveColor\n\tSyntaxKeywordColor lipgloss.AdaptiveColor\n\tSyntaxFunctionColor lipgloss.AdaptiveColor\n\tSyntaxVariableColor lipgloss.AdaptiveColor\n\tSyntaxStringColor lipgloss.AdaptiveColor\n\tSyntaxNumberColor lipgloss.AdaptiveColor\n\tSyntaxTypeColor lipgloss.AdaptiveColor\n\tSyntaxOperatorColor lipgloss.AdaptiveColor\n\tSyntaxPunctuationColor lipgloss.AdaptiveColor\n}\n\n// Implement the Theme interface for BaseTheme\nfunc (t *BaseTheme) Primary() lipgloss.AdaptiveColor { return t.PrimaryColor }\nfunc (t *BaseTheme) Secondary() lipgloss.AdaptiveColor { return t.SecondaryColor }\nfunc (t *BaseTheme) Accent() lipgloss.AdaptiveColor { return t.AccentColor }\n\nfunc (t *BaseTheme) Error() lipgloss.AdaptiveColor { return t.ErrorColor }\nfunc (t *BaseTheme) Warning() lipgloss.AdaptiveColor { return t.WarningColor }\nfunc (t *BaseTheme) Success() lipgloss.AdaptiveColor { return t.SuccessColor }\nfunc (t *BaseTheme) Info() lipgloss.AdaptiveColor { return t.InfoColor }\n\nfunc (t *BaseTheme) Text() lipgloss.AdaptiveColor { return t.TextColor }\nfunc (t *BaseTheme) TextMuted() lipgloss.AdaptiveColor { return t.TextMutedColor }\nfunc (t *BaseTheme) TextEmphasized() lipgloss.AdaptiveColor { return t.TextEmphasizedColor }\n\nfunc (t *BaseTheme) Background() lipgloss.AdaptiveColor { return t.BackgroundColor }\nfunc (t *BaseTheme) BackgroundSecondary() lipgloss.AdaptiveColor { return t.BackgroundSecondaryColor }\nfunc (t *BaseTheme) BackgroundDarker() lipgloss.AdaptiveColor { return t.BackgroundDarkerColor }\n\nfunc (t *BaseTheme) BorderNormal() lipgloss.AdaptiveColor { return t.BorderNormalColor }\nfunc (t *BaseTheme) BorderFocused() lipgloss.AdaptiveColor { return t.BorderFocusedColor }\nfunc (t *BaseTheme) BorderDim() lipgloss.AdaptiveColor { return t.BorderDimColor }\n\nfunc (t *BaseTheme) DiffAdded() lipgloss.AdaptiveColor { return t.DiffAddedColor }\nfunc (t *BaseTheme) DiffRemoved() lipgloss.AdaptiveColor { return t.DiffRemovedColor }\nfunc (t *BaseTheme) DiffContext() lipgloss.AdaptiveColor { return t.DiffContextColor }\nfunc (t *BaseTheme) DiffHunkHeader() lipgloss.AdaptiveColor { return t.DiffHunkHeaderColor }\nfunc (t *BaseTheme) DiffHighlightAdded() lipgloss.AdaptiveColor { return t.DiffHighlightAddedColor }\nfunc (t *BaseTheme) DiffHighlightRemoved() lipgloss.AdaptiveColor { return t.DiffHighlightRemovedColor }\nfunc (t *BaseTheme) DiffAddedBg() lipgloss.AdaptiveColor { return t.DiffAddedBgColor }\nfunc (t *BaseTheme) DiffRemovedBg() lipgloss.AdaptiveColor { return t.DiffRemovedBgColor }\nfunc (t *BaseTheme) DiffContextBg() lipgloss.AdaptiveColor { return t.DiffContextBgColor }\nfunc (t *BaseTheme) DiffLineNumber() lipgloss.AdaptiveColor { return t.DiffLineNumberColor }\nfunc (t *BaseTheme) DiffAddedLineNumberBg() lipgloss.AdaptiveColor { return t.DiffAddedLineNumberBgColor }\nfunc (t *BaseTheme) DiffRemovedLineNumberBg() lipgloss.AdaptiveColor { return t.DiffRemovedLineNumberBgColor }\n\nfunc (t *BaseTheme) MarkdownText() lipgloss.AdaptiveColor { return t.MarkdownTextColor }\nfunc (t *BaseTheme) MarkdownHeading() lipgloss.AdaptiveColor { return t.MarkdownHeadingColor }\nfunc (t *BaseTheme) MarkdownLink() lipgloss.AdaptiveColor { return t.MarkdownLinkColor }\nfunc (t *BaseTheme) MarkdownLinkText() lipgloss.AdaptiveColor { return t.MarkdownLinkTextColor }\nfunc (t *BaseTheme) MarkdownCode() lipgloss.AdaptiveColor { return t.MarkdownCodeColor }\nfunc (t *BaseTheme) MarkdownBlockQuote() lipgloss.AdaptiveColor { return t.MarkdownBlockQuoteColor }\nfunc (t *BaseTheme) MarkdownEmph() lipgloss.AdaptiveColor { return t.MarkdownEmphColor }\nfunc (t *BaseTheme) MarkdownStrong() lipgloss.AdaptiveColor { return t.MarkdownStrongColor }\nfunc (t *BaseTheme) MarkdownHorizontalRule() lipgloss.AdaptiveColor { return t.MarkdownHorizontalRuleColor }\nfunc (t *BaseTheme) MarkdownListItem() lipgloss.AdaptiveColor { return t.MarkdownListItemColor }\nfunc (t *BaseTheme) MarkdownListEnumeration() lipgloss.AdaptiveColor { return t.MarkdownListEnumerationColor }\nfunc (t *BaseTheme) MarkdownImage() lipgloss.AdaptiveColor { return t.MarkdownImageColor }\nfunc (t *BaseTheme) MarkdownImageText() lipgloss.AdaptiveColor { return t.MarkdownImageTextColor }\nfunc (t *BaseTheme) MarkdownCodeBlock() lipgloss.AdaptiveColor { return t.MarkdownCodeBlockColor }\n\nfunc (t *BaseTheme) SyntaxComment() lipgloss.AdaptiveColor { return t.SyntaxCommentColor }\nfunc (t *BaseTheme) SyntaxKeyword() lipgloss.AdaptiveColor { return t.SyntaxKeywordColor }\nfunc (t *BaseTheme) SyntaxFunction() lipgloss.AdaptiveColor { return t.SyntaxFunctionColor }\nfunc (t *BaseTheme) SyntaxVariable() lipgloss.AdaptiveColor { return t.SyntaxVariableColor }\nfunc (t *BaseTheme) SyntaxString() lipgloss.AdaptiveColor { return t.SyntaxStringColor }\nfunc (t *BaseTheme) SyntaxNumber() lipgloss.AdaptiveColor { return t.SyntaxNumberColor }\nfunc (t *BaseTheme) SyntaxType() lipgloss.AdaptiveColor { return t.SyntaxTypeColor }\nfunc (t *BaseTheme) SyntaxOperator() lipgloss.AdaptiveColor { return t.SyntaxOperatorColor }\nfunc (t *BaseTheme) SyntaxPunctuation() lipgloss.AdaptiveColor { return t.SyntaxPunctuationColor }"], ["/opencode/internal/logging/logger.go", "package logging\n\nimport (\n\t\"fmt\"\n\t\"log/slog\"\n\t\"os\"\n\t// \"path/filepath\"\n\t\"encoding/json\"\n\t\"runtime\"\n\t\"runtime/debug\"\n\t\"sync\"\n\t\"time\"\n)\n\nfunc getCaller() string {\n\tvar caller string\n\tif _, file, line, ok := runtime.Caller(2); ok {\n\t\t// caller = fmt.Sprintf(\"%s:%d\", filepath.Base(file), line)\n\t\tcaller = fmt.Sprintf(\"%s:%d\", file, line)\n\t} else {\n\t\tcaller = \"unknown\"\n\t}\n\treturn caller\n}\nfunc Info(msg string, args ...any) {\n\tsource := getCaller()\n\tslog.Info(msg, append([]any{\"source\", source}, args...)...)\n}\n\nfunc Debug(msg string, args ...any) {\n\t// slog.Debug(msg, args...)\n\tsource := getCaller()\n\tslog.Debug(msg, append([]any{\"source\", source}, args...)...)\n}\n\nfunc Warn(msg string, args ...any) {\n\tslog.Warn(msg, args...)\n}\n\nfunc Error(msg string, args ...any) {\n\tslog.Error(msg, args...)\n}\n\nfunc InfoPersist(msg string, args ...any) {\n\targs = append(args, persistKeyArg, true)\n\tslog.Info(msg, args...)\n}\n\nfunc DebugPersist(msg string, args ...any) {\n\targs = append(args, persistKeyArg, true)\n\tslog.Debug(msg, args...)\n}\n\nfunc WarnPersist(msg string, args ...any) {\n\targs = append(args, persistKeyArg, true)\n\tslog.Warn(msg, args...)\n}\n\nfunc ErrorPersist(msg string, args ...any) {\n\targs = append(args, persistKeyArg, true)\n\tslog.Error(msg, args...)\n}\n\n// RecoverPanic is a common function to handle panics gracefully.\n// It logs the error, creates a panic log file with stack trace,\n// and executes an optional cleanup function before returning.\nfunc RecoverPanic(name string, cleanup func()) {\n\tif r := recover(); r != nil {\n\t\t// Log the panic\n\t\tErrorPersist(fmt.Sprintf(\"Panic in %s: %v\", name, r))\n\n\t\t// Create a timestamped panic log file\n\t\ttimestamp := time.Now().Format(\"20060102-150405\")\n\t\tfilename := fmt.Sprintf(\"opencode-panic-%s-%s.log\", name, timestamp)\n\n\t\tfile, err := os.Create(filename)\n\t\tif err != nil {\n\t\t\tErrorPersist(fmt.Sprintf(\"Failed to create panic log: %v\", err))\n\t\t} else {\n\t\t\tdefer file.Close()\n\n\t\t\t// Write panic information and stack trace\n\t\t\tfmt.Fprintf(file, \"Panic in %s: %v\\n\\n\", name, r)\n\t\t\tfmt.Fprintf(file, \"Time: %s\\n\\n\", time.Now().Format(time.RFC3339))\n\t\t\tfmt.Fprintf(file, \"Stack Trace:\\n%s\\n\", debug.Stack())\n\n\t\t\tInfoPersist(fmt.Sprintf(\"Panic details written to %s\", filename))\n\t\t}\n\n\t\t// Execute cleanup function if provided\n\t\tif cleanup != nil {\n\t\t\tcleanup()\n\t\t}\n\t}\n}\n\n// Message Logging for Debug\nvar MessageDir string\n\nfunc GetSessionPrefix(sessionId string) string {\n\treturn sessionId[:8]\n}\n\nvar sessionLogMutex sync.Mutex\n\nfunc AppendToSessionLogFile(sessionId string, filename string, content string) string {\n\tif MessageDir == \"\" || sessionId == \"\" {\n\t\treturn \"\"\n\t}\n\tsessionPrefix := GetSessionPrefix(sessionId)\n\n\tsessionLogMutex.Lock()\n\tdefer sessionLogMutex.Unlock()\n\n\tsessionPath := fmt.Sprintf(\"%s/%s\", MessageDir, sessionPrefix)\n\tif _, err := os.Stat(sessionPath); os.IsNotExist(err) {\n\t\tif err := os.MkdirAll(sessionPath, 0o766); err != nil {\n\t\t\tError(\"Failed to create session directory\", \"dirpath\", sessionPath, \"error\", err)\n\t\t\treturn \"\"\n\t\t}\n\t}\n\n\tfilePath := fmt.Sprintf(\"%s/%s\", sessionPath, filename)\n\n\tf, err := os.OpenFile(filePath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)\n\tif err != nil {\n\t\tError(\"Failed to open session log file\", \"filepath\", filePath, \"error\", err)\n\t\treturn \"\"\n\t}\n\tdefer f.Close()\n\n\t// Append chunk to file\n\t_, err = f.WriteString(content)\n\tif err != nil {\n\t\tError(\"Failed to write chunk to session log file\", \"filepath\", filePath, \"error\", err)\n\t\treturn \"\"\n\t}\n\treturn filePath\n}\n\nfunc WriteRequestMessageJson(sessionId string, requestSeqId int, message any) string {\n\tif MessageDir == \"\" || sessionId == \"\" || requestSeqId <= 0 {\n\t\treturn \"\"\n\t}\n\tmsgJson, err := json.Marshal(message)\n\tif err != nil {\n\t\tError(\"Failed to marshal message\", \"session_id\", sessionId, \"request_seq_id\", requestSeqId, \"error\", err)\n\t\treturn \"\"\n\t}\n\treturn WriteRequestMessage(sessionId, requestSeqId, string(msgJson))\n}\n\nfunc WriteRequestMessage(sessionId string, requestSeqId int, message string) string {\n\tif MessageDir == \"\" || sessionId == \"\" || requestSeqId <= 0 {\n\t\treturn \"\"\n\t}\n\tfilename := fmt.Sprintf(\"%d_request.json\", requestSeqId)\n\n\treturn AppendToSessionLogFile(sessionId, filename, message)\n}\n\nfunc AppendToStreamSessionLogJson(sessionId string, requestSeqId int, jsonableChunk any) string {\n\tif MessageDir == \"\" || sessionId == \"\" || requestSeqId <= 0 {\n\t\treturn \"\"\n\t}\n\tchunkJson, err := json.Marshal(jsonableChunk)\n\tif err != nil {\n\t\tError(\"Failed to marshal message\", \"session_id\", sessionId, \"request_seq_id\", requestSeqId, \"error\", err)\n\t\treturn \"\"\n\t}\n\treturn AppendToStreamSessionLog(sessionId, requestSeqId, string(chunkJson))\n}\n\nfunc AppendToStreamSessionLog(sessionId string, requestSeqId int, chunk string) string {\n\tif MessageDir == \"\" || sessionId == \"\" || requestSeqId <= 0 {\n\t\treturn \"\"\n\t}\n\tfilename := fmt.Sprintf(\"%d_response_stream.log\", requestSeqId)\n\treturn AppendToSessionLogFile(sessionId, filename, chunk)\n}\n\nfunc WriteChatResponseJson(sessionId string, requestSeqId int, response any) string {\n\tif MessageDir == \"\" || sessionId == \"\" || requestSeqId <= 0 {\n\t\treturn \"\"\n\t}\n\tresponseJson, err := json.Marshal(response)\n\tif err != nil {\n\t\tError(\"Failed to marshal response\", \"session_id\", sessionId, \"request_seq_id\", requestSeqId, \"error\", err)\n\t\treturn \"\"\n\t}\n\tfilename := fmt.Sprintf(\"%d_response.json\", requestSeqId)\n\n\treturn AppendToSessionLogFile(sessionId, filename, string(responseJson))\n}\n\nfunc WriteToolResultsJson(sessionId string, requestSeqId int, toolResults any) string {\n\tif MessageDir == \"\" || sessionId == \"\" || requestSeqId <= 0 {\n\t\treturn \"\"\n\t}\n\ttoolResultsJson, err := json.Marshal(toolResults)\n\tif err != nil {\n\t\tError(\"Failed to marshal tool results\", \"session_id\", sessionId, \"request_seq_id\", requestSeqId, \"error\", err)\n\t\treturn \"\"\n\t}\n\tfilename := fmt.Sprintf(\"%d_tool_results.json\", requestSeqId)\n\treturn AppendToSessionLogFile(sessionId, filename, string(toolResultsJson))\n}\n"], ["/opencode/internal/llm/provider/bedrock.go", "package provider\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"os\"\n\t\"strings\"\n\n\t\"github.com/opencode-ai/opencode/internal/llm/tools\"\n\t\"github.com/opencode-ai/opencode/internal/message\"\n)\n\ntype bedrockOptions struct {\n\t// Bedrock specific options can be added here\n}\n\ntype BedrockOption func(*bedrockOptions)\n\ntype bedrockClient struct {\n\tproviderOptions providerClientOptions\n\toptions bedrockOptions\n\tchildProvider ProviderClient\n}\n\ntype BedrockClient ProviderClient\n\nfunc newBedrockClient(opts providerClientOptions) BedrockClient {\n\tbedrockOpts := bedrockOptions{}\n\t// Apply bedrock specific options if they are added in the future\n\n\t// Get AWS region from environment\n\tregion := os.Getenv(\"AWS_REGION\")\n\tif region == \"\" {\n\t\tregion = os.Getenv(\"AWS_DEFAULT_REGION\")\n\t}\n\n\tif region == \"\" {\n\t\tregion = \"us-east-1\" // default region\n\t}\n\tif len(region) < 2 {\n\t\treturn &bedrockClient{\n\t\t\tproviderOptions: opts,\n\t\t\toptions: bedrockOpts,\n\t\t\tchildProvider: nil, // Will cause an error when used\n\t\t}\n\t}\n\n\t// Prefix the model name with region\n\tregionPrefix := region[:2]\n\tmodelName := opts.model.APIModel\n\topts.model.APIModel = fmt.Sprintf(\"%s.%s\", regionPrefix, modelName)\n\n\t// Determine which provider to use based on the model\n\tif strings.Contains(string(opts.model.APIModel), \"anthropic\") {\n\t\t// Create Anthropic client with Bedrock configuration\n\t\tanthropicOpts := opts\n\t\tanthropicOpts.anthropicOptions = append(anthropicOpts.anthropicOptions,\n\t\t\tWithAnthropicBedrock(true),\n\t\t\tWithAnthropicDisableCache(),\n\t\t)\n\t\treturn &bedrockClient{\n\t\t\tproviderOptions: opts,\n\t\t\toptions: bedrockOpts,\n\t\t\tchildProvider: newAnthropicClient(anthropicOpts),\n\t\t}\n\t}\n\n\t// Return client with nil childProvider if model is not supported\n\t// This will cause an error when used\n\treturn &bedrockClient{\n\t\tproviderOptions: opts,\n\t\toptions: bedrockOpts,\n\t\tchildProvider: nil,\n\t}\n}\n\nfunc (b *bedrockClient) send(ctx context.Context, messages []message.Message, tools []tools.BaseTool) (*ProviderResponse, error) {\n\tif b.childProvider == nil {\n\t\treturn nil, errors.New(\"unsupported model for bedrock provider\")\n\t}\n\treturn b.childProvider.send(ctx, messages, tools)\n}\n\nfunc (b *bedrockClient) stream(ctx context.Context, messages []message.Message, tools []tools.BaseTool) <-chan ProviderEvent {\n\teventChan := make(chan ProviderEvent)\n\n\tif b.childProvider == nil {\n\t\tgo func() {\n\t\t\teventChan <- ProviderEvent{\n\t\t\t\tType: EventError,\n\t\t\t\tError: errors.New(\"unsupported model for bedrock provider\"),\n\t\t\t}\n\t\t\tclose(eventChan)\n\t\t}()\n\t\treturn eventChan\n\t}\n\n\treturn b.childProvider.stream(ctx, messages, tools)\n}\n\n"], ["/opencode/internal/lsp/protocol/tsprotocol.go", "// Copyright 2023 The Go Authors. All rights reserved.\n// Use of this source code is governed by a BSD-style\n// license that can be found in the LICENSE file.\n\n// Code generated for LSP. DO NOT EDIT.\n\npackage protocol\n\n// Code generated from protocol/metaModel.json at ref release/protocol/3.17.6-next.9 (hash c94395b5da53729e6dff931293b051009ccaaaa4).\n// https://github.com/microsoft/vscode-languageserver-node/blob/release/protocol/3.17.6-next.9/protocol/metaModel.json\n// LSP metaData.version = 3.17.0.\n\nimport \"encoding/json\"\n\n// created for And\ntype And_RegOpt_textDocument_colorPresentation struct {\n\tWorkDoneProgressOptions\n\tTextDocumentRegistrationOptions\n}\n\n// A special text edit with an additional change annotation.\n//\n// @since 3.16.0.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#annotatedTextEdit\ntype AnnotatedTextEdit struct {\n\t// The actual identifier of the change annotation\n\tAnnotationID *ChangeAnnotationIdentifier `json:\"annotationId,omitempty\"`\n\tTextEdit\n}\n\n// The parameters passed via an apply workspace edit request.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#applyWorkspaceEditParams\ntype ApplyWorkspaceEditParams struct {\n\t// An optional label of the workspace edit. This label is\n\t// presented in the user interface for example on an undo\n\t// stack to undo the workspace edit.\n\tLabel string `json:\"label,omitempty\"`\n\t// The edits to apply.\n\tEdit WorkspaceEdit `json:\"edit\"`\n\t// Additional data about the edit.\n\t//\n\t// @since 3.18.0\n\t// @proposed\n\tMetadata *WorkspaceEditMetadata `json:\"metadata,omitempty\"`\n}\n\n// The result returned from the apply workspace edit request.\n//\n// @since 3.17 renamed from ApplyWorkspaceEditResponse\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#applyWorkspaceEditResult\ntype ApplyWorkspaceEditResult struct {\n\t// Indicates whether the edit was applied or not.\n\tApplied bool `json:\"applied\"`\n\t// An optional textual description for why the edit was not applied.\n\t// This may be used by the server for diagnostic logging or to provide\n\t// a suitable error for a request that triggered the edit.\n\tFailureReason string `json:\"failureReason,omitempty\"`\n\t// Depending on the client's failure handling strategy `failedChange` might\n\t// contain the index of the change that failed. This property is only available\n\t// if the client signals a `failureHandlingStrategy` in its client capabilities.\n\tFailedChange uint32 `json:\"failedChange,omitempty\"`\n}\n\n// A base for all symbol information.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#baseSymbolInformation\ntype BaseSymbolInformation struct {\n\t// The name of this symbol.\n\tName string `json:\"name\"`\n\t// The kind of this symbol.\n\tKind SymbolKind `json:\"kind\"`\n\t// Tags for this symbol.\n\t//\n\t// @since 3.16.0\n\tTags []SymbolTag `json:\"tags,omitempty\"`\n\t// The name of the symbol containing this symbol. This information is for\n\t// user interface purposes (e.g. to render a qualifier in the user interface\n\t// if necessary). It can't be used to re-infer a hierarchy for the document\n\t// symbols.\n\tContainerName string `json:\"containerName,omitempty\"`\n}\n\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#callHierarchyClientCapabilities\ntype CallHierarchyClientCapabilities struct {\n\t// Whether implementation supports dynamic registration. If this is set to `true`\n\t// the client supports the new `(TextDocumentRegistrationOptions & StaticRegistrationOptions)`\n\t// return value for the corresponding server capability as well.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n}\n\n// Represents an incoming call, e.g. a caller of a method or constructor.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#callHierarchyIncomingCall\ntype CallHierarchyIncomingCall struct {\n\t// The item that makes the call.\n\tFrom CallHierarchyItem `json:\"from\"`\n\t// The ranges at which the calls appear. This is relative to the caller\n\t// denoted by {@link CallHierarchyIncomingCall.from `this.from`}.\n\tFromRanges []Range `json:\"fromRanges\"`\n}\n\n// The parameter of a `callHierarchy/incomingCalls` request.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#callHierarchyIncomingCallsParams\ntype CallHierarchyIncomingCallsParams struct {\n\tItem CallHierarchyItem `json:\"item\"`\n\tWorkDoneProgressParams\n\tPartialResultParams\n}\n\n// Represents programming constructs like functions or constructors in the context\n// of call hierarchy.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#callHierarchyItem\ntype CallHierarchyItem struct {\n\t// The name of this item.\n\tName string `json:\"name\"`\n\t// The kind of this item.\n\tKind SymbolKind `json:\"kind\"`\n\t// Tags for this item.\n\tTags []SymbolTag `json:\"tags,omitempty\"`\n\t// More detail for this item, e.g. the signature of a function.\n\tDetail string `json:\"detail,omitempty\"`\n\t// The resource identifier of this item.\n\tURI DocumentUri `json:\"uri\"`\n\t// The range enclosing this symbol not including leading/trailing whitespace but everything else, e.g. comments and code.\n\tRange Range `json:\"range\"`\n\t// The range that should be selected and revealed when this symbol is being picked, e.g. the name of a function.\n\t// Must be contained by the {@link CallHierarchyItem.range `range`}.\n\tSelectionRange Range `json:\"selectionRange\"`\n\t// A data entry field that is preserved between a call hierarchy prepare and\n\t// incoming calls or outgoing calls requests.\n\tData interface{} `json:\"data,omitempty\"`\n}\n\n// Call hierarchy options used during static registration.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#callHierarchyOptions\ntype CallHierarchyOptions struct {\n\tWorkDoneProgressOptions\n}\n\n// Represents an outgoing call, e.g. calling a getter from a method or a method from a constructor etc.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#callHierarchyOutgoingCall\ntype CallHierarchyOutgoingCall struct {\n\t// The item that is called.\n\tTo CallHierarchyItem `json:\"to\"`\n\t// The range at which this item is called. This is the range relative to the caller, e.g the item\n\t// passed to {@link CallHierarchyItemProvider.provideCallHierarchyOutgoingCalls `provideCallHierarchyOutgoingCalls`}\n\t// and not {@link CallHierarchyOutgoingCall.to `this.to`}.\n\tFromRanges []Range `json:\"fromRanges\"`\n}\n\n// The parameter of a `callHierarchy/outgoingCalls` request.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#callHierarchyOutgoingCallsParams\ntype CallHierarchyOutgoingCallsParams struct {\n\tItem CallHierarchyItem `json:\"item\"`\n\tWorkDoneProgressParams\n\tPartialResultParams\n}\n\n// The parameter of a `textDocument/prepareCallHierarchy` request.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#callHierarchyPrepareParams\ntype CallHierarchyPrepareParams struct {\n\tTextDocumentPositionParams\n\tWorkDoneProgressParams\n}\n\n// Call hierarchy options used during static or dynamic registration.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#callHierarchyRegistrationOptions\ntype CallHierarchyRegistrationOptions struct {\n\tTextDocumentRegistrationOptions\n\tCallHierarchyOptions\n\tStaticRegistrationOptions\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#cancelParams\ntype CancelParams struct {\n\t// The request id to cancel.\n\tID interface{} `json:\"id\"`\n}\n\n// Additional information that describes document changes.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#changeAnnotation\ntype ChangeAnnotation struct {\n\t// A human-readable string describing the actual change. The string\n\t// is rendered prominent in the user interface.\n\tLabel string `json:\"label\"`\n\t// A flag which indicates that user confirmation is needed\n\t// before applying the change.\n\tNeedsConfirmation bool `json:\"needsConfirmation,omitempty\"`\n\t// A human-readable string which is rendered less prominent in\n\t// the user interface.\n\tDescription string `json:\"description,omitempty\"`\n}\n\n// An identifier to refer to a change annotation stored with a workspace edit.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#changeAnnotationIdentifier\ntype ChangeAnnotationIdentifier = string // (alias)\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#changeAnnotationsSupportOptions\ntype ChangeAnnotationsSupportOptions struct {\n\t// Whether the client groups edits with equal labels into tree nodes,\n\t// for instance all edits labelled with \"Changes in Strings\" would\n\t// be a tree node.\n\tGroupsOnLabel bool `json:\"groupsOnLabel,omitempty\"`\n}\n\n// Defines the capabilities provided by the client.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#clientCapabilities\ntype ClientCapabilities struct {\n\t// Workspace specific client capabilities.\n\tWorkspace WorkspaceClientCapabilities `json:\"workspace,omitempty\"`\n\t// Text document specific client capabilities.\n\tTextDocument TextDocumentClientCapabilities `json:\"textDocument,omitempty\"`\n\t// Capabilities specific to the notebook document support.\n\t//\n\t// @since 3.17.0\n\tNotebookDocument *NotebookDocumentClientCapabilities `json:\"notebookDocument,omitempty\"`\n\t// Window specific client capabilities.\n\tWindow WindowClientCapabilities `json:\"window,omitempty\"`\n\t// General client capabilities.\n\t//\n\t// @since 3.16.0\n\tGeneral *GeneralClientCapabilities `json:\"general,omitempty\"`\n\t// Experimental client capabilities.\n\tExperimental interface{} `json:\"experimental,omitempty\"`\n}\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#clientCodeActionKindOptions\ntype ClientCodeActionKindOptions struct {\n\t// The code action kind values the client supports. When this\n\t// property exists the client also guarantees that it will\n\t// handle values outside its set gracefully and falls back\n\t// to a default value when unknown.\n\tValueSet []CodeActionKind `json:\"valueSet\"`\n}\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#clientCodeActionLiteralOptions\ntype ClientCodeActionLiteralOptions struct {\n\t// The code action kind is support with the following value\n\t// set.\n\tCodeActionKind ClientCodeActionKindOptions `json:\"codeActionKind\"`\n}\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#clientCodeActionResolveOptions\ntype ClientCodeActionResolveOptions struct {\n\t// The properties that a client can resolve lazily.\n\tProperties []string `json:\"properties\"`\n}\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#clientCodeLensResolveOptions\ntype ClientCodeLensResolveOptions struct {\n\t// The properties that a client can resolve lazily.\n\tProperties []string `json:\"properties\"`\n}\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#clientCompletionItemInsertTextModeOptions\ntype ClientCompletionItemInsertTextModeOptions struct {\n\tValueSet []InsertTextMode `json:\"valueSet\"`\n}\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#clientCompletionItemOptions\ntype ClientCompletionItemOptions struct {\n\t// Client supports snippets as insert text.\n\t//\n\t// A snippet can define tab stops and placeholders with `$1`, `$2`\n\t// and `${3:foo}`. `$0` defines the final tab stop, it defaults to\n\t// the end of the snippet. Placeholders with equal identifiers are linked,\n\t// that is typing in one will update others too.\n\tSnippetSupport bool `json:\"snippetSupport,omitempty\"`\n\t// Client supports commit characters on a completion item.\n\tCommitCharactersSupport bool `json:\"commitCharactersSupport,omitempty\"`\n\t// Client supports the following content formats for the documentation\n\t// property. The order describes the preferred format of the client.\n\tDocumentationFormat []MarkupKind `json:\"documentationFormat,omitempty\"`\n\t// Client supports the deprecated property on a completion item.\n\tDeprecatedSupport bool `json:\"deprecatedSupport,omitempty\"`\n\t// Client supports the preselect property on a completion item.\n\tPreselectSupport bool `json:\"preselectSupport,omitempty\"`\n\t// Client supports the tag property on a completion item. Clients supporting\n\t// tags have to handle unknown tags gracefully. Clients especially need to\n\t// preserve unknown tags when sending a completion item back to the server in\n\t// a resolve call.\n\t//\n\t// @since 3.15.0\n\tTagSupport *CompletionItemTagOptions `json:\"tagSupport,omitempty\"`\n\t// Client support insert replace edit to control different behavior if a\n\t// completion item is inserted in the text or should replace text.\n\t//\n\t// @since 3.16.0\n\tInsertReplaceSupport bool `json:\"insertReplaceSupport,omitempty\"`\n\t// Indicates which properties a client can resolve lazily on a completion\n\t// item. Before version 3.16.0 only the predefined properties `documentation`\n\t// and `details` could be resolved lazily.\n\t//\n\t// @since 3.16.0\n\tResolveSupport *ClientCompletionItemResolveOptions `json:\"resolveSupport,omitempty\"`\n\t// The client supports the `insertTextMode` property on\n\t// a completion item to override the whitespace handling mode\n\t// as defined by the client (see `insertTextMode`).\n\t//\n\t// @since 3.16.0\n\tInsertTextModeSupport *ClientCompletionItemInsertTextModeOptions `json:\"insertTextModeSupport,omitempty\"`\n\t// The client has support for completion item label\n\t// details (see also `CompletionItemLabelDetails`).\n\t//\n\t// @since 3.17.0\n\tLabelDetailsSupport bool `json:\"labelDetailsSupport,omitempty\"`\n}\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#clientCompletionItemOptionsKind\ntype ClientCompletionItemOptionsKind struct {\n\t// The completion item kind values the client supports. When this\n\t// property exists the client also guarantees that it will\n\t// handle values outside its set gracefully and falls back\n\t// to a default value when unknown.\n\t//\n\t// If this property is not present the client only supports\n\t// the completion items kinds from `Text` to `Reference` as defined in\n\t// the initial version of the protocol.\n\tValueSet []CompletionItemKind `json:\"valueSet,omitempty\"`\n}\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#clientCompletionItemResolveOptions\ntype ClientCompletionItemResolveOptions struct {\n\t// The properties that a client can resolve lazily.\n\tProperties []string `json:\"properties\"`\n}\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#clientDiagnosticsTagOptions\ntype ClientDiagnosticsTagOptions struct {\n\t// The tags supported by the client.\n\tValueSet []DiagnosticTag `json:\"valueSet\"`\n}\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#clientFoldingRangeKindOptions\ntype ClientFoldingRangeKindOptions struct {\n\t// The folding range kind values the client supports. When this\n\t// property exists the client also guarantees that it will\n\t// handle values outside its set gracefully and falls back\n\t// to a default value when unknown.\n\tValueSet []FoldingRangeKind `json:\"valueSet,omitempty\"`\n}\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#clientFoldingRangeOptions\ntype ClientFoldingRangeOptions struct {\n\t// If set, the client signals that it supports setting collapsedText on\n\t// folding ranges to display custom labels instead of the default text.\n\t//\n\t// @since 3.17.0\n\tCollapsedText bool `json:\"collapsedText,omitempty\"`\n}\n\n// Information about the client\n//\n// @since 3.15.0\n// @since 3.18.0 ClientInfo type name added.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#clientInfo\ntype ClientInfo struct {\n\t// The name of the client as defined by the client.\n\tName string `json:\"name\"`\n\t// The client's version as defined by the client.\n\tVersion string `json:\"version,omitempty\"`\n}\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#clientInlayHintResolveOptions\ntype ClientInlayHintResolveOptions struct {\n\t// The properties that a client can resolve lazily.\n\tProperties []string `json:\"properties\"`\n}\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#clientSemanticTokensRequestFullDelta\ntype ClientSemanticTokensRequestFullDelta struct {\n\t// The client will send the `textDocument/semanticTokens/full/delta` request if\n\t// the server provides a corresponding handler.\n\tDelta bool `json:\"delta,omitempty\"`\n}\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#clientSemanticTokensRequestOptions\ntype ClientSemanticTokensRequestOptions struct {\n\t// The client will send the `textDocument/semanticTokens/range` request if\n\t// the server provides a corresponding handler.\n\tRange *Or_ClientSemanticTokensRequestOptions_range `json:\"range,omitempty\"`\n\t// The client will send the `textDocument/semanticTokens/full` request if\n\t// the server provides a corresponding handler.\n\tFull *Or_ClientSemanticTokensRequestOptions_full `json:\"full,omitempty\"`\n}\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#clientShowMessageActionItemOptions\ntype ClientShowMessageActionItemOptions struct {\n\t// Whether the client supports additional attributes which\n\t// are preserved and send back to the server in the\n\t// request's response.\n\tAdditionalPropertiesSupport bool `json:\"additionalPropertiesSupport,omitempty\"`\n}\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#clientSignatureInformationOptions\ntype ClientSignatureInformationOptions struct {\n\t// Client supports the following content formats for the documentation\n\t// property. The order describes the preferred format of the client.\n\tDocumentationFormat []MarkupKind `json:\"documentationFormat,omitempty\"`\n\t// Client capabilities specific to parameter information.\n\tParameterInformation *ClientSignatureParameterInformationOptions `json:\"parameterInformation,omitempty\"`\n\t// The client supports the `activeParameter` property on `SignatureInformation`\n\t// literal.\n\t//\n\t// @since 3.16.0\n\tActiveParameterSupport bool `json:\"activeParameterSupport,omitempty\"`\n\t// The client supports the `activeParameter` property on\n\t// `SignatureHelp`/`SignatureInformation` being set to `null` to\n\t// indicate that no parameter should be active.\n\t//\n\t// @since 3.18.0\n\t// @proposed\n\tNoActiveParameterSupport bool `json:\"noActiveParameterSupport,omitempty\"`\n}\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#clientSignatureParameterInformationOptions\ntype ClientSignatureParameterInformationOptions struct {\n\t// The client supports processing label offsets instead of a\n\t// simple label string.\n\t//\n\t// @since 3.14.0\n\tLabelOffsetSupport bool `json:\"labelOffsetSupport,omitempty\"`\n}\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#clientSymbolKindOptions\ntype ClientSymbolKindOptions struct {\n\t// The symbol kind values the client supports. When this\n\t// property exists the client also guarantees that it will\n\t// handle values outside its set gracefully and falls back\n\t// to a default value when unknown.\n\t//\n\t// If this property is not present the client only supports\n\t// the symbol kinds from `File` to `Array` as defined in\n\t// the initial version of the protocol.\n\tValueSet []SymbolKind `json:\"valueSet,omitempty\"`\n}\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#clientSymbolResolveOptions\ntype ClientSymbolResolveOptions struct {\n\t// The properties that a client can resolve lazily. Usually\n\t// `location.range`\n\tProperties []string `json:\"properties\"`\n}\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#clientSymbolTagOptions\ntype ClientSymbolTagOptions struct {\n\t// The tags supported by the client.\n\tValueSet []SymbolTag `json:\"valueSet\"`\n}\n\n// A code action represents a change that can be performed in code, e.g. to fix a problem or\n// to refactor code.\n//\n// A CodeAction must set either `edit` and/or a `command`. If both are supplied, the `edit` is applied first, then the `command` is executed.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#codeAction\ntype CodeAction struct {\n\t// A short, human-readable, title for this code action.\n\tTitle string `json:\"title\"`\n\t// The kind of the code action.\n\t//\n\t// Used to filter code actions.\n\tKind CodeActionKind `json:\"kind,omitempty\"`\n\t// The diagnostics that this code action resolves.\n\tDiagnostics []Diagnostic `json:\"diagnostics,omitempty\"`\n\t// Marks this as a preferred action. Preferred actions are used by the `auto fix` command and can be targeted\n\t// by keybindings.\n\t//\n\t// A quick fix should be marked preferred if it properly addresses the underlying error.\n\t// A refactoring should be marked preferred if it is the most reasonable choice of actions to take.\n\t//\n\t// @since 3.15.0\n\tIsPreferred bool `json:\"isPreferred,omitempty\"`\n\t// Marks that the code action cannot currently be applied.\n\t//\n\t// Clients should follow the following guidelines regarding disabled code actions:\n\t//\n\t// - Disabled code actions are not shown in automatic [lightbulbs](https://code.visualstudio.com/docs/editor/editingevolved#_code-action)\n\t// code action menus.\n\t//\n\t// - Disabled actions are shown as faded out in the code action menu when the user requests a more specific type\n\t// of code action, such as refactorings.\n\t//\n\t// - If the user has a [keybinding](https://code.visualstudio.com/docs/editor/refactoring#_keybindings-for-code-actions)\n\t// that auto applies a code action and only disabled code actions are returned, the client should show the user an\n\t// error message with `reason` in the editor.\n\t//\n\t// @since 3.16.0\n\tDisabled *CodeActionDisabled `json:\"disabled,omitempty\"`\n\t// The workspace edit this code action performs.\n\tEdit *WorkspaceEdit `json:\"edit,omitempty\"`\n\t// A command this code action executes. If a code action\n\t// provides an edit and a command, first the edit is\n\t// executed and then the command.\n\tCommand *Command `json:\"command,omitempty\"`\n\t// A data entry field that is preserved on a code action between\n\t// a `textDocument/codeAction` and a `codeAction/resolve` request.\n\t//\n\t// @since 3.16.0\n\tData *json.RawMessage `json:\"data,omitempty\"`\n}\n\n// The Client Capabilities of a {@link CodeActionRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#codeActionClientCapabilities\ntype CodeActionClientCapabilities struct {\n\t// Whether code action supports dynamic registration.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n\t// The client support code action literals of type `CodeAction` as a valid\n\t// response of the `textDocument/codeAction` request. If the property is not\n\t// set the request can only return `Command` literals.\n\t//\n\t// @since 3.8.0\n\tCodeActionLiteralSupport ClientCodeActionLiteralOptions `json:\"codeActionLiteralSupport,omitempty\"`\n\t// Whether code action supports the `isPreferred` property.\n\t//\n\t// @since 3.15.0\n\tIsPreferredSupport bool `json:\"isPreferredSupport,omitempty\"`\n\t// Whether code action supports the `disabled` property.\n\t//\n\t// @since 3.16.0\n\tDisabledSupport bool `json:\"disabledSupport,omitempty\"`\n\t// Whether code action supports the `data` property which is\n\t// preserved between a `textDocument/codeAction` and a\n\t// `codeAction/resolve` request.\n\t//\n\t// @since 3.16.0\n\tDataSupport bool `json:\"dataSupport,omitempty\"`\n\t// Whether the client supports resolving additional code action\n\t// properties via a separate `codeAction/resolve` request.\n\t//\n\t// @since 3.16.0\n\tResolveSupport *ClientCodeActionResolveOptions `json:\"resolveSupport,omitempty\"`\n\t// Whether the client honors the change annotations in\n\t// text edits and resource operations returned via the\n\t// `CodeAction#edit` property by for example presenting\n\t// the workspace edit in the user interface and asking\n\t// for confirmation.\n\t//\n\t// @since 3.16.0\n\tHonorsChangeAnnotations bool `json:\"honorsChangeAnnotations,omitempty\"`\n\t// Whether the client supports documentation for a class of\n\t// code actions.\n\t//\n\t// @since 3.18.0\n\t// @proposed\n\tDocumentationSupport bool `json:\"documentationSupport,omitempty\"`\n}\n\n// Contains additional diagnostic information about the context in which\n// a {@link CodeActionProvider.provideCodeActions code action} is run.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#codeActionContext\ntype CodeActionContext struct {\n\t// An array of diagnostics known on the client side overlapping the range provided to the\n\t// `textDocument/codeAction` request. They are provided so that the server knows which\n\t// errors are currently presented to the user for the given range. There is no guarantee\n\t// that these accurately reflect the error state of the resource. The primary parameter\n\t// to compute code actions is the provided range.\n\tDiagnostics []Diagnostic `json:\"diagnostics\"`\n\t// Requested kind of actions to return.\n\t//\n\t// Actions not of this kind are filtered out by the client before being shown. So servers\n\t// can omit computing them.\n\tOnly []CodeActionKind `json:\"only,omitempty\"`\n\t// The reason why code actions were requested.\n\t//\n\t// @since 3.17.0\n\tTriggerKind *CodeActionTriggerKind `json:\"triggerKind,omitempty\"`\n}\n\n// Captures why the code action is currently disabled.\n//\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#codeActionDisabled\ntype CodeActionDisabled struct {\n\t// Human readable description of why the code action is currently disabled.\n\t//\n\t// This is displayed in the code actions UI.\n\tReason string `json:\"reason\"`\n}\n\n// A set of predefined code action kinds\ntype CodeActionKind string\n\n// Documentation for a class of code actions.\n//\n// @since 3.18.0\n// @proposed\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#codeActionKindDocumentation\ntype CodeActionKindDocumentation struct {\n\t// The kind of the code action being documented.\n\t//\n\t// If the kind is generic, such as `CodeActionKind.Refactor`, the documentation will be shown whenever any\n\t// refactorings are returned. If the kind if more specific, such as `CodeActionKind.RefactorExtract`, the\n\t// documentation will only be shown when extract refactoring code actions are returned.\n\tKind CodeActionKind `json:\"kind\"`\n\t// Command that is ued to display the documentation to the user.\n\t//\n\t// The title of this documentation code action is taken from {@linkcode Command.title}\n\tCommand Command `json:\"command\"`\n}\n\n// Provider options for a {@link CodeActionRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#codeActionOptions\ntype CodeActionOptions struct {\n\t// CodeActionKinds that this server may return.\n\t//\n\t// The list of kinds may be generic, such as `CodeActionKind.Refactor`, or the server\n\t// may list out every specific kind they provide.\n\tCodeActionKinds []CodeActionKind `json:\"codeActionKinds,omitempty\"`\n\t// Static documentation for a class of code actions.\n\t//\n\t// Documentation from the provider should be shown in the code actions menu if either:\n\t//\n\t//\n\t// - Code actions of `kind` are requested by the editor. In this case, the editor will show the documentation that\n\t// most closely matches the requested code action kind. For example, if a provider has documentation for\n\t// both `Refactor` and `RefactorExtract`, when the user requests code actions for `RefactorExtract`,\n\t// the editor will use the documentation for `RefactorExtract` instead of the documentation for `Refactor`.\n\t//\n\t//\n\t// - Any code actions of `kind` are returned by the provider.\n\t//\n\t// At most one documentation entry should be shown per provider.\n\t//\n\t// @since 3.18.0\n\t// @proposed\n\tDocumentation []CodeActionKindDocumentation `json:\"documentation,omitempty\"`\n\t// The server provides support to resolve additional\n\t// information for a code action.\n\t//\n\t// @since 3.16.0\n\tResolveProvider bool `json:\"resolveProvider,omitempty\"`\n\tWorkDoneProgressOptions\n}\n\n// The parameters of a {@link CodeActionRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#codeActionParams\ntype CodeActionParams struct {\n\t// The document in which the command was invoked.\n\tTextDocument TextDocumentIdentifier `json:\"textDocument\"`\n\t// The range for which the command was invoked.\n\tRange Range `json:\"range\"`\n\t// Context carrying additional information.\n\tContext CodeActionContext `json:\"context\"`\n\tWorkDoneProgressParams\n\tPartialResultParams\n}\n\n// Registration options for a {@link CodeActionRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#codeActionRegistrationOptions\ntype CodeActionRegistrationOptions struct {\n\tTextDocumentRegistrationOptions\n\tCodeActionOptions\n}\n\n// The reason why code actions were requested.\n//\n// @since 3.17.0\ntype CodeActionTriggerKind uint32\n\n// Structure to capture a description for an error code.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#codeDescription\ntype CodeDescription struct {\n\t// An URI to open with more information about the diagnostic error.\n\tHref URI `json:\"href\"`\n}\n\n// A code lens represents a {@link Command command} that should be shown along with\n// source text, like the number of references, a way to run tests, etc.\n//\n// A code lens is _unresolved_ when no command is associated to it. For performance\n// reasons the creation of a code lens and resolving should be done in two stages.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#codeLens\ntype CodeLens struct {\n\t// The range in which this code lens is valid. Should only span a single line.\n\tRange Range `json:\"range\"`\n\t// The command this code lens represents.\n\tCommand *Command `json:\"command,omitempty\"`\n\t// A data entry field that is preserved on a code lens item between\n\t// a {@link CodeLensRequest} and a {@link CodeLensResolveRequest}\n\tData interface{} `json:\"data,omitempty\"`\n}\n\n// The client capabilities of a {@link CodeLensRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#codeLensClientCapabilities\ntype CodeLensClientCapabilities struct {\n\t// Whether code lens supports dynamic registration.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n\t// Whether the client supports resolving additional code lens\n\t// properties via a separate `codeLens/resolve` request.\n\t//\n\t// @since 3.18.0\n\tResolveSupport *ClientCodeLensResolveOptions `json:\"resolveSupport,omitempty\"`\n}\n\n// Code Lens provider options of a {@link CodeLensRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#codeLensOptions\ntype CodeLensOptions struct {\n\t// Code lens has a resolve provider as well.\n\tResolveProvider bool `json:\"resolveProvider,omitempty\"`\n\tWorkDoneProgressOptions\n}\n\n// The parameters of a {@link CodeLensRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#codeLensParams\ntype CodeLensParams struct {\n\t// The document to request code lens for.\n\tTextDocument TextDocumentIdentifier `json:\"textDocument\"`\n\tWorkDoneProgressParams\n\tPartialResultParams\n}\n\n// Registration options for a {@link CodeLensRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#codeLensRegistrationOptions\ntype CodeLensRegistrationOptions struct {\n\tTextDocumentRegistrationOptions\n\tCodeLensOptions\n}\n\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#codeLensWorkspaceClientCapabilities\ntype CodeLensWorkspaceClientCapabilities struct {\n\t// Whether the client implementation supports a refresh request sent from the\n\t// server to the client.\n\t//\n\t// Note that this event is global and will force the client to refresh all\n\t// code lenses currently shown. It should be used with absolute care and is\n\t// useful for situation where a server for example detect a project wide\n\t// change that requires such a calculation.\n\tRefreshSupport bool `json:\"refreshSupport,omitempty\"`\n}\n\n// Represents a color in RGBA space.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#color\ntype Color struct {\n\t// The red component of this color in the range [0-1].\n\tRed float64 `json:\"red\"`\n\t// The green component of this color in the range [0-1].\n\tGreen float64 `json:\"green\"`\n\t// The blue component of this color in the range [0-1].\n\tBlue float64 `json:\"blue\"`\n\t// The alpha component of this color in the range [0-1].\n\tAlpha float64 `json:\"alpha\"`\n}\n\n// Represents a color range from a document.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#colorInformation\ntype ColorInformation struct {\n\t// The range in the document where this color appears.\n\tRange Range `json:\"range\"`\n\t// The actual color value for this color range.\n\tColor Color `json:\"color\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#colorPresentation\ntype ColorPresentation struct {\n\t// The label of this color presentation. It will be shown on the color\n\t// picker header. By default this is also the text that is inserted when selecting\n\t// this color presentation.\n\tLabel string `json:\"label\"`\n\t// An {@link TextEdit edit} which is applied to a document when selecting\n\t// this presentation for the color. When `falsy` the {@link ColorPresentation.label label}\n\t// is used.\n\tTextEdit *TextEdit `json:\"textEdit,omitempty\"`\n\t// An optional array of additional {@link TextEdit text edits} that are applied when\n\t// selecting this color presentation. Edits must not overlap with the main {@link ColorPresentation.textEdit edit} nor with themselves.\n\tAdditionalTextEdits []TextEdit `json:\"additionalTextEdits,omitempty\"`\n}\n\n// Parameters for a {@link ColorPresentationRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#colorPresentationParams\ntype ColorPresentationParams struct {\n\t// The text document.\n\tTextDocument TextDocumentIdentifier `json:\"textDocument\"`\n\t// The color to request presentations for.\n\tColor Color `json:\"color\"`\n\t// The range where the color would be inserted. Serves as a context.\n\tRange Range `json:\"range\"`\n\tWorkDoneProgressParams\n\tPartialResultParams\n}\n\n// Represents a reference to a command. Provides a title which\n// will be used to represent a command in the UI and, optionally,\n// an array of arguments which will be passed to the command handler\n// function when invoked.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#command\ntype Command struct {\n\t// Title of the command, like `save`.\n\tTitle string `json:\"title\"`\n\t// An optional tooltip.\n\t//\n\t// @since 3.18.0\n\t// @proposed\n\tTooltip string `json:\"tooltip,omitempty\"`\n\t// The identifier of the actual command handler.\n\tCommand string `json:\"command\"`\n\t// Arguments that the command handler should be\n\t// invoked with.\n\tArguments []json.RawMessage `json:\"arguments,omitempty\"`\n}\n\n// Completion client capabilities\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#completionClientCapabilities\ntype CompletionClientCapabilities struct {\n\t// Whether completion supports dynamic registration.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n\t// The client supports the following `CompletionItem` specific\n\t// capabilities.\n\tCompletionItem ClientCompletionItemOptions `json:\"completionItem,omitempty\"`\n\tCompletionItemKind *ClientCompletionItemOptionsKind `json:\"completionItemKind,omitempty\"`\n\t// Defines how the client handles whitespace and indentation\n\t// when accepting a completion item that uses multi line\n\t// text in either `insertText` or `textEdit`.\n\t//\n\t// @since 3.17.0\n\tInsertTextMode InsertTextMode `json:\"insertTextMode,omitempty\"`\n\t// The client supports to send additional context information for a\n\t// `textDocument/completion` request.\n\tContextSupport bool `json:\"contextSupport,omitempty\"`\n\t// The client supports the following `CompletionList` specific\n\t// capabilities.\n\t//\n\t// @since 3.17.0\n\tCompletionList *CompletionListCapabilities `json:\"completionList,omitempty\"`\n}\n\n// Contains additional information about the context in which a completion request is triggered.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#completionContext\ntype CompletionContext struct {\n\t// How the completion was triggered.\n\tTriggerKind CompletionTriggerKind `json:\"triggerKind\"`\n\t// The trigger character (a single character) that has trigger code complete.\n\t// Is undefined if `triggerKind !== CompletionTriggerKind.TriggerCharacter`\n\tTriggerCharacter string `json:\"triggerCharacter,omitempty\"`\n}\n\n// A completion item represents a text snippet that is\n// proposed to complete text that is being typed.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#completionItem\ntype CompletionItem struct {\n\t// The label of this completion item.\n\t//\n\t// The label property is also by default the text that\n\t// is inserted when selecting this completion.\n\t//\n\t// If label details are provided the label itself should\n\t// be an unqualified name of the completion item.\n\tLabel string `json:\"label\"`\n\t// Additional details for the label\n\t//\n\t// @since 3.17.0\n\tLabelDetails *CompletionItemLabelDetails `json:\"labelDetails,omitempty\"`\n\t// The kind of this completion item. Based of the kind\n\t// an icon is chosen by the editor.\n\tKind CompletionItemKind `json:\"kind,omitempty\"`\n\t// Tags for this completion item.\n\t//\n\t// @since 3.15.0\n\tTags []CompletionItemTag `json:\"tags,omitempty\"`\n\t// A human-readable string with additional information\n\t// about this item, like type or symbol information.\n\tDetail string `json:\"detail,omitempty\"`\n\t// A human-readable string that represents a doc-comment.\n\tDocumentation *Or_CompletionItem_documentation `json:\"documentation,omitempty\"`\n\t// Indicates if this item is deprecated.\n\t// @deprecated Use `tags` instead.\n\tDeprecated bool `json:\"deprecated,omitempty\"`\n\t// Select this item when showing.\n\t//\n\t// *Note* that only one completion item can be selected and that the\n\t// tool / client decides which item that is. The rule is that the *first*\n\t// item of those that match best is selected.\n\tPreselect bool `json:\"preselect,omitempty\"`\n\t// A string that should be used when comparing this item\n\t// with other items. When `falsy` the {@link CompletionItem.label label}\n\t// is used.\n\tSortText string `json:\"sortText,omitempty\"`\n\t// A string that should be used when filtering a set of\n\t// completion items. When `falsy` the {@link CompletionItem.label label}\n\t// is used.\n\tFilterText string `json:\"filterText,omitempty\"`\n\t// A string that should be inserted into a document when selecting\n\t// this completion. When `falsy` the {@link CompletionItem.label label}\n\t// is used.\n\t//\n\t// The `insertText` is subject to interpretation by the client side.\n\t// Some tools might not take the string literally. For example\n\t// VS Code when code complete is requested in this example\n\t// `con` and a completion item with an `insertText` of\n\t// `console` is provided it will only insert `sole`. Therefore it is\n\t// recommended to use `textEdit` instead since it avoids additional client\n\t// side interpretation.\n\tInsertText string `json:\"insertText,omitempty\"`\n\t// The format of the insert text. The format applies to both the\n\t// `insertText` property and the `newText` property of a provided\n\t// `textEdit`. If omitted defaults to `InsertTextFormat.PlainText`.\n\t//\n\t// Please note that the insertTextFormat doesn't apply to\n\t// `additionalTextEdits`.\n\tInsertTextFormat *InsertTextFormat `json:\"insertTextFormat,omitempty\"`\n\t// How whitespace and indentation is handled during completion\n\t// item insertion. If not provided the clients default value depends on\n\t// the `textDocument.completion.insertTextMode` client capability.\n\t//\n\t// @since 3.16.0\n\tInsertTextMode *InsertTextMode `json:\"insertTextMode,omitempty\"`\n\t// An {@link TextEdit edit} which is applied to a document when selecting\n\t// this completion. When an edit is provided the value of\n\t// {@link CompletionItem.insertText insertText} is ignored.\n\t//\n\t// Most editors support two different operations when accepting a completion\n\t// item. One is to insert a completion text and the other is to replace an\n\t// existing text with a completion text. Since this can usually not be\n\t// predetermined by a server it can report both ranges. Clients need to\n\t// signal support for `InsertReplaceEdits` via the\n\t// `textDocument.completion.insertReplaceSupport` client capability\n\t// property.\n\t//\n\t// *Note 1:* The text edit's range as well as both ranges from an insert\n\t// replace edit must be a [single line] and they must contain the position\n\t// at which completion has been requested.\n\t// *Note 2:* If an `InsertReplaceEdit` is returned the edit's insert range\n\t// must be a prefix of the edit's replace range, that means it must be\n\t// contained and starting at the same position.\n\t//\n\t// @since 3.16.0 additional type `InsertReplaceEdit`\n\tTextEdit *Or_CompletionItem_textEdit `json:\"textEdit,omitempty\"`\n\t// The edit text used if the completion item is part of a CompletionList and\n\t// CompletionList defines an item default for the text edit range.\n\t//\n\t// Clients will only honor this property if they opt into completion list\n\t// item defaults using the capability `completionList.itemDefaults`.\n\t//\n\t// If not provided and a list's default range is provided the label\n\t// property is used as a text.\n\t//\n\t// @since 3.17.0\n\tTextEditText string `json:\"textEditText,omitempty\"`\n\t// An optional array of additional {@link TextEdit text edits} that are applied when\n\t// selecting this completion. Edits must not overlap (including the same insert position)\n\t// with the main {@link CompletionItem.textEdit edit} nor with themselves.\n\t//\n\t// Additional text edits should be used to change text unrelated to the current cursor position\n\t// (for example adding an import statement at the top of the file if the completion item will\n\t// insert an unqualified type).\n\tAdditionalTextEdits []TextEdit `json:\"additionalTextEdits,omitempty\"`\n\t// An optional set of characters that when pressed while this completion is active will accept it first and\n\t// then type that character. *Note* that all commit characters should have `length=1` and that superfluous\n\t// characters will be ignored.\n\tCommitCharacters []string `json:\"commitCharacters,omitempty\"`\n\t// An optional {@link Command command} that is executed *after* inserting this completion. *Note* that\n\t// additional modifications to the current document should be described with the\n\t// {@link CompletionItem.additionalTextEdits additionalTextEdits}-property.\n\tCommand *Command `json:\"command,omitempty\"`\n\t// A data entry field that is preserved on a completion item between a\n\t// {@link CompletionRequest} and a {@link CompletionResolveRequest}.\n\tData interface{} `json:\"data,omitempty\"`\n}\n\n// In many cases the items of an actual completion result share the same\n// value for properties like `commitCharacters` or the range of a text\n// edit. A completion list can therefore define item defaults which will\n// be used if a completion item itself doesn't specify the value.\n//\n// If a completion list specifies a default value and a completion item\n// also specifies a corresponding value the one from the item is used.\n//\n// Servers are only allowed to return default values if the client\n// signals support for this via the `completionList.itemDefaults`\n// capability.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#completionItemDefaults\ntype CompletionItemDefaults struct {\n\t// A default commit character set.\n\t//\n\t// @since 3.17.0\n\tCommitCharacters []string `json:\"commitCharacters,omitempty\"`\n\t// A default edit range.\n\t//\n\t// @since 3.17.0\n\tEditRange *Or_CompletionItemDefaults_editRange `json:\"editRange,omitempty\"`\n\t// A default insert text format.\n\t//\n\t// @since 3.17.0\n\tInsertTextFormat *InsertTextFormat `json:\"insertTextFormat,omitempty\"`\n\t// A default insert text mode.\n\t//\n\t// @since 3.17.0\n\tInsertTextMode *InsertTextMode `json:\"insertTextMode,omitempty\"`\n\t// A default data value.\n\t//\n\t// @since 3.17.0\n\tData interface{} `json:\"data,omitempty\"`\n}\n\n// The kind of a completion entry.\ntype CompletionItemKind uint32\n\n// Additional details for a completion item label.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#completionItemLabelDetails\ntype CompletionItemLabelDetails struct {\n\t// An optional string which is rendered less prominently directly after {@link CompletionItem.label label},\n\t// without any spacing. Should be used for function signatures and type annotations.\n\tDetail string `json:\"detail,omitempty\"`\n\t// An optional string which is rendered less prominently after {@link CompletionItem.detail}. Should be used\n\t// for fully qualified names and file paths.\n\tDescription string `json:\"description,omitempty\"`\n}\n\n// Completion item tags are extra annotations that tweak the rendering of a completion\n// item.\n//\n// @since 3.15.0\ntype CompletionItemTag uint32\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#completionItemTagOptions\ntype CompletionItemTagOptions struct {\n\t// The tags supported by the client.\n\tValueSet []CompletionItemTag `json:\"valueSet\"`\n}\n\n// Represents a collection of {@link CompletionItem completion items} to be presented\n// in the editor.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#completionList\ntype CompletionList struct {\n\t// This list it not complete. Further typing results in recomputing this list.\n\t//\n\t// Recomputed lists have all their items replaced (not appended) in the\n\t// incomplete completion sessions.\n\tIsIncomplete bool `json:\"isIncomplete\"`\n\t// In many cases the items of an actual completion result share the same\n\t// value for properties like `commitCharacters` or the range of a text\n\t// edit. A completion list can therefore define item defaults which will\n\t// be used if a completion item itself doesn't specify the value.\n\t//\n\t// If a completion list specifies a default value and a completion item\n\t// also specifies a corresponding value the one from the item is used.\n\t//\n\t// Servers are only allowed to return default values if the client\n\t// signals support for this via the `completionList.itemDefaults`\n\t// capability.\n\t//\n\t// @since 3.17.0\n\tItemDefaults *CompletionItemDefaults `json:\"itemDefaults,omitempty\"`\n\t// The completion items.\n\tItems []CompletionItem `json:\"items\"`\n}\n\n// The client supports the following `CompletionList` specific\n// capabilities.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#completionListCapabilities\ntype CompletionListCapabilities struct {\n\t// The client supports the following itemDefaults on\n\t// a completion list.\n\t//\n\t// The value lists the supported property names of the\n\t// `CompletionList.itemDefaults` object. If omitted\n\t// no properties are supported.\n\t//\n\t// @since 3.17.0\n\tItemDefaults []string `json:\"itemDefaults,omitempty\"`\n}\n\n// Completion options.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#completionOptions\ntype CompletionOptions struct {\n\t// Most tools trigger completion request automatically without explicitly requesting\n\t// it using a keyboard shortcut (e.g. Ctrl+Space). Typically they do so when the user\n\t// starts to type an identifier. For example if the user types `c` in a JavaScript file\n\t// code complete will automatically pop up present `console` besides others as a\n\t// completion item. Characters that make up identifiers don't need to be listed here.\n\t//\n\t// If code complete should automatically be trigger on characters not being valid inside\n\t// an identifier (for example `.` in JavaScript) list them in `triggerCharacters`.\n\tTriggerCharacters []string `json:\"triggerCharacters,omitempty\"`\n\t// The list of all possible characters that commit a completion. This field can be used\n\t// if clients don't support individual commit characters per completion item. See\n\t// `ClientCapabilities.textDocument.completion.completionItem.commitCharactersSupport`\n\t//\n\t// If a server provides both `allCommitCharacters` and commit characters on an individual\n\t// completion item the ones on the completion item win.\n\t//\n\t// @since 3.2.0\n\tAllCommitCharacters []string `json:\"allCommitCharacters,omitempty\"`\n\t// The server provides support to resolve additional\n\t// information for a completion item.\n\tResolveProvider bool `json:\"resolveProvider,omitempty\"`\n\t// The server supports the following `CompletionItem` specific\n\t// capabilities.\n\t//\n\t// @since 3.17.0\n\tCompletionItem *ServerCompletionItemOptions `json:\"completionItem,omitempty\"`\n\tWorkDoneProgressOptions\n}\n\n// Completion parameters\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#completionParams\ntype CompletionParams struct {\n\t// The completion context. This is only available it the client specifies\n\t// to send this using the client capability `textDocument.completion.contextSupport === true`\n\tContext CompletionContext `json:\"context,omitempty\"`\n\tTextDocumentPositionParams\n\tWorkDoneProgressParams\n\tPartialResultParams\n}\n\n// Registration options for a {@link CompletionRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#completionRegistrationOptions\ntype CompletionRegistrationOptions struct {\n\tTextDocumentRegistrationOptions\n\tCompletionOptions\n}\n\n// How a completion was triggered\ntype CompletionTriggerKind uint32\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#configurationItem\ntype ConfigurationItem struct {\n\t// The scope to get the configuration section for.\n\tScopeURI *URI `json:\"scopeUri,omitempty\"`\n\t// The configuration section asked for.\n\tSection string `json:\"section,omitempty\"`\n}\n\n// The parameters of a configuration request.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#configurationParams\ntype ConfigurationParams struct {\n\tItems []ConfigurationItem `json:\"items\"`\n}\n\n// Create file operation.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#createFile\ntype CreateFile struct {\n\t// A create\n\tKind string `json:\"kind\"`\n\t// The resource to create.\n\tURI DocumentUri `json:\"uri\"`\n\t// Additional options\n\tOptions *CreateFileOptions `json:\"options,omitempty\"`\n\tResourceOperation\n}\n\n// Options to create a file.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#createFileOptions\ntype CreateFileOptions struct {\n\t// Overwrite existing file. Overwrite wins over `ignoreIfExists`\n\tOverwrite bool `json:\"overwrite,omitempty\"`\n\t// Ignore if exists.\n\tIgnoreIfExists bool `json:\"ignoreIfExists,omitempty\"`\n}\n\n// The parameters sent in notifications/requests for user-initiated creation of\n// files.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#createFilesParams\ntype CreateFilesParams struct {\n\t// An array of all files/folders created in this operation.\n\tFiles []FileCreate `json:\"files\"`\n}\n\n// The declaration of a symbol representation as one or many {@link Location locations}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#declaration\ntype Declaration = Or_Declaration // (alias)\n// @since 3.14.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#declarationClientCapabilities\ntype DeclarationClientCapabilities struct {\n\t// Whether declaration supports dynamic registration. If this is set to `true`\n\t// the client supports the new `DeclarationRegistrationOptions` return value\n\t// for the corresponding server capability as well.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n\t// The client supports additional metadata in the form of declaration links.\n\tLinkSupport bool `json:\"linkSupport,omitempty\"`\n}\n\n// Information about where a symbol is declared.\n//\n// Provides additional metadata over normal {@link Location location} declarations, including the range of\n// the declaring symbol.\n//\n// Servers should prefer returning `DeclarationLink` over `Declaration` if supported\n// by the client.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#declarationLink\ntype DeclarationLink = LocationLink // (alias)\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#declarationOptions\ntype DeclarationOptions struct {\n\tWorkDoneProgressOptions\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#declarationParams\ntype DeclarationParams struct {\n\tTextDocumentPositionParams\n\tWorkDoneProgressParams\n\tPartialResultParams\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#declarationRegistrationOptions\ntype DeclarationRegistrationOptions struct {\n\tDeclarationOptions\n\tTextDocumentRegistrationOptions\n\tStaticRegistrationOptions\n}\n\n// The definition of a symbol represented as one or many {@link Location locations}.\n// For most programming languages there is only one location at which a symbol is\n// defined.\n//\n// Servers should prefer returning `DefinitionLink` over `Definition` if supported\n// by the client.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#definition\ntype Definition = Or_Definition // (alias)\n// Client Capabilities for a {@link DefinitionRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#definitionClientCapabilities\ntype DefinitionClientCapabilities struct {\n\t// Whether definition supports dynamic registration.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n\t// The client supports additional metadata in the form of definition links.\n\t//\n\t// @since 3.14.0\n\tLinkSupport bool `json:\"linkSupport,omitempty\"`\n}\n\n// Information about where a symbol is defined.\n//\n// Provides additional metadata over normal {@link Location location} definitions, including the range of\n// the defining symbol\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#definitionLink\ntype DefinitionLink = LocationLink // (alias)\n// Server Capabilities for a {@link DefinitionRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#definitionOptions\ntype DefinitionOptions struct {\n\tWorkDoneProgressOptions\n}\n\n// Parameters for a {@link DefinitionRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#definitionParams\ntype DefinitionParams struct {\n\tTextDocumentPositionParams\n\tWorkDoneProgressParams\n\tPartialResultParams\n}\n\n// Registration options for a {@link DefinitionRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#definitionRegistrationOptions\ntype DefinitionRegistrationOptions struct {\n\tTextDocumentRegistrationOptions\n\tDefinitionOptions\n}\n\n// Delete file operation\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#deleteFile\ntype DeleteFile struct {\n\t// A delete\n\tKind string `json:\"kind\"`\n\t// The file to delete.\n\tURI DocumentUri `json:\"uri\"`\n\t// Delete options.\n\tOptions *DeleteFileOptions `json:\"options,omitempty\"`\n\tResourceOperation\n}\n\n// Delete file options\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#deleteFileOptions\ntype DeleteFileOptions struct {\n\t// Delete the content recursively if a folder is denoted.\n\tRecursive bool `json:\"recursive,omitempty\"`\n\t// Ignore the operation if the file doesn't exist.\n\tIgnoreIfNotExists bool `json:\"ignoreIfNotExists,omitempty\"`\n}\n\n// The parameters sent in notifications/requests for user-initiated deletes of\n// files.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#deleteFilesParams\ntype DeleteFilesParams struct {\n\t// An array of all files/folders deleted in this operation.\n\tFiles []FileDelete `json:\"files\"`\n}\n\n// Represents a diagnostic, such as a compiler error or warning. Diagnostic objects\n// are only valid in the scope of a resource.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#diagnostic\ntype Diagnostic struct {\n\t// The range at which the message applies\n\tRange Range `json:\"range\"`\n\t// The diagnostic's severity. To avoid interpretation mismatches when a\n\t// server is used with different clients it is highly recommended that servers\n\t// always provide a severity value.\n\tSeverity DiagnosticSeverity `json:\"severity,omitempty\"`\n\t// The diagnostic's code, which usually appear in the user interface.\n\tCode interface{} `json:\"code,omitempty\"`\n\t// An optional property to describe the error code.\n\t// Requires the code field (above) to be present/not null.\n\t//\n\t// @since 3.16.0\n\tCodeDescription *CodeDescription `json:\"codeDescription,omitempty\"`\n\t// A human-readable string describing the source of this\n\t// diagnostic, e.g. 'typescript' or 'super lint'. It usually\n\t// appears in the user interface.\n\tSource string `json:\"source,omitempty\"`\n\t// The diagnostic's message. It usually appears in the user interface\n\tMessage string `json:\"message\"`\n\t// Additional metadata about the diagnostic.\n\t//\n\t// @since 3.15.0\n\tTags []DiagnosticTag `json:\"tags,omitempty\"`\n\t// An array of related diagnostic information, e.g. when symbol-names within\n\t// a scope collide all definitions can be marked via this property.\n\tRelatedInformation []DiagnosticRelatedInformation `json:\"relatedInformation,omitempty\"`\n\t// A data entry field that is preserved between a `textDocument/publishDiagnostics`\n\t// notification and `textDocument/codeAction` request.\n\t//\n\t// @since 3.16.0\n\tData *json.RawMessage `json:\"data,omitempty\"`\n}\n\n// Client capabilities specific to diagnostic pull requests.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#diagnosticClientCapabilities\ntype DiagnosticClientCapabilities struct {\n\t// Whether implementation supports dynamic registration. If this is set to `true`\n\t// the client supports the new `(TextDocumentRegistrationOptions & StaticRegistrationOptions)`\n\t// return value for the corresponding server capability as well.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n\t// Whether the clients supports related documents for document diagnostic pulls.\n\tRelatedDocumentSupport bool `json:\"relatedDocumentSupport,omitempty\"`\n\tDiagnosticsCapabilities\n}\n\n// Diagnostic options.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#diagnosticOptions\ntype DiagnosticOptions struct {\n\t// An optional identifier under which the diagnostics are\n\t// managed by the client.\n\tIdentifier string `json:\"identifier,omitempty\"`\n\t// Whether the language has inter file dependencies meaning that\n\t// editing code in one file can result in a different diagnostic\n\t// set in another file. Inter file dependencies are common for\n\t// most programming languages and typically uncommon for linters.\n\tInterFileDependencies bool `json:\"interFileDependencies\"`\n\t// The server provides support for workspace diagnostics as well.\n\tWorkspaceDiagnostics bool `json:\"workspaceDiagnostics\"`\n\tWorkDoneProgressOptions\n}\n\n// Diagnostic registration options.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#diagnosticRegistrationOptions\ntype DiagnosticRegistrationOptions struct {\n\tTextDocumentRegistrationOptions\n\tDiagnosticOptions\n\tStaticRegistrationOptions\n}\n\n// Represents a related message and source code location for a diagnostic. This should be\n// used to point to code locations that cause or related to a diagnostics, e.g when duplicating\n// a symbol in a scope.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#diagnosticRelatedInformation\ntype DiagnosticRelatedInformation struct {\n\t// The location of this related diagnostic information.\n\tLocation Location `json:\"location\"`\n\t// The message of this related diagnostic information.\n\tMessage string `json:\"message\"`\n}\n\n// Cancellation data returned from a diagnostic request.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#diagnosticServerCancellationData\ntype DiagnosticServerCancellationData struct {\n\tRetriggerRequest bool `json:\"retriggerRequest\"`\n}\n\n// The diagnostic's severity.\ntype DiagnosticSeverity uint32\n\n// The diagnostic tags.\n//\n// @since 3.15.0\ntype DiagnosticTag uint32\n\n// Workspace client capabilities specific to diagnostic pull requests.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#diagnosticWorkspaceClientCapabilities\ntype DiagnosticWorkspaceClientCapabilities struct {\n\t// Whether the client implementation supports a refresh request sent from\n\t// the server to the client.\n\t//\n\t// Note that this event is global and will force the client to refresh all\n\t// pulled diagnostics currently shown. It should be used with absolute care and\n\t// is useful for situation where a server for example detects a project wide\n\t// change that requires such a calculation.\n\tRefreshSupport bool `json:\"refreshSupport,omitempty\"`\n}\n\n// General diagnostics capabilities for pull and push model.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#diagnosticsCapabilities\ntype DiagnosticsCapabilities struct {\n\t// Whether the clients accepts diagnostics with related information.\n\tRelatedInformation bool `json:\"relatedInformation,omitempty\"`\n\t// Client supports the tag property to provide meta data about a diagnostic.\n\t// Clients supporting tags have to handle unknown tags gracefully.\n\t//\n\t// @since 3.15.0\n\tTagSupport *ClientDiagnosticsTagOptions `json:\"tagSupport,omitempty\"`\n\t// Client supports a codeDescription property\n\t//\n\t// @since 3.16.0\n\tCodeDescriptionSupport bool `json:\"codeDescriptionSupport,omitempty\"`\n\t// Whether code action supports the `data` property which is\n\t// preserved between a `textDocument/publishDiagnostics` and\n\t// `textDocument/codeAction` request.\n\t//\n\t// @since 3.16.0\n\tDataSupport bool `json:\"dataSupport,omitempty\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#didChangeConfigurationClientCapabilities\ntype DidChangeConfigurationClientCapabilities struct {\n\t// Did change configuration notification supports dynamic registration.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n}\n\n// The parameters of a change configuration notification.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#didChangeConfigurationParams\ntype DidChangeConfigurationParams struct {\n\t// The actual changed settings\n\tSettings interface{} `json:\"settings\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#didChangeConfigurationRegistrationOptions\ntype DidChangeConfigurationRegistrationOptions struct {\n\tSection *Or_DidChangeConfigurationRegistrationOptions_section `json:\"section,omitempty\"`\n}\n\n// The params sent in a change notebook document notification.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#didChangeNotebookDocumentParams\ntype DidChangeNotebookDocumentParams struct {\n\t// The notebook document that did change. The version number points\n\t// to the version after all provided changes have been applied. If\n\t// only the text document content of a cell changes the notebook version\n\t// doesn't necessarily have to change.\n\tNotebookDocument VersionedNotebookDocumentIdentifier `json:\"notebookDocument\"`\n\t// The actual changes to the notebook document.\n\t//\n\t// The changes describe single state changes to the notebook document.\n\t// So if there are two changes c1 (at array index 0) and c2 (at array\n\t// index 1) for a notebook in state S then c1 moves the notebook from\n\t// S to S' and c2 from S' to S''. So c1 is computed on the state S and\n\t// c2 is computed on the state S'.\n\t//\n\t// To mirror the content of a notebook using change events use the following approach:\n\t//\n\t// - start with the same initial content\n\t// - apply the 'notebookDocument/didChange' notifications in the order you receive them.\n\t// - apply the `NotebookChangeEvent`s in a single notification in the order\n\t// you receive them.\n\tChange NotebookDocumentChangeEvent `json:\"change\"`\n}\n\n// The change text document notification's parameters.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#didChangeTextDocumentParams\ntype DidChangeTextDocumentParams struct {\n\t// The document that did change. The version number points\n\t// to the version after all provided content changes have\n\t// been applied.\n\tTextDocument VersionedTextDocumentIdentifier `json:\"textDocument\"`\n\t// The actual content changes. The content changes describe single state changes\n\t// to the document. So if there are two content changes c1 (at array index 0) and\n\t// c2 (at array index 1) for a document in state S then c1 moves the document from\n\t// S to S' and c2 from S' to S''. So c1 is computed on the state S and c2 is computed\n\t// on the state S'.\n\t//\n\t// To mirror the content of a document using change events use the following approach:\n\t//\n\t// - start with the same initial content\n\t// - apply the 'textDocument/didChange' notifications in the order you receive them.\n\t// - apply the `TextDocumentContentChangeEvent`s in a single notification in the order\n\t// you receive them.\n\tContentChanges []TextDocumentContentChangeEvent `json:\"contentChanges\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#didChangeWatchedFilesClientCapabilities\ntype DidChangeWatchedFilesClientCapabilities struct {\n\t// Did change watched files notification supports dynamic registration. Please note\n\t// that the current protocol doesn't support static configuration for file changes\n\t// from the server side.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n\t// Whether the client has support for {@link RelativePattern relative pattern}\n\t// or not.\n\t//\n\t// @since 3.17.0\n\tRelativePatternSupport bool `json:\"relativePatternSupport,omitempty\"`\n}\n\n// The watched files change notification's parameters.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#didChangeWatchedFilesParams\ntype DidChangeWatchedFilesParams struct {\n\t// The actual file events.\n\tChanges []FileEvent `json:\"changes\"`\n}\n\n// Describe options to be used when registered for text document change events.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#didChangeWatchedFilesRegistrationOptions\ntype DidChangeWatchedFilesRegistrationOptions struct {\n\t// The watchers to register.\n\tWatchers []FileSystemWatcher `json:\"watchers\"`\n}\n\n// The parameters of a `workspace/didChangeWorkspaceFolders` notification.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#didChangeWorkspaceFoldersParams\ntype DidChangeWorkspaceFoldersParams struct {\n\t// The actual workspace folder change event.\n\tEvent WorkspaceFoldersChangeEvent `json:\"event\"`\n}\n\n// The params sent in a close notebook document notification.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#didCloseNotebookDocumentParams\ntype DidCloseNotebookDocumentParams struct {\n\t// The notebook document that got closed.\n\tNotebookDocument NotebookDocumentIdentifier `json:\"notebookDocument\"`\n\t// The text documents that represent the content\n\t// of a notebook cell that got closed.\n\tCellTextDocuments []TextDocumentIdentifier `json:\"cellTextDocuments\"`\n}\n\n// The parameters sent in a close text document notification\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#didCloseTextDocumentParams\ntype DidCloseTextDocumentParams struct {\n\t// The document that was closed.\n\tTextDocument TextDocumentIdentifier `json:\"textDocument\"`\n}\n\n// The params sent in an open notebook document notification.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#didOpenNotebookDocumentParams\ntype DidOpenNotebookDocumentParams struct {\n\t// The notebook document that got opened.\n\tNotebookDocument NotebookDocument `json:\"notebookDocument\"`\n\t// The text documents that represent the content\n\t// of a notebook cell.\n\tCellTextDocuments []TextDocumentItem `json:\"cellTextDocuments\"`\n}\n\n// The parameters sent in an open text document notification\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#didOpenTextDocumentParams\ntype DidOpenTextDocumentParams struct {\n\t// The document that was opened.\n\tTextDocument TextDocumentItem `json:\"textDocument\"`\n}\n\n// The params sent in a save notebook document notification.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#didSaveNotebookDocumentParams\ntype DidSaveNotebookDocumentParams struct {\n\t// The notebook document that got saved.\n\tNotebookDocument NotebookDocumentIdentifier `json:\"notebookDocument\"`\n}\n\n// The parameters sent in a save text document notification\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#didSaveTextDocumentParams\ntype DidSaveTextDocumentParams struct {\n\t// The document that was saved.\n\tTextDocument TextDocumentIdentifier `json:\"textDocument\"`\n\t// Optional the content when saved. Depends on the includeText value\n\t// when the save notification was requested.\n\tText *string `json:\"text,omitempty\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentColorClientCapabilities\ntype DocumentColorClientCapabilities struct {\n\t// Whether implementation supports dynamic registration. If this is set to `true`\n\t// the client supports the new `DocumentColorRegistrationOptions` return value\n\t// for the corresponding server capability as well.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentColorOptions\ntype DocumentColorOptions struct {\n\tWorkDoneProgressOptions\n}\n\n// Parameters for a {@link DocumentColorRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentColorParams\ntype DocumentColorParams struct {\n\t// The text document.\n\tTextDocument TextDocumentIdentifier `json:\"textDocument\"`\n\tWorkDoneProgressParams\n\tPartialResultParams\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentColorRegistrationOptions\ntype DocumentColorRegistrationOptions struct {\n\tTextDocumentRegistrationOptions\n\tDocumentColorOptions\n\tStaticRegistrationOptions\n}\n\n// Parameters of the document diagnostic request.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentDiagnosticParams\ntype DocumentDiagnosticParams struct {\n\t// The text document.\n\tTextDocument TextDocumentIdentifier `json:\"textDocument\"`\n\t// The additional identifier provided during registration.\n\tIdentifier string `json:\"identifier,omitempty\"`\n\t// The result id of a previous response if provided.\n\tPreviousResultID string `json:\"previousResultId,omitempty\"`\n\tWorkDoneProgressParams\n\tPartialResultParams\n}\n\n// The result of a document diagnostic pull request. A report can\n// either be a full report containing all diagnostics for the\n// requested document or an unchanged report indicating that nothing\n// has changed in terms of diagnostics in comparison to the last\n// pull request.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentDiagnosticReport\ntype DocumentDiagnosticReport = Or_DocumentDiagnosticReport // (alias)\n// The document diagnostic report kinds.\n//\n// @since 3.17.0\ntype DocumentDiagnosticReportKind string\n\n// A partial result for a document diagnostic report.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentDiagnosticReportPartialResult\ntype DocumentDiagnosticReportPartialResult struct {\n\tRelatedDocuments map[DocumentUri]interface{} `json:\"relatedDocuments\"`\n}\n\n// A document filter describes a top level text document or\n// a notebook cell document.\n//\n// @since 3.17.0 - proposed support for NotebookCellTextDocumentFilter.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentFilter\ntype DocumentFilter = Or_DocumentFilter // (alias)\n// Client capabilities of a {@link DocumentFormattingRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentFormattingClientCapabilities\ntype DocumentFormattingClientCapabilities struct {\n\t// Whether formatting supports dynamic registration.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n}\n\n// Provider options for a {@link DocumentFormattingRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentFormattingOptions\ntype DocumentFormattingOptions struct {\n\tWorkDoneProgressOptions\n}\n\n// The parameters of a {@link DocumentFormattingRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentFormattingParams\ntype DocumentFormattingParams struct {\n\t// The document to format.\n\tTextDocument TextDocumentIdentifier `json:\"textDocument\"`\n\t// The format options.\n\tOptions FormattingOptions `json:\"options\"`\n\tWorkDoneProgressParams\n}\n\n// Registration options for a {@link DocumentFormattingRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentFormattingRegistrationOptions\ntype DocumentFormattingRegistrationOptions struct {\n\tTextDocumentRegistrationOptions\n\tDocumentFormattingOptions\n}\n\n// A document highlight is a range inside a text document which deserves\n// special attention. Usually a document highlight is visualized by changing\n// the background color of its range.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentHighlight\ntype DocumentHighlight struct {\n\t// The range this highlight applies to.\n\tRange Range `json:\"range\"`\n\t// The highlight kind, default is {@link DocumentHighlightKind.Text text}.\n\tKind DocumentHighlightKind `json:\"kind,omitempty\"`\n}\n\n// Client Capabilities for a {@link DocumentHighlightRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentHighlightClientCapabilities\ntype DocumentHighlightClientCapabilities struct {\n\t// Whether document highlight supports dynamic registration.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n}\n\n// A document highlight kind.\ntype DocumentHighlightKind uint32\n\n// Provider options for a {@link DocumentHighlightRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentHighlightOptions\ntype DocumentHighlightOptions struct {\n\tWorkDoneProgressOptions\n}\n\n// Parameters for a {@link DocumentHighlightRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentHighlightParams\ntype DocumentHighlightParams struct {\n\tTextDocumentPositionParams\n\tWorkDoneProgressParams\n\tPartialResultParams\n}\n\n// Registration options for a {@link DocumentHighlightRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentHighlightRegistrationOptions\ntype DocumentHighlightRegistrationOptions struct {\n\tTextDocumentRegistrationOptions\n\tDocumentHighlightOptions\n}\n\n// A document link is a range in a text document that links to an internal or external resource, like another\n// text document or a web site.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentLink\ntype DocumentLink struct {\n\t// The range this link applies to.\n\tRange Range `json:\"range\"`\n\t// The uri this link points to. If missing a resolve request is sent later.\n\tTarget *URI `json:\"target,omitempty\"`\n\t// The tooltip text when you hover over this link.\n\t//\n\t// If a tooltip is provided, is will be displayed in a string that includes instructions on how to\n\t// trigger the link, such as `{0} (ctrl + click)`. The specific instructions vary depending on OS,\n\t// user settings, and localization.\n\t//\n\t// @since 3.15.0\n\tTooltip string `json:\"tooltip,omitempty\"`\n\t// A data entry field that is preserved on a document link between a\n\t// DocumentLinkRequest and a DocumentLinkResolveRequest.\n\tData interface{} `json:\"data,omitempty\"`\n}\n\n// The client capabilities of a {@link DocumentLinkRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentLinkClientCapabilities\ntype DocumentLinkClientCapabilities struct {\n\t// Whether document link supports dynamic registration.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n\t// Whether the client supports the `tooltip` property on `DocumentLink`.\n\t//\n\t// @since 3.15.0\n\tTooltipSupport bool `json:\"tooltipSupport,omitempty\"`\n}\n\n// Provider options for a {@link DocumentLinkRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentLinkOptions\ntype DocumentLinkOptions struct {\n\t// Document links have a resolve provider as well.\n\tResolveProvider bool `json:\"resolveProvider,omitempty\"`\n\tWorkDoneProgressOptions\n}\n\n// The parameters of a {@link DocumentLinkRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentLinkParams\ntype DocumentLinkParams struct {\n\t// The document to provide document links for.\n\tTextDocument TextDocumentIdentifier `json:\"textDocument\"`\n\tWorkDoneProgressParams\n\tPartialResultParams\n}\n\n// Registration options for a {@link DocumentLinkRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentLinkRegistrationOptions\ntype DocumentLinkRegistrationOptions struct {\n\tTextDocumentRegistrationOptions\n\tDocumentLinkOptions\n}\n\n// Client capabilities of a {@link DocumentOnTypeFormattingRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentOnTypeFormattingClientCapabilities\ntype DocumentOnTypeFormattingClientCapabilities struct {\n\t// Whether on type formatting supports dynamic registration.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n}\n\n// Provider options for a {@link DocumentOnTypeFormattingRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentOnTypeFormattingOptions\ntype DocumentOnTypeFormattingOptions struct {\n\t// A character on which formatting should be triggered, like `{`.\n\tFirstTriggerCharacter string `json:\"firstTriggerCharacter\"`\n\t// More trigger characters.\n\tMoreTriggerCharacter []string `json:\"moreTriggerCharacter,omitempty\"`\n}\n\n// The parameters of a {@link DocumentOnTypeFormattingRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentOnTypeFormattingParams\ntype DocumentOnTypeFormattingParams struct {\n\t// The document to format.\n\tTextDocument TextDocumentIdentifier `json:\"textDocument\"`\n\t// The position around which the on type formatting should happen.\n\t// This is not necessarily the exact position where the character denoted\n\t// by the property `ch` got typed.\n\tPosition Position `json:\"position\"`\n\t// The character that has been typed that triggered the formatting\n\t// on type request. That is not necessarily the last character that\n\t// got inserted into the document since the client could auto insert\n\t// characters as well (e.g. like automatic brace completion).\n\tCh string `json:\"ch\"`\n\t// The formatting options.\n\tOptions FormattingOptions `json:\"options\"`\n}\n\n// Registration options for a {@link DocumentOnTypeFormattingRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentOnTypeFormattingRegistrationOptions\ntype DocumentOnTypeFormattingRegistrationOptions struct {\n\tTextDocumentRegistrationOptions\n\tDocumentOnTypeFormattingOptions\n}\n\n// Client capabilities of a {@link DocumentRangeFormattingRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentRangeFormattingClientCapabilities\ntype DocumentRangeFormattingClientCapabilities struct {\n\t// Whether range formatting supports dynamic registration.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n\t// Whether the client supports formatting multiple ranges at once.\n\t//\n\t// @since 3.18.0\n\t// @proposed\n\tRangesSupport bool `json:\"rangesSupport,omitempty\"`\n}\n\n// Provider options for a {@link DocumentRangeFormattingRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentRangeFormattingOptions\ntype DocumentRangeFormattingOptions struct {\n\t// Whether the server supports formatting multiple ranges at once.\n\t//\n\t// @since 3.18.0\n\t// @proposed\n\tRangesSupport bool `json:\"rangesSupport,omitempty\"`\n\tWorkDoneProgressOptions\n}\n\n// The parameters of a {@link DocumentRangeFormattingRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentRangeFormattingParams\ntype DocumentRangeFormattingParams struct {\n\t// The document to format.\n\tTextDocument TextDocumentIdentifier `json:\"textDocument\"`\n\t// The range to format\n\tRange Range `json:\"range\"`\n\t// The format options\n\tOptions FormattingOptions `json:\"options\"`\n\tWorkDoneProgressParams\n}\n\n// Registration options for a {@link DocumentRangeFormattingRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentRangeFormattingRegistrationOptions\ntype DocumentRangeFormattingRegistrationOptions struct {\n\tTextDocumentRegistrationOptions\n\tDocumentRangeFormattingOptions\n}\n\n// The parameters of a {@link DocumentRangesFormattingRequest}.\n//\n// @since 3.18.0\n// @proposed\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentRangesFormattingParams\ntype DocumentRangesFormattingParams struct {\n\t// The document to format.\n\tTextDocument TextDocumentIdentifier `json:\"textDocument\"`\n\t// The ranges to format\n\tRanges []Range `json:\"ranges\"`\n\t// The format options\n\tOptions FormattingOptions `json:\"options\"`\n\tWorkDoneProgressParams\n}\n\n// A document selector is the combination of one or many document filters.\n//\n// @sample `let sel:DocumentSelector = [{ language: 'typescript' }, { language: 'json', pattern: '**∕tsconfig.json' }]`;\n//\n// The use of a string as a document filter is deprecated @since 3.16.0.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentSelector\ntype DocumentSelector = []DocumentFilter // (alias)\n// Represents programming constructs like variables, classes, interfaces etc.\n// that appear in a document. Document symbols can be hierarchical and they\n// have two ranges: one that encloses its definition and one that points to\n// its most interesting range, e.g. the range of an identifier.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentSymbol\ntype DocumentSymbol struct {\n\t// The name of this symbol. Will be displayed in the user interface and therefore must not be\n\t// an empty string or a string only consisting of white spaces.\n\tName string `json:\"name\"`\n\t// More detail for this symbol, e.g the signature of a function.\n\tDetail string `json:\"detail,omitempty\"`\n\t// The kind of this symbol.\n\tKind SymbolKind `json:\"kind\"`\n\t// Tags for this document symbol.\n\t//\n\t// @since 3.16.0\n\tTags []SymbolTag `json:\"tags,omitempty\"`\n\t// Indicates if this symbol is deprecated.\n\t//\n\t// @deprecated Use tags instead\n\tDeprecated bool `json:\"deprecated,omitempty\"`\n\t// The range enclosing this symbol not including leading/trailing whitespace but everything else\n\t// like comments. This information is typically used to determine if the clients cursor is\n\t// inside the symbol to reveal in the symbol in the UI.\n\tRange Range `json:\"range\"`\n\t// The range that should be selected and revealed when this symbol is being picked, e.g the name of a function.\n\t// Must be contained by the `range`.\n\tSelectionRange Range `json:\"selectionRange\"`\n\t// Children of this symbol, e.g. properties of a class.\n\tChildren []DocumentSymbol `json:\"children,omitempty\"`\n}\n\n// Client Capabilities for a {@link DocumentSymbolRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentSymbolClientCapabilities\ntype DocumentSymbolClientCapabilities struct {\n\t// Whether document symbol supports dynamic registration.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n\t// Specific capabilities for the `SymbolKind` in the\n\t// `textDocument/documentSymbol` request.\n\tSymbolKind *ClientSymbolKindOptions `json:\"symbolKind,omitempty\"`\n\t// The client supports hierarchical document symbols.\n\tHierarchicalDocumentSymbolSupport bool `json:\"hierarchicalDocumentSymbolSupport,omitempty\"`\n\t// The client supports tags on `SymbolInformation`. Tags are supported on\n\t// `DocumentSymbol` if `hierarchicalDocumentSymbolSupport` is set to true.\n\t// Clients supporting tags have to handle unknown tags gracefully.\n\t//\n\t// @since 3.16.0\n\tTagSupport *ClientSymbolTagOptions `json:\"tagSupport,omitempty\"`\n\t// The client supports an additional label presented in the UI when\n\t// registering a document symbol provider.\n\t//\n\t// @since 3.16.0\n\tLabelSupport bool `json:\"labelSupport,omitempty\"`\n}\n\n// Provider options for a {@link DocumentSymbolRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentSymbolOptions\ntype DocumentSymbolOptions struct {\n\t// A human-readable string that is shown when multiple outlines trees\n\t// are shown for the same document.\n\t//\n\t// @since 3.16.0\n\tLabel string `json:\"label,omitempty\"`\n\tWorkDoneProgressOptions\n}\n\n// Parameters for a {@link DocumentSymbolRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentSymbolParams\ntype DocumentSymbolParams struct {\n\t// The text document.\n\tTextDocument TextDocumentIdentifier `json:\"textDocument\"`\n\tWorkDoneProgressParams\n\tPartialResultParams\n}\n\n// Registration options for a {@link DocumentSymbolRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentSymbolRegistrationOptions\ntype DocumentSymbolRegistrationOptions struct {\n\tTextDocumentRegistrationOptions\n\tDocumentSymbolOptions\n}\n\n// Edit range variant that includes ranges for insert and replace operations.\n//\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#editRangeWithInsertReplace\ntype EditRangeWithInsertReplace struct {\n\tInsert Range `json:\"insert\"`\n\tReplace Range `json:\"replace\"`\n}\n\n// Predefined error codes.\ntype ErrorCodes int32\n\n// The client capabilities of a {@link ExecuteCommandRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#executeCommandClientCapabilities\ntype ExecuteCommandClientCapabilities struct {\n\t// Execute command supports dynamic registration.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n}\n\n// The server capabilities of a {@link ExecuteCommandRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#executeCommandOptions\ntype ExecuteCommandOptions struct {\n\t// The commands to be executed on the server\n\tCommands []string `json:\"commands\"`\n\tWorkDoneProgressOptions\n}\n\n// The parameters of a {@link ExecuteCommandRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#executeCommandParams\ntype ExecuteCommandParams struct {\n\t// The identifier of the actual command handler.\n\tCommand string `json:\"command\"`\n\t// Arguments that the command should be invoked with.\n\tArguments []json.RawMessage `json:\"arguments,omitempty\"`\n\tWorkDoneProgressParams\n}\n\n// Registration options for a {@link ExecuteCommandRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#executeCommandRegistrationOptions\ntype ExecuteCommandRegistrationOptions struct {\n\tExecuteCommandOptions\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#executionSummary\ntype ExecutionSummary struct {\n\t// A strict monotonically increasing value\n\t// indicating the execution order of a cell\n\t// inside a notebook.\n\tExecutionOrder uint32 `json:\"executionOrder\"`\n\t// Whether the execution was successful or\n\t// not if known by the client.\n\tSuccess bool `json:\"success,omitempty\"`\n}\ntype FailureHandlingKind string\n\n// The file event type\ntype FileChangeType uint32\n\n// Represents information on a file/folder create.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#fileCreate\ntype FileCreate struct {\n\t// A file:// URI for the location of the file/folder being created.\n\tURI string `json:\"uri\"`\n}\n\n// Represents information on a file/folder delete.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#fileDelete\ntype FileDelete struct {\n\t// A file:// URI for the location of the file/folder being deleted.\n\tURI string `json:\"uri\"`\n}\n\n// An event describing a file change.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#fileEvent\ntype FileEvent struct {\n\t// The file's uri.\n\tURI DocumentUri `json:\"uri\"`\n\t// The change type.\n\tType FileChangeType `json:\"type\"`\n}\n\n// Capabilities relating to events from file operations by the user in the client.\n//\n// These events do not come from the file system, they come from user operations\n// like renaming a file in the UI.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#fileOperationClientCapabilities\ntype FileOperationClientCapabilities struct {\n\t// Whether the client supports dynamic registration for file requests/notifications.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n\t// The client has support for sending didCreateFiles notifications.\n\tDidCreate bool `json:\"didCreate,omitempty\"`\n\t// The client has support for sending willCreateFiles requests.\n\tWillCreate bool `json:\"willCreate,omitempty\"`\n\t// The client has support for sending didRenameFiles notifications.\n\tDidRename bool `json:\"didRename,omitempty\"`\n\t// The client has support for sending willRenameFiles requests.\n\tWillRename bool `json:\"willRename,omitempty\"`\n\t// The client has support for sending didDeleteFiles notifications.\n\tDidDelete bool `json:\"didDelete,omitempty\"`\n\t// The client has support for sending willDeleteFiles requests.\n\tWillDelete bool `json:\"willDelete,omitempty\"`\n}\n\n// A filter to describe in which file operation requests or notifications\n// the server is interested in receiving.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#fileOperationFilter\ntype FileOperationFilter struct {\n\t// A Uri scheme like `file` or `untitled`.\n\tScheme string `json:\"scheme,omitempty\"`\n\t// The actual file operation pattern.\n\tPattern FileOperationPattern `json:\"pattern\"`\n}\n\n// Options for notifications/requests for user operations on files.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#fileOperationOptions\ntype FileOperationOptions struct {\n\t// The server is interested in receiving didCreateFiles notifications.\n\tDidCreate *FileOperationRegistrationOptions `json:\"didCreate,omitempty\"`\n\t// The server is interested in receiving willCreateFiles requests.\n\tWillCreate *FileOperationRegistrationOptions `json:\"willCreate,omitempty\"`\n\t// The server is interested in receiving didRenameFiles notifications.\n\tDidRename *FileOperationRegistrationOptions `json:\"didRename,omitempty\"`\n\t// The server is interested in receiving willRenameFiles requests.\n\tWillRename *FileOperationRegistrationOptions `json:\"willRename,omitempty\"`\n\t// The server is interested in receiving didDeleteFiles file notifications.\n\tDidDelete *FileOperationRegistrationOptions `json:\"didDelete,omitempty\"`\n\t// The server is interested in receiving willDeleteFiles file requests.\n\tWillDelete *FileOperationRegistrationOptions `json:\"willDelete,omitempty\"`\n}\n\n// A pattern to describe in which file operation requests or notifications\n// the server is interested in receiving.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#fileOperationPattern\ntype FileOperationPattern struct {\n\t// The glob pattern to match. Glob patterns can have the following syntax:\n\t//\n\t// - `*` to match one or more characters in a path segment\n\t// - `?` to match on one character in a path segment\n\t// - `**` to match any number of path segments, including none\n\t// - `{}` to group sub patterns into an OR expression. (e.g. `**/*.{ts,js}` matches all TypeScript and JavaScript files)\n\t// - `[]` to declare a range of characters to match in a path segment (e.g., `example.[0-9]` to match on `example.0`, `example.1`, …)\n\t// - `[!...]` to negate a range of characters to match in a path segment (e.g., `example.[!0-9]` to match on `example.a`, `example.b`, but not `example.0`)\n\tGlob string `json:\"glob\"`\n\t// Whether to match files or folders with this pattern.\n\t//\n\t// Matches both if undefined.\n\tMatches *FileOperationPatternKind `json:\"matches,omitempty\"`\n\t// Additional options used during matching.\n\tOptions *FileOperationPatternOptions `json:\"options,omitempty\"`\n}\n\n// A pattern kind describing if a glob pattern matches a file a folder or\n// both.\n//\n// @since 3.16.0\ntype FileOperationPatternKind string\n\n// Matching options for the file operation pattern.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#fileOperationPatternOptions\ntype FileOperationPatternOptions struct {\n\t// The pattern should be matched ignoring casing.\n\tIgnoreCase bool `json:\"ignoreCase,omitempty\"`\n}\n\n// The options to register for file operations.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#fileOperationRegistrationOptions\ntype FileOperationRegistrationOptions struct {\n\t// The actual filters.\n\tFilters []FileOperationFilter `json:\"filters\"`\n}\n\n// Represents information on a file/folder rename.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#fileRename\ntype FileRename struct {\n\t// A file:// URI for the original location of the file/folder being renamed.\n\tOldURI string `json:\"oldUri\"`\n\t// A file:// URI for the new location of the file/folder being renamed.\n\tNewURI string `json:\"newUri\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#fileSystemWatcher\ntype FileSystemWatcher struct {\n\t// The glob pattern to watch. See {@link GlobPattern glob pattern} for more detail.\n\t//\n\t// @since 3.17.0 support for relative patterns.\n\tGlobPattern GlobPattern `json:\"globPattern\"`\n\t// The kind of events of interest. If omitted it defaults\n\t// to WatchKind.Create | WatchKind.Change | WatchKind.Delete\n\t// which is 7.\n\tKind *WatchKind `json:\"kind,omitempty\"`\n}\n\n// Represents a folding range. To be valid, start and end line must be bigger than zero and smaller\n// than the number of lines in the document. Clients are free to ignore invalid ranges.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#foldingRange\ntype FoldingRange struct {\n\t// The zero-based start line of the range to fold. The folded area starts after the line's last character.\n\t// To be valid, the end must be zero or larger and smaller than the number of lines in the document.\n\tStartLine uint32 `json:\"startLine\"`\n\t// The zero-based character offset from where the folded range starts. If not defined, defaults to the length of the start line.\n\tStartCharacter uint32 `json:\"startCharacter,omitempty\"`\n\t// The zero-based end line of the range to fold. The folded area ends with the line's last character.\n\t// To be valid, the end must be zero or larger and smaller than the number of lines in the document.\n\tEndLine uint32 `json:\"endLine\"`\n\t// The zero-based character offset before the folded range ends. If not defined, defaults to the length of the end line.\n\tEndCharacter uint32 `json:\"endCharacter,omitempty\"`\n\t// Describes the kind of the folding range such as 'comment' or 'region'. The kind\n\t// is used to categorize folding ranges and used by commands like 'Fold all comments'.\n\t// See {@link FoldingRangeKind} for an enumeration of standardized kinds.\n\tKind string `json:\"kind,omitempty\"`\n\t// The text that the client should show when the specified range is\n\t// collapsed. If not defined or not supported by the client, a default\n\t// will be chosen by the client.\n\t//\n\t// @since 3.17.0\n\tCollapsedText string `json:\"collapsedText,omitempty\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#foldingRangeClientCapabilities\ntype FoldingRangeClientCapabilities struct {\n\t// Whether implementation supports dynamic registration for folding range\n\t// providers. If this is set to `true` the client supports the new\n\t// `FoldingRangeRegistrationOptions` return value for the corresponding\n\t// server capability as well.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n\t// The maximum number of folding ranges that the client prefers to receive\n\t// per document. The value serves as a hint, servers are free to follow the\n\t// limit.\n\tRangeLimit uint32 `json:\"rangeLimit,omitempty\"`\n\t// If set, the client signals that it only supports folding complete lines.\n\t// If set, client will ignore specified `startCharacter` and `endCharacter`\n\t// properties in a FoldingRange.\n\tLineFoldingOnly bool `json:\"lineFoldingOnly,omitempty\"`\n\t// Specific options for the folding range kind.\n\t//\n\t// @since 3.17.0\n\tFoldingRangeKind *ClientFoldingRangeKindOptions `json:\"foldingRangeKind,omitempty\"`\n\t// Specific options for the folding range.\n\t//\n\t// @since 3.17.0\n\tFoldingRange *ClientFoldingRangeOptions `json:\"foldingRange,omitempty\"`\n}\n\n// A set of predefined range kinds.\ntype FoldingRangeKind string\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#foldingRangeOptions\ntype FoldingRangeOptions struct {\n\tWorkDoneProgressOptions\n}\n\n// Parameters for a {@link FoldingRangeRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#foldingRangeParams\ntype FoldingRangeParams struct {\n\t// The text document.\n\tTextDocument TextDocumentIdentifier `json:\"textDocument\"`\n\tWorkDoneProgressParams\n\tPartialResultParams\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#foldingRangeRegistrationOptions\ntype FoldingRangeRegistrationOptions struct {\n\tTextDocumentRegistrationOptions\n\tFoldingRangeOptions\n\tStaticRegistrationOptions\n}\n\n// Client workspace capabilities specific to folding ranges\n//\n// @since 3.18.0\n// @proposed\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#foldingRangeWorkspaceClientCapabilities\ntype FoldingRangeWorkspaceClientCapabilities struct {\n\t// Whether the client implementation supports a refresh request sent from the\n\t// server to the client.\n\t//\n\t// Note that this event is global and will force the client to refresh all\n\t// folding ranges currently shown. It should be used with absolute care and is\n\t// useful for situation where a server for example detects a project wide\n\t// change that requires such a calculation.\n\t//\n\t// @since 3.18.0\n\t// @proposed\n\tRefreshSupport bool `json:\"refreshSupport,omitempty\"`\n}\n\n// Value-object describing what options formatting should use.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#formattingOptions\ntype FormattingOptions struct {\n\t// Size of a tab in spaces.\n\tTabSize uint32 `json:\"tabSize\"`\n\t// Prefer spaces over tabs.\n\tInsertSpaces bool `json:\"insertSpaces\"`\n\t// Trim trailing whitespace on a line.\n\t//\n\t// @since 3.15.0\n\tTrimTrailingWhitespace bool `json:\"trimTrailingWhitespace,omitempty\"`\n\t// Insert a newline character at the end of the file if one does not exist.\n\t//\n\t// @since 3.15.0\n\tInsertFinalNewline bool `json:\"insertFinalNewline,omitempty\"`\n\t// Trim all newlines after the final newline at the end of the file.\n\t//\n\t// @since 3.15.0\n\tTrimFinalNewlines bool `json:\"trimFinalNewlines,omitempty\"`\n}\n\n// A diagnostic report with a full set of problems.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#fullDocumentDiagnosticReport\ntype FullDocumentDiagnosticReport struct {\n\t// A full document diagnostic report.\n\tKind string `json:\"kind\"`\n\t// An optional result id. If provided it will\n\t// be sent on the next diagnostic request for the\n\t// same document.\n\tResultID string `json:\"resultId,omitempty\"`\n\t// The actual items.\n\tItems []Diagnostic `json:\"items\"`\n}\n\n// General client capabilities.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#generalClientCapabilities\ntype GeneralClientCapabilities struct {\n\t// Client capability that signals how the client\n\t// handles stale requests (e.g. a request\n\t// for which the client will not process the response\n\t// anymore since the information is outdated).\n\t//\n\t// @since 3.17.0\n\tStaleRequestSupport *StaleRequestSupportOptions `json:\"staleRequestSupport,omitempty\"`\n\t// Client capabilities specific to regular expressions.\n\t//\n\t// @since 3.16.0\n\tRegularExpressions *RegularExpressionsClientCapabilities `json:\"regularExpressions,omitempty\"`\n\t// Client capabilities specific to the client's markdown parser.\n\t//\n\t// @since 3.16.0\n\tMarkdown *MarkdownClientCapabilities `json:\"markdown,omitempty\"`\n\t// The position encodings supported by the client. Client and server\n\t// have to agree on the same position encoding to ensure that offsets\n\t// (e.g. character position in a line) are interpreted the same on both\n\t// sides.\n\t//\n\t// To keep the protocol backwards compatible the following applies: if\n\t// the value 'utf-16' is missing from the array of position encodings\n\t// servers can assume that the client supports UTF-16. UTF-16 is\n\t// therefore a mandatory encoding.\n\t//\n\t// If omitted it defaults to ['utf-16'].\n\t//\n\t// Implementation considerations: since the conversion from one encoding\n\t// into another requires the content of the file / line the conversion\n\t// is best done where the file is read which is usually on the server\n\t// side.\n\t//\n\t// @since 3.17.0\n\tPositionEncodings []PositionEncodingKind `json:\"positionEncodings,omitempty\"`\n}\n\n// The glob pattern. Either a string pattern or a relative pattern.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#globPattern\ntype GlobPattern = Or_GlobPattern // (alias)\n// The result of a hover request.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#hover\ntype Hover struct {\n\t// The hover's content\n\tContents MarkupContent `json:\"contents\"`\n\t// An optional range inside the text document that is used to\n\t// visualize the hover, e.g. by changing the background color.\n\tRange Range `json:\"range,omitempty\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#hoverClientCapabilities\ntype HoverClientCapabilities struct {\n\t// Whether hover supports dynamic registration.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n\t// Client supports the following content formats for the content\n\t// property. The order describes the preferred format of the client.\n\tContentFormat []MarkupKind `json:\"contentFormat,omitempty\"`\n}\n\n// Hover options.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#hoverOptions\ntype HoverOptions struct {\n\tWorkDoneProgressOptions\n}\n\n// Parameters for a {@link HoverRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#hoverParams\ntype HoverParams struct {\n\tTextDocumentPositionParams\n\tWorkDoneProgressParams\n}\n\n// Registration options for a {@link HoverRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#hoverRegistrationOptions\ntype HoverRegistrationOptions struct {\n\tTextDocumentRegistrationOptions\n\tHoverOptions\n}\n\n// @since 3.6.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#implementationClientCapabilities\ntype ImplementationClientCapabilities struct {\n\t// Whether implementation supports dynamic registration. If this is set to `true`\n\t// the client supports the new `ImplementationRegistrationOptions` return value\n\t// for the corresponding server capability as well.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n\t// The client supports additional metadata in the form of definition links.\n\t//\n\t// @since 3.14.0\n\tLinkSupport bool `json:\"linkSupport,omitempty\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#implementationOptions\ntype ImplementationOptions struct {\n\tWorkDoneProgressOptions\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#implementationParams\ntype ImplementationParams struct {\n\tTextDocumentPositionParams\n\tWorkDoneProgressParams\n\tPartialResultParams\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#implementationRegistrationOptions\ntype ImplementationRegistrationOptions struct {\n\tTextDocumentRegistrationOptions\n\tImplementationOptions\n\tStaticRegistrationOptions\n}\n\n// The data type of the ResponseError if the\n// initialize request fails.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#initializeError\ntype InitializeError struct {\n\t// Indicates whether the client execute the following retry logic:\n\t// (1) show the message provided by the ResponseError to the user\n\t// (2) user selects retry or cancel\n\t// (3) if user selected retry the initialize method is sent again.\n\tRetry bool `json:\"retry\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#initializeParams\ntype InitializeParams struct {\n\tXInitializeParams\n\tWorkspaceFoldersInitializeParams\n}\n\n// The result returned from an initialize request.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#initializeResult\ntype InitializeResult struct {\n\t// The capabilities the language server provides.\n\tCapabilities ServerCapabilities `json:\"capabilities\"`\n\t// Information about the server.\n\t//\n\t// @since 3.15.0\n\tServerInfo *ServerInfo `json:\"serverInfo,omitempty\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#initializedParams\ntype InitializedParams struct {\n}\n\n// Inlay hint information.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#inlayHint\ntype InlayHint struct {\n\t// The position of this hint.\n\t//\n\t// If multiple hints have the same position, they will be shown in the order\n\t// they appear in the response.\n\tPosition Position `json:\"position\"`\n\t// The label of this hint. A human readable string or an array of\n\t// InlayHintLabelPart label parts.\n\t//\n\t// *Note* that neither the string nor the label part can be empty.\n\tLabel []InlayHintLabelPart `json:\"label\"`\n\t// The kind of this hint. Can be omitted in which case the client\n\t// should fall back to a reasonable default.\n\tKind InlayHintKind `json:\"kind,omitempty\"`\n\t// Optional text edits that are performed when accepting this inlay hint.\n\t//\n\t// *Note* that edits are expected to change the document so that the inlay\n\t// hint (or its nearest variant) is now part of the document and the inlay\n\t// hint itself is now obsolete.\n\tTextEdits []TextEdit `json:\"textEdits,omitempty\"`\n\t// The tooltip text when you hover over this item.\n\tTooltip *Or_InlayHint_tooltip `json:\"tooltip,omitempty\"`\n\t// Render padding before the hint.\n\t//\n\t// Note: Padding should use the editor's background color, not the\n\t// background color of the hint itself. That means padding can be used\n\t// to visually align/separate an inlay hint.\n\tPaddingLeft bool `json:\"paddingLeft,omitempty\"`\n\t// Render padding after the hint.\n\t//\n\t// Note: Padding should use the editor's background color, not the\n\t// background color of the hint itself. That means padding can be used\n\t// to visually align/separate an inlay hint.\n\tPaddingRight bool `json:\"paddingRight,omitempty\"`\n\t// A data entry field that is preserved on an inlay hint between\n\t// a `textDocument/inlayHint` and a `inlayHint/resolve` request.\n\tData interface{} `json:\"data,omitempty\"`\n}\n\n// Inlay hint client capabilities.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#inlayHintClientCapabilities\ntype InlayHintClientCapabilities struct {\n\t// Whether inlay hints support dynamic registration.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n\t// Indicates which properties a client can resolve lazily on an inlay\n\t// hint.\n\tResolveSupport *ClientInlayHintResolveOptions `json:\"resolveSupport,omitempty\"`\n}\n\n// Inlay hint kinds.\n//\n// @since 3.17.0\ntype InlayHintKind uint32\n\n// An inlay hint label part allows for interactive and composite labels\n// of inlay hints.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#inlayHintLabelPart\ntype InlayHintLabelPart struct {\n\t// The value of this label part.\n\tValue string `json:\"value\"`\n\t// The tooltip text when you hover over this label part. Depending on\n\t// the client capability `inlayHint.resolveSupport` clients might resolve\n\t// this property late using the resolve request.\n\tTooltip *Or_InlayHintLabelPart_tooltip `json:\"tooltip,omitempty\"`\n\t// An optional source code location that represents this\n\t// label part.\n\t//\n\t// The editor will use this location for the hover and for code navigation\n\t// features: This part will become a clickable link that resolves to the\n\t// definition of the symbol at the given location (not necessarily the\n\t// location itself), it shows the hover that shows at the given location,\n\t// and it shows a context menu with further code navigation commands.\n\t//\n\t// Depending on the client capability `inlayHint.resolveSupport` clients\n\t// might resolve this property late using the resolve request.\n\tLocation *Location `json:\"location,omitempty\"`\n\t// An optional command for this label part.\n\t//\n\t// Depending on the client capability `inlayHint.resolveSupport` clients\n\t// might resolve this property late using the resolve request.\n\tCommand *Command `json:\"command,omitempty\"`\n}\n\n// Inlay hint options used during static registration.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#inlayHintOptions\ntype InlayHintOptions struct {\n\t// The server provides support to resolve additional\n\t// information for an inlay hint item.\n\tResolveProvider bool `json:\"resolveProvider,omitempty\"`\n\tWorkDoneProgressOptions\n}\n\n// A parameter literal used in inlay hint requests.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#inlayHintParams\ntype InlayHintParams struct {\n\t// The text document.\n\tTextDocument TextDocumentIdentifier `json:\"textDocument\"`\n\t// The document range for which inlay hints should be computed.\n\tRange Range `json:\"range\"`\n\tWorkDoneProgressParams\n}\n\n// Inlay hint options used during static or dynamic registration.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#inlayHintRegistrationOptions\ntype InlayHintRegistrationOptions struct {\n\tInlayHintOptions\n\tTextDocumentRegistrationOptions\n\tStaticRegistrationOptions\n}\n\n// Client workspace capabilities specific to inlay hints.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#inlayHintWorkspaceClientCapabilities\ntype InlayHintWorkspaceClientCapabilities struct {\n\t// Whether the client implementation supports a refresh request sent from\n\t// the server to the client.\n\t//\n\t// Note that this event is global and will force the client to refresh all\n\t// inlay hints currently shown. It should be used with absolute care and\n\t// is useful for situation where a server for example detects a project wide\n\t// change that requires such a calculation.\n\tRefreshSupport bool `json:\"refreshSupport,omitempty\"`\n}\n\n// Client capabilities specific to inline completions.\n//\n// @since 3.18.0\n// @proposed\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#inlineCompletionClientCapabilities\ntype InlineCompletionClientCapabilities struct {\n\t// Whether implementation supports dynamic registration for inline completion providers.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n}\n\n// Provides information about the context in which an inline completion was requested.\n//\n// @since 3.18.0\n// @proposed\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#inlineCompletionContext\ntype InlineCompletionContext struct {\n\t// Describes how the inline completion was triggered.\n\tTriggerKind InlineCompletionTriggerKind `json:\"triggerKind\"`\n\t// Provides information about the currently selected item in the autocomplete widget if it is visible.\n\tSelectedCompletionInfo *SelectedCompletionInfo `json:\"selectedCompletionInfo,omitempty\"`\n}\n\n// An inline completion item represents a text snippet that is proposed inline to complete text that is being typed.\n//\n// @since 3.18.0\n// @proposed\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#inlineCompletionItem\ntype InlineCompletionItem struct {\n\t// The text to replace the range with. Must be set.\n\tInsertText Or_InlineCompletionItem_insertText `json:\"insertText\"`\n\t// A text that is used to decide if this inline completion should be shown. When `falsy` the {@link InlineCompletionItem.insertText} is used.\n\tFilterText string `json:\"filterText,omitempty\"`\n\t// The range to replace. Must begin and end on the same line.\n\tRange *Range `json:\"range,omitempty\"`\n\t// An optional {@link Command} that is executed *after* inserting this completion.\n\tCommand *Command `json:\"command,omitempty\"`\n}\n\n// Represents a collection of {@link InlineCompletionItem inline completion items} to be presented in the editor.\n//\n// @since 3.18.0\n// @proposed\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#inlineCompletionList\ntype InlineCompletionList struct {\n\t// The inline completion items\n\tItems []InlineCompletionItem `json:\"items\"`\n}\n\n// Inline completion options used during static registration.\n//\n// @since 3.18.0\n// @proposed\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#inlineCompletionOptions\ntype InlineCompletionOptions struct {\n\tWorkDoneProgressOptions\n}\n\n// A parameter literal used in inline completion requests.\n//\n// @since 3.18.0\n// @proposed\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#inlineCompletionParams\ntype InlineCompletionParams struct {\n\t// Additional information about the context in which inline completions were\n\t// requested.\n\tContext InlineCompletionContext `json:\"context\"`\n\tTextDocumentPositionParams\n\tWorkDoneProgressParams\n}\n\n// Inline completion options used during static or dynamic registration.\n//\n// @since 3.18.0\n// @proposed\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#inlineCompletionRegistrationOptions\ntype InlineCompletionRegistrationOptions struct {\n\tInlineCompletionOptions\n\tTextDocumentRegistrationOptions\n\tStaticRegistrationOptions\n}\n\n// Describes how an {@link InlineCompletionItemProvider inline completion provider} was triggered.\n//\n// @since 3.18.0\n// @proposed\ntype InlineCompletionTriggerKind uint32\n\n// Inline value information can be provided by different means:\n//\n// - directly as a text value (class InlineValueText).\n// - as a name to use for a variable lookup (class InlineValueVariableLookup)\n// - as an evaluatable expression (class InlineValueEvaluatableExpression)\n//\n// The InlineValue types combines all inline value types into one type.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#inlineValue\ntype InlineValue = Or_InlineValue // (alias)\n// Client capabilities specific to inline values.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#inlineValueClientCapabilities\ntype InlineValueClientCapabilities struct {\n\t// Whether implementation supports dynamic registration for inline value providers.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n}\n\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#inlineValueContext\ntype InlineValueContext struct {\n\t// The stack frame (as a DAP Id) where the execution has stopped.\n\tFrameID int32 `json:\"frameId\"`\n\t// The document range where execution has stopped.\n\t// Typically the end position of the range denotes the line where the inline values are shown.\n\tStoppedLocation Range `json:\"stoppedLocation\"`\n}\n\n// Provide an inline value through an expression evaluation.\n// If only a range is specified, the expression will be extracted from the underlying document.\n// An optional expression can be used to override the extracted expression.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#inlineValueEvaluatableExpression\ntype InlineValueEvaluatableExpression struct {\n\t// The document range for which the inline value applies.\n\t// The range is used to extract the evaluatable expression from the underlying document.\n\tRange Range `json:\"range\"`\n\t// If specified the expression overrides the extracted expression.\n\tExpression string `json:\"expression,omitempty\"`\n}\n\n// Inline value options used during static registration.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#inlineValueOptions\ntype InlineValueOptions struct {\n\tWorkDoneProgressOptions\n}\n\n// A parameter literal used in inline value requests.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#inlineValueParams\ntype InlineValueParams struct {\n\t// The text document.\n\tTextDocument TextDocumentIdentifier `json:\"textDocument\"`\n\t// The document range for which inline values should be computed.\n\tRange Range `json:\"range\"`\n\t// Additional information about the context in which inline values were\n\t// requested.\n\tContext InlineValueContext `json:\"context\"`\n\tWorkDoneProgressParams\n}\n\n// Inline value options used during static or dynamic registration.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#inlineValueRegistrationOptions\ntype InlineValueRegistrationOptions struct {\n\tInlineValueOptions\n\tTextDocumentRegistrationOptions\n\tStaticRegistrationOptions\n}\n\n// Provide inline value as text.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#inlineValueText\ntype InlineValueText struct {\n\t// The document range for which the inline value applies.\n\tRange Range `json:\"range\"`\n\t// The text of the inline value.\n\tText string `json:\"text\"`\n}\n\n// Provide inline value through a variable lookup.\n// If only a range is specified, the variable name will be extracted from the underlying document.\n// An optional variable name can be used to override the extracted name.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#inlineValueVariableLookup\ntype InlineValueVariableLookup struct {\n\t// The document range for which the inline value applies.\n\t// The range is used to extract the variable name from the underlying document.\n\tRange Range `json:\"range\"`\n\t// If specified the name of the variable to look up.\n\tVariableName string `json:\"variableName,omitempty\"`\n\t// How to perform the lookup.\n\tCaseSensitiveLookup bool `json:\"caseSensitiveLookup\"`\n}\n\n// Client workspace capabilities specific to inline values.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#inlineValueWorkspaceClientCapabilities\ntype InlineValueWorkspaceClientCapabilities struct {\n\t// Whether the client implementation supports a refresh request sent from the\n\t// server to the client.\n\t//\n\t// Note that this event is global and will force the client to refresh all\n\t// inline values currently shown. It should be used with absolute care and is\n\t// useful for situation where a server for example detects a project wide\n\t// change that requires such a calculation.\n\tRefreshSupport bool `json:\"refreshSupport,omitempty\"`\n}\n\n// A special text edit to provide an insert and a replace operation.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#insertReplaceEdit\ntype InsertReplaceEdit struct {\n\t// The string to be inserted.\n\tNewText string `json:\"newText\"`\n\t// The range if the insert is requested\n\tInsert Range `json:\"insert\"`\n\t// The range if the replace is requested.\n\tReplace Range `json:\"replace\"`\n}\n\n// Defines whether the insert text in a completion item should be interpreted as\n// plain text or a snippet.\ntype InsertTextFormat uint32\n\n// How whitespace and indentation is handled during completion\n// item insertion.\n//\n// @since 3.16.0\ntype InsertTextMode uint32\ntype LSPAny = interface{}\n\n// LSP arrays.\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#lSPArray\ntype LSPArray = []interface{} // (alias)\ntype LSPErrorCodes int32\n\n// LSP object definition.\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#lSPObject\ntype LSPObject = map[string]LSPAny // (alias)\n// Predefined Language kinds\n// @since 3.18.0\n// @proposed\ntype LanguageKind string\n\n// Client capabilities for the linked editing range request.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#linkedEditingRangeClientCapabilities\ntype LinkedEditingRangeClientCapabilities struct {\n\t// Whether implementation supports dynamic registration. If this is set to `true`\n\t// the client supports the new `(TextDocumentRegistrationOptions & StaticRegistrationOptions)`\n\t// return value for the corresponding server capability as well.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#linkedEditingRangeOptions\ntype LinkedEditingRangeOptions struct {\n\tWorkDoneProgressOptions\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#linkedEditingRangeParams\ntype LinkedEditingRangeParams struct {\n\tTextDocumentPositionParams\n\tWorkDoneProgressParams\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#linkedEditingRangeRegistrationOptions\ntype LinkedEditingRangeRegistrationOptions struct {\n\tTextDocumentRegistrationOptions\n\tLinkedEditingRangeOptions\n\tStaticRegistrationOptions\n}\n\n// The result of a linked editing range request.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#linkedEditingRanges\ntype LinkedEditingRanges struct {\n\t// A list of ranges that can be edited together. The ranges must have\n\t// identical length and contain identical text content. The ranges cannot overlap.\n\tRanges []Range `json:\"ranges\"`\n\t// An optional word pattern (regular expression) that describes valid contents for\n\t// the given ranges. If no pattern is provided, the client configuration's word\n\t// pattern will be used.\n\tWordPattern string `json:\"wordPattern,omitempty\"`\n}\n\n// created for Literal (Lit_ClientSemanticTokensRequestOptions_range_Item1)\ntype Lit_ClientSemanticTokensRequestOptions_range_Item1 struct {\n}\n\n// created for Literal (Lit_SemanticTokensOptions_range_Item1)\ntype Lit_SemanticTokensOptions_range_Item1 struct {\n}\n\n// Represents a location inside a resource, such as a line\n// inside a text file.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#location\ntype Location struct {\n\tURI DocumentUri `json:\"uri\"`\n\tRange Range `json:\"range\"`\n}\n\n// Represents the connection of two locations. Provides additional metadata over normal {@link Location locations},\n// including an origin range.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#locationLink\ntype LocationLink struct {\n\t// Span of the origin of this link.\n\t//\n\t// Used as the underlined span for mouse interaction. Defaults to the word range at\n\t// the definition position.\n\tOriginSelectionRange *Range `json:\"originSelectionRange,omitempty\"`\n\t// The target resource identifier of this link.\n\tTargetURI DocumentUri `json:\"targetUri\"`\n\t// The full target range of this link. If the target for example is a symbol then target range is the\n\t// range enclosing this symbol not including leading/trailing whitespace but everything else\n\t// like comments. This information is typically used to highlight the range in the editor.\n\tTargetRange Range `json:\"targetRange\"`\n\t// The range that should be selected and revealed when this link is being followed, e.g the name of a function.\n\t// Must be contained by the `targetRange`. See also `DocumentSymbol#range`\n\tTargetSelectionRange Range `json:\"targetSelectionRange\"`\n}\n\n// Location with only uri and does not include range.\n//\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#locationUriOnly\ntype LocationUriOnly struct {\n\tURI DocumentUri `json:\"uri\"`\n}\n\n// The log message parameters.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#logMessageParams\ntype LogMessageParams struct {\n\t// The message type. See {@link MessageType}\n\tType MessageType `json:\"type\"`\n\t// The actual message.\n\tMessage string `json:\"message\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#logTraceParams\ntype LogTraceParams struct {\n\tMessage string `json:\"message\"`\n\tVerbose string `json:\"verbose,omitempty\"`\n}\n\n// Client capabilities specific to the used markdown parser.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#markdownClientCapabilities\ntype MarkdownClientCapabilities struct {\n\t// The name of the parser.\n\tParser string `json:\"parser\"`\n\t// The version of the parser.\n\tVersion string `json:\"version,omitempty\"`\n\t// A list of HTML tags that the client allows / supports in\n\t// Markdown.\n\t//\n\t// @since 3.17.0\n\tAllowedTags []string `json:\"allowedTags,omitempty\"`\n}\n\n// MarkedString can be used to render human readable text. It is either a markdown string\n// or a code-block that provides a language and a code snippet. The language identifier\n// is semantically equal to the optional language identifier in fenced code blocks in GitHub\n// issues. See https://help.github.com/articles/creating-and-highlighting-code-blocks/#syntax-highlighting\n//\n// The pair of a language and a value is an equivalent to markdown:\n// ```${language}\n// ${value}\n// ```\n//\n// Note that markdown strings will be sanitized - that means html will be escaped.\n// @deprecated use MarkupContent instead.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#markedString\ntype MarkedString = Or_MarkedString // (alias)\n// @since 3.18.0\n// @deprecated use MarkupContent instead.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#markedStringWithLanguage\ntype MarkedStringWithLanguage struct {\n\tLanguage string `json:\"language\"`\n\tValue string `json:\"value\"`\n}\n\n// A `MarkupContent` literal represents a string value which content is interpreted base on its\n// kind flag. Currently the protocol supports `plaintext` and `markdown` as markup kinds.\n//\n// If the kind is `markdown` then the value can contain fenced code blocks like in GitHub issues.\n// See https://help.github.com/articles/creating-and-highlighting-code-blocks/#syntax-highlighting\n//\n// Here is an example how such a string can be constructed using JavaScript / TypeScript:\n// ```ts\n//\n//\tlet markdown: MarkdownContent = {\n//\t kind: MarkupKind.Markdown,\n//\t value: [\n//\t '# Header',\n//\t 'Some text',\n//\t '```typescript',\n//\t 'someCode();',\n//\t '```'\n//\t ].join('\\n')\n//\t};\n//\n// ```\n//\n// *Please Note* that clients might sanitize the return markdown. A client could decide to\n// remove HTML from the markdown to avoid script execution.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#markupContent\ntype MarkupContent struct {\n\t// The type of the Markup\n\tKind MarkupKind `json:\"kind\"`\n\t// The content itself\n\tValue string `json:\"value\"`\n}\n\n// Describes the content type that a client supports in various\n// result literals like `Hover`, `ParameterInfo` or `CompletionItem`.\n//\n// Please note that `MarkupKinds` must not start with a `$`. This kinds\n// are reserved for internal usage.\ntype MarkupKind string\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#messageActionItem\ntype MessageActionItem struct {\n\t// A short title like 'Retry', 'Open Log' etc.\n\tTitle string `json:\"title\"`\n}\n\n// The message type\ntype MessageType uint32\n\n// Moniker definition to match LSIF 0.5 moniker definition.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#moniker\ntype Moniker struct {\n\t// The scheme of the moniker. For example tsc or .Net\n\tScheme string `json:\"scheme\"`\n\t// The identifier of the moniker. The value is opaque in LSIF however\n\t// schema owners are allowed to define the structure if they want.\n\tIdentifier string `json:\"identifier\"`\n\t// The scope in which the moniker is unique\n\tUnique UniquenessLevel `json:\"unique\"`\n\t// The moniker kind if known.\n\tKind *MonikerKind `json:\"kind,omitempty\"`\n}\n\n// Client capabilities specific to the moniker request.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#monikerClientCapabilities\ntype MonikerClientCapabilities struct {\n\t// Whether moniker supports dynamic registration. If this is set to `true`\n\t// the client supports the new `MonikerRegistrationOptions` return value\n\t// for the corresponding server capability as well.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n}\n\n// The moniker kind.\n//\n// @since 3.16.0\ntype MonikerKind string\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#monikerOptions\ntype MonikerOptions struct {\n\tWorkDoneProgressOptions\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#monikerParams\ntype MonikerParams struct {\n\tTextDocumentPositionParams\n\tWorkDoneProgressParams\n\tPartialResultParams\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#monikerRegistrationOptions\ntype MonikerRegistrationOptions struct {\n\tTextDocumentRegistrationOptions\n\tMonikerOptions\n}\n\n// A notebook cell.\n//\n// A cell's document URI must be unique across ALL notebook\n// cells and can therefore be used to uniquely identify a\n// notebook cell or the cell's text document.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#notebookCell\ntype NotebookCell struct {\n\t// The cell's kind\n\tKind NotebookCellKind `json:\"kind\"`\n\t// The URI of the cell's text document\n\t// content.\n\tDocument DocumentUri `json:\"document\"`\n\t// Additional metadata stored with the cell.\n\t//\n\t// Note: should always be an object literal (e.g. LSPObject)\n\tMetadata *LSPObject `json:\"metadata,omitempty\"`\n\t// Additional execution summary information\n\t// if supported by the client.\n\tExecutionSummary *ExecutionSummary `json:\"executionSummary,omitempty\"`\n}\n\n// A change describing how to move a `NotebookCell`\n// array from state S to S'.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#notebookCellArrayChange\ntype NotebookCellArrayChange struct {\n\t// The start oftest of the cell that changed.\n\tStart uint32 `json:\"start\"`\n\t// The deleted cells\n\tDeleteCount uint32 `json:\"deleteCount\"`\n\t// The new cells, if any\n\tCells []NotebookCell `json:\"cells,omitempty\"`\n}\n\n// A notebook cell kind.\n//\n// @since 3.17.0\ntype NotebookCellKind uint32\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#notebookCellLanguage\ntype NotebookCellLanguage struct {\n\tLanguage string `json:\"language\"`\n}\n\n// A notebook cell text document filter denotes a cell text\n// document by different properties.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#notebookCellTextDocumentFilter\ntype NotebookCellTextDocumentFilter struct {\n\t// A filter that matches against the notebook\n\t// containing the notebook cell. If a string\n\t// value is provided it matches against the\n\t// notebook type. '*' matches every notebook.\n\tNotebook Or_NotebookCellTextDocumentFilter_notebook `json:\"notebook\"`\n\t// A language id like `python`.\n\t//\n\t// Will be matched against the language id of the\n\t// notebook cell document. '*' matches every language.\n\tLanguage string `json:\"language,omitempty\"`\n}\n\n// A notebook document.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#notebookDocument\ntype NotebookDocument struct {\n\t// The notebook document's uri.\n\tURI URI `json:\"uri\"`\n\t// The type of the notebook.\n\tNotebookType string `json:\"notebookType\"`\n\t// The version number of this document (it will increase after each\n\t// change, including undo/redo).\n\tVersion int32 `json:\"version\"`\n\t// Additional metadata stored with the notebook\n\t// document.\n\t//\n\t// Note: should always be an object literal (e.g. LSPObject)\n\tMetadata *LSPObject `json:\"metadata,omitempty\"`\n\t// The cells of a notebook.\n\tCells []NotebookCell `json:\"cells\"`\n}\n\n// Structural changes to cells in a notebook document.\n//\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#notebookDocumentCellChangeStructure\ntype NotebookDocumentCellChangeStructure struct {\n\t// The change to the cell array.\n\tArray NotebookCellArrayChange `json:\"array\"`\n\t// Additional opened cell text documents.\n\tDidOpen []TextDocumentItem `json:\"didOpen,omitempty\"`\n\t// Additional closed cell text documents.\n\tDidClose []TextDocumentIdentifier `json:\"didClose,omitempty\"`\n}\n\n// Cell changes to a notebook document.\n//\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#notebookDocumentCellChanges\ntype NotebookDocumentCellChanges struct {\n\t// Changes to the cell structure to add or\n\t// remove cells.\n\tStructure *NotebookDocumentCellChangeStructure `json:\"structure,omitempty\"`\n\t// Changes to notebook cells properties like its\n\t// kind, execution summary or metadata.\n\tData []NotebookCell `json:\"data,omitempty\"`\n\t// Changes to the text content of notebook cells.\n\tTextContent []NotebookDocumentCellContentChanges `json:\"textContent,omitempty\"`\n}\n\n// Content changes to a cell in a notebook document.\n//\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#notebookDocumentCellContentChanges\ntype NotebookDocumentCellContentChanges struct {\n\tDocument VersionedTextDocumentIdentifier `json:\"document\"`\n\tChanges []TextDocumentContentChangeEvent `json:\"changes\"`\n}\n\n// A change event for a notebook document.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#notebookDocumentChangeEvent\ntype NotebookDocumentChangeEvent struct {\n\t// The changed meta data if any.\n\t//\n\t// Note: should always be an object literal (e.g. LSPObject)\n\tMetadata *LSPObject `json:\"metadata,omitempty\"`\n\t// Changes to cells\n\tCells *NotebookDocumentCellChanges `json:\"cells,omitempty\"`\n}\n\n// Capabilities specific to the notebook document support.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#notebookDocumentClientCapabilities\ntype NotebookDocumentClientCapabilities struct {\n\t// Capabilities specific to notebook document synchronization\n\t//\n\t// @since 3.17.0\n\tSynchronization NotebookDocumentSyncClientCapabilities `json:\"synchronization\"`\n}\n\n// A notebook document filter denotes a notebook document by\n// different properties. The properties will be match\n// against the notebook's URI (same as with documents)\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#notebookDocumentFilter\ntype NotebookDocumentFilter = Or_NotebookDocumentFilter // (alias)\n// A notebook document filter where `notebookType` is required field.\n//\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#notebookDocumentFilterNotebookType\ntype NotebookDocumentFilterNotebookType struct {\n\t// The type of the enclosing notebook.\n\tNotebookType string `json:\"notebookType\"`\n\t// A Uri {@link Uri.scheme scheme}, like `file` or `untitled`.\n\tScheme string `json:\"scheme,omitempty\"`\n\t// A glob pattern.\n\tPattern *GlobPattern `json:\"pattern,omitempty\"`\n}\n\n// A notebook document filter where `pattern` is required field.\n//\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#notebookDocumentFilterPattern\ntype NotebookDocumentFilterPattern struct {\n\t// The type of the enclosing notebook.\n\tNotebookType string `json:\"notebookType,omitempty\"`\n\t// A Uri {@link Uri.scheme scheme}, like `file` or `untitled`.\n\tScheme string `json:\"scheme,omitempty\"`\n\t// A glob pattern.\n\tPattern GlobPattern `json:\"pattern\"`\n}\n\n// A notebook document filter where `scheme` is required field.\n//\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#notebookDocumentFilterScheme\ntype NotebookDocumentFilterScheme struct {\n\t// The type of the enclosing notebook.\n\tNotebookType string `json:\"notebookType,omitempty\"`\n\t// A Uri {@link Uri.scheme scheme}, like `file` or `untitled`.\n\tScheme string `json:\"scheme\"`\n\t// A glob pattern.\n\tPattern *GlobPattern `json:\"pattern,omitempty\"`\n}\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#notebookDocumentFilterWithCells\ntype NotebookDocumentFilterWithCells struct {\n\t// The notebook to be synced If a string\n\t// value is provided it matches against the\n\t// notebook type. '*' matches every notebook.\n\tNotebook *Or_NotebookDocumentFilterWithCells_notebook `json:\"notebook,omitempty\"`\n\t// The cells of the matching notebook to be synced.\n\tCells []NotebookCellLanguage `json:\"cells\"`\n}\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#notebookDocumentFilterWithNotebook\ntype NotebookDocumentFilterWithNotebook struct {\n\t// The notebook to be synced If a string\n\t// value is provided it matches against the\n\t// notebook type. '*' matches every notebook.\n\tNotebook Or_NotebookDocumentFilterWithNotebook_notebook `json:\"notebook\"`\n\t// The cells of the matching notebook to be synced.\n\tCells []NotebookCellLanguage `json:\"cells,omitempty\"`\n}\n\n// A literal to identify a notebook document in the client.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#notebookDocumentIdentifier\ntype NotebookDocumentIdentifier struct {\n\t// The notebook document's uri.\n\tURI URI `json:\"uri\"`\n}\n\n// Notebook specific client capabilities.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#notebookDocumentSyncClientCapabilities\ntype NotebookDocumentSyncClientCapabilities struct {\n\t// Whether implementation supports dynamic registration. If this is\n\t// set to `true` the client supports the new\n\t// `(TextDocumentRegistrationOptions & StaticRegistrationOptions)`\n\t// return value for the corresponding server capability as well.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n\t// The client supports sending execution summary data per cell.\n\tExecutionSummarySupport bool `json:\"executionSummarySupport,omitempty\"`\n}\n\n// Options specific to a notebook plus its cells\n// to be synced to the server.\n//\n// If a selector provides a notebook document\n// filter but no cell selector all cells of a\n// matching notebook document will be synced.\n//\n// If a selector provides no notebook document\n// filter but only a cell selector all notebook\n// document that contain at least one matching\n// cell will be synced.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#notebookDocumentSyncOptions\ntype NotebookDocumentSyncOptions struct {\n\t// The notebooks to be synced\n\tNotebookSelector []Or_NotebookDocumentSyncOptions_notebookSelector_Elem `json:\"notebookSelector\"`\n\t// Whether save notification should be forwarded to\n\t// the server. Will only be honored if mode === `notebook`.\n\tSave bool `json:\"save,omitempty\"`\n}\n\n// Registration options specific to a notebook.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#notebookDocumentSyncRegistrationOptions\ntype NotebookDocumentSyncRegistrationOptions struct {\n\tNotebookDocumentSyncOptions\n\tStaticRegistrationOptions\n}\n\n// A text document identifier to optionally denote a specific version of a text document.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#optionalVersionedTextDocumentIdentifier\ntype OptionalVersionedTextDocumentIdentifier struct {\n\t// The version number of this document. If a versioned text document identifier\n\t// is sent from the server to the client and the file is not open in the editor\n\t// (the server has not received an open notification before) the server can send\n\t// `null` to indicate that the version is unknown and the content on disk is the\n\t// truth (as specified with document content ownership).\n\tVersion int32 `json:\"version\"`\n\tTextDocumentIdentifier\n}\n\n// created for Or [int32 string]\ntype Or_CancelParams_id struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [ClientSemanticTokensRequestFullDelta bool]\ntype Or_ClientSemanticTokensRequestOptions_full struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [Lit_ClientSemanticTokensRequestOptions_range_Item1 bool]\ntype Or_ClientSemanticTokensRequestOptions_range struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [EditRangeWithInsertReplace Range]\ntype Or_CompletionItemDefaults_editRange struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [MarkupContent string]\ntype Or_CompletionItem_documentation struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [InsertReplaceEdit TextEdit]\ntype Or_CompletionItem_textEdit struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [Location []Location]\ntype Or_Declaration struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [Location []Location]\ntype Or_Definition struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [int32 string]\ntype Or_Diagnostic_code struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [[]string string]\ntype Or_DidChangeConfigurationRegistrationOptions_section struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [RelatedFullDocumentDiagnosticReport RelatedUnchangedDocumentDiagnosticReport]\ntype Or_DocumentDiagnosticReport struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [FullDocumentDiagnosticReport UnchangedDocumentDiagnosticReport]\ntype Or_DocumentDiagnosticReportPartialResult_relatedDocuments_Value struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [NotebookCellTextDocumentFilter TextDocumentFilter]\ntype Or_DocumentFilter struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [Pattern RelativePattern]\ntype Or_GlobPattern struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [MarkedString MarkupContent []MarkedString]\ntype Or_Hover_contents struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [MarkupContent string]\ntype Or_InlayHintLabelPart_tooltip struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [[]InlayHintLabelPart string]\ntype Or_InlayHint_label struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [MarkupContent string]\ntype Or_InlayHint_tooltip struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [StringValue string]\ntype Or_InlineCompletionItem_insertText struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [InlineValueEvaluatableExpression InlineValueText InlineValueVariableLookup]\ntype Or_InlineValue struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [LSPArray LSPObject bool float64 int32 string uint32]\ntype Or_LSPAny struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [MarkedStringWithLanguage string]\ntype Or_MarkedString struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [NotebookDocumentFilter string]\ntype Or_NotebookCellTextDocumentFilter_notebook struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [NotebookDocumentFilterNotebookType NotebookDocumentFilterPattern NotebookDocumentFilterScheme]\ntype Or_NotebookDocumentFilter struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [NotebookDocumentFilter string]\ntype Or_NotebookDocumentFilterWithCells_notebook struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [NotebookDocumentFilter string]\ntype Or_NotebookDocumentFilterWithNotebook_notebook struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [NotebookDocumentFilterWithCells NotebookDocumentFilterWithNotebook]\ntype Or_NotebookDocumentSyncOptions_notebookSelector_Elem struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [MarkupContent string]\ntype Or_ParameterInformation_documentation struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [Tuple_ParameterInformation_label_Item1 string]\ntype Or_ParameterInformation_label struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [PrepareRenameDefaultBehavior PrepareRenamePlaceholder Range]\ntype Or_PrepareRenameResult struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [int32 string]\ntype Or_ProgressToken struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [FullDocumentDiagnosticReport UnchangedDocumentDiagnosticReport]\ntype Or_RelatedFullDocumentDiagnosticReport_relatedDocuments_Value struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [FullDocumentDiagnosticReport UnchangedDocumentDiagnosticReport]\ntype Or_RelatedUnchangedDocumentDiagnosticReport_relatedDocuments_Value struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [URI WorkspaceFolder]\ntype Or_RelativePattern_baseUri struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [CodeAction Command]\ntype Or_Result_textDocument_codeAction_Item0_Elem struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [CompletionList []CompletionItem]\ntype Or_Result_textDocument_completion struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [Declaration []DeclarationLink]\ntype Or_Result_textDocument_declaration struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [Definition []DefinitionLink]\ntype Or_Result_textDocument_definition struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [[]DocumentSymbol []SymbolInformation]\ntype Or_Result_textDocument_documentSymbol struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [Definition []DefinitionLink]\ntype Or_Result_textDocument_implementation struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [InlineCompletionList []InlineCompletionItem]\ntype Or_Result_textDocument_inlineCompletion struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [SemanticTokens SemanticTokensDelta]\ntype Or_Result_textDocument_semanticTokens_full_delta struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [Definition []DefinitionLink]\ntype Or_Result_textDocument_typeDefinition struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [[]SymbolInformation []WorkspaceSymbol]\ntype Or_Result_workspace_symbol struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [SemanticTokensFullDelta bool]\ntype Or_SemanticTokensOptions_full struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [Lit_SemanticTokensOptions_range_Item1 bool]\ntype Or_SemanticTokensOptions_range struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [CallHierarchyOptions CallHierarchyRegistrationOptions bool]\ntype Or_ServerCapabilities_callHierarchyProvider struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [CodeActionOptions bool]\ntype Or_ServerCapabilities_codeActionProvider struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [DocumentColorOptions DocumentColorRegistrationOptions bool]\ntype Or_ServerCapabilities_colorProvider struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [DeclarationOptions DeclarationRegistrationOptions bool]\ntype Or_ServerCapabilities_declarationProvider struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [DefinitionOptions bool]\ntype Or_ServerCapabilities_definitionProvider struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [DiagnosticOptions DiagnosticRegistrationOptions]\ntype Or_ServerCapabilities_diagnosticProvider struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [DocumentFormattingOptions bool]\ntype Or_ServerCapabilities_documentFormattingProvider struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [DocumentHighlightOptions bool]\ntype Or_ServerCapabilities_documentHighlightProvider struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [DocumentRangeFormattingOptions bool]\ntype Or_ServerCapabilities_documentRangeFormattingProvider struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [DocumentSymbolOptions bool]\ntype Or_ServerCapabilities_documentSymbolProvider struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [FoldingRangeOptions FoldingRangeRegistrationOptions bool]\ntype Or_ServerCapabilities_foldingRangeProvider struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [HoverOptions bool]\ntype Or_ServerCapabilities_hoverProvider struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [ImplementationOptions ImplementationRegistrationOptions bool]\ntype Or_ServerCapabilities_implementationProvider struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [InlayHintOptions InlayHintRegistrationOptions bool]\ntype Or_ServerCapabilities_inlayHintProvider struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [InlineCompletionOptions bool]\ntype Or_ServerCapabilities_inlineCompletionProvider struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [InlineValueOptions InlineValueRegistrationOptions bool]\ntype Or_ServerCapabilities_inlineValueProvider struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [LinkedEditingRangeOptions LinkedEditingRangeRegistrationOptions bool]\ntype Or_ServerCapabilities_linkedEditingRangeProvider struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [MonikerOptions MonikerRegistrationOptions bool]\ntype Or_ServerCapabilities_monikerProvider struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [NotebookDocumentSyncOptions NotebookDocumentSyncRegistrationOptions]\ntype Or_ServerCapabilities_notebookDocumentSync struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [ReferenceOptions bool]\ntype Or_ServerCapabilities_referencesProvider struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [RenameOptions bool]\ntype Or_ServerCapabilities_renameProvider struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [SelectionRangeOptions SelectionRangeRegistrationOptions bool]\ntype Or_ServerCapabilities_selectionRangeProvider struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [SemanticTokensOptions SemanticTokensRegistrationOptions]\ntype Or_ServerCapabilities_semanticTokensProvider struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [TextDocumentSyncKind TextDocumentSyncOptions]\ntype Or_ServerCapabilities_textDocumentSync struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [TypeDefinitionOptions TypeDefinitionRegistrationOptions bool]\ntype Or_ServerCapabilities_typeDefinitionProvider struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [TypeHierarchyOptions TypeHierarchyRegistrationOptions bool]\ntype Or_ServerCapabilities_typeHierarchyProvider struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [WorkspaceSymbolOptions bool]\ntype Or_ServerCapabilities_workspaceSymbolProvider struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [MarkupContent string]\ntype Or_SignatureInformation_documentation struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [TextDocumentContentChangePartial TextDocumentContentChangeWholeDocument]\ntype Or_TextDocumentContentChangeEvent struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [AnnotatedTextEdit SnippetTextEdit TextEdit]\ntype Or_TextDocumentEdit_edits_Elem struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [TextDocumentFilterLanguage TextDocumentFilterPattern TextDocumentFilterScheme]\ntype Or_TextDocumentFilter struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [SaveOptions bool]\ntype Or_TextDocumentSyncOptions_save struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [WorkspaceFullDocumentDiagnosticReport WorkspaceUnchangedDocumentDiagnosticReport]\ntype Or_WorkspaceDocumentDiagnosticReport struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [CreateFile DeleteFile RenameFile TextDocumentEdit]\ntype Or_WorkspaceEdit_documentChanges_Elem struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [bool string]\ntype Or_WorkspaceFoldersServerCapabilities_changeNotifications struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [TextDocumentContentOptions TextDocumentContentRegistrationOptions]\ntype Or_WorkspaceOptions_textDocumentContent struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [Location LocationUriOnly]\ntype Or_WorkspaceSymbol_location struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// The parameters of a configuration request.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#configurationParams\ntype ParamConfiguration struct {\n\tItems []ConfigurationItem `json:\"items\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#initializeParams\ntype ParamInitialize struct {\n\tXInitializeParams\n\tWorkspaceFoldersInitializeParams\n}\n\n// Represents a parameter of a callable-signature. A parameter can\n// have a label and a doc-comment.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#parameterInformation\ntype ParameterInformation struct {\n\t// The label of this parameter information.\n\t//\n\t// Either a string or an inclusive start and exclusive end offsets within its containing\n\t// signature label. (see SignatureInformation.label). The offsets are based on a UTF-16\n\t// string representation as `Position` and `Range` does.\n\t//\n\t// To avoid ambiguities a server should use the [start, end] offset value instead of using\n\t// a substring. Whether a client support this is controlled via `labelOffsetSupport` client\n\t// capability.\n\t//\n\t// *Note*: a label of type string should be a substring of its containing signature label.\n\t// Its intended use case is to highlight the parameter label part in the `SignatureInformation.label`.\n\tLabel Or_ParameterInformation_label `json:\"label\"`\n\t// The human-readable doc-comment of this parameter. Will be shown\n\t// in the UI but can be omitted.\n\tDocumentation *Or_ParameterInformation_documentation `json:\"documentation,omitempty\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#partialResultParams\ntype PartialResultParams struct {\n\t// An optional token that a server can use to report partial results (e.g. streaming) to\n\t// the client.\n\tPartialResultToken *ProgressToken `json:\"partialResultToken,omitempty\"`\n}\n\n// The glob pattern to watch relative to the base path. Glob patterns can have the following syntax:\n//\n// - `*` to match one or more characters in a path segment\n// - `?` to match on one character in a path segment\n// - `**` to match any number of path segments, including none\n// - `{}` to group conditions (e.g. `**/*.{ts,js}` matches all TypeScript and JavaScript files)\n// - `[]` to declare a range of characters to match in a path segment (e.g., `example.[0-9]` to match on `example.0`, `example.1`, …)\n// - `[!...]` to negate a range of characters to match in a path segment (e.g., `example.[!0-9]` to match on `example.a`, `example.b`, but not `example.0`)\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#pattern\ntype Pattern = string // (alias)\n// Position in a text document expressed as zero-based line and character\n// offset. Prior to 3.17 the offsets were always based on a UTF-16 string\n// representation. So a string of the form `a𐐀b` the character offset of the\n// character `a` is 0, the character offset of `𐐀` is 1 and the character\n// offset of b is 3 since `𐐀` is represented using two code units in UTF-16.\n// Since 3.17 clients and servers can agree on a different string encoding\n// representation (e.g. UTF-8). The client announces it's supported encoding\n// via the client capability [`general.positionEncodings`](https://microsoft.github.io/language-server-protocol/specifications/specification-current/#clientCapabilities).\n// The value is an array of position encodings the client supports, with\n// decreasing preference (e.g. the encoding at index `0` is the most preferred\n// one). To stay backwards compatible the only mandatory encoding is UTF-16\n// represented via the string `utf-16`. The server can pick one of the\n// encodings offered by the client and signals that encoding back to the\n// client via the initialize result's property\n// [`capabilities.positionEncoding`](https://microsoft.github.io/language-server-protocol/specifications/specification-current/#serverCapabilities). If the string value\n// `utf-16` is missing from the client's capability `general.positionEncodings`\n// servers can safely assume that the client supports UTF-16. If the server\n// omits the position encoding in its initialize result the encoding defaults\n// to the string value `utf-16`. Implementation considerations: since the\n// conversion from one encoding into another requires the content of the\n// file / line the conversion is best done where the file is read which is\n// usually on the server side.\n//\n// Positions are line end character agnostic. So you can not specify a position\n// that denotes `\\r|\\n` or `\\n|` where `|` represents the character offset.\n//\n// @since 3.17.0 - support for negotiated position encoding.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#position\ntype Position struct {\n\t// Line position in a document (zero-based).\n\t//\n\t// If a line number is greater than the number of lines in a document, it defaults back to the number of lines in the document.\n\t// If a line number is negative, it defaults to 0.\n\tLine uint32 `json:\"line\"`\n\t// Character offset on a line in a document (zero-based).\n\t//\n\t// The meaning of this offset is determined by the negotiated\n\t// `PositionEncodingKind`.\n\t//\n\t// If the character value is greater than the line length it defaults back to the\n\t// line length.\n\tCharacter uint32 `json:\"character\"`\n}\n\n// A set of predefined position encoding kinds.\n//\n// @since 3.17.0\ntype PositionEncodingKind string\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#prepareRenameDefaultBehavior\ntype PrepareRenameDefaultBehavior struct {\n\tDefaultBehavior bool `json:\"defaultBehavior\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#prepareRenameParams\ntype PrepareRenameParams struct {\n\tTextDocumentPositionParams\n\tWorkDoneProgressParams\n}\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#prepareRenamePlaceholder\ntype PrepareRenamePlaceholder struct {\n\tRange Range `json:\"range\"`\n\tPlaceholder string `json:\"placeholder\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#prepareRenameResult\ntype PrepareRenameResult = Or_PrepareRenameResult // (alias)\ntype PrepareSupportDefaultBehavior uint32\n\n// A previous result id in a workspace pull request.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#previousResultId\ntype PreviousResultID struct {\n\t// The URI for which the client knowns a\n\t// result id.\n\tURI DocumentUri `json:\"uri\"`\n\t// The value of the previous result id.\n\tValue string `json:\"value\"`\n}\n\n// A previous result id in a workspace pull request.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#previousResultId\ntype PreviousResultId struct {\n\t// The URI for which the client knowns a\n\t// result id.\n\tURI DocumentUri `json:\"uri\"`\n\t// The value of the previous result id.\n\tValue string `json:\"value\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#progressParams\ntype ProgressParams struct {\n\t// The progress token provided by the client or server.\n\tToken ProgressToken `json:\"token\"`\n\t// The progress data.\n\tValue interface{} `json:\"value\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#progressToken\ntype ProgressToken = Or_ProgressToken // (alias)\n// The publish diagnostic client capabilities.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#publishDiagnosticsClientCapabilities\ntype PublishDiagnosticsClientCapabilities struct {\n\t// Whether the client interprets the version property of the\n\t// `textDocument/publishDiagnostics` notification's parameter.\n\t//\n\t// @since 3.15.0\n\tVersionSupport bool `json:\"versionSupport,omitempty\"`\n\tDiagnosticsCapabilities\n}\n\n// The publish diagnostic notification's parameters.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#publishDiagnosticsParams\ntype PublishDiagnosticsParams struct {\n\t// The URI for which diagnostic information is reported.\n\tURI DocumentUri `json:\"uri\"`\n\t// Optional the version number of the document the diagnostics are published for.\n\t//\n\t// @since 3.15.0\n\tVersion int32 `json:\"version,omitempty\"`\n\t// An array of diagnostic information items.\n\tDiagnostics []Diagnostic `json:\"diagnostics\"`\n}\n\n// A range in a text document expressed as (zero-based) start and end positions.\n//\n// If you want to specify a range that contains a line including the line ending\n// character(s) then use an end position denoting the start of the next line.\n// For example:\n// ```ts\n//\n//\t{\n//\t start: { line: 5, character: 23 }\n//\t end : { line 6, character : 0 }\n//\t}\n//\n// ```\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#range\ntype Range struct {\n\t// The range's start position.\n\tStart Position `json:\"start\"`\n\t// The range's end position.\n\tEnd Position `json:\"end\"`\n}\n\n// Client Capabilities for a {@link ReferencesRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#referenceClientCapabilities\ntype ReferenceClientCapabilities struct {\n\t// Whether references supports dynamic registration.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n}\n\n// Value-object that contains additional information when\n// requesting references.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#referenceContext\ntype ReferenceContext struct {\n\t// Include the declaration of the current symbol.\n\tIncludeDeclaration bool `json:\"includeDeclaration\"`\n}\n\n// Reference options.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#referenceOptions\ntype ReferenceOptions struct {\n\tWorkDoneProgressOptions\n}\n\n// Parameters for a {@link ReferencesRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#referenceParams\ntype ReferenceParams struct {\n\tContext ReferenceContext `json:\"context\"`\n\tTextDocumentPositionParams\n\tWorkDoneProgressParams\n\tPartialResultParams\n}\n\n// Registration options for a {@link ReferencesRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#referenceRegistrationOptions\ntype ReferenceRegistrationOptions struct {\n\tTextDocumentRegistrationOptions\n\tReferenceOptions\n}\n\n// General parameters to register for a notification or to register a provider.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#registration\ntype Registration struct {\n\t// The id used to register the request. The id can be used to deregister\n\t// the request again.\n\tID string `json:\"id\"`\n\t// The method / capability to register for.\n\tMethod string `json:\"method\"`\n\t// Options necessary for the registration.\n\tRegisterOptions interface{} `json:\"registerOptions,omitempty\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#registrationParams\ntype RegistrationParams struct {\n\tRegistrations []Registration `json:\"registrations\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#regularExpressionEngineKind\ntype RegularExpressionEngineKind = string // (alias)\n// Client capabilities specific to regular expressions.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#regularExpressionsClientCapabilities\ntype RegularExpressionsClientCapabilities struct {\n\t// The engine's name.\n\tEngine RegularExpressionEngineKind `json:\"engine\"`\n\t// The engine's version.\n\tVersion string `json:\"version,omitempty\"`\n}\n\n// A full diagnostic report with a set of related documents.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#relatedFullDocumentDiagnosticReport\ntype RelatedFullDocumentDiagnosticReport struct {\n\t// Diagnostics of related documents. This information is useful\n\t// in programming languages where code in a file A can generate\n\t// diagnostics in a file B which A depends on. An example of\n\t// such a language is C/C++ where marco definitions in a file\n\t// a.cpp and result in errors in a header file b.hpp.\n\t//\n\t// @since 3.17.0\n\tRelatedDocuments map[DocumentUri]interface{} `json:\"relatedDocuments,omitempty\"`\n\tFullDocumentDiagnosticReport\n}\n\n// An unchanged diagnostic report with a set of related documents.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#relatedUnchangedDocumentDiagnosticReport\ntype RelatedUnchangedDocumentDiagnosticReport struct {\n\t// Diagnostics of related documents. This information is useful\n\t// in programming languages where code in a file A can generate\n\t// diagnostics in a file B which A depends on. An example of\n\t// such a language is C/C++ where marco definitions in a file\n\t// a.cpp and result in errors in a header file b.hpp.\n\t//\n\t// @since 3.17.0\n\tRelatedDocuments map[DocumentUri]interface{} `json:\"relatedDocuments,omitempty\"`\n\tUnchangedDocumentDiagnosticReport\n}\n\n// A relative pattern is a helper to construct glob patterns that are matched\n// relatively to a base URI. The common value for a `baseUri` is a workspace\n// folder root, but it can be another absolute URI as well.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#relativePattern\ntype RelativePattern struct {\n\t// A workspace folder or a base URI to which this pattern will be matched\n\t// against relatively.\n\tBaseURI Or_RelativePattern_baseUri `json:\"baseUri\"`\n\t// The actual glob pattern;\n\tPattern Pattern `json:\"pattern\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#renameClientCapabilities\ntype RenameClientCapabilities struct {\n\t// Whether rename supports dynamic registration.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n\t// Client supports testing for validity of rename operations\n\t// before execution.\n\t//\n\t// @since 3.12.0\n\tPrepareSupport bool `json:\"prepareSupport,omitempty\"`\n\t// Client supports the default behavior result.\n\t//\n\t// The value indicates the default behavior used by the\n\t// client.\n\t//\n\t// @since 3.16.0\n\tPrepareSupportDefaultBehavior *PrepareSupportDefaultBehavior `json:\"prepareSupportDefaultBehavior,omitempty\"`\n\t// Whether the client honors the change annotations in\n\t// text edits and resource operations returned via the\n\t// rename request's workspace edit by for example presenting\n\t// the workspace edit in the user interface and asking\n\t// for confirmation.\n\t//\n\t// @since 3.16.0\n\tHonorsChangeAnnotations bool `json:\"honorsChangeAnnotations,omitempty\"`\n}\n\n// Rename file operation\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#renameFile\ntype RenameFile struct {\n\t// A rename\n\tKind string `json:\"kind\"`\n\t// The old (existing) location.\n\tOldURI DocumentUri `json:\"oldUri\"`\n\t// The new location.\n\tNewURI DocumentUri `json:\"newUri\"`\n\t// Rename options.\n\tOptions *RenameFileOptions `json:\"options,omitempty\"`\n\tResourceOperation\n}\n\n// Rename file options\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#renameFileOptions\ntype RenameFileOptions struct {\n\t// Overwrite target if existing. Overwrite wins over `ignoreIfExists`\n\tOverwrite bool `json:\"overwrite,omitempty\"`\n\t// Ignores if target exists.\n\tIgnoreIfExists bool `json:\"ignoreIfExists,omitempty\"`\n}\n\n// The parameters sent in notifications/requests for user-initiated renames of\n// files.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#renameFilesParams\ntype RenameFilesParams struct {\n\t// An array of all files/folders renamed in this operation. When a folder is renamed, only\n\t// the folder will be included, and not its children.\n\tFiles []FileRename `json:\"files\"`\n}\n\n// Provider options for a {@link RenameRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#renameOptions\ntype RenameOptions struct {\n\t// Renames should be checked and tested before being executed.\n\t//\n\t// @since version 3.12.0\n\tPrepareProvider bool `json:\"prepareProvider,omitempty\"`\n\tWorkDoneProgressOptions\n}\n\n// The parameters of a {@link RenameRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#renameParams\ntype RenameParams struct {\n\t// The document to rename.\n\tTextDocument TextDocumentIdentifier `json:\"textDocument\"`\n\t// The position at which this request was sent.\n\tPosition Position `json:\"position\"`\n\t// The new name of the symbol. If the given name is not valid the\n\t// request must return a {@link ResponseError} with an\n\t// appropriate message set.\n\tNewName string `json:\"newName\"`\n\tWorkDoneProgressParams\n}\n\n// Registration options for a {@link RenameRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#renameRegistrationOptions\ntype RenameRegistrationOptions struct {\n\tTextDocumentRegistrationOptions\n\tRenameOptions\n}\n\n// A generic resource operation.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#resourceOperation\ntype ResourceOperation struct {\n\t// The resource operation kind.\n\tKind string `json:\"kind\"`\n\t// An optional annotation identifier describing the operation.\n\t//\n\t// @since 3.16.0\n\tAnnotationID *ChangeAnnotationIdentifier `json:\"annotationId,omitempty\"`\n}\ntype ResourceOperationKind string\n\n// Save options.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#saveOptions\ntype SaveOptions struct {\n\t// The client is supposed to include the content on save.\n\tIncludeText bool `json:\"includeText,omitempty\"`\n}\n\n// Describes the currently selected completion item.\n//\n// @since 3.18.0\n// @proposed\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#selectedCompletionInfo\ntype SelectedCompletionInfo struct {\n\t// The range that will be replaced if this completion item is accepted.\n\tRange Range `json:\"range\"`\n\t// The text the range will be replaced with if this completion is accepted.\n\tText string `json:\"text\"`\n}\n\n// A selection range represents a part of a selection hierarchy. A selection range\n// may have a parent selection range that contains it.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#selectionRange\ntype SelectionRange struct {\n\t// The {@link Range range} of this selection range.\n\tRange Range `json:\"range\"`\n\t// The parent selection range containing this range. Therefore `parent.range` must contain `this.range`.\n\tParent *SelectionRange `json:\"parent,omitempty\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#selectionRangeClientCapabilities\ntype SelectionRangeClientCapabilities struct {\n\t// Whether implementation supports dynamic registration for selection range providers. If this is set to `true`\n\t// the client supports the new `SelectionRangeRegistrationOptions` return value for the corresponding server\n\t// capability as well.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#selectionRangeOptions\ntype SelectionRangeOptions struct {\n\tWorkDoneProgressOptions\n}\n\n// A parameter literal used in selection range requests.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#selectionRangeParams\ntype SelectionRangeParams struct {\n\t// The text document.\n\tTextDocument TextDocumentIdentifier `json:\"textDocument\"`\n\t// The positions inside the text document.\n\tPositions []Position `json:\"positions\"`\n\tWorkDoneProgressParams\n\tPartialResultParams\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#selectionRangeRegistrationOptions\ntype SelectionRangeRegistrationOptions struct {\n\tSelectionRangeOptions\n\tTextDocumentRegistrationOptions\n\tStaticRegistrationOptions\n}\n\n// A set of predefined token modifiers. This set is not fixed\n// an clients can specify additional token types via the\n// corresponding client capabilities.\n//\n// @since 3.16.0\ntype SemanticTokenModifiers string\n\n// A set of predefined token types. This set is not fixed\n// an clients can specify additional token types via the\n// corresponding client capabilities.\n//\n// @since 3.16.0\ntype SemanticTokenTypes string\n\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#semanticTokens\ntype SemanticTokens struct {\n\t// An optional result id. If provided and clients support delta updating\n\t// the client will include the result id in the next semantic token request.\n\t// A server can then instead of computing all semantic tokens again simply\n\t// send a delta.\n\tResultID string `json:\"resultId,omitempty\"`\n\t// The actual tokens.\n\tData []uint32 `json:\"data\"`\n}\n\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#semanticTokensClientCapabilities\ntype SemanticTokensClientCapabilities struct {\n\t// Whether implementation supports dynamic registration. If this is set to `true`\n\t// the client supports the new `(TextDocumentRegistrationOptions & StaticRegistrationOptions)`\n\t// return value for the corresponding server capability as well.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n\t// Which requests the client supports and might send to the server\n\t// depending on the server's capability. Please note that clients might not\n\t// show semantic tokens or degrade some of the user experience if a range\n\t// or full request is advertised by the client but not provided by the\n\t// server. If for example the client capability `requests.full` and\n\t// `request.range` are both set to true but the server only provides a\n\t// range provider the client might not render a minimap correctly or might\n\t// even decide to not show any semantic tokens at all.\n\tRequests ClientSemanticTokensRequestOptions `json:\"requests\"`\n\t// The token types that the client supports.\n\tTokenTypes []string `json:\"tokenTypes\"`\n\t// The token modifiers that the client supports.\n\tTokenModifiers []string `json:\"tokenModifiers\"`\n\t// The token formats the clients supports.\n\tFormats []TokenFormat `json:\"formats\"`\n\t// Whether the client supports tokens that can overlap each other.\n\tOverlappingTokenSupport bool `json:\"overlappingTokenSupport,omitempty\"`\n\t// Whether the client supports tokens that can span multiple lines.\n\tMultilineTokenSupport bool `json:\"multilineTokenSupport,omitempty\"`\n\t// Whether the client allows the server to actively cancel a\n\t// semantic token request, e.g. supports returning\n\t// LSPErrorCodes.ServerCancelled. If a server does the client\n\t// needs to retrigger the request.\n\t//\n\t// @since 3.17.0\n\tServerCancelSupport bool `json:\"serverCancelSupport,omitempty\"`\n\t// Whether the client uses semantic tokens to augment existing\n\t// syntax tokens. If set to `true` client side created syntax\n\t// tokens and semantic tokens are both used for colorization. If\n\t// set to `false` the client only uses the returned semantic tokens\n\t// for colorization.\n\t//\n\t// If the value is `undefined` then the client behavior is not\n\t// specified.\n\t//\n\t// @since 3.17.0\n\tAugmentsSyntaxTokens bool `json:\"augmentsSyntaxTokens,omitempty\"`\n}\n\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#semanticTokensDelta\ntype SemanticTokensDelta struct {\n\tResultID string `json:\"resultId,omitempty\"`\n\t// The semantic token edits to transform a previous result into a new result.\n\tEdits []SemanticTokensEdit `json:\"edits\"`\n}\n\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#semanticTokensDeltaParams\ntype SemanticTokensDeltaParams struct {\n\t// The text document.\n\tTextDocument TextDocumentIdentifier `json:\"textDocument\"`\n\t// The result id of a previous response. The result Id can either point to a full response\n\t// or a delta response depending on what was received last.\n\tPreviousResultID string `json:\"previousResultId\"`\n\tWorkDoneProgressParams\n\tPartialResultParams\n}\n\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#semanticTokensDeltaPartialResult\ntype SemanticTokensDeltaPartialResult struct {\n\tEdits []SemanticTokensEdit `json:\"edits\"`\n}\n\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#semanticTokensEdit\ntype SemanticTokensEdit struct {\n\t// The start offset of the edit.\n\tStart uint32 `json:\"start\"`\n\t// The count of elements to remove.\n\tDeleteCount uint32 `json:\"deleteCount\"`\n\t// The elements to insert.\n\tData []uint32 `json:\"data,omitempty\"`\n}\n\n// Semantic tokens options to support deltas for full documents\n//\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#semanticTokensFullDelta\ntype SemanticTokensFullDelta struct {\n\t// The server supports deltas for full documents.\n\tDelta bool `json:\"delta,omitempty\"`\n}\n\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#semanticTokensLegend\ntype SemanticTokensLegend struct {\n\t// The token types a server uses.\n\tTokenTypes []string `json:\"tokenTypes\"`\n\t// The token modifiers a server uses.\n\tTokenModifiers []string `json:\"tokenModifiers\"`\n}\n\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#semanticTokensOptions\ntype SemanticTokensOptions struct {\n\t// The legend used by the server\n\tLegend SemanticTokensLegend `json:\"legend\"`\n\t// Server supports providing semantic tokens for a specific range\n\t// of a document.\n\tRange *Or_SemanticTokensOptions_range `json:\"range,omitempty\"`\n\t// Server supports providing semantic tokens for a full document.\n\tFull *Or_SemanticTokensOptions_full `json:\"full,omitempty\"`\n\tWorkDoneProgressOptions\n}\n\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#semanticTokensParams\ntype SemanticTokensParams struct {\n\t// The text document.\n\tTextDocument TextDocumentIdentifier `json:\"textDocument\"`\n\tWorkDoneProgressParams\n\tPartialResultParams\n}\n\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#semanticTokensPartialResult\ntype SemanticTokensPartialResult struct {\n\tData []uint32 `json:\"data\"`\n}\n\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#semanticTokensRangeParams\ntype SemanticTokensRangeParams struct {\n\t// The text document.\n\tTextDocument TextDocumentIdentifier `json:\"textDocument\"`\n\t// The range the semantic tokens are requested for.\n\tRange Range `json:\"range\"`\n\tWorkDoneProgressParams\n\tPartialResultParams\n}\n\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#semanticTokensRegistrationOptions\ntype SemanticTokensRegistrationOptions struct {\n\tTextDocumentRegistrationOptions\n\tSemanticTokensOptions\n\tStaticRegistrationOptions\n}\n\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#semanticTokensWorkspaceClientCapabilities\ntype SemanticTokensWorkspaceClientCapabilities struct {\n\t// Whether the client implementation supports a refresh request sent from\n\t// the server to the client.\n\t//\n\t// Note that this event is global and will force the client to refresh all\n\t// semantic tokens currently shown. It should be used with absolute care\n\t// and is useful for situation where a server for example detects a project\n\t// wide change that requires such a calculation.\n\tRefreshSupport bool `json:\"refreshSupport,omitempty\"`\n}\n\n// Defines the capabilities provided by a language\n// server.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#serverCapabilities\ntype ServerCapabilities struct {\n\t// The position encoding the server picked from the encodings offered\n\t// by the client via the client capability `general.positionEncodings`.\n\t//\n\t// If the client didn't provide any position encodings the only valid\n\t// value that a server can return is 'utf-16'.\n\t//\n\t// If omitted it defaults to 'utf-16'.\n\t//\n\t// @since 3.17.0\n\tPositionEncoding *PositionEncodingKind `json:\"positionEncoding,omitempty\"`\n\t// Defines how text documents are synced. Is either a detailed structure\n\t// defining each notification or for backwards compatibility the\n\t// TextDocumentSyncKind number.\n\tTextDocumentSync interface{} `json:\"textDocumentSync,omitempty\"`\n\t// Defines how notebook documents are synced.\n\t//\n\t// @since 3.17.0\n\tNotebookDocumentSync *Or_ServerCapabilities_notebookDocumentSync `json:\"notebookDocumentSync,omitempty\"`\n\t// The server provides completion support.\n\tCompletionProvider *CompletionOptions `json:\"completionProvider,omitempty\"`\n\t// The server provides hover support.\n\tHoverProvider *Or_ServerCapabilities_hoverProvider `json:\"hoverProvider,omitempty\"`\n\t// The server provides signature help support.\n\tSignatureHelpProvider *SignatureHelpOptions `json:\"signatureHelpProvider,omitempty\"`\n\t// The server provides Goto Declaration support.\n\tDeclarationProvider *Or_ServerCapabilities_declarationProvider `json:\"declarationProvider,omitempty\"`\n\t// The server provides goto definition support.\n\tDefinitionProvider *Or_ServerCapabilities_definitionProvider `json:\"definitionProvider,omitempty\"`\n\t// The server provides Goto Type Definition support.\n\tTypeDefinitionProvider *Or_ServerCapabilities_typeDefinitionProvider `json:\"typeDefinitionProvider,omitempty\"`\n\t// The server provides Goto Implementation support.\n\tImplementationProvider *Or_ServerCapabilities_implementationProvider `json:\"implementationProvider,omitempty\"`\n\t// The server provides find references support.\n\tReferencesProvider *Or_ServerCapabilities_referencesProvider `json:\"referencesProvider,omitempty\"`\n\t// The server provides document highlight support.\n\tDocumentHighlightProvider *Or_ServerCapabilities_documentHighlightProvider `json:\"documentHighlightProvider,omitempty\"`\n\t// The server provides document symbol support.\n\tDocumentSymbolProvider *Or_ServerCapabilities_documentSymbolProvider `json:\"documentSymbolProvider,omitempty\"`\n\t// The server provides code actions. CodeActionOptions may only be\n\t// specified if the client states that it supports\n\t// `codeActionLiteralSupport` in its initial `initialize` request.\n\tCodeActionProvider interface{} `json:\"codeActionProvider,omitempty\"`\n\t// The server provides code lens.\n\tCodeLensProvider *CodeLensOptions `json:\"codeLensProvider,omitempty\"`\n\t// The server provides document link support.\n\tDocumentLinkProvider *DocumentLinkOptions `json:\"documentLinkProvider,omitempty\"`\n\t// The server provides color provider support.\n\tColorProvider *Or_ServerCapabilities_colorProvider `json:\"colorProvider,omitempty\"`\n\t// The server provides workspace symbol support.\n\tWorkspaceSymbolProvider *Or_ServerCapabilities_workspaceSymbolProvider `json:\"workspaceSymbolProvider,omitempty\"`\n\t// The server provides document formatting.\n\tDocumentFormattingProvider *Or_ServerCapabilities_documentFormattingProvider `json:\"documentFormattingProvider,omitempty\"`\n\t// The server provides document range formatting.\n\tDocumentRangeFormattingProvider *Or_ServerCapabilities_documentRangeFormattingProvider `json:\"documentRangeFormattingProvider,omitempty\"`\n\t// The server provides document formatting on typing.\n\tDocumentOnTypeFormattingProvider *DocumentOnTypeFormattingOptions `json:\"documentOnTypeFormattingProvider,omitempty\"`\n\t// The server provides rename support. RenameOptions may only be\n\t// specified if the client states that it supports\n\t// `prepareSupport` in its initial `initialize` request.\n\tRenameProvider interface{} `json:\"renameProvider,omitempty\"`\n\t// The server provides folding provider support.\n\tFoldingRangeProvider *Or_ServerCapabilities_foldingRangeProvider `json:\"foldingRangeProvider,omitempty\"`\n\t// The server provides selection range support.\n\tSelectionRangeProvider *Or_ServerCapabilities_selectionRangeProvider `json:\"selectionRangeProvider,omitempty\"`\n\t// The server provides execute command support.\n\tExecuteCommandProvider *ExecuteCommandOptions `json:\"executeCommandProvider,omitempty\"`\n\t// The server provides call hierarchy support.\n\t//\n\t// @since 3.16.0\n\tCallHierarchyProvider *Or_ServerCapabilities_callHierarchyProvider `json:\"callHierarchyProvider,omitempty\"`\n\t// The server provides linked editing range support.\n\t//\n\t// @since 3.16.0\n\tLinkedEditingRangeProvider *Or_ServerCapabilities_linkedEditingRangeProvider `json:\"linkedEditingRangeProvider,omitempty\"`\n\t// The server provides semantic tokens support.\n\t//\n\t// @since 3.16.0\n\tSemanticTokensProvider interface{} `json:\"semanticTokensProvider,omitempty\"`\n\t// The server provides moniker support.\n\t//\n\t// @since 3.16.0\n\tMonikerProvider *Or_ServerCapabilities_monikerProvider `json:\"monikerProvider,omitempty\"`\n\t// The server provides type hierarchy support.\n\t//\n\t// @since 3.17.0\n\tTypeHierarchyProvider *Or_ServerCapabilities_typeHierarchyProvider `json:\"typeHierarchyProvider,omitempty\"`\n\t// The server provides inline values.\n\t//\n\t// @since 3.17.0\n\tInlineValueProvider *Or_ServerCapabilities_inlineValueProvider `json:\"inlineValueProvider,omitempty\"`\n\t// The server provides inlay hints.\n\t//\n\t// @since 3.17.0\n\tInlayHintProvider interface{} `json:\"inlayHintProvider,omitempty\"`\n\t// The server has support for pull model diagnostics.\n\t//\n\t// @since 3.17.0\n\tDiagnosticProvider *Or_ServerCapabilities_diagnosticProvider `json:\"diagnosticProvider,omitempty\"`\n\t// Inline completion options used during static registration.\n\t//\n\t// @since 3.18.0\n\t// @proposed\n\tInlineCompletionProvider *Or_ServerCapabilities_inlineCompletionProvider `json:\"inlineCompletionProvider,omitempty\"`\n\t// Workspace specific server capabilities.\n\tWorkspace *WorkspaceOptions `json:\"workspace,omitempty\"`\n\t// Experimental server capabilities.\n\tExperimental interface{} `json:\"experimental,omitempty\"`\n}\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#serverCompletionItemOptions\ntype ServerCompletionItemOptions struct {\n\t// The server has support for completion item label\n\t// details (see also `CompletionItemLabelDetails`) when\n\t// receiving a completion item in a resolve call.\n\t//\n\t// @since 3.17.0\n\tLabelDetailsSupport bool `json:\"labelDetailsSupport,omitempty\"`\n}\n\n// Information about the server\n//\n// @since 3.15.0\n// @since 3.18.0 ServerInfo type name added.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#serverInfo\ntype ServerInfo struct {\n\t// The name of the server as defined by the server.\n\tName string `json:\"name\"`\n\t// The server's version as defined by the server.\n\tVersion string `json:\"version,omitempty\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#setTraceParams\ntype SetTraceParams struct {\n\tValue TraceValue `json:\"value\"`\n}\n\n// Client capabilities for the showDocument request.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#showDocumentClientCapabilities\ntype ShowDocumentClientCapabilities struct {\n\t// The client has support for the showDocument\n\t// request.\n\tSupport bool `json:\"support\"`\n}\n\n// Params to show a resource in the UI.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#showDocumentParams\ntype ShowDocumentParams struct {\n\t// The uri to show.\n\tURI URI `json:\"uri\"`\n\t// Indicates to show the resource in an external program.\n\t// To show, for example, `https://code.visualstudio.com/`\n\t// in the default WEB browser set `external` to `true`.\n\tExternal bool `json:\"external,omitempty\"`\n\t// An optional property to indicate whether the editor\n\t// showing the document should take focus or not.\n\t// Clients might ignore this property if an external\n\t// program is started.\n\tTakeFocus bool `json:\"takeFocus,omitempty\"`\n\t// An optional selection range if the document is a text\n\t// document. Clients might ignore the property if an\n\t// external program is started or the file is not a text\n\t// file.\n\tSelection *Range `json:\"selection,omitempty\"`\n}\n\n// The result of a showDocument request.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#showDocumentResult\ntype ShowDocumentResult struct {\n\t// A boolean indicating if the show was successful.\n\tSuccess bool `json:\"success\"`\n}\n\n// The parameters of a notification message.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#showMessageParams\ntype ShowMessageParams struct {\n\t// The message type. See {@link MessageType}\n\tType MessageType `json:\"type\"`\n\t// The actual message.\n\tMessage string `json:\"message\"`\n}\n\n// Show message request client capabilities\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#showMessageRequestClientCapabilities\ntype ShowMessageRequestClientCapabilities struct {\n\t// Capabilities specific to the `MessageActionItem` type.\n\tMessageActionItem *ClientShowMessageActionItemOptions `json:\"messageActionItem,omitempty\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#showMessageRequestParams\ntype ShowMessageRequestParams struct {\n\t// The message type. See {@link MessageType}\n\tType MessageType `json:\"type\"`\n\t// The actual message.\n\tMessage string `json:\"message\"`\n\t// The message action items to present.\n\tActions []MessageActionItem `json:\"actions,omitempty\"`\n}\n\n// Signature help represents the signature of something\n// callable. There can be multiple signature but only one\n// active and only one active parameter.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#signatureHelp\ntype SignatureHelp struct {\n\t// One or more signatures.\n\tSignatures []SignatureInformation `json:\"signatures\"`\n\t// The active signature. If omitted or the value lies outside the\n\t// range of `signatures` the value defaults to zero or is ignored if\n\t// the `SignatureHelp` has no signatures.\n\t//\n\t// Whenever possible implementors should make an active decision about\n\t// the active signature and shouldn't rely on a default value.\n\t//\n\t// In future version of the protocol this property might become\n\t// mandatory to better express this.\n\tActiveSignature uint32 `json:\"activeSignature,omitempty\"`\n\t// The active parameter of the active signature.\n\t//\n\t// If `null`, no parameter of the signature is active (for example a named\n\t// argument that does not match any declared parameters). This is only valid\n\t// if the client specifies the client capability\n\t// `textDocument.signatureHelp.noActiveParameterSupport === true`\n\t//\n\t// If omitted or the value lies outside the range of\n\t// `signatures[activeSignature].parameters` defaults to 0 if the active\n\t// signature has parameters.\n\t//\n\t// If the active signature has no parameters it is ignored.\n\t//\n\t// In future version of the protocol this property might become\n\t// mandatory (but still nullable) to better express the active parameter if\n\t// the active signature does have any.\n\tActiveParameter uint32 `json:\"activeParameter,omitempty\"`\n}\n\n// Client Capabilities for a {@link SignatureHelpRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#signatureHelpClientCapabilities\ntype SignatureHelpClientCapabilities struct {\n\t// Whether signature help supports dynamic registration.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n\t// The client supports the following `SignatureInformation`\n\t// specific properties.\n\tSignatureInformation *ClientSignatureInformationOptions `json:\"signatureInformation,omitempty\"`\n\t// The client supports to send additional context information for a\n\t// `textDocument/signatureHelp` request. A client that opts into\n\t// contextSupport will also support the `retriggerCharacters` on\n\t// `SignatureHelpOptions`.\n\t//\n\t// @since 3.15.0\n\tContextSupport bool `json:\"contextSupport,omitempty\"`\n}\n\n// Additional information about the context in which a signature help request was triggered.\n//\n// @since 3.15.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#signatureHelpContext\ntype SignatureHelpContext struct {\n\t// Action that caused signature help to be triggered.\n\tTriggerKind SignatureHelpTriggerKind `json:\"triggerKind\"`\n\t// Character that caused signature help to be triggered.\n\t//\n\t// This is undefined when `triggerKind !== SignatureHelpTriggerKind.TriggerCharacter`\n\tTriggerCharacter string `json:\"triggerCharacter,omitempty\"`\n\t// `true` if signature help was already showing when it was triggered.\n\t//\n\t// Retriggers occurs when the signature help is already active and can be caused by actions such as\n\t// typing a trigger character, a cursor move, or document content changes.\n\tIsRetrigger bool `json:\"isRetrigger\"`\n\t// The currently active `SignatureHelp`.\n\t//\n\t// The `activeSignatureHelp` has its `SignatureHelp.activeSignature` field updated based on\n\t// the user navigating through available signatures.\n\tActiveSignatureHelp *SignatureHelp `json:\"activeSignatureHelp,omitempty\"`\n}\n\n// Server Capabilities for a {@link SignatureHelpRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#signatureHelpOptions\ntype SignatureHelpOptions struct {\n\t// List of characters that trigger signature help automatically.\n\tTriggerCharacters []string `json:\"triggerCharacters,omitempty\"`\n\t// List of characters that re-trigger signature help.\n\t//\n\t// These trigger characters are only active when signature help is already showing. All trigger characters\n\t// are also counted as re-trigger characters.\n\t//\n\t// @since 3.15.0\n\tRetriggerCharacters []string `json:\"retriggerCharacters,omitempty\"`\n\tWorkDoneProgressOptions\n}\n\n// Parameters for a {@link SignatureHelpRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#signatureHelpParams\ntype SignatureHelpParams struct {\n\t// The signature help context. This is only available if the client specifies\n\t// to send this using the client capability `textDocument.signatureHelp.contextSupport === true`\n\t//\n\t// @since 3.15.0\n\tContext *SignatureHelpContext `json:\"context,omitempty\"`\n\tTextDocumentPositionParams\n\tWorkDoneProgressParams\n}\n\n// Registration options for a {@link SignatureHelpRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#signatureHelpRegistrationOptions\ntype SignatureHelpRegistrationOptions struct {\n\tTextDocumentRegistrationOptions\n\tSignatureHelpOptions\n}\n\n// How a signature help was triggered.\n//\n// @since 3.15.0\ntype SignatureHelpTriggerKind uint32\n\n// Represents the signature of something callable. A signature\n// can have a label, like a function-name, a doc-comment, and\n// a set of parameters.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#signatureInformation\ntype SignatureInformation struct {\n\t// The label of this signature. Will be shown in\n\t// the UI.\n\tLabel string `json:\"label\"`\n\t// The human-readable doc-comment of this signature. Will be shown\n\t// in the UI but can be omitted.\n\tDocumentation *Or_SignatureInformation_documentation `json:\"documentation,omitempty\"`\n\t// The parameters of this signature.\n\tParameters []ParameterInformation `json:\"parameters,omitempty\"`\n\t// The index of the active parameter.\n\t//\n\t// If `null`, no parameter of the signature is active (for example a named\n\t// argument that does not match any declared parameters). This is only valid\n\t// if the client specifies the client capability\n\t// `textDocument.signatureHelp.noActiveParameterSupport === true`\n\t//\n\t// If provided (or `null`), this is used in place of\n\t// `SignatureHelp.activeParameter`.\n\t//\n\t// @since 3.16.0\n\tActiveParameter uint32 `json:\"activeParameter,omitempty\"`\n}\n\n// An interactive text edit.\n//\n// @since 3.18.0\n// @proposed\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#snippetTextEdit\ntype SnippetTextEdit struct {\n\t// The range of the text document to be manipulated.\n\tRange Range `json:\"range\"`\n\t// The snippet to be inserted.\n\tSnippet StringValue `json:\"snippet\"`\n\t// The actual identifier of the snippet edit.\n\tAnnotationID *ChangeAnnotationIdentifier `json:\"annotationId,omitempty\"`\n}\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#staleRequestSupportOptions\ntype StaleRequestSupportOptions struct {\n\t// The client will actively cancel the request.\n\tCancel bool `json:\"cancel\"`\n\t// The list of requests for which the client\n\t// will retry the request if it receives a\n\t// response with error code `ContentModified`\n\tRetryOnContentModified []string `json:\"retryOnContentModified\"`\n}\n\n// Static registration options to be returned in the initialize\n// request.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#staticRegistrationOptions\ntype StaticRegistrationOptions struct {\n\t// The id used to register the request. The id can be used to deregister\n\t// the request again. See also Registration#id.\n\tID string `json:\"id,omitempty\"`\n}\n\n// A string value used as a snippet is a template which allows to insert text\n// and to control the editor cursor when insertion happens.\n//\n// A snippet can define tab stops and placeholders with `$1`, `$2`\n// and `${3:foo}`. `$0` defines the final tab stop, it defaults to\n// the end of the snippet. Variables are defined with `$name` and\n// `${name:default value}`.\n//\n// @since 3.18.0\n// @proposed\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#stringValue\ntype StringValue struct {\n\t// The kind of string value.\n\tKind string `json:\"kind\"`\n\t// The snippet string.\n\tValue string `json:\"value\"`\n}\n\n// Represents information about programming constructs like variables, classes,\n// interfaces etc.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#symbolInformation\ntype SymbolInformation struct {\n\t// extends BaseSymbolInformation\n\t// Indicates if this symbol is deprecated.\n\t//\n\t// @deprecated Use tags instead\n\tDeprecated bool `json:\"deprecated,omitempty\"`\n\t// The location of this symbol. The location's range is used by a tool\n\t// to reveal the location in the editor. If the symbol is selected in the\n\t// tool the range's start information is used to position the cursor. So\n\t// the range usually spans more than the actual symbol's name and does\n\t// normally include things like visibility modifiers.\n\t//\n\t// The range doesn't have to denote a node range in the sense of an abstract\n\t// syntax tree. It can therefore not be used to re-construct a hierarchy of\n\t// the symbols.\n\tLocation Location `json:\"location\"`\n\t// The name of this symbol.\n\tName string `json:\"name\"`\n\t// The kind of this symbol.\n\tKind SymbolKind `json:\"kind\"`\n\t// Tags for this symbol.\n\t//\n\t// @since 3.16.0\n\tTags []SymbolTag `json:\"tags,omitempty\"`\n\t// The name of the symbol containing this symbol. This information is for\n\t// user interface purposes (e.g. to render a qualifier in the user interface\n\t// if necessary). It can't be used to re-infer a hierarchy for the document\n\t// symbols.\n\tContainerName string `json:\"containerName,omitempty\"`\n}\n\n// A symbol kind.\ntype SymbolKind uint32\n\n// Symbol tags are extra annotations that tweak the rendering of a symbol.\n//\n// @since 3.16\ntype SymbolTag uint32\n\n// Describe options to be used when registered for text document change events.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#textDocumentChangeRegistrationOptions\ntype TextDocumentChangeRegistrationOptions struct {\n\t// How documents are synced to the server.\n\tSyncKind TextDocumentSyncKind `json:\"syncKind\"`\n\tTextDocumentRegistrationOptions\n}\n\n// Text document specific client capabilities.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#textDocumentClientCapabilities\ntype TextDocumentClientCapabilities struct {\n\t// Defines which synchronization capabilities the client supports.\n\tSynchronization *TextDocumentSyncClientCapabilities `json:\"synchronization,omitempty\"`\n\t// Capabilities specific to the `textDocument/completion` request.\n\tCompletion CompletionClientCapabilities `json:\"completion,omitempty\"`\n\t// Capabilities specific to the `textDocument/hover` request.\n\tHover *HoverClientCapabilities `json:\"hover,omitempty\"`\n\t// Capabilities specific to the `textDocument/signatureHelp` request.\n\tSignatureHelp *SignatureHelpClientCapabilities `json:\"signatureHelp,omitempty\"`\n\t// Capabilities specific to the `textDocument/declaration` request.\n\t//\n\t// @since 3.14.0\n\tDeclaration *DeclarationClientCapabilities `json:\"declaration,omitempty\"`\n\t// Capabilities specific to the `textDocument/definition` request.\n\tDefinition *DefinitionClientCapabilities `json:\"definition,omitempty\"`\n\t// Capabilities specific to the `textDocument/typeDefinition` request.\n\t//\n\t// @since 3.6.0\n\tTypeDefinition *TypeDefinitionClientCapabilities `json:\"typeDefinition,omitempty\"`\n\t// Capabilities specific to the `textDocument/implementation` request.\n\t//\n\t// @since 3.6.0\n\tImplementation *ImplementationClientCapabilities `json:\"implementation,omitempty\"`\n\t// Capabilities specific to the `textDocument/references` request.\n\tReferences *ReferenceClientCapabilities `json:\"references,omitempty\"`\n\t// Capabilities specific to the `textDocument/documentHighlight` request.\n\tDocumentHighlight *DocumentHighlightClientCapabilities `json:\"documentHighlight,omitempty\"`\n\t// Capabilities specific to the `textDocument/documentSymbol` request.\n\tDocumentSymbol DocumentSymbolClientCapabilities `json:\"documentSymbol,omitempty\"`\n\t// Capabilities specific to the `textDocument/codeAction` request.\n\tCodeAction CodeActionClientCapabilities `json:\"codeAction,omitempty\"`\n\t// Capabilities specific to the `textDocument/codeLens` request.\n\tCodeLens *CodeLensClientCapabilities `json:\"codeLens,omitempty\"`\n\t// Capabilities specific to the `textDocument/documentLink` request.\n\tDocumentLink *DocumentLinkClientCapabilities `json:\"documentLink,omitempty\"`\n\t// Capabilities specific to the `textDocument/documentColor` and the\n\t// `textDocument/colorPresentation` request.\n\t//\n\t// @since 3.6.0\n\tColorProvider *DocumentColorClientCapabilities `json:\"colorProvider,omitempty\"`\n\t// Capabilities specific to the `textDocument/formatting` request.\n\tFormatting *DocumentFormattingClientCapabilities `json:\"formatting,omitempty\"`\n\t// Capabilities specific to the `textDocument/rangeFormatting` request.\n\tRangeFormatting *DocumentRangeFormattingClientCapabilities `json:\"rangeFormatting,omitempty\"`\n\t// Capabilities specific to the `textDocument/onTypeFormatting` request.\n\tOnTypeFormatting *DocumentOnTypeFormattingClientCapabilities `json:\"onTypeFormatting,omitempty\"`\n\t// Capabilities specific to the `textDocument/rename` request.\n\tRename *RenameClientCapabilities `json:\"rename,omitempty\"`\n\t// Capabilities specific to the `textDocument/foldingRange` request.\n\t//\n\t// @since 3.10.0\n\tFoldingRange *FoldingRangeClientCapabilities `json:\"foldingRange,omitempty\"`\n\t// Capabilities specific to the `textDocument/selectionRange` request.\n\t//\n\t// @since 3.15.0\n\tSelectionRange *SelectionRangeClientCapabilities `json:\"selectionRange,omitempty\"`\n\t// Capabilities specific to the `textDocument/publishDiagnostics` notification.\n\tPublishDiagnostics PublishDiagnosticsClientCapabilities `json:\"publishDiagnostics,omitempty\"`\n\t// Capabilities specific to the various call hierarchy requests.\n\t//\n\t// @since 3.16.0\n\tCallHierarchy *CallHierarchyClientCapabilities `json:\"callHierarchy,omitempty\"`\n\t// Capabilities specific to the various semantic token request.\n\t//\n\t// @since 3.16.0\n\tSemanticTokens SemanticTokensClientCapabilities `json:\"semanticTokens,omitempty\"`\n\t// Capabilities specific to the `textDocument/linkedEditingRange` request.\n\t//\n\t// @since 3.16.0\n\tLinkedEditingRange *LinkedEditingRangeClientCapabilities `json:\"linkedEditingRange,omitempty\"`\n\t// Client capabilities specific to the `textDocument/moniker` request.\n\t//\n\t// @since 3.16.0\n\tMoniker *MonikerClientCapabilities `json:\"moniker,omitempty\"`\n\t// Capabilities specific to the various type hierarchy requests.\n\t//\n\t// @since 3.17.0\n\tTypeHierarchy *TypeHierarchyClientCapabilities `json:\"typeHierarchy,omitempty\"`\n\t// Capabilities specific to the `textDocument/inlineValue` request.\n\t//\n\t// @since 3.17.0\n\tInlineValue *InlineValueClientCapabilities `json:\"inlineValue,omitempty\"`\n\t// Capabilities specific to the `textDocument/inlayHint` request.\n\t//\n\t// @since 3.17.0\n\tInlayHint *InlayHintClientCapabilities `json:\"inlayHint,omitempty\"`\n\t// Capabilities specific to the diagnostic pull model.\n\t//\n\t// @since 3.17.0\n\tDiagnostic *DiagnosticClientCapabilities `json:\"diagnostic,omitempty\"`\n\t// Client capabilities specific to inline completions.\n\t//\n\t// @since 3.18.0\n\t// @proposed\n\tInlineCompletion *InlineCompletionClientCapabilities `json:\"inlineCompletion,omitempty\"`\n}\n\n// An event describing a change to a text document. If only a text is provided\n// it is considered to be the full content of the document.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#textDocumentContentChangeEvent\ntype TextDocumentContentChangeEvent = Or_TextDocumentContentChangeEvent // (alias)\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#textDocumentContentChangePartial\ntype TextDocumentContentChangePartial struct {\n\t// The range of the document that changed.\n\tRange *Range `json:\"range,omitempty\"`\n\t// The optional length of the range that got replaced.\n\t//\n\t// @deprecated use range instead.\n\tRangeLength uint32 `json:\"rangeLength,omitempty\"`\n\t// The new text for the provided range.\n\tText string `json:\"text\"`\n}\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#textDocumentContentChangeWholeDocument\ntype TextDocumentContentChangeWholeDocument struct {\n\t// The new text of the whole document.\n\tText string `json:\"text\"`\n}\n\n// Client capabilities for a text document content provider.\n//\n// @since 3.18.0\n// @proposed\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#textDocumentContentClientCapabilities\ntype TextDocumentContentClientCapabilities struct {\n\t// Text document content provider supports dynamic registration.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n}\n\n// Text document content provider options.\n//\n// @since 3.18.0\n// @proposed\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#textDocumentContentOptions\ntype TextDocumentContentOptions struct {\n\t// The scheme for which the server provides content.\n\tScheme string `json:\"scheme\"`\n}\n\n// Parameters for the `workspace/textDocumentContent` request.\n//\n// @since 3.18.0\n// @proposed\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#textDocumentContentParams\ntype TextDocumentContentParams struct {\n\t// The uri of the text document.\n\tURI DocumentUri `json:\"uri\"`\n}\n\n// Parameters for the `workspace/textDocumentContent/refresh` request.\n//\n// @since 3.18.0\n// @proposed\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#textDocumentContentRefreshParams\ntype TextDocumentContentRefreshParams struct {\n\t// The uri of the text document to refresh.\n\tURI DocumentUri `json:\"uri\"`\n}\n\n// Text document content provider registration options.\n//\n// @since 3.18.0\n// @proposed\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#textDocumentContentRegistrationOptions\ntype TextDocumentContentRegistrationOptions struct {\n\tTextDocumentContentOptions\n\tStaticRegistrationOptions\n}\n\n// Describes textual changes on a text document. A TextDocumentEdit describes all changes\n// on a document version Si and after they are applied move the document to version Si+1.\n// So the creator of a TextDocumentEdit doesn't need to sort the array of edits or do any\n// kind of ordering. However the edits must be non overlapping.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#textDocumentEdit\ntype TextDocumentEdit struct {\n\t// The text document to change.\n\tTextDocument OptionalVersionedTextDocumentIdentifier `json:\"textDocument\"`\n\t// The edits to be applied.\n\t//\n\t// @since 3.16.0 - support for AnnotatedTextEdit. This is guarded using a\n\t// client capability.\n\t//\n\t// @since 3.18.0 - support for SnippetTextEdit. This is guarded using a\n\t// client capability.\n\tEdits []Or_TextDocumentEdit_edits_Elem `json:\"edits\"`\n}\n\n// A document filter denotes a document by different properties like\n// the {@link TextDocument.languageId language}, the {@link Uri.scheme scheme} of\n// its resource, or a glob-pattern that is applied to the {@link TextDocument.fileName path}.\n//\n// Glob patterns can have the following syntax:\n//\n// - `*` to match one or more characters in a path segment\n// - `?` to match on one character in a path segment\n// - `**` to match any number of path segments, including none\n// - `{}` to group sub patterns into an OR expression. (e.g. `**/*.{ts,js}` matches all TypeScript and JavaScript files)\n// - `[]` to declare a range of characters to match in a path segment (e.g., `example.[0-9]` to match on `example.0`, `example.1`, …)\n// - `[!...]` to negate a range of characters to match in a path segment (e.g., `example.[!0-9]` to match on `example.a`, `example.b`, but not `example.0`)\n//\n// @sample A language filter that applies to typescript files on disk: `{ language: 'typescript', scheme: 'file' }`\n// @sample A language filter that applies to all package.json paths: `{ language: 'json', pattern: '**package.json' }`\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#textDocumentFilter\ntype TextDocumentFilter = Or_TextDocumentFilter // (alias)\n// A document filter where `language` is required field.\n//\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#textDocumentFilterLanguage\ntype TextDocumentFilterLanguage struct {\n\t// A language id, like `typescript`.\n\tLanguage string `json:\"language\"`\n\t// A Uri {@link Uri.scheme scheme}, like `file` or `untitled`.\n\tScheme string `json:\"scheme,omitempty\"`\n\t// A glob pattern, like **/*.{ts,js}. See TextDocumentFilter for examples.\n\t//\n\t// @since 3.18.0 - support for relative patterns.\n\tPattern *GlobPattern `json:\"pattern,omitempty\"`\n}\n\n// A document filter where `pattern` is required field.\n//\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#textDocumentFilterPattern\ntype TextDocumentFilterPattern struct {\n\t// A language id, like `typescript`.\n\tLanguage string `json:\"language,omitempty\"`\n\t// A Uri {@link Uri.scheme scheme}, like `file` or `untitled`.\n\tScheme string `json:\"scheme,omitempty\"`\n\t// A glob pattern, like **/*.{ts,js}. See TextDocumentFilter for examples.\n\t//\n\t// @since 3.18.0 - support for relative patterns.\n\tPattern GlobPattern `json:\"pattern\"`\n}\n\n// A document filter where `scheme` is required field.\n//\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#textDocumentFilterScheme\ntype TextDocumentFilterScheme struct {\n\t// A language id, like `typescript`.\n\tLanguage string `json:\"language,omitempty\"`\n\t// A Uri {@link Uri.scheme scheme}, like `file` or `untitled`.\n\tScheme string `json:\"scheme\"`\n\t// A glob pattern, like **/*.{ts,js}. See TextDocumentFilter for examples.\n\t//\n\t// @since 3.18.0 - support for relative patterns.\n\tPattern *GlobPattern `json:\"pattern,omitempty\"`\n}\n\n// A literal to identify a text document in the client.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#textDocumentIdentifier\ntype TextDocumentIdentifier struct {\n\t// The text document's uri.\n\tURI DocumentUri `json:\"uri\"`\n}\n\n// An item to transfer a text document from the client to the\n// server.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#textDocumentItem\ntype TextDocumentItem struct {\n\t// The text document's uri.\n\tURI DocumentUri `json:\"uri\"`\n\t// The text document's language identifier.\n\tLanguageID LanguageKind `json:\"languageId\"`\n\t// The version number of this document (it will increase after each\n\t// change, including undo/redo).\n\tVersion int32 `json:\"version\"`\n\t// The content of the opened text document.\n\tText string `json:\"text\"`\n}\n\n// A parameter literal used in requests to pass a text document and a position inside that\n// document.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#textDocumentPositionParams\ntype TextDocumentPositionParams struct {\n\t// The text document.\n\tTextDocument TextDocumentIdentifier `json:\"textDocument\"`\n\t// The position inside the text document.\n\tPosition Position `json:\"position\"`\n}\n\n// General text document registration options.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#textDocumentRegistrationOptions\ntype TextDocumentRegistrationOptions struct {\n\t// A document selector to identify the scope of the registration. If set to null\n\t// the document selector provided on the client side will be used.\n\tDocumentSelector DocumentSelector `json:\"documentSelector\"`\n}\n\n// Represents reasons why a text document is saved.\ntype TextDocumentSaveReason uint32\n\n// Save registration options.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#textDocumentSaveRegistrationOptions\ntype TextDocumentSaveRegistrationOptions struct {\n\tTextDocumentRegistrationOptions\n\tSaveOptions\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#textDocumentSyncClientCapabilities\ntype TextDocumentSyncClientCapabilities struct {\n\t// Whether text document synchronization supports dynamic registration.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n\t// The client supports sending will save notifications.\n\tWillSave bool `json:\"willSave,omitempty\"`\n\t// The client supports sending a will save request and\n\t// waits for a response providing text edits which will\n\t// be applied to the document before it is saved.\n\tWillSaveWaitUntil bool `json:\"willSaveWaitUntil,omitempty\"`\n\t// The client supports did save notifications.\n\tDidSave bool `json:\"didSave,omitempty\"`\n}\n\n// Defines how the host (editor) should sync\n// document changes to the language server.\ntype TextDocumentSyncKind uint32\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#textDocumentSyncOptions\ntype TextDocumentSyncOptions struct {\n\t// Open and close notifications are sent to the server. If omitted open close notification should not\n\t// be sent.\n\tOpenClose bool `json:\"openClose,omitempty\"`\n\t// Change notifications are sent to the server. See TextDocumentSyncKind.None, TextDocumentSyncKind.Full\n\t// and TextDocumentSyncKind.Incremental. If omitted it defaults to TextDocumentSyncKind.None.\n\tChange TextDocumentSyncKind `json:\"change,omitempty\"`\n\t// If present will save notifications are sent to the server. If omitted the notification should not be\n\t// sent.\n\tWillSave bool `json:\"willSave,omitempty\"`\n\t// If present will save wait until requests are sent to the server. If omitted the request should not be\n\t// sent.\n\tWillSaveWaitUntil bool `json:\"willSaveWaitUntil,omitempty\"`\n\t// If present save notifications are sent to the server. If omitted the notification should not be\n\t// sent.\n\tSave *SaveOptions `json:\"save,omitempty\"`\n}\n\n// A text edit applicable to a text document.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#textEdit\ntype TextEdit struct {\n\t// The range of the text document to be manipulated. To insert\n\t// text into a document create a range where start === end.\n\tRange Range `json:\"range\"`\n\t// The string to be inserted. For delete operations use an\n\t// empty string.\n\tNewText string `json:\"newText\"`\n}\ntype TokenFormat string\ntype TraceValue string\n\n// created for Tuple\ntype Tuple_ParameterInformation_label_Item1 struct {\n\tFld0 uint32 `json:\"fld0\"`\n\tFld1 uint32 `json:\"fld1\"`\n}\n\n// Since 3.6.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#typeDefinitionClientCapabilities\ntype TypeDefinitionClientCapabilities struct {\n\t// Whether implementation supports dynamic registration. If this is set to `true`\n\t// the client supports the new `TypeDefinitionRegistrationOptions` return value\n\t// for the corresponding server capability as well.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n\t// The client supports additional metadata in the form of definition links.\n\t//\n\t// Since 3.14.0\n\tLinkSupport bool `json:\"linkSupport,omitempty\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#typeDefinitionOptions\ntype TypeDefinitionOptions struct {\n\tWorkDoneProgressOptions\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#typeDefinitionParams\ntype TypeDefinitionParams struct {\n\tTextDocumentPositionParams\n\tWorkDoneProgressParams\n\tPartialResultParams\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#typeDefinitionRegistrationOptions\ntype TypeDefinitionRegistrationOptions struct {\n\tTextDocumentRegistrationOptions\n\tTypeDefinitionOptions\n\tStaticRegistrationOptions\n}\n\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#typeHierarchyClientCapabilities\ntype TypeHierarchyClientCapabilities struct {\n\t// Whether implementation supports dynamic registration. If this is set to `true`\n\t// the client supports the new `(TextDocumentRegistrationOptions & StaticRegistrationOptions)`\n\t// return value for the corresponding server capability as well.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n}\n\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#typeHierarchyItem\ntype TypeHierarchyItem struct {\n\t// The name of this item.\n\tName string `json:\"name\"`\n\t// The kind of this item.\n\tKind SymbolKind `json:\"kind\"`\n\t// Tags for this item.\n\tTags []SymbolTag `json:\"tags,omitempty\"`\n\t// More detail for this item, e.g. the signature of a function.\n\tDetail string `json:\"detail,omitempty\"`\n\t// The resource identifier of this item.\n\tURI DocumentUri `json:\"uri\"`\n\t// The range enclosing this symbol not including leading/trailing whitespace\n\t// but everything else, e.g. comments and code.\n\tRange Range `json:\"range\"`\n\t// The range that should be selected and revealed when this symbol is being\n\t// picked, e.g. the name of a function. Must be contained by the\n\t// {@link TypeHierarchyItem.range `range`}.\n\tSelectionRange Range `json:\"selectionRange\"`\n\t// A data entry field that is preserved between a type hierarchy prepare and\n\t// supertypes or subtypes requests. It could also be used to identify the\n\t// type hierarchy in the server, helping improve the performance on\n\t// resolving supertypes and subtypes.\n\tData interface{} `json:\"data,omitempty\"`\n}\n\n// Type hierarchy options used during static registration.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#typeHierarchyOptions\ntype TypeHierarchyOptions struct {\n\tWorkDoneProgressOptions\n}\n\n// The parameter of a `textDocument/prepareTypeHierarchy` request.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#typeHierarchyPrepareParams\ntype TypeHierarchyPrepareParams struct {\n\tTextDocumentPositionParams\n\tWorkDoneProgressParams\n}\n\n// Type hierarchy options used during static or dynamic registration.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#typeHierarchyRegistrationOptions\ntype TypeHierarchyRegistrationOptions struct {\n\tTextDocumentRegistrationOptions\n\tTypeHierarchyOptions\n\tStaticRegistrationOptions\n}\n\n// The parameter of a `typeHierarchy/subtypes` request.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#typeHierarchySubtypesParams\ntype TypeHierarchySubtypesParams struct {\n\tItem TypeHierarchyItem `json:\"item\"`\n\tWorkDoneProgressParams\n\tPartialResultParams\n}\n\n// The parameter of a `typeHierarchy/supertypes` request.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#typeHierarchySupertypesParams\ntype TypeHierarchySupertypesParams struct {\n\tItem TypeHierarchyItem `json:\"item\"`\n\tWorkDoneProgressParams\n\tPartialResultParams\n}\n\n// A diagnostic report indicating that the last returned\n// report is still accurate.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#unchangedDocumentDiagnosticReport\ntype UnchangedDocumentDiagnosticReport struct {\n\t// A document diagnostic report indicating\n\t// no changes to the last result. A server can\n\t// only return `unchanged` if result ids are\n\t// provided.\n\tKind string `json:\"kind\"`\n\t// A result id which will be sent on the next\n\t// diagnostic request for the same document.\n\tResultID string `json:\"resultId\"`\n}\n\n// Moniker uniqueness level to define scope of the moniker.\n//\n// @since 3.16.0\ntype UniquenessLevel string\n\n// General parameters to unregister a request or notification.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#unregistration\ntype Unregistration struct {\n\t// The id used to unregister the request or notification. Usually an id\n\t// provided during the register request.\n\tID string `json:\"id\"`\n\t// The method to unregister for.\n\tMethod string `json:\"method\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#unregistrationParams\ntype UnregistrationParams struct {\n\tUnregisterations []Unregistration `json:\"unregisterations\"`\n}\n\n// A versioned notebook document identifier.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#versionedNotebookDocumentIdentifier\ntype VersionedNotebookDocumentIdentifier struct {\n\t// The version number of this notebook document.\n\tVersion int32 `json:\"version\"`\n\t// The notebook document's uri.\n\tURI URI `json:\"uri\"`\n}\n\n// A text document identifier to denote a specific version of a text document.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#versionedTextDocumentIdentifier\ntype VersionedTextDocumentIdentifier struct {\n\t// The version number of this document.\n\tVersion int32 `json:\"version\"`\n\tTextDocumentIdentifier\n}\ntype WatchKind = uint32 // The parameters sent in a will save text document notification.\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#willSaveTextDocumentParams\ntype WillSaveTextDocumentParams struct {\n\t// The document that will be saved.\n\tTextDocument TextDocumentIdentifier `json:\"textDocument\"`\n\t// The 'TextDocumentSaveReason'.\n\tReason TextDocumentSaveReason `json:\"reason\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#windowClientCapabilities\ntype WindowClientCapabilities struct {\n\t// It indicates whether the client supports server initiated\n\t// progress using the `window/workDoneProgress/create` request.\n\t//\n\t// The capability also controls Whether client supports handling\n\t// of progress notifications. If set servers are allowed to report a\n\t// `workDoneProgress` property in the request specific server\n\t// capabilities.\n\t//\n\t// @since 3.15.0\n\tWorkDoneProgress bool `json:\"workDoneProgress,omitempty\"`\n\t// Capabilities specific to the showMessage request.\n\t//\n\t// @since 3.16.0\n\tShowMessage *ShowMessageRequestClientCapabilities `json:\"showMessage,omitempty\"`\n\t// Capabilities specific to the showDocument request.\n\t//\n\t// @since 3.16.0\n\tShowDocument *ShowDocumentClientCapabilities `json:\"showDocument,omitempty\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#workDoneProgressBegin\ntype WorkDoneProgressBegin struct {\n\tKind string `json:\"kind\"`\n\t// Mandatory title of the progress operation. Used to briefly inform about\n\t// the kind of operation being performed.\n\t//\n\t// Examples: \"Indexing\" or \"Linking dependencies\".\n\tTitle string `json:\"title\"`\n\t// Controls if a cancel button should show to allow the user to cancel the\n\t// long running operation. Clients that don't support cancellation are allowed\n\t// to ignore the setting.\n\tCancellable bool `json:\"cancellable,omitempty\"`\n\t// Optional, more detailed associated progress message. Contains\n\t// complementary information to the `title`.\n\t//\n\t// Examples: \"3/25 files\", \"project/src/module2\", \"node_modules/some_dep\".\n\t// If unset, the previous progress message (if any) is still valid.\n\tMessage string `json:\"message,omitempty\"`\n\t// Optional progress percentage to display (value 100 is considered 100%).\n\t// If not provided infinite progress is assumed and clients are allowed\n\t// to ignore the `percentage` value in subsequent in report notifications.\n\t//\n\t// The value should be steadily rising. Clients are free to ignore values\n\t// that are not following this rule. The value range is [0, 100].\n\tPercentage uint32 `json:\"percentage,omitempty\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#workDoneProgressCancelParams\ntype WorkDoneProgressCancelParams struct {\n\t// The token to be used to report progress.\n\tToken ProgressToken `json:\"token\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#workDoneProgressCreateParams\ntype WorkDoneProgressCreateParams struct {\n\t// The token to be used to report progress.\n\tToken ProgressToken `json:\"token\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#workDoneProgressEnd\ntype WorkDoneProgressEnd struct {\n\tKind string `json:\"kind\"`\n\t// Optional, a final message indicating to for example indicate the outcome\n\t// of the operation.\n\tMessage string `json:\"message,omitempty\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#workDoneProgressOptions\ntype WorkDoneProgressOptions struct {\n\tWorkDoneProgress bool `json:\"workDoneProgress,omitempty\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#workDoneProgressParams\ntype WorkDoneProgressParams struct {\n\t// An optional token that a server can use to report work done progress.\n\tWorkDoneToken ProgressToken `json:\"workDoneToken,omitempty\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#workDoneProgressReport\ntype WorkDoneProgressReport struct {\n\tKind string `json:\"kind\"`\n\t// Controls enablement state of a cancel button.\n\t//\n\t// Clients that don't support cancellation or don't support controlling the button's\n\t// enablement state are allowed to ignore the property.\n\tCancellable bool `json:\"cancellable,omitempty\"`\n\t// Optional, more detailed associated progress message. Contains\n\t// complementary information to the `title`.\n\t//\n\t// Examples: \"3/25 files\", \"project/src/module2\", \"node_modules/some_dep\".\n\t// If unset, the previous progress message (if any) is still valid.\n\tMessage string `json:\"message,omitempty\"`\n\t// Optional progress percentage to display (value 100 is considered 100%).\n\t// If not provided infinite progress is assumed and clients are allowed\n\t// to ignore the `percentage` value in subsequent in report notifications.\n\t//\n\t// The value should be steadily rising. Clients are free to ignore values\n\t// that are not following this rule. The value range is [0, 100]\n\tPercentage uint32 `json:\"percentage,omitempty\"`\n}\n\n// Workspace specific client capabilities.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#workspaceClientCapabilities\ntype WorkspaceClientCapabilities struct {\n\t// The client supports applying batch edits\n\t// to the workspace by supporting the request\n\t// 'workspace/applyEdit'\n\tApplyEdit bool `json:\"applyEdit,omitempty\"`\n\t// Capabilities specific to `WorkspaceEdit`s.\n\tWorkspaceEdit *WorkspaceEditClientCapabilities `json:\"workspaceEdit,omitempty\"`\n\t// Capabilities specific to the `workspace/didChangeConfiguration` notification.\n\tDidChangeConfiguration DidChangeConfigurationClientCapabilities `json:\"didChangeConfiguration,omitempty\"`\n\t// Capabilities specific to the `workspace/didChangeWatchedFiles` notification.\n\tDidChangeWatchedFiles DidChangeWatchedFilesClientCapabilities `json:\"didChangeWatchedFiles,omitempty\"`\n\t// Capabilities specific to the `workspace/symbol` request.\n\tSymbol *WorkspaceSymbolClientCapabilities `json:\"symbol,omitempty\"`\n\t// Capabilities specific to the `workspace/executeCommand` request.\n\tExecuteCommand *ExecuteCommandClientCapabilities `json:\"executeCommand,omitempty\"`\n\t// The client has support for workspace folders.\n\t//\n\t// @since 3.6.0\n\tWorkspaceFolders bool `json:\"workspaceFolders,omitempty\"`\n\t// The client supports `workspace/configuration` requests.\n\t//\n\t// @since 3.6.0\n\tConfiguration bool `json:\"configuration,omitempty\"`\n\t// Capabilities specific to the semantic token requests scoped to the\n\t// workspace.\n\t//\n\t// @since 3.16.0.\n\tSemanticTokens *SemanticTokensWorkspaceClientCapabilities `json:\"semanticTokens,omitempty\"`\n\t// Capabilities specific to the code lens requests scoped to the\n\t// workspace.\n\t//\n\t// @since 3.16.0.\n\tCodeLens *CodeLensWorkspaceClientCapabilities `json:\"codeLens,omitempty\"`\n\t// The client has support for file notifications/requests for user operations on files.\n\t//\n\t// Since 3.16.0\n\tFileOperations *FileOperationClientCapabilities `json:\"fileOperations,omitempty\"`\n\t// Capabilities specific to the inline values requests scoped to the\n\t// workspace.\n\t//\n\t// @since 3.17.0.\n\tInlineValue *InlineValueWorkspaceClientCapabilities `json:\"inlineValue,omitempty\"`\n\t// Capabilities specific to the inlay hint requests scoped to the\n\t// workspace.\n\t//\n\t// @since 3.17.0.\n\tInlayHint *InlayHintWorkspaceClientCapabilities `json:\"inlayHint,omitempty\"`\n\t// Capabilities specific to the diagnostic requests scoped to the\n\t// workspace.\n\t//\n\t// @since 3.17.0.\n\tDiagnostics *DiagnosticWorkspaceClientCapabilities `json:\"diagnostics,omitempty\"`\n\t// Capabilities specific to the folding range requests scoped to the workspace.\n\t//\n\t// @since 3.18.0\n\t// @proposed\n\tFoldingRange *FoldingRangeWorkspaceClientCapabilities `json:\"foldingRange,omitempty\"`\n\t// Capabilities specific to the `workspace/textDocumentContent` request.\n\t//\n\t// @since 3.18.0\n\t// @proposed\n\tTextDocumentContent *TextDocumentContentClientCapabilities `json:\"textDocumentContent,omitempty\"`\n}\n\n// Parameters of the workspace diagnostic request.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#workspaceDiagnosticParams\ntype WorkspaceDiagnosticParams struct {\n\t// The additional identifier provided during registration.\n\tIdentifier string `json:\"identifier,omitempty\"`\n\t// The currently known diagnostic reports with their\n\t// previous result ids.\n\tPreviousResultIds []PreviousResultId `json:\"previousResultIds\"`\n\tWorkDoneProgressParams\n\tPartialResultParams\n}\n\n// A workspace diagnostic report.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#workspaceDiagnosticReport\ntype WorkspaceDiagnosticReport struct {\n\tItems []WorkspaceDocumentDiagnosticReport `json:\"items\"`\n}\n\n// A partial result for a workspace diagnostic report.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#workspaceDiagnosticReportPartialResult\ntype WorkspaceDiagnosticReportPartialResult struct {\n\tItems []WorkspaceDocumentDiagnosticReport `json:\"items\"`\n}\n\n// A workspace diagnostic document report.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#workspaceDocumentDiagnosticReport\ntype WorkspaceDocumentDiagnosticReport = Or_WorkspaceDocumentDiagnosticReport // (alias)\n// A workspace edit represents changes to many resources managed in the workspace. The edit\n// should either provide `changes` or `documentChanges`. If documentChanges are present\n// they are preferred over `changes` if the client can handle versioned document edits.\n//\n// Since version 3.13.0 a workspace edit can contain resource operations as well. If resource\n// operations are present clients need to execute the operations in the order in which they\n// are provided. So a workspace edit for example can consist of the following two changes:\n// (1) a create file a.txt and (2) a text document edit which insert text into file a.txt.\n//\n// An invalid sequence (e.g. (1) delete file a.txt and (2) insert text into file a.txt) will\n// cause failure of the operation. How the client recovers from the failure is described by\n// the client capability: `workspace.workspaceEdit.failureHandling`\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#workspaceEdit\ntype WorkspaceEdit struct {\n\t// Holds changes to existing resources.\n\tChanges map[DocumentUri][]TextEdit `json:\"changes,omitempty\"`\n\t// Depending on the client capability `workspace.workspaceEdit.resourceOperations` document changes\n\t// are either an array of `TextDocumentEdit`s to express changes to n different text documents\n\t// where each text document edit addresses a specific version of a text document. Or it can contain\n\t// above `TextDocumentEdit`s mixed with create, rename and delete file / folder operations.\n\t//\n\t// Whether a client supports versioned document edits is expressed via\n\t// `workspace.workspaceEdit.documentChanges` client capability.\n\t//\n\t// If a client neither supports `documentChanges` nor `workspace.workspaceEdit.resourceOperations` then\n\t// only plain `TextEdit`s using the `changes` property are supported.\n\tDocumentChanges []DocumentChange `json:\"documentChanges,omitempty\"`\n\t// A map of change annotations that can be referenced in `AnnotatedTextEdit`s or create, rename and\n\t// delete file / folder operations.\n\t//\n\t// Whether clients honor this property depends on the client capability `workspace.changeAnnotationSupport`.\n\t//\n\t// @since 3.16.0\n\tChangeAnnotations map[ChangeAnnotationIdentifier]ChangeAnnotation `json:\"changeAnnotations,omitempty\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#workspaceEditClientCapabilities\ntype WorkspaceEditClientCapabilities struct {\n\t// The client supports versioned document changes in `WorkspaceEdit`s\n\tDocumentChanges bool `json:\"documentChanges,omitempty\"`\n\t// The resource operations the client supports. Clients should at least\n\t// support 'create', 'rename' and 'delete' files and folders.\n\t//\n\t// @since 3.13.0\n\tResourceOperations []ResourceOperationKind `json:\"resourceOperations,omitempty\"`\n\t// The failure handling strategy of a client if applying the workspace edit\n\t// fails.\n\t//\n\t// @since 3.13.0\n\tFailureHandling *FailureHandlingKind `json:\"failureHandling,omitempty\"`\n\t// Whether the client normalizes line endings to the client specific\n\t// setting.\n\t// If set to `true` the client will normalize line ending characters\n\t// in a workspace edit to the client-specified new line\n\t// character.\n\t//\n\t// @since 3.16.0\n\tNormalizesLineEndings bool `json:\"normalizesLineEndings,omitempty\"`\n\t// Whether the client in general supports change annotations on text edits,\n\t// create file, rename file and delete file changes.\n\t//\n\t// @since 3.16.0\n\tChangeAnnotationSupport *ChangeAnnotationsSupportOptions `json:\"changeAnnotationSupport,omitempty\"`\n\t// Whether the client supports `WorkspaceEditMetadata` in `WorkspaceEdit`s.\n\t//\n\t// @since 3.18.0\n\t// @proposed\n\tMetadataSupport bool `json:\"metadataSupport,omitempty\"`\n\t// Whether the client supports snippets as text edits.\n\t//\n\t// @since 3.18.0\n\t// @proposed\n\tSnippetEditSupport bool `json:\"snippetEditSupport,omitempty\"`\n}\n\n// Additional data about a workspace edit.\n//\n// @since 3.18.0\n// @proposed\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#workspaceEditMetadata\ntype WorkspaceEditMetadata struct {\n\t// Signal to the editor that this edit is a refactoring.\n\tIsRefactoring bool `json:\"isRefactoring,omitempty\"`\n}\n\n// A workspace folder inside a client.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#workspaceFolder\ntype WorkspaceFolder struct {\n\t// The associated URI for this workspace folder.\n\tURI URI `json:\"uri\"`\n\t// The name of the workspace folder. Used to refer to this\n\t// workspace folder in the user interface.\n\tName string `json:\"name\"`\n}\n\n// The workspace folder change event.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#workspaceFoldersChangeEvent\ntype WorkspaceFoldersChangeEvent struct {\n\t// The array of added workspace folders\n\tAdded []WorkspaceFolder `json:\"added\"`\n\t// The array of the removed workspace folders\n\tRemoved []WorkspaceFolder `json:\"removed\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#workspaceFoldersInitializeParams\ntype WorkspaceFoldersInitializeParams struct {\n\t// The workspace folders configured in the client when the server starts.\n\t//\n\t// This property is only available if the client supports workspace folders.\n\t// It can be `null` if the client supports workspace folders but none are\n\t// configured.\n\t//\n\t// @since 3.6.0\n\tWorkspaceFolders []WorkspaceFolder `json:\"workspaceFolders,omitempty\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#workspaceFoldersServerCapabilities\ntype WorkspaceFoldersServerCapabilities struct {\n\t// The server has support for workspace folders\n\tSupported bool `json:\"supported,omitempty\"`\n\t// Whether the server wants to receive workspace folder\n\t// change notifications.\n\t//\n\t// If a string is provided the string is treated as an ID\n\t// under which the notification is registered on the client\n\t// side. The ID can be used to unregister for these events\n\t// using the `client/unregisterCapability` request.\n\tChangeNotifications *Or_WorkspaceFoldersServerCapabilities_changeNotifications `json:\"changeNotifications,omitempty\"`\n}\n\n// A full document diagnostic report for a workspace diagnostic result.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#workspaceFullDocumentDiagnosticReport\ntype WorkspaceFullDocumentDiagnosticReport struct {\n\t// The URI for which diagnostic information is reported.\n\tURI DocumentUri `json:\"uri\"`\n\t// The version number for which the diagnostics are reported.\n\t// If the document is not marked as open `null` can be provided.\n\tVersion int32 `json:\"version\"`\n\tFullDocumentDiagnosticReport\n}\n\n// Defines workspace specific capabilities of the server.\n//\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#workspaceOptions\ntype WorkspaceOptions struct {\n\t// The server supports workspace folder.\n\t//\n\t// @since 3.6.0\n\tWorkspaceFolders *WorkspaceFoldersServerCapabilities `json:\"workspaceFolders,omitempty\"`\n\t// The server is interested in notifications/requests for operations on files.\n\t//\n\t// @since 3.16.0\n\tFileOperations *FileOperationOptions `json:\"fileOperations,omitempty\"`\n\t// The server supports the `workspace/textDocumentContent` request.\n\t//\n\t// @since 3.18.0\n\t// @proposed\n\tTextDocumentContent *Or_WorkspaceOptions_textDocumentContent `json:\"textDocumentContent,omitempty\"`\n}\n\n// A special workspace symbol that supports locations without a range.\n//\n// See also SymbolInformation.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#workspaceSymbol\ntype WorkspaceSymbol struct {\n\t// The location of the symbol. Whether a server is allowed to\n\t// return a location without a range depends on the client\n\t// capability `workspace.symbol.resolveSupport`.\n\t//\n\t// See SymbolInformation#location for more details.\n\tLocation Or_WorkspaceSymbol_location `json:\"location\"`\n\t// A data entry field that is preserved on a workspace symbol between a\n\t// workspace symbol request and a workspace symbol resolve request.\n\tData interface{} `json:\"data,omitempty\"`\n\tBaseSymbolInformation\n}\n\n// Client capabilities for a {@link WorkspaceSymbolRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#workspaceSymbolClientCapabilities\ntype WorkspaceSymbolClientCapabilities struct {\n\t// Symbol request supports dynamic registration.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n\t// Specific capabilities for the `SymbolKind` in the `workspace/symbol` request.\n\tSymbolKind *ClientSymbolKindOptions `json:\"symbolKind,omitempty\"`\n\t// The client supports tags on `SymbolInformation`.\n\t// Clients supporting tags have to handle unknown tags gracefully.\n\t//\n\t// @since 3.16.0\n\tTagSupport *ClientSymbolTagOptions `json:\"tagSupport,omitempty\"`\n\t// The client support partial workspace symbols. The client will send the\n\t// request `workspaceSymbol/resolve` to the server to resolve additional\n\t// properties.\n\t//\n\t// @since 3.17.0\n\tResolveSupport *ClientSymbolResolveOptions `json:\"resolveSupport,omitempty\"`\n}\n\n// Server capabilities for a {@link WorkspaceSymbolRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#workspaceSymbolOptions\ntype WorkspaceSymbolOptions struct {\n\t// The server provides support to resolve additional\n\t// information for a workspace symbol.\n\t//\n\t// @since 3.17.0\n\tResolveProvider bool `json:\"resolveProvider,omitempty\"`\n\tWorkDoneProgressOptions\n}\n\n// The parameters of a {@link WorkspaceSymbolRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#workspaceSymbolParams\ntype WorkspaceSymbolParams struct {\n\t// A query string to filter symbols by. Clients may send an empty\n\t// string here to request all symbols.\n\t//\n\t// The `query`-parameter should be interpreted in a *relaxed way* as editors\n\t// will apply their own highlighting and scoring on the results. A good rule\n\t// of thumb is to match case-insensitive and to simply check that the\n\t// characters of *query* appear in their order in a candidate symbol.\n\t// Servers shouldn't use prefix, substring, or similar strict matching.\n\tQuery string `json:\"query\"`\n\tWorkDoneProgressParams\n\tPartialResultParams\n}\n\n// Registration options for a {@link WorkspaceSymbolRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#workspaceSymbolRegistrationOptions\ntype WorkspaceSymbolRegistrationOptions struct {\n\tWorkspaceSymbolOptions\n}\n\n// An unchanged document diagnostic report for a workspace diagnostic result.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#workspaceUnchangedDocumentDiagnosticReport\ntype WorkspaceUnchangedDocumentDiagnosticReport struct {\n\t// The URI for which diagnostic information is reported.\n\tURI DocumentUri `json:\"uri\"`\n\t// The version number for which the diagnostics are reported.\n\t// If the document is not marked as open `null` can be provided.\n\tVersion int32 `json:\"version\"`\n\tUnchangedDocumentDiagnosticReport\n}\n\n// The initialize parameters\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#_InitializeParams\ntype XInitializeParams struct {\n\t// The process Id of the parent process that started\n\t// the server.\n\t//\n\t// Is `null` if the process has not been started by another process.\n\t// If the parent process is not alive then the server should exit.\n\tProcessID int32 `json:\"processId\"`\n\t// Information about the client\n\t//\n\t// @since 3.15.0\n\tClientInfo *ClientInfo `json:\"clientInfo,omitempty\"`\n\t// The locale the client is currently showing the user interface\n\t// in. This must not necessarily be the locale of the operating\n\t// system.\n\t//\n\t// Uses IETF language tags as the value's syntax\n\t// (See https://en.wikipedia.org/wiki/IETF_language_tag)\n\t//\n\t// @since 3.16.0\n\tLocale string `json:\"locale,omitempty\"`\n\t// The rootPath of the workspace. Is null\n\t// if no folder is open.\n\t//\n\t// @deprecated in favour of rootUri.\n\tRootPath string `json:\"rootPath,omitempty\"`\n\t// The rootUri of the workspace. Is null if no\n\t// folder is open. If both `rootPath` and `rootUri` are set\n\t// `rootUri` wins.\n\t//\n\t// @deprecated in favour of workspaceFolders.\n\tRootURI DocumentUri `json:\"rootUri\"`\n\t// The capabilities provided by the client (editor or tool)\n\tCapabilities ClientCapabilities `json:\"capabilities\"`\n\t// User provided initialization options.\n\tInitializationOptions interface{} `json:\"initializationOptions,omitempty\"`\n\t// The initial trace setting. If omitted trace is disabled ('off').\n\tTrace *TraceValue `json:\"trace,omitempty\"`\n\tWorkDoneProgressParams\n}\n\n// The initialize parameters\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#_InitializeParams\ntype _InitializeParams struct {\n\t// The process Id of the parent process that started\n\t// the server.\n\t//\n\t// Is `null` if the process has not been started by another process.\n\t// If the parent process is not alive then the server should exit.\n\tProcessID int32 `json:\"processId\"`\n\t// Information about the client\n\t//\n\t// @since 3.15.0\n\tClientInfo *ClientInfo `json:\"clientInfo,omitempty\"`\n\t// The locale the client is currently showing the user interface\n\t// in. This must not necessarily be the locale of the operating\n\t// system.\n\t//\n\t// Uses IETF language tags as the value's syntax\n\t// (See https://en.wikipedia.org/wiki/IETF_language_tag)\n\t//\n\t// @since 3.16.0\n\tLocale string `json:\"locale,omitempty\"`\n\t// The rootPath of the workspace. Is null\n\t// if no folder is open.\n\t//\n\t// @deprecated in favour of rootUri.\n\tRootPath string `json:\"rootPath,omitempty\"`\n\t// The rootUri of the workspace. Is null if no\n\t// folder is open. If both `rootPath` and `rootUri` are set\n\t// `rootUri` wins.\n\t//\n\t// @deprecated in favour of workspaceFolders.\n\tRootURI DocumentUri `json:\"rootUri\"`\n\t// The capabilities provided by the client (editor or tool)\n\tCapabilities ClientCapabilities `json:\"capabilities\"`\n\t// User provided initialization options.\n\tInitializationOptions interface{} `json:\"initializationOptions,omitempty\"`\n\t// The initial trace setting. If omitted trace is disabled ('off').\n\tTrace *TraceValue `json:\"trace,omitempty\"`\n\tWorkDoneProgressParams\n}\n\nconst (\n\t// A set of predefined code action kinds\n\t// Empty kind.\n\tEmpty CodeActionKind = \"\"\n\t// Base kind for quickfix actions: 'quickfix'\n\tQuickFix CodeActionKind = \"quickfix\"\n\t// Base kind for refactoring actions: 'refactor'\n\tRefactor CodeActionKind = \"refactor\"\n\t// Base kind for refactoring extraction actions: 'refactor.extract'\n\t//\n\t// Example extract actions:\n\t//\n\t//\n\t// - Extract method\n\t// - Extract function\n\t// - Extract variable\n\t// - Extract interface from class\n\t// - ...\n\tRefactorExtract CodeActionKind = \"refactor.extract\"\n\t// Base kind for refactoring inline actions: 'refactor.inline'\n\t//\n\t// Example inline actions:\n\t//\n\t//\n\t// - Inline function\n\t// - Inline variable\n\t// - Inline constant\n\t// - ...\n\tRefactorInline CodeActionKind = \"refactor.inline\"\n\t// Base kind for refactoring move actions: `refactor.move`\n\t//\n\t// Example move actions:\n\t//\n\t//\n\t// - Move a function to a new file\n\t// - Move a property between classes\n\t// - Move method to base class\n\t// - ...\n\t//\n\t// @since 3.18.0\n\t// @proposed\n\tRefactorMove CodeActionKind = \"refactor.move\"\n\t// Base kind for refactoring rewrite actions: 'refactor.rewrite'\n\t//\n\t// Example rewrite actions:\n\t//\n\t//\n\t// - Convert JavaScript function to class\n\t// - Add or remove parameter\n\t// - Encapsulate field\n\t// - Make method static\n\t// - Move method to base class\n\t// - ...\n\tRefactorRewrite CodeActionKind = \"refactor.rewrite\"\n\t// Base kind for source actions: `source`\n\t//\n\t// Source code actions apply to the entire file.\n\tSource CodeActionKind = \"source\"\n\t// Base kind for an organize imports source action: `source.organizeImports`\n\tSourceOrganizeImports CodeActionKind = \"source.organizeImports\"\n\t// Base kind for auto-fix source actions: `source.fixAll`.\n\t//\n\t// Fix all actions automatically fix errors that have a clear fix that do not require user input.\n\t// They should not suppress errors or perform unsafe fixes such as generating new types or classes.\n\t//\n\t// @since 3.15.0\n\tSourceFixAll CodeActionKind = \"source.fixAll\"\n\t// Base kind for all code actions applying to the entire notebook's scope. CodeActionKinds using\n\t// this should always begin with `notebook.`\n\t//\n\t// @since 3.18.0\n\tNotebook CodeActionKind = \"notebook\"\n\t// The reason why code actions were requested.\n\t//\n\t// @since 3.17.0\n\t// Code actions were explicitly requested by the user or by an extension.\n\tCodeActionInvoked CodeActionTriggerKind = 1\n\t// Code actions were requested automatically.\n\t//\n\t// This typically happens when current selection in a file changes, but can\n\t// also be triggered when file content changes.\n\tCodeActionAutomatic CodeActionTriggerKind = 2\n\t// The kind of a completion entry.\n\tTextCompletion CompletionItemKind = 1\n\tMethodCompletion CompletionItemKind = 2\n\tFunctionCompletion CompletionItemKind = 3\n\tConstructorCompletion CompletionItemKind = 4\n\tFieldCompletion CompletionItemKind = 5\n\tVariableCompletion CompletionItemKind = 6\n\tClassCompletion CompletionItemKind = 7\n\tInterfaceCompletion CompletionItemKind = 8\n\tModuleCompletion CompletionItemKind = 9\n\tPropertyCompletion CompletionItemKind = 10\n\tUnitCompletion CompletionItemKind = 11\n\tValueCompletion CompletionItemKind = 12\n\tEnumCompletion CompletionItemKind = 13\n\tKeywordCompletion CompletionItemKind = 14\n\tSnippetCompletion CompletionItemKind = 15\n\tColorCompletion CompletionItemKind = 16\n\tFileCompletion CompletionItemKind = 17\n\tReferenceCompletion CompletionItemKind = 18\n\tFolderCompletion CompletionItemKind = 19\n\tEnumMemberCompletion CompletionItemKind = 20\n\tConstantCompletion CompletionItemKind = 21\n\tStructCompletion CompletionItemKind = 22\n\tEventCompletion CompletionItemKind = 23\n\tOperatorCompletion CompletionItemKind = 24\n\tTypeParameterCompletion CompletionItemKind = 25\n\t// Completion item tags are extra annotations that tweak the rendering of a completion\n\t// item.\n\t//\n\t// @since 3.15.0\n\t// Render a completion as obsolete, usually using a strike-out.\n\tComplDeprecated CompletionItemTag = 1\n\t// How a completion was triggered\n\t// Completion was triggered by typing an identifier (24x7 code\n\t// complete), manual invocation (e.g Ctrl+Space) or via API.\n\tInvoked CompletionTriggerKind = 1\n\t// Completion was triggered by a trigger character specified by\n\t// the `triggerCharacters` properties of the `CompletionRegistrationOptions`.\n\tTriggerCharacter CompletionTriggerKind = 2\n\t// Completion was re-triggered as current completion list is incomplete\n\tTriggerForIncompleteCompletions CompletionTriggerKind = 3\n\t// The diagnostic's severity.\n\t// Reports an error.\n\tSeverityError DiagnosticSeverity = 1\n\t// Reports a warning.\n\tSeverityWarning DiagnosticSeverity = 2\n\t// Reports an information.\n\tSeverityInformation DiagnosticSeverity = 3\n\t// Reports a hint.\n\tSeverityHint DiagnosticSeverity = 4\n\t// The diagnostic tags.\n\t//\n\t// @since 3.15.0\n\t// Unused or unnecessary code.\n\t//\n\t// Clients are allowed to render diagnostics with this tag faded out instead of having\n\t// an error squiggle.\n\tUnnecessary DiagnosticTag = 1\n\t// Deprecated or obsolete code.\n\t//\n\t// Clients are allowed to rendered diagnostics with this tag strike through.\n\tDeprecated DiagnosticTag = 2\n\t// The document diagnostic report kinds.\n\t//\n\t// @since 3.17.0\n\t// A diagnostic report with a full\n\t// set of problems.\n\tDiagnosticFull DocumentDiagnosticReportKind = \"full\"\n\t// A report indicating that the last\n\t// returned report is still accurate.\n\tDiagnosticUnchanged DocumentDiagnosticReportKind = \"unchanged\"\n\t// A document highlight kind.\n\t// A textual occurrence.\n\tText DocumentHighlightKind = 1\n\t// Read-access of a symbol, like reading a variable.\n\tRead DocumentHighlightKind = 2\n\t// Write-access of a symbol, like writing to a variable.\n\tWrite DocumentHighlightKind = 3\n\t// Predefined error codes.\n\tParseError ErrorCodes = -32700\n\tInvalidRequest ErrorCodes = -32600\n\tMethodNotFound ErrorCodes = -32601\n\tInvalidParams ErrorCodes = -32602\n\tInternalError ErrorCodes = -32603\n\t// Error code indicating that a server received a notification or\n\t// request before the server has received the `initialize` request.\n\tServerNotInitialized ErrorCodes = -32002\n\tUnknownErrorCode ErrorCodes = -32001\n\t// Applying the workspace change is simply aborted if one of the changes provided\n\t// fails. All operations executed before the failing operation stay executed.\n\tAbort FailureHandlingKind = \"abort\"\n\t// All operations are executed transactional. That means they either all\n\t// succeed or no changes at all are applied to the workspace.\n\tTransactional FailureHandlingKind = \"transactional\"\n\t// If the workspace edit contains only textual file changes they are executed transactional.\n\t// If resource changes (create, rename or delete file) are part of the change the failure\n\t// handling strategy is abort.\n\tTextOnlyTransactional FailureHandlingKind = \"textOnlyTransactional\"\n\t// The client tries to undo the operations already executed. But there is no\n\t// guarantee that this is succeeding.\n\tUndo FailureHandlingKind = \"undo\"\n\t// The file event type\n\t// The file got created.\n\tCreated FileChangeType = 1\n\t// The file got changed.\n\tChanged FileChangeType = 2\n\t// The file got deleted.\n\tDeleted FileChangeType = 3\n\t// A pattern kind describing if a glob pattern matches a file a folder or\n\t// both.\n\t//\n\t// @since 3.16.0\n\t// The pattern matches a file only.\n\tFilePattern FileOperationPatternKind = \"file\"\n\t// The pattern matches a folder only.\n\tFolderPattern FileOperationPatternKind = \"folder\"\n\t// A set of predefined range kinds.\n\t// Folding range for a comment\n\tComment FoldingRangeKind = \"comment\"\n\t// Folding range for an import or include\n\tImports FoldingRangeKind = \"imports\"\n\t// Folding range for a region (e.g. `#region`)\n\tRegion FoldingRangeKind = \"region\"\n\t// Inlay hint kinds.\n\t//\n\t// @since 3.17.0\n\t// An inlay hint that for a type annotation.\n\tType InlayHintKind = 1\n\t// An inlay hint that is for a parameter.\n\tParameter InlayHintKind = 2\n\t// Describes how an {@link InlineCompletionItemProvider inline completion provider} was triggered.\n\t//\n\t// @since 3.18.0\n\t// @proposed\n\t// Completion was triggered explicitly by a user gesture.\n\tInlineInvoked InlineCompletionTriggerKind = 1\n\t// Completion was triggered automatically while editing.\n\tInlineAutomatic InlineCompletionTriggerKind = 2\n\t// Defines whether the insert text in a completion item should be interpreted as\n\t// plain text or a snippet.\n\t// The primary text to be inserted is treated as a plain string.\n\tPlainTextTextFormat InsertTextFormat = 1\n\t// The primary text to be inserted is treated as a snippet.\n\t//\n\t// A snippet can define tab stops and placeholders with `$1`, `$2`\n\t// and `${3:foo}`. `$0` defines the final tab stop, it defaults to\n\t// the end of the snippet. Placeholders with equal identifiers are linked,\n\t// that is typing in one will update others too.\n\t//\n\t// See also: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#snippet_syntax\n\tSnippetTextFormat InsertTextFormat = 2\n\t// How whitespace and indentation is handled during completion\n\t// item insertion.\n\t//\n\t// @since 3.16.0\n\t// The insertion or replace strings is taken as it is. If the\n\t// value is multi line the lines below the cursor will be\n\t// inserted using the indentation defined in the string value.\n\t// The client will not apply any kind of adjustments to the\n\t// string.\n\tAsIs InsertTextMode = 1\n\t// The editor adjusts leading whitespace of new lines so that\n\t// they match the indentation up to the cursor of the line for\n\t// which the item is accepted.\n\t//\n\t// Consider a line like this: <2tabs><3tabs>foo. Accepting a\n\t// multi line completion item is indented using 2 tabs and all\n\t// following lines inserted will be indented using 2 tabs as well.\n\tAdjustIndentation InsertTextMode = 2\n\t// A request failed but it was syntactically correct, e.g the\n\t// method name was known and the parameters were valid. The error\n\t// message should contain human readable information about why\n\t// the request failed.\n\t//\n\t// @since 3.17.0\n\tRequestFailed LSPErrorCodes = -32803\n\t// The server cancelled the request. This error code should\n\t// only be used for requests that explicitly support being\n\t// server cancellable.\n\t//\n\t// @since 3.17.0\n\tServerCancelled LSPErrorCodes = -32802\n\t// The server detected that the content of a document got\n\t// modified outside normal conditions. A server should\n\t// NOT send this error code if it detects a content change\n\t// in it unprocessed messages. The result even computed\n\t// on an older state might still be useful for the client.\n\t//\n\t// If a client decides that a result is not of any use anymore\n\t// the client should cancel the request.\n\tContentModified LSPErrorCodes = -32801\n\t// The client has canceled a request and a server has detected\n\t// the cancel.\n\tRequestCancelled LSPErrorCodes = -32800\n\t// Predefined Language kinds\n\t// @since 3.18.0\n\t// @proposed\n\tLangABAP LanguageKind = \"abap\"\n\tLangWindowsBat LanguageKind = \"bat\"\n\tLangBibTeX LanguageKind = \"bibtex\"\n\tLangClojure LanguageKind = \"clojure\"\n\tLangCoffeescript LanguageKind = \"coffeescript\"\n\tLangC LanguageKind = \"c\"\n\tLangCPP LanguageKind = \"cpp\"\n\tLangCSharp LanguageKind = \"csharp\"\n\tLangCSS LanguageKind = \"css\"\n\t// @since 3.18.0\n\t// @proposed\n\tLangD LanguageKind = \"d\"\n\t// @since 3.18.0\n\t// @proposed\n\tLangDelphi LanguageKind = \"pascal\"\n\tLangDiff LanguageKind = \"diff\"\n\tLangDart LanguageKind = \"dart\"\n\tLangDockerfile LanguageKind = \"dockerfile\"\n\tLangElixir LanguageKind = \"elixir\"\n\tLangErlang LanguageKind = \"erlang\"\n\tLangFSharp LanguageKind = \"fsharp\"\n\tLangGitCommit LanguageKind = \"git-commit\"\n\tLangGitRebase LanguageKind = \"rebase\"\n\tLangGo LanguageKind = \"go\"\n\tLangGroovy LanguageKind = \"groovy\"\n\tLangHandlebars LanguageKind = \"handlebars\"\n\tLangHaskell LanguageKind = \"haskell\"\n\tLangHTML LanguageKind = \"html\"\n\tLangIni LanguageKind = \"ini\"\n\tLangJava LanguageKind = \"java\"\n\tLangJavaScript LanguageKind = \"javascript\"\n\tLangJavaScriptReact LanguageKind = \"javascriptreact\"\n\tLangJSON LanguageKind = \"json\"\n\tLangLaTeX LanguageKind = \"latex\"\n\tLangLess LanguageKind = \"less\"\n\tLangLua LanguageKind = \"lua\"\n\tLangMakefile LanguageKind = \"makefile\"\n\tLangMarkdown LanguageKind = \"markdown\"\n\tLangObjectiveC LanguageKind = \"objective-c\"\n\tLangObjectiveCPP LanguageKind = \"objective-cpp\"\n\t// @since 3.18.0\n\t// @proposed\n\tLangPascal LanguageKind = \"pascal\"\n\tLangPerl LanguageKind = \"perl\"\n\tLangPerl6 LanguageKind = \"perl6\"\n\tLangPHP LanguageKind = \"php\"\n\tLangPowershell LanguageKind = \"powershell\"\n\tLangPug LanguageKind = \"jade\"\n\tLangPython LanguageKind = \"python\"\n\tLangR LanguageKind = \"r\"\n\tLangRazor LanguageKind = \"razor\"\n\tLangRuby LanguageKind = \"ruby\"\n\tLangRust LanguageKind = \"rust\"\n\tLangSCSS LanguageKind = \"scss\"\n\tLangSASS LanguageKind = \"sass\"\n\tLangScala LanguageKind = \"scala\"\n\tLangShaderLab LanguageKind = \"shaderlab\"\n\tLangShellScript LanguageKind = \"shellscript\"\n\tLangSQL LanguageKind = \"sql\"\n\tLangSwift LanguageKind = \"swift\"\n\tLangTypeScript LanguageKind = \"typescript\"\n\tLangTypeScriptReact LanguageKind = \"typescriptreact\"\n\tLangTeX LanguageKind = \"tex\"\n\tLangVisualBasic LanguageKind = \"vb\"\n\tLangXML LanguageKind = \"xml\"\n\tLangXSL LanguageKind = \"xsl\"\n\tLangYAML LanguageKind = \"yaml\"\n\t// Describes the content type that a client supports in various\n\t// result literals like `Hover`, `ParameterInfo` or `CompletionItem`.\n\t//\n\t// Please note that `MarkupKinds` must not start with a `$`. This kinds\n\t// are reserved for internal usage.\n\t// Plain text is supported as a content format\n\tPlainText MarkupKind = \"plaintext\"\n\t// Markdown is supported as a content format\n\tMarkdown MarkupKind = \"markdown\"\n\t// The message type\n\t// An error message.\n\tError MessageType = 1\n\t// A warning message.\n\tWarning MessageType = 2\n\t// An information message.\n\tInfo MessageType = 3\n\t// A log message.\n\tLog MessageType = 4\n\t// A debug message.\n\t//\n\t// @since 3.18.0\n\t// @proposed\n\tDebug MessageType = 5\n\t// The moniker kind.\n\t//\n\t// @since 3.16.0\n\t// The moniker represent a symbol that is imported into a project\n\tImport MonikerKind = \"import\"\n\t// The moniker represents a symbol that is exported from a project\n\tExport MonikerKind = \"export\"\n\t// The moniker represents a symbol that is local to a project (e.g. a local\n\t// variable of a function, a class not visible outside the project, ...)\n\tLocal MonikerKind = \"local\"\n\t// A notebook cell kind.\n\t//\n\t// @since 3.17.0\n\t// A markup-cell is formatted source that is used for display.\n\tMarkup NotebookCellKind = 1\n\t// A code-cell is source code.\n\tCode NotebookCellKind = 2\n\t// A set of predefined position encoding kinds.\n\t//\n\t// @since 3.17.0\n\t// Character offsets count UTF-8 code units (e.g. bytes).\n\tUTF8 PositionEncodingKind = \"utf-8\"\n\t// Character offsets count UTF-16 code units.\n\t//\n\t// This is the default and must always be supported\n\t// by servers\n\tUTF16 PositionEncodingKind = \"utf-16\"\n\t// Character offsets count UTF-32 code units.\n\t//\n\t// Implementation note: these are the same as Unicode codepoints,\n\t// so this `PositionEncodingKind` may also be used for an\n\t// encoding-agnostic representation of character offsets.\n\tUTF32 PositionEncodingKind = \"utf-32\"\n\t// The client's default behavior is to select the identifier\n\t// according the to language's syntax rule.\n\tIdentifier PrepareSupportDefaultBehavior = 1\n\t// Supports creating new files and folders.\n\tCreate ResourceOperationKind = \"create\"\n\t// Supports renaming existing files and folders.\n\tRename ResourceOperationKind = \"rename\"\n\t// Supports deleting existing files and folders.\n\tDelete ResourceOperationKind = \"delete\"\n\t// A set of predefined token modifiers. This set is not fixed\n\t// an clients can specify additional token types via the\n\t// corresponding client capabilities.\n\t//\n\t// @since 3.16.0\n\tModDeclaration SemanticTokenModifiers = \"declaration\"\n\tModDefinition SemanticTokenModifiers = \"definition\"\n\tModReadonly SemanticTokenModifiers = \"readonly\"\n\tModStatic SemanticTokenModifiers = \"static\"\n\tModDeprecated SemanticTokenModifiers = \"deprecated\"\n\tModAbstract SemanticTokenModifiers = \"abstract\"\n\tModAsync SemanticTokenModifiers = \"async\"\n\tModModification SemanticTokenModifiers = \"modification\"\n\tModDocumentation SemanticTokenModifiers = \"documentation\"\n\tModDefaultLibrary SemanticTokenModifiers = \"defaultLibrary\"\n\t// A set of predefined token types. This set is not fixed\n\t// an clients can specify additional token types via the\n\t// corresponding client capabilities.\n\t//\n\t// @since 3.16.0\n\tNamespaceType SemanticTokenTypes = \"namespace\"\n\t// Represents a generic type. Acts as a fallback for types which can't be mapped to\n\t// a specific type like class or enum.\n\tTypeType SemanticTokenTypes = \"type\"\n\tClassType SemanticTokenTypes = \"class\"\n\tEnumType SemanticTokenTypes = \"enum\"\n\tInterfaceType SemanticTokenTypes = \"interface\"\n\tStructType SemanticTokenTypes = \"struct\"\n\tTypeParameterType SemanticTokenTypes = \"typeParameter\"\n\tParameterType SemanticTokenTypes = \"parameter\"\n\tVariableType SemanticTokenTypes = \"variable\"\n\tPropertyType SemanticTokenTypes = \"property\"\n\tEnumMemberType SemanticTokenTypes = \"enumMember\"\n\tEventType SemanticTokenTypes = \"event\"\n\tFunctionType SemanticTokenTypes = \"function\"\n\tMethodType SemanticTokenTypes = \"method\"\n\tMacroType SemanticTokenTypes = \"macro\"\n\tKeywordType SemanticTokenTypes = \"keyword\"\n\tModifierType SemanticTokenTypes = \"modifier\"\n\tCommentType SemanticTokenTypes = \"comment\"\n\tStringType SemanticTokenTypes = \"string\"\n\tNumberType SemanticTokenTypes = \"number\"\n\tRegexpType SemanticTokenTypes = \"regexp\"\n\tOperatorType SemanticTokenTypes = \"operator\"\n\t// @since 3.17.0\n\tDecoratorType SemanticTokenTypes = \"decorator\"\n\t// @since 3.18.0\n\tLabelType SemanticTokenTypes = \"label\"\n\t// How a signature help was triggered.\n\t//\n\t// @since 3.15.0\n\t// Signature help was invoked manually by the user or by a command.\n\tSigInvoked SignatureHelpTriggerKind = 1\n\t// Signature help was triggered by a trigger character.\n\tSigTriggerCharacter SignatureHelpTriggerKind = 2\n\t// Signature help was triggered by the cursor moving or by the document content changing.\n\tSigContentChange SignatureHelpTriggerKind = 3\n\t// A symbol kind.\n\tFile SymbolKind = 1\n\tModule SymbolKind = 2\n\tNamespace SymbolKind = 3\n\tPackage SymbolKind = 4\n\tClass SymbolKind = 5\n\tMethod SymbolKind = 6\n\tProperty SymbolKind = 7\n\tField SymbolKind = 8\n\tConstructor SymbolKind = 9\n\tEnum SymbolKind = 10\n\tInterface SymbolKind = 11\n\tFunction SymbolKind = 12\n\tVariable SymbolKind = 13\n\tConstant SymbolKind = 14\n\tString SymbolKind = 15\n\tNumber SymbolKind = 16\n\tBoolean SymbolKind = 17\n\tArray SymbolKind = 18\n\tObject SymbolKind = 19\n\tKey SymbolKind = 20\n\tNull SymbolKind = 21\n\tEnumMember SymbolKind = 22\n\tStruct SymbolKind = 23\n\tEvent SymbolKind = 24\n\tOperator SymbolKind = 25\n\tTypeParameter SymbolKind = 26\n\t// Symbol tags are extra annotations that tweak the rendering of a symbol.\n\t//\n\t// @since 3.16\n\t// Render a symbol as obsolete, usually using a strike-out.\n\tDeprecatedSymbol SymbolTag = 1\n\t// Represents reasons why a text document is saved.\n\t// Manually triggered, e.g. by the user pressing save, by starting debugging,\n\t// or by an API call.\n\tManual TextDocumentSaveReason = 1\n\t// Automatic after a delay.\n\tAfterDelay TextDocumentSaveReason = 2\n\t// When the editor lost focus.\n\tFocusOut TextDocumentSaveReason = 3\n\t// Defines how the host (editor) should sync\n\t// document changes to the language server.\n\t// Documents should not be synced at all.\n\tNone TextDocumentSyncKind = 0\n\t// Documents are synced by always sending the full content\n\t// of the document.\n\tFull TextDocumentSyncKind = 1\n\t// Documents are synced by sending the full content on open.\n\t// After that only incremental updates to the document are\n\t// send.\n\tIncremental TextDocumentSyncKind = 2\n\tRelative TokenFormat = \"relative\"\n\t// Turn tracing off.\n\tOff TraceValue = \"off\"\n\t// Trace messages only.\n\tMessages TraceValue = \"messages\"\n\t// Verbose message tracing.\n\tVerbose TraceValue = \"verbose\"\n\t// Moniker uniqueness level to define scope of the moniker.\n\t//\n\t// @since 3.16.0\n\t// The moniker is only unique inside a document\n\tDocument UniquenessLevel = \"document\"\n\t// The moniker is unique inside a project for which a dump got created\n\tProject UniquenessLevel = \"project\"\n\t// The moniker is unique inside the group to which a project belongs\n\tGroup UniquenessLevel = \"group\"\n\t// The moniker is unique inside the moniker scheme.\n\tScheme UniquenessLevel = \"scheme\"\n\t// The moniker is globally unique\n\tGlobal UniquenessLevel = \"global\"\n\t// Interested in create events.\n\tWatchCreate WatchKind = 1\n\t// Interested in change events\n\tWatchChange WatchKind = 2\n\t// Interested in delete events\n\tWatchDelete WatchKind = 4\n)\n"], ["/opencode/internal/lsp/protocol/tsjson.go", "// Copyright 2023 The Go Authors. All rights reserved.\n// Use of this source code is governed by a BSD-style\n// license that can be found in the LICENSE file.\n\n// Code generated for LSP. DO NOT EDIT.\n\npackage protocol\n\n// Code generated from protocol/metaModel.json at ref release/protocol/3.17.6-next.9 (hash c94395b5da53729e6dff931293b051009ccaaaa4).\n// https://github.com/microsoft/vscode-languageserver-node/blob/release/protocol/3.17.6-next.9/protocol/metaModel.json\n// LSP metaData.version = 3.17.0.\n\nimport \"bytes\"\nimport \"encoding/json\"\n\nimport \"fmt\"\n\n// UnmarshalError indicates that a JSON value did not conform to\n// one of the expected cases of an LSP union type.\ntype UnmarshalError struct {\n\tmsg string\n}\n\nfunc (e UnmarshalError) Error() string {\n\treturn e.msg\n}\nfunc (t Or_CancelParams_id) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase int32:\n\t\treturn json.Marshal(x)\n\tcase string:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [int32 string]\", t)\n}\n\nfunc (t *Or_CancelParams_id) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder41 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder41.DisallowUnknownFields()\n\tvar int32Val int32\n\tif err := decoder41.Decode(&int32Val); err == nil {\n\t\tt.Value = int32Val\n\t\treturn nil\n\t}\n\tdecoder42 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder42.DisallowUnknownFields()\n\tvar stringVal string\n\tif err := decoder42.Decode(&stringVal); err == nil {\n\t\tt.Value = stringVal\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [int32 string]\"}\n}\n\nfunc (t Or_ClientSemanticTokensRequestOptions_full) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase ClientSemanticTokensRequestFullDelta:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [ClientSemanticTokensRequestFullDelta bool]\", t)\n}\n\nfunc (t *Or_ClientSemanticTokensRequestOptions_full) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder220 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder220.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder220.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder221 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder221.DisallowUnknownFields()\n\tvar h221 ClientSemanticTokensRequestFullDelta\n\tif err := decoder221.Decode(&h221); err == nil {\n\t\tt.Value = h221\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [ClientSemanticTokensRequestFullDelta bool]\"}\n}\n\nfunc (t Or_ClientSemanticTokensRequestOptions_range) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase Lit_ClientSemanticTokensRequestOptions_range_Item1:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [Lit_ClientSemanticTokensRequestOptions_range_Item1 bool]\", t)\n}\n\nfunc (t *Or_ClientSemanticTokensRequestOptions_range) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder217 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder217.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder217.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder218 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder218.DisallowUnknownFields()\n\tvar h218 Lit_ClientSemanticTokensRequestOptions_range_Item1\n\tif err := decoder218.Decode(&h218); err == nil {\n\t\tt.Value = h218\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [Lit_ClientSemanticTokensRequestOptions_range_Item1 bool]\"}\n}\n\nfunc (t Or_CompletionItemDefaults_editRange) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase EditRangeWithInsertReplace:\n\t\treturn json.Marshal(x)\n\tcase Range:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [EditRangeWithInsertReplace Range]\", t)\n}\n\nfunc (t *Or_CompletionItemDefaults_editRange) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder183 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder183.DisallowUnknownFields()\n\tvar h183 EditRangeWithInsertReplace\n\tif err := decoder183.Decode(&h183); err == nil {\n\t\tt.Value = h183\n\t\treturn nil\n\t}\n\tdecoder184 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder184.DisallowUnknownFields()\n\tvar h184 Range\n\tif err := decoder184.Decode(&h184); err == nil {\n\t\tt.Value = h184\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [EditRangeWithInsertReplace Range]\"}\n}\n\nfunc (t Or_CompletionItem_documentation) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase MarkupContent:\n\t\treturn json.Marshal(x)\n\tcase string:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [MarkupContent string]\", t)\n}\n\nfunc (t *Or_CompletionItem_documentation) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder25 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder25.DisallowUnknownFields()\n\tvar stringVal string\n\tif err := decoder25.Decode(&stringVal); err == nil {\n\t\tt.Value = stringVal\n\t\treturn nil\n\t}\n\tdecoder26 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder26.DisallowUnknownFields()\n\tvar h26 MarkupContent\n\tif err := decoder26.Decode(&h26); err == nil {\n\t\tt.Value = h26\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [MarkupContent string]\"}\n}\n\nfunc (t Or_CompletionItem_textEdit) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase InsertReplaceEdit:\n\t\treturn json.Marshal(x)\n\tcase TextEdit:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [InsertReplaceEdit TextEdit]\", t)\n}\n\nfunc (t *Or_CompletionItem_textEdit) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder29 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder29.DisallowUnknownFields()\n\tvar h29 InsertReplaceEdit\n\tif err := decoder29.Decode(&h29); err == nil {\n\t\tt.Value = h29\n\t\treturn nil\n\t}\n\tdecoder30 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder30.DisallowUnknownFields()\n\tvar h30 TextEdit\n\tif err := decoder30.Decode(&h30); err == nil {\n\t\tt.Value = h30\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [InsertReplaceEdit TextEdit]\"}\n}\n\nfunc (t Or_Declaration) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase Location:\n\t\treturn json.Marshal(x)\n\tcase []Location:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [Location []Location]\", t)\n}\n\nfunc (t *Or_Declaration) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder237 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder237.DisallowUnknownFields()\n\tvar h237 Location\n\tif err := decoder237.Decode(&h237); err == nil {\n\t\tt.Value = h237\n\t\treturn nil\n\t}\n\tdecoder238 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder238.DisallowUnknownFields()\n\tvar h238 []Location\n\tif err := decoder238.Decode(&h238); err == nil {\n\t\tt.Value = h238\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [Location []Location]\"}\n}\n\nfunc (t Or_Definition) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase Location:\n\t\treturn json.Marshal(x)\n\tcase []Location:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [Location []Location]\", t)\n}\n\nfunc (t *Or_Definition) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder224 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder224.DisallowUnknownFields()\n\tvar h224 Location\n\tif err := decoder224.Decode(&h224); err == nil {\n\t\tt.Value = h224\n\t\treturn nil\n\t}\n\tdecoder225 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder225.DisallowUnknownFields()\n\tvar h225 []Location\n\tif err := decoder225.Decode(&h225); err == nil {\n\t\tt.Value = h225\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [Location []Location]\"}\n}\n\nfunc (t Or_Diagnostic_code) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase int32:\n\t\treturn json.Marshal(x)\n\tcase string:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [int32 string]\", t)\n}\n\nfunc (t *Or_Diagnostic_code) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder179 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder179.DisallowUnknownFields()\n\tvar int32Val int32\n\tif err := decoder179.Decode(&int32Val); err == nil {\n\t\tt.Value = int32Val\n\t\treturn nil\n\t}\n\tdecoder180 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder180.DisallowUnknownFields()\n\tvar stringVal string\n\tif err := decoder180.Decode(&stringVal); err == nil {\n\t\tt.Value = stringVal\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [int32 string]\"}\n}\n\nfunc (t Or_DidChangeConfigurationRegistrationOptions_section) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase []string:\n\t\treturn json.Marshal(x)\n\tcase string:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [[]string string]\", t)\n}\n\nfunc (t *Or_DidChangeConfigurationRegistrationOptions_section) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder22 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder22.DisallowUnknownFields()\n\tvar stringVal string\n\tif err := decoder22.Decode(&stringVal); err == nil {\n\t\tt.Value = stringVal\n\t\treturn nil\n\t}\n\tdecoder23 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder23.DisallowUnknownFields()\n\tvar h23 []string\n\tif err := decoder23.Decode(&h23); err == nil {\n\t\tt.Value = h23\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [[]string string]\"}\n}\n\nfunc (t Or_DocumentDiagnosticReport) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase RelatedFullDocumentDiagnosticReport:\n\t\treturn json.Marshal(x)\n\tcase RelatedUnchangedDocumentDiagnosticReport:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [RelatedFullDocumentDiagnosticReport RelatedUnchangedDocumentDiagnosticReport]\", t)\n}\n\nfunc (t *Or_DocumentDiagnosticReport) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder247 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder247.DisallowUnknownFields()\n\tvar h247 RelatedFullDocumentDiagnosticReport\n\tif err := decoder247.Decode(&h247); err == nil {\n\t\tt.Value = h247\n\t\treturn nil\n\t}\n\tdecoder248 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder248.DisallowUnknownFields()\n\tvar h248 RelatedUnchangedDocumentDiagnosticReport\n\tif err := decoder248.Decode(&h248); err == nil {\n\t\tt.Value = h248\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [RelatedFullDocumentDiagnosticReport RelatedUnchangedDocumentDiagnosticReport]\"}\n}\n\nfunc (t Or_DocumentDiagnosticReportPartialResult_relatedDocuments_Value) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase FullDocumentDiagnosticReport:\n\t\treturn json.Marshal(x)\n\tcase UnchangedDocumentDiagnosticReport:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [FullDocumentDiagnosticReport UnchangedDocumentDiagnosticReport]\", t)\n}\n\nfunc (t *Or_DocumentDiagnosticReportPartialResult_relatedDocuments_Value) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder16 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder16.DisallowUnknownFields()\n\tvar h16 FullDocumentDiagnosticReport\n\tif err := decoder16.Decode(&h16); err == nil {\n\t\tt.Value = h16\n\t\treturn nil\n\t}\n\tdecoder17 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder17.DisallowUnknownFields()\n\tvar h17 UnchangedDocumentDiagnosticReport\n\tif err := decoder17.Decode(&h17); err == nil {\n\t\tt.Value = h17\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [FullDocumentDiagnosticReport UnchangedDocumentDiagnosticReport]\"}\n}\n\nfunc (t Or_DocumentFilter) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase NotebookCellTextDocumentFilter:\n\t\treturn json.Marshal(x)\n\tcase TextDocumentFilter:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [NotebookCellTextDocumentFilter TextDocumentFilter]\", t)\n}\n\nfunc (t *Or_DocumentFilter) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder270 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder270.DisallowUnknownFields()\n\tvar h270 NotebookCellTextDocumentFilter\n\tif err := decoder270.Decode(&h270); err == nil {\n\t\tt.Value = h270\n\t\treturn nil\n\t}\n\tdecoder271 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder271.DisallowUnknownFields()\n\tvar h271 TextDocumentFilter\n\tif err := decoder271.Decode(&h271); err == nil {\n\t\tt.Value = h271\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [NotebookCellTextDocumentFilter TextDocumentFilter]\"}\n}\n\nfunc (t Or_GlobPattern) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase Pattern:\n\t\treturn json.Marshal(x)\n\tcase RelativePattern:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [Pattern RelativePattern]\", t)\n}\n\nfunc (t *Or_GlobPattern) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder274 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder274.DisallowUnknownFields()\n\tvar h274 Pattern\n\tif err := decoder274.Decode(&h274); err == nil {\n\t\tt.Value = h274\n\t\treturn nil\n\t}\n\tdecoder275 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder275.DisallowUnknownFields()\n\tvar h275 RelativePattern\n\tif err := decoder275.Decode(&h275); err == nil {\n\t\tt.Value = h275\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [Pattern RelativePattern]\"}\n}\n\nfunc (t Or_Hover_contents) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase MarkedString:\n\t\treturn json.Marshal(x)\n\tcase MarkupContent:\n\t\treturn json.Marshal(x)\n\tcase []MarkedString:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [MarkedString MarkupContent []MarkedString]\", t)\n}\n\nfunc (t *Or_Hover_contents) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder34 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder34.DisallowUnknownFields()\n\tvar h34 MarkedString\n\tif err := decoder34.Decode(&h34); err == nil {\n\t\tt.Value = h34\n\t\treturn nil\n\t}\n\tdecoder35 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder35.DisallowUnknownFields()\n\tvar h35 MarkupContent\n\tif err := decoder35.Decode(&h35); err == nil {\n\t\tt.Value = h35\n\t\treturn nil\n\t}\n\tdecoder36 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder36.DisallowUnknownFields()\n\tvar h36 []MarkedString\n\tif err := decoder36.Decode(&h36); err == nil {\n\t\tt.Value = h36\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [MarkedString MarkupContent []MarkedString]\"}\n}\n\nfunc (t Or_InlayHintLabelPart_tooltip) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase MarkupContent:\n\t\treturn json.Marshal(x)\n\tcase string:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [MarkupContent string]\", t)\n}\n\nfunc (t *Or_InlayHintLabelPart_tooltip) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder56 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder56.DisallowUnknownFields()\n\tvar stringVal string\n\tif err := decoder56.Decode(&stringVal); err == nil {\n\t\tt.Value = stringVal\n\t\treturn nil\n\t}\n\tdecoder57 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder57.DisallowUnknownFields()\n\tvar h57 MarkupContent\n\tif err := decoder57.Decode(&h57); err == nil {\n\t\tt.Value = h57\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [MarkupContent string]\"}\n}\n\nfunc (t Or_InlayHint_label) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase []InlayHintLabelPart:\n\t\treturn json.Marshal(x)\n\tcase string:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [[]InlayHintLabelPart string]\", t)\n}\n\nfunc (t *Or_InlayHint_label) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder9 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder9.DisallowUnknownFields()\n\tvar stringVal string\n\tif err := decoder9.Decode(&stringVal); err == nil {\n\t\tt.Value = stringVal\n\t\treturn nil\n\t}\n\tdecoder10 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder10.DisallowUnknownFields()\n\tvar h10 []InlayHintLabelPart\n\tif err := decoder10.Decode(&h10); err == nil {\n\t\tt.Value = h10\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [[]InlayHintLabelPart string]\"}\n}\n\nfunc (t Or_InlayHint_tooltip) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase MarkupContent:\n\t\treturn json.Marshal(x)\n\tcase string:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [MarkupContent string]\", t)\n}\n\nfunc (t *Or_InlayHint_tooltip) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder12 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder12.DisallowUnknownFields()\n\tvar stringVal string\n\tif err := decoder12.Decode(&stringVal); err == nil {\n\t\tt.Value = stringVal\n\t\treturn nil\n\t}\n\tdecoder13 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder13.DisallowUnknownFields()\n\tvar h13 MarkupContent\n\tif err := decoder13.Decode(&h13); err == nil {\n\t\tt.Value = h13\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [MarkupContent string]\"}\n}\n\nfunc (t Or_InlineCompletionItem_insertText) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase StringValue:\n\t\treturn json.Marshal(x)\n\tcase string:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [StringValue string]\", t)\n}\n\nfunc (t *Or_InlineCompletionItem_insertText) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder19 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder19.DisallowUnknownFields()\n\tvar stringVal string\n\tif err := decoder19.Decode(&stringVal); err == nil {\n\t\tt.Value = stringVal\n\t\treturn nil\n\t}\n\tdecoder20 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder20.DisallowUnknownFields()\n\tvar h20 StringValue\n\tif err := decoder20.Decode(&h20); err == nil {\n\t\tt.Value = h20\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [StringValue string]\"}\n}\n\nfunc (t Or_InlineValue) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase InlineValueEvaluatableExpression:\n\t\treturn json.Marshal(x)\n\tcase InlineValueText:\n\t\treturn json.Marshal(x)\n\tcase InlineValueVariableLookup:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [InlineValueEvaluatableExpression InlineValueText InlineValueVariableLookup]\", t)\n}\n\nfunc (t *Or_InlineValue) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder242 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder242.DisallowUnknownFields()\n\tvar h242 InlineValueEvaluatableExpression\n\tif err := decoder242.Decode(&h242); err == nil {\n\t\tt.Value = h242\n\t\treturn nil\n\t}\n\tdecoder243 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder243.DisallowUnknownFields()\n\tvar h243 InlineValueText\n\tif err := decoder243.Decode(&h243); err == nil {\n\t\tt.Value = h243\n\t\treturn nil\n\t}\n\tdecoder244 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder244.DisallowUnknownFields()\n\tvar h244 InlineValueVariableLookup\n\tif err := decoder244.Decode(&h244); err == nil {\n\t\tt.Value = h244\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [InlineValueEvaluatableExpression InlineValueText InlineValueVariableLookup]\"}\n}\n\nfunc (t Or_LSPAny) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase LSPArray:\n\t\treturn json.Marshal(x)\n\tcase LSPObject:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase float64:\n\t\treturn json.Marshal(x)\n\tcase int32:\n\t\treturn json.Marshal(x)\n\tcase string:\n\t\treturn json.Marshal(x)\n\tcase uint32:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [LSPArray LSPObject bool float64 int32 string uint32]\", t)\n}\n\nfunc (t *Or_LSPAny) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder228 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder228.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder228.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder229 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder229.DisallowUnknownFields()\n\tvar float64Val float64\n\tif err := decoder229.Decode(&float64Val); err == nil {\n\t\tt.Value = float64Val\n\t\treturn nil\n\t}\n\tdecoder230 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder230.DisallowUnknownFields()\n\tvar int32Val int32\n\tif err := decoder230.Decode(&int32Val); err == nil {\n\t\tt.Value = int32Val\n\t\treturn nil\n\t}\n\tdecoder231 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder231.DisallowUnknownFields()\n\tvar stringVal string\n\tif err := decoder231.Decode(&stringVal); err == nil {\n\t\tt.Value = stringVal\n\t\treturn nil\n\t}\n\tdecoder232 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder232.DisallowUnknownFields()\n\tvar uint32Val uint32\n\tif err := decoder232.Decode(&uint32Val); err == nil {\n\t\tt.Value = uint32Val\n\t\treturn nil\n\t}\n\tdecoder233 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder233.DisallowUnknownFields()\n\tvar h233 LSPArray\n\tif err := decoder233.Decode(&h233); err == nil {\n\t\tt.Value = h233\n\t\treturn nil\n\t}\n\tdecoder234 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder234.DisallowUnknownFields()\n\tvar h234 LSPObject\n\tif err := decoder234.Decode(&h234); err == nil {\n\t\tt.Value = h234\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [LSPArray LSPObject bool float64 int32 string uint32]\"}\n}\n\nfunc (t Or_MarkedString) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase MarkedStringWithLanguage:\n\t\treturn json.Marshal(x)\n\tcase string:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [MarkedStringWithLanguage string]\", t)\n}\n\nfunc (t *Or_MarkedString) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder266 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder266.DisallowUnknownFields()\n\tvar stringVal string\n\tif err := decoder266.Decode(&stringVal); err == nil {\n\t\tt.Value = stringVal\n\t\treturn nil\n\t}\n\tdecoder267 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder267.DisallowUnknownFields()\n\tvar h267 MarkedStringWithLanguage\n\tif err := decoder267.Decode(&h267); err == nil {\n\t\tt.Value = h267\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [MarkedStringWithLanguage string]\"}\n}\n\nfunc (t Or_NotebookCellTextDocumentFilter_notebook) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase NotebookDocumentFilter:\n\t\treturn json.Marshal(x)\n\tcase string:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [NotebookDocumentFilter string]\", t)\n}\n\nfunc (t *Or_NotebookCellTextDocumentFilter_notebook) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder208 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder208.DisallowUnknownFields()\n\tvar stringVal string\n\tif err := decoder208.Decode(&stringVal); err == nil {\n\t\tt.Value = stringVal\n\t\treturn nil\n\t}\n\tdecoder209 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder209.DisallowUnknownFields()\n\tvar h209 NotebookDocumentFilter\n\tif err := decoder209.Decode(&h209); err == nil {\n\t\tt.Value = h209\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [NotebookDocumentFilter string]\"}\n}\n\nfunc (t Or_NotebookDocumentFilter) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase NotebookDocumentFilterNotebookType:\n\t\treturn json.Marshal(x)\n\tcase NotebookDocumentFilterPattern:\n\t\treturn json.Marshal(x)\n\tcase NotebookDocumentFilterScheme:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [NotebookDocumentFilterNotebookType NotebookDocumentFilterPattern NotebookDocumentFilterScheme]\", t)\n}\n\nfunc (t *Or_NotebookDocumentFilter) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder285 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder285.DisallowUnknownFields()\n\tvar h285 NotebookDocumentFilterNotebookType\n\tif err := decoder285.Decode(&h285); err == nil {\n\t\tt.Value = h285\n\t\treturn nil\n\t}\n\tdecoder286 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder286.DisallowUnknownFields()\n\tvar h286 NotebookDocumentFilterPattern\n\tif err := decoder286.Decode(&h286); err == nil {\n\t\tt.Value = h286\n\t\treturn nil\n\t}\n\tdecoder287 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder287.DisallowUnknownFields()\n\tvar h287 NotebookDocumentFilterScheme\n\tif err := decoder287.Decode(&h287); err == nil {\n\t\tt.Value = h287\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [NotebookDocumentFilterNotebookType NotebookDocumentFilterPattern NotebookDocumentFilterScheme]\"}\n}\n\nfunc (t Or_NotebookDocumentFilterWithCells_notebook) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase NotebookDocumentFilter:\n\t\treturn json.Marshal(x)\n\tcase string:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [NotebookDocumentFilter string]\", t)\n}\n\nfunc (t *Or_NotebookDocumentFilterWithCells_notebook) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder192 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder192.DisallowUnknownFields()\n\tvar stringVal string\n\tif err := decoder192.Decode(&stringVal); err == nil {\n\t\tt.Value = stringVal\n\t\treturn nil\n\t}\n\tdecoder193 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder193.DisallowUnknownFields()\n\tvar h193 NotebookDocumentFilter\n\tif err := decoder193.Decode(&h193); err == nil {\n\t\tt.Value = h193\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [NotebookDocumentFilter string]\"}\n}\n\nfunc (t Or_NotebookDocumentFilterWithNotebook_notebook) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase NotebookDocumentFilter:\n\t\treturn json.Marshal(x)\n\tcase string:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [NotebookDocumentFilter string]\", t)\n}\n\nfunc (t *Or_NotebookDocumentFilterWithNotebook_notebook) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder189 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder189.DisallowUnknownFields()\n\tvar stringVal string\n\tif err := decoder189.Decode(&stringVal); err == nil {\n\t\tt.Value = stringVal\n\t\treturn nil\n\t}\n\tdecoder190 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder190.DisallowUnknownFields()\n\tvar h190 NotebookDocumentFilter\n\tif err := decoder190.Decode(&h190); err == nil {\n\t\tt.Value = h190\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [NotebookDocumentFilter string]\"}\n}\n\nfunc (t Or_NotebookDocumentSyncOptions_notebookSelector_Elem) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase NotebookDocumentFilterWithCells:\n\t\treturn json.Marshal(x)\n\tcase NotebookDocumentFilterWithNotebook:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [NotebookDocumentFilterWithCells NotebookDocumentFilterWithNotebook]\", t)\n}\n\nfunc (t *Or_NotebookDocumentSyncOptions_notebookSelector_Elem) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder68 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder68.DisallowUnknownFields()\n\tvar h68 NotebookDocumentFilterWithCells\n\tif err := decoder68.Decode(&h68); err == nil {\n\t\tt.Value = h68\n\t\treturn nil\n\t}\n\tdecoder69 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder69.DisallowUnknownFields()\n\tvar h69 NotebookDocumentFilterWithNotebook\n\tif err := decoder69.Decode(&h69); err == nil {\n\t\tt.Value = h69\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [NotebookDocumentFilterWithCells NotebookDocumentFilterWithNotebook]\"}\n}\n\nfunc (t Or_ParameterInformation_documentation) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase MarkupContent:\n\t\treturn json.Marshal(x)\n\tcase string:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [MarkupContent string]\", t)\n}\n\nfunc (t *Or_ParameterInformation_documentation) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder205 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder205.DisallowUnknownFields()\n\tvar stringVal string\n\tif err := decoder205.Decode(&stringVal); err == nil {\n\t\tt.Value = stringVal\n\t\treturn nil\n\t}\n\tdecoder206 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder206.DisallowUnknownFields()\n\tvar h206 MarkupContent\n\tif err := decoder206.Decode(&h206); err == nil {\n\t\tt.Value = h206\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [MarkupContent string]\"}\n}\n\nfunc (t Or_ParameterInformation_label) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase Tuple_ParameterInformation_label_Item1:\n\t\treturn json.Marshal(x)\n\tcase string:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [Tuple_ParameterInformation_label_Item1 string]\", t)\n}\n\nfunc (t *Or_ParameterInformation_label) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder202 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder202.DisallowUnknownFields()\n\tvar stringVal string\n\tif err := decoder202.Decode(&stringVal); err == nil {\n\t\tt.Value = stringVal\n\t\treturn nil\n\t}\n\tdecoder203 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder203.DisallowUnknownFields()\n\tvar h203 Tuple_ParameterInformation_label_Item1\n\tif err := decoder203.Decode(&h203); err == nil {\n\t\tt.Value = h203\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [Tuple_ParameterInformation_label_Item1 string]\"}\n}\n\nfunc (t Or_PrepareRenameResult) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase PrepareRenameDefaultBehavior:\n\t\treturn json.Marshal(x)\n\tcase PrepareRenamePlaceholder:\n\t\treturn json.Marshal(x)\n\tcase Range:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [PrepareRenameDefaultBehavior PrepareRenamePlaceholder Range]\", t)\n}\n\nfunc (t *Or_PrepareRenameResult) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder252 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder252.DisallowUnknownFields()\n\tvar h252 PrepareRenameDefaultBehavior\n\tif err := decoder252.Decode(&h252); err == nil {\n\t\tt.Value = h252\n\t\treturn nil\n\t}\n\tdecoder253 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder253.DisallowUnknownFields()\n\tvar h253 PrepareRenamePlaceholder\n\tif err := decoder253.Decode(&h253); err == nil {\n\t\tt.Value = h253\n\t\treturn nil\n\t}\n\tdecoder254 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder254.DisallowUnknownFields()\n\tvar h254 Range\n\tif err := decoder254.Decode(&h254); err == nil {\n\t\tt.Value = h254\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [PrepareRenameDefaultBehavior PrepareRenamePlaceholder Range]\"}\n}\n\nfunc (t Or_ProgressToken) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase int32:\n\t\treturn json.Marshal(x)\n\tcase string:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [int32 string]\", t)\n}\n\nfunc (t *Or_ProgressToken) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder255 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder255.DisallowUnknownFields()\n\tvar int32Val int32\n\tif err := decoder255.Decode(&int32Val); err == nil {\n\t\tt.Value = int32Val\n\t\treturn nil\n\t}\n\tdecoder256 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder256.DisallowUnknownFields()\n\tvar stringVal string\n\tif err := decoder256.Decode(&stringVal); err == nil {\n\t\tt.Value = stringVal\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [int32 string]\"}\n}\n\nfunc (t Or_RelatedFullDocumentDiagnosticReport_relatedDocuments_Value) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase FullDocumentDiagnosticReport:\n\t\treturn json.Marshal(x)\n\tcase UnchangedDocumentDiagnosticReport:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [FullDocumentDiagnosticReport UnchangedDocumentDiagnosticReport]\", t)\n}\n\nfunc (t *Or_RelatedFullDocumentDiagnosticReport_relatedDocuments_Value) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder60 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder60.DisallowUnknownFields()\n\tvar h60 FullDocumentDiagnosticReport\n\tif err := decoder60.Decode(&h60); err == nil {\n\t\tt.Value = h60\n\t\treturn nil\n\t}\n\tdecoder61 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder61.DisallowUnknownFields()\n\tvar h61 UnchangedDocumentDiagnosticReport\n\tif err := decoder61.Decode(&h61); err == nil {\n\t\tt.Value = h61\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [FullDocumentDiagnosticReport UnchangedDocumentDiagnosticReport]\"}\n}\n\nfunc (t Or_RelatedUnchangedDocumentDiagnosticReport_relatedDocuments_Value) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase FullDocumentDiagnosticReport:\n\t\treturn json.Marshal(x)\n\tcase UnchangedDocumentDiagnosticReport:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [FullDocumentDiagnosticReport UnchangedDocumentDiagnosticReport]\", t)\n}\n\nfunc (t *Or_RelatedUnchangedDocumentDiagnosticReport_relatedDocuments_Value) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder64 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder64.DisallowUnknownFields()\n\tvar h64 FullDocumentDiagnosticReport\n\tif err := decoder64.Decode(&h64); err == nil {\n\t\tt.Value = h64\n\t\treturn nil\n\t}\n\tdecoder65 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder65.DisallowUnknownFields()\n\tvar h65 UnchangedDocumentDiagnosticReport\n\tif err := decoder65.Decode(&h65); err == nil {\n\t\tt.Value = h65\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [FullDocumentDiagnosticReport UnchangedDocumentDiagnosticReport]\"}\n}\n\nfunc (t Or_RelativePattern_baseUri) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase URI:\n\t\treturn json.Marshal(x)\n\tcase WorkspaceFolder:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [URI WorkspaceFolder]\", t)\n}\n\nfunc (t *Or_RelativePattern_baseUri) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder214 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder214.DisallowUnknownFields()\n\tvar h214 URI\n\tif err := decoder214.Decode(&h214); err == nil {\n\t\tt.Value = h214\n\t\treturn nil\n\t}\n\tdecoder215 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder215.DisallowUnknownFields()\n\tvar h215 WorkspaceFolder\n\tif err := decoder215.Decode(&h215); err == nil {\n\t\tt.Value = h215\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [URI WorkspaceFolder]\"}\n}\n\nfunc (t Or_Result_textDocument_codeAction_Item0_Elem) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase CodeAction:\n\t\treturn json.Marshal(x)\n\tcase Command:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [CodeAction Command]\", t)\n}\n\nfunc (t *Or_Result_textDocument_codeAction_Item0_Elem) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder322 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder322.DisallowUnknownFields()\n\tvar h322 CodeAction\n\tif err := decoder322.Decode(&h322); err == nil {\n\t\tt.Value = h322\n\t\treturn nil\n\t}\n\tdecoder323 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder323.DisallowUnknownFields()\n\tvar h323 Command\n\tif err := decoder323.Decode(&h323); err == nil {\n\t\tt.Value = h323\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [CodeAction Command]\"}\n}\n\nfunc (t Or_Result_textDocument_completion) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase CompletionList:\n\t\treturn json.Marshal(x)\n\tcase []CompletionItem:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [CompletionList []CompletionItem]\", t)\n}\n\nfunc (t *Or_Result_textDocument_completion) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder310 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder310.DisallowUnknownFields()\n\tvar h310 CompletionList\n\tif err := decoder310.Decode(&h310); err == nil {\n\t\tt.Value = h310\n\t\treturn nil\n\t}\n\tdecoder311 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder311.DisallowUnknownFields()\n\tvar h311 []CompletionItem\n\tif err := decoder311.Decode(&h311); err == nil {\n\t\tt.Value = h311\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [CompletionList []CompletionItem]\"}\n}\n\nfunc (t Or_Result_textDocument_declaration) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase Declaration:\n\t\treturn json.Marshal(x)\n\tcase []DeclarationLink:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [Declaration []DeclarationLink]\", t)\n}\n\nfunc (t *Or_Result_textDocument_declaration) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder298 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder298.DisallowUnknownFields()\n\tvar h298 Declaration\n\tif err := decoder298.Decode(&h298); err == nil {\n\t\tt.Value = h298\n\t\treturn nil\n\t}\n\tdecoder299 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder299.DisallowUnknownFields()\n\tvar h299 []DeclarationLink\n\tif err := decoder299.Decode(&h299); err == nil {\n\t\tt.Value = h299\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [Declaration []DeclarationLink]\"}\n}\n\nfunc (t Or_Result_textDocument_definition) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase Definition:\n\t\treturn json.Marshal(x)\n\tcase []DefinitionLink:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [Definition []DefinitionLink]\", t)\n}\n\nfunc (t *Or_Result_textDocument_definition) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder314 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder314.DisallowUnknownFields()\n\tvar h314 Definition\n\tif err := decoder314.Decode(&h314); err == nil {\n\t\tt.Value = h314\n\t\treturn nil\n\t}\n\tdecoder315 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder315.DisallowUnknownFields()\n\tvar h315 []DefinitionLink\n\tif err := decoder315.Decode(&h315); err == nil {\n\t\tt.Value = h315\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [Definition []DefinitionLink]\"}\n}\n\nfunc (t Or_Result_textDocument_documentSymbol) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase []DocumentSymbol:\n\t\treturn json.Marshal(x)\n\tcase []SymbolInformation:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [[]DocumentSymbol []SymbolInformation]\", t)\n}\n\nfunc (t *Or_Result_textDocument_documentSymbol) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder318 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder318.DisallowUnknownFields()\n\tvar h318 []DocumentSymbol\n\tif err := decoder318.Decode(&h318); err == nil {\n\t\tt.Value = h318\n\t\treturn nil\n\t}\n\tdecoder319 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder319.DisallowUnknownFields()\n\tvar h319 []SymbolInformation\n\tif err := decoder319.Decode(&h319); err == nil {\n\t\tt.Value = h319\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [[]DocumentSymbol []SymbolInformation]\"}\n}\n\nfunc (t Or_Result_textDocument_implementation) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase Definition:\n\t\treturn json.Marshal(x)\n\tcase []DefinitionLink:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [Definition []DefinitionLink]\", t)\n}\n\nfunc (t *Or_Result_textDocument_implementation) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder290 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder290.DisallowUnknownFields()\n\tvar h290 Definition\n\tif err := decoder290.Decode(&h290); err == nil {\n\t\tt.Value = h290\n\t\treturn nil\n\t}\n\tdecoder291 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder291.DisallowUnknownFields()\n\tvar h291 []DefinitionLink\n\tif err := decoder291.Decode(&h291); err == nil {\n\t\tt.Value = h291\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [Definition []DefinitionLink]\"}\n}\n\nfunc (t Or_Result_textDocument_inlineCompletion) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase InlineCompletionList:\n\t\treturn json.Marshal(x)\n\tcase []InlineCompletionItem:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [InlineCompletionList []InlineCompletionItem]\", t)\n}\n\nfunc (t *Or_Result_textDocument_inlineCompletion) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder306 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder306.DisallowUnknownFields()\n\tvar h306 InlineCompletionList\n\tif err := decoder306.Decode(&h306); err == nil {\n\t\tt.Value = h306\n\t\treturn nil\n\t}\n\tdecoder307 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder307.DisallowUnknownFields()\n\tvar h307 []InlineCompletionItem\n\tif err := decoder307.Decode(&h307); err == nil {\n\t\tt.Value = h307\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [InlineCompletionList []InlineCompletionItem]\"}\n}\n\nfunc (t Or_Result_textDocument_semanticTokens_full_delta) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase SemanticTokens:\n\t\treturn json.Marshal(x)\n\tcase SemanticTokensDelta:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [SemanticTokens SemanticTokensDelta]\", t)\n}\n\nfunc (t *Or_Result_textDocument_semanticTokens_full_delta) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder302 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder302.DisallowUnknownFields()\n\tvar h302 SemanticTokens\n\tif err := decoder302.Decode(&h302); err == nil {\n\t\tt.Value = h302\n\t\treturn nil\n\t}\n\tdecoder303 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder303.DisallowUnknownFields()\n\tvar h303 SemanticTokensDelta\n\tif err := decoder303.Decode(&h303); err == nil {\n\t\tt.Value = h303\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [SemanticTokens SemanticTokensDelta]\"}\n}\n\nfunc (t Or_Result_textDocument_typeDefinition) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase Definition:\n\t\treturn json.Marshal(x)\n\tcase []DefinitionLink:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [Definition []DefinitionLink]\", t)\n}\n\nfunc (t *Or_Result_textDocument_typeDefinition) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder294 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder294.DisallowUnknownFields()\n\tvar h294 Definition\n\tif err := decoder294.Decode(&h294); err == nil {\n\t\tt.Value = h294\n\t\treturn nil\n\t}\n\tdecoder295 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder295.DisallowUnknownFields()\n\tvar h295 []DefinitionLink\n\tif err := decoder295.Decode(&h295); err == nil {\n\t\tt.Value = h295\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [Definition []DefinitionLink]\"}\n}\n\nfunc (t Or_Result_workspace_symbol) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase []SymbolInformation:\n\t\treturn json.Marshal(x)\n\tcase []WorkspaceSymbol:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [[]SymbolInformation []WorkspaceSymbol]\", t)\n}\n\nfunc (t *Or_Result_workspace_symbol) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder326 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder326.DisallowUnknownFields()\n\tvar h326 []SymbolInformation\n\tif err := decoder326.Decode(&h326); err == nil {\n\t\tt.Value = h326\n\t\treturn nil\n\t}\n\tdecoder327 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder327.DisallowUnknownFields()\n\tvar h327 []WorkspaceSymbol\n\tif err := decoder327.Decode(&h327); err == nil {\n\t\tt.Value = h327\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [[]SymbolInformation []WorkspaceSymbol]\"}\n}\n\nfunc (t Or_SemanticTokensOptions_full) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase SemanticTokensFullDelta:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [SemanticTokensFullDelta bool]\", t)\n}\n\nfunc (t *Or_SemanticTokensOptions_full) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder47 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder47.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder47.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder48 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder48.DisallowUnknownFields()\n\tvar h48 SemanticTokensFullDelta\n\tif err := decoder48.Decode(&h48); err == nil {\n\t\tt.Value = h48\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [SemanticTokensFullDelta bool]\"}\n}\n\nfunc (t Or_SemanticTokensOptions_range) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase Lit_SemanticTokensOptions_range_Item1:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [Lit_SemanticTokensOptions_range_Item1 bool]\", t)\n}\n\nfunc (t *Or_SemanticTokensOptions_range) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder44 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder44.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder44.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder45 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder45.DisallowUnknownFields()\n\tvar h45 Lit_SemanticTokensOptions_range_Item1\n\tif err := decoder45.Decode(&h45); err == nil {\n\t\tt.Value = h45\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [Lit_SemanticTokensOptions_range_Item1 bool]\"}\n}\n\nfunc (t Or_ServerCapabilities_callHierarchyProvider) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase CallHierarchyOptions:\n\t\treturn json.Marshal(x)\n\tcase CallHierarchyRegistrationOptions:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [CallHierarchyOptions CallHierarchyRegistrationOptions bool]\", t)\n}\n\nfunc (t *Or_ServerCapabilities_callHierarchyProvider) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder140 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder140.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder140.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder141 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder141.DisallowUnknownFields()\n\tvar h141 CallHierarchyOptions\n\tif err := decoder141.Decode(&h141); err == nil {\n\t\tt.Value = h141\n\t\treturn nil\n\t}\n\tdecoder142 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder142.DisallowUnknownFields()\n\tvar h142 CallHierarchyRegistrationOptions\n\tif err := decoder142.Decode(&h142); err == nil {\n\t\tt.Value = h142\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [CallHierarchyOptions CallHierarchyRegistrationOptions bool]\"}\n}\n\nfunc (t Or_ServerCapabilities_codeActionProvider) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase CodeActionOptions:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [CodeActionOptions bool]\", t)\n}\n\nfunc (t *Or_ServerCapabilities_codeActionProvider) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder109 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder109.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder109.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder110 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder110.DisallowUnknownFields()\n\tvar h110 CodeActionOptions\n\tif err := decoder110.Decode(&h110); err == nil {\n\t\tt.Value = h110\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [CodeActionOptions bool]\"}\n}\n\nfunc (t Or_ServerCapabilities_colorProvider) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase DocumentColorOptions:\n\t\treturn json.Marshal(x)\n\tcase DocumentColorRegistrationOptions:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [DocumentColorOptions DocumentColorRegistrationOptions bool]\", t)\n}\n\nfunc (t *Or_ServerCapabilities_colorProvider) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder113 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder113.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder113.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder114 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder114.DisallowUnknownFields()\n\tvar h114 DocumentColorOptions\n\tif err := decoder114.Decode(&h114); err == nil {\n\t\tt.Value = h114\n\t\treturn nil\n\t}\n\tdecoder115 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder115.DisallowUnknownFields()\n\tvar h115 DocumentColorRegistrationOptions\n\tif err := decoder115.Decode(&h115); err == nil {\n\t\tt.Value = h115\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [DocumentColorOptions DocumentColorRegistrationOptions bool]\"}\n}\n\nfunc (t Or_ServerCapabilities_declarationProvider) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase DeclarationOptions:\n\t\treturn json.Marshal(x)\n\tcase DeclarationRegistrationOptions:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [DeclarationOptions DeclarationRegistrationOptions bool]\", t)\n}\n\nfunc (t *Or_ServerCapabilities_declarationProvider) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder83 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder83.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder83.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder84 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder84.DisallowUnknownFields()\n\tvar h84 DeclarationOptions\n\tif err := decoder84.Decode(&h84); err == nil {\n\t\tt.Value = h84\n\t\treturn nil\n\t}\n\tdecoder85 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder85.DisallowUnknownFields()\n\tvar h85 DeclarationRegistrationOptions\n\tif err := decoder85.Decode(&h85); err == nil {\n\t\tt.Value = h85\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [DeclarationOptions DeclarationRegistrationOptions bool]\"}\n}\n\nfunc (t Or_ServerCapabilities_definitionProvider) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase DefinitionOptions:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [DefinitionOptions bool]\", t)\n}\n\nfunc (t *Or_ServerCapabilities_definitionProvider) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder87 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder87.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder87.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder88 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder88.DisallowUnknownFields()\n\tvar h88 DefinitionOptions\n\tif err := decoder88.Decode(&h88); err == nil {\n\t\tt.Value = h88\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [DefinitionOptions bool]\"}\n}\n\nfunc (t Or_ServerCapabilities_diagnosticProvider) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase DiagnosticOptions:\n\t\treturn json.Marshal(x)\n\tcase DiagnosticRegistrationOptions:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [DiagnosticOptions DiagnosticRegistrationOptions]\", t)\n}\n\nfunc (t *Or_ServerCapabilities_diagnosticProvider) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder174 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder174.DisallowUnknownFields()\n\tvar h174 DiagnosticOptions\n\tif err := decoder174.Decode(&h174); err == nil {\n\t\tt.Value = h174\n\t\treturn nil\n\t}\n\tdecoder175 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder175.DisallowUnknownFields()\n\tvar h175 DiagnosticRegistrationOptions\n\tif err := decoder175.Decode(&h175); err == nil {\n\t\tt.Value = h175\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [DiagnosticOptions DiagnosticRegistrationOptions]\"}\n}\n\nfunc (t Or_ServerCapabilities_documentFormattingProvider) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase DocumentFormattingOptions:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [DocumentFormattingOptions bool]\", t)\n}\n\nfunc (t *Or_ServerCapabilities_documentFormattingProvider) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder120 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder120.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder120.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder121 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder121.DisallowUnknownFields()\n\tvar h121 DocumentFormattingOptions\n\tif err := decoder121.Decode(&h121); err == nil {\n\t\tt.Value = h121\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [DocumentFormattingOptions bool]\"}\n}\n\nfunc (t Or_ServerCapabilities_documentHighlightProvider) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase DocumentHighlightOptions:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [DocumentHighlightOptions bool]\", t)\n}\n\nfunc (t *Or_ServerCapabilities_documentHighlightProvider) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder103 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder103.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder103.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder104 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder104.DisallowUnknownFields()\n\tvar h104 DocumentHighlightOptions\n\tif err := decoder104.Decode(&h104); err == nil {\n\t\tt.Value = h104\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [DocumentHighlightOptions bool]\"}\n}\n\nfunc (t Or_ServerCapabilities_documentRangeFormattingProvider) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase DocumentRangeFormattingOptions:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [DocumentRangeFormattingOptions bool]\", t)\n}\n\nfunc (t *Or_ServerCapabilities_documentRangeFormattingProvider) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder123 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder123.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder123.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder124 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder124.DisallowUnknownFields()\n\tvar h124 DocumentRangeFormattingOptions\n\tif err := decoder124.Decode(&h124); err == nil {\n\t\tt.Value = h124\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [DocumentRangeFormattingOptions bool]\"}\n}\n\nfunc (t Or_ServerCapabilities_documentSymbolProvider) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase DocumentSymbolOptions:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [DocumentSymbolOptions bool]\", t)\n}\n\nfunc (t *Or_ServerCapabilities_documentSymbolProvider) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder106 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder106.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder106.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder107 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder107.DisallowUnknownFields()\n\tvar h107 DocumentSymbolOptions\n\tif err := decoder107.Decode(&h107); err == nil {\n\t\tt.Value = h107\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [DocumentSymbolOptions bool]\"}\n}\n\nfunc (t Or_ServerCapabilities_foldingRangeProvider) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase FoldingRangeOptions:\n\t\treturn json.Marshal(x)\n\tcase FoldingRangeRegistrationOptions:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [FoldingRangeOptions FoldingRangeRegistrationOptions bool]\", t)\n}\n\nfunc (t *Or_ServerCapabilities_foldingRangeProvider) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder130 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder130.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder130.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder131 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder131.DisallowUnknownFields()\n\tvar h131 FoldingRangeOptions\n\tif err := decoder131.Decode(&h131); err == nil {\n\t\tt.Value = h131\n\t\treturn nil\n\t}\n\tdecoder132 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder132.DisallowUnknownFields()\n\tvar h132 FoldingRangeRegistrationOptions\n\tif err := decoder132.Decode(&h132); err == nil {\n\t\tt.Value = h132\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [FoldingRangeOptions FoldingRangeRegistrationOptions bool]\"}\n}\n\nfunc (t Or_ServerCapabilities_hoverProvider) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase HoverOptions:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [HoverOptions bool]\", t)\n}\n\nfunc (t *Or_ServerCapabilities_hoverProvider) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder79 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder79.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder79.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder80 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder80.DisallowUnknownFields()\n\tvar h80 HoverOptions\n\tif err := decoder80.Decode(&h80); err == nil {\n\t\tt.Value = h80\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [HoverOptions bool]\"}\n}\n\nfunc (t Or_ServerCapabilities_implementationProvider) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase ImplementationOptions:\n\t\treturn json.Marshal(x)\n\tcase ImplementationRegistrationOptions:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [ImplementationOptions ImplementationRegistrationOptions bool]\", t)\n}\n\nfunc (t *Or_ServerCapabilities_implementationProvider) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder96 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder96.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder96.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder97 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder97.DisallowUnknownFields()\n\tvar h97 ImplementationOptions\n\tif err := decoder97.Decode(&h97); err == nil {\n\t\tt.Value = h97\n\t\treturn nil\n\t}\n\tdecoder98 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder98.DisallowUnknownFields()\n\tvar h98 ImplementationRegistrationOptions\n\tif err := decoder98.Decode(&h98); err == nil {\n\t\tt.Value = h98\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [ImplementationOptions ImplementationRegistrationOptions bool]\"}\n}\n\nfunc (t Or_ServerCapabilities_inlayHintProvider) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase InlayHintOptions:\n\t\treturn json.Marshal(x)\n\tcase InlayHintRegistrationOptions:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [InlayHintOptions InlayHintRegistrationOptions bool]\", t)\n}\n\nfunc (t *Or_ServerCapabilities_inlayHintProvider) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder169 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder169.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder169.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder170 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder170.DisallowUnknownFields()\n\tvar h170 InlayHintOptions\n\tif err := decoder170.Decode(&h170); err == nil {\n\t\tt.Value = h170\n\t\treturn nil\n\t}\n\tdecoder171 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder171.DisallowUnknownFields()\n\tvar h171 InlayHintRegistrationOptions\n\tif err := decoder171.Decode(&h171); err == nil {\n\t\tt.Value = h171\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [InlayHintOptions InlayHintRegistrationOptions bool]\"}\n}\n\nfunc (t Or_ServerCapabilities_inlineCompletionProvider) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase InlineCompletionOptions:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [InlineCompletionOptions bool]\", t)\n}\n\nfunc (t *Or_ServerCapabilities_inlineCompletionProvider) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder177 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder177.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder177.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder178 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder178.DisallowUnknownFields()\n\tvar h178 InlineCompletionOptions\n\tif err := decoder178.Decode(&h178); err == nil {\n\t\tt.Value = h178\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [InlineCompletionOptions bool]\"}\n}\n\nfunc (t Or_ServerCapabilities_inlineValueProvider) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase InlineValueOptions:\n\t\treturn json.Marshal(x)\n\tcase InlineValueRegistrationOptions:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [InlineValueOptions InlineValueRegistrationOptions bool]\", t)\n}\n\nfunc (t *Or_ServerCapabilities_inlineValueProvider) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder164 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder164.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder164.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder165 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder165.DisallowUnknownFields()\n\tvar h165 InlineValueOptions\n\tif err := decoder165.Decode(&h165); err == nil {\n\t\tt.Value = h165\n\t\treturn nil\n\t}\n\tdecoder166 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder166.DisallowUnknownFields()\n\tvar h166 InlineValueRegistrationOptions\n\tif err := decoder166.Decode(&h166); err == nil {\n\t\tt.Value = h166\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [InlineValueOptions InlineValueRegistrationOptions bool]\"}\n}\n\nfunc (t Or_ServerCapabilities_linkedEditingRangeProvider) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase LinkedEditingRangeOptions:\n\t\treturn json.Marshal(x)\n\tcase LinkedEditingRangeRegistrationOptions:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [LinkedEditingRangeOptions LinkedEditingRangeRegistrationOptions bool]\", t)\n}\n\nfunc (t *Or_ServerCapabilities_linkedEditingRangeProvider) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder145 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder145.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder145.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder146 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder146.DisallowUnknownFields()\n\tvar h146 LinkedEditingRangeOptions\n\tif err := decoder146.Decode(&h146); err == nil {\n\t\tt.Value = h146\n\t\treturn nil\n\t}\n\tdecoder147 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder147.DisallowUnknownFields()\n\tvar h147 LinkedEditingRangeRegistrationOptions\n\tif err := decoder147.Decode(&h147); err == nil {\n\t\tt.Value = h147\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [LinkedEditingRangeOptions LinkedEditingRangeRegistrationOptions bool]\"}\n}\n\nfunc (t Or_ServerCapabilities_monikerProvider) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase MonikerOptions:\n\t\treturn json.Marshal(x)\n\tcase MonikerRegistrationOptions:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [MonikerOptions MonikerRegistrationOptions bool]\", t)\n}\n\nfunc (t *Or_ServerCapabilities_monikerProvider) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder154 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder154.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder154.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder155 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder155.DisallowUnknownFields()\n\tvar h155 MonikerOptions\n\tif err := decoder155.Decode(&h155); err == nil {\n\t\tt.Value = h155\n\t\treturn nil\n\t}\n\tdecoder156 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder156.DisallowUnknownFields()\n\tvar h156 MonikerRegistrationOptions\n\tif err := decoder156.Decode(&h156); err == nil {\n\t\tt.Value = h156\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [MonikerOptions MonikerRegistrationOptions bool]\"}\n}\n\nfunc (t Or_ServerCapabilities_notebookDocumentSync) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase NotebookDocumentSyncOptions:\n\t\treturn json.Marshal(x)\n\tcase NotebookDocumentSyncRegistrationOptions:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [NotebookDocumentSyncOptions NotebookDocumentSyncRegistrationOptions]\", t)\n}\n\nfunc (t *Or_ServerCapabilities_notebookDocumentSync) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder76 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder76.DisallowUnknownFields()\n\tvar h76 NotebookDocumentSyncOptions\n\tif err := decoder76.Decode(&h76); err == nil {\n\t\tt.Value = h76\n\t\treturn nil\n\t}\n\tdecoder77 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder77.DisallowUnknownFields()\n\tvar h77 NotebookDocumentSyncRegistrationOptions\n\tif err := decoder77.Decode(&h77); err == nil {\n\t\tt.Value = h77\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [NotebookDocumentSyncOptions NotebookDocumentSyncRegistrationOptions]\"}\n}\n\nfunc (t Or_ServerCapabilities_referencesProvider) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase ReferenceOptions:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [ReferenceOptions bool]\", t)\n}\n\nfunc (t *Or_ServerCapabilities_referencesProvider) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder100 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder100.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder100.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder101 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder101.DisallowUnknownFields()\n\tvar h101 ReferenceOptions\n\tif err := decoder101.Decode(&h101); err == nil {\n\t\tt.Value = h101\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [ReferenceOptions bool]\"}\n}\n\nfunc (t Or_ServerCapabilities_renameProvider) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase RenameOptions:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [RenameOptions bool]\", t)\n}\n\nfunc (t *Or_ServerCapabilities_renameProvider) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder126 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder126.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder126.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder127 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder127.DisallowUnknownFields()\n\tvar h127 RenameOptions\n\tif err := decoder127.Decode(&h127); err == nil {\n\t\tt.Value = h127\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [RenameOptions bool]\"}\n}\n\nfunc (t Or_ServerCapabilities_selectionRangeProvider) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase SelectionRangeOptions:\n\t\treturn json.Marshal(x)\n\tcase SelectionRangeRegistrationOptions:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [SelectionRangeOptions SelectionRangeRegistrationOptions bool]\", t)\n}\n\nfunc (t *Or_ServerCapabilities_selectionRangeProvider) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder135 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder135.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder135.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder136 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder136.DisallowUnknownFields()\n\tvar h136 SelectionRangeOptions\n\tif err := decoder136.Decode(&h136); err == nil {\n\t\tt.Value = h136\n\t\treturn nil\n\t}\n\tdecoder137 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder137.DisallowUnknownFields()\n\tvar h137 SelectionRangeRegistrationOptions\n\tif err := decoder137.Decode(&h137); err == nil {\n\t\tt.Value = h137\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [SelectionRangeOptions SelectionRangeRegistrationOptions bool]\"}\n}\n\nfunc (t Or_ServerCapabilities_semanticTokensProvider) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase SemanticTokensOptions:\n\t\treturn json.Marshal(x)\n\tcase SemanticTokensRegistrationOptions:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [SemanticTokensOptions SemanticTokensRegistrationOptions]\", t)\n}\n\nfunc (t *Or_ServerCapabilities_semanticTokensProvider) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder150 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder150.DisallowUnknownFields()\n\tvar h150 SemanticTokensOptions\n\tif err := decoder150.Decode(&h150); err == nil {\n\t\tt.Value = h150\n\t\treturn nil\n\t}\n\tdecoder151 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder151.DisallowUnknownFields()\n\tvar h151 SemanticTokensRegistrationOptions\n\tif err := decoder151.Decode(&h151); err == nil {\n\t\tt.Value = h151\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [SemanticTokensOptions SemanticTokensRegistrationOptions]\"}\n}\n\nfunc (t Or_ServerCapabilities_textDocumentSync) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase TextDocumentSyncKind:\n\t\treturn json.Marshal(x)\n\tcase TextDocumentSyncOptions:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [TextDocumentSyncKind TextDocumentSyncOptions]\", t)\n}\n\nfunc (t *Or_ServerCapabilities_textDocumentSync) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder72 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder72.DisallowUnknownFields()\n\tvar h72 TextDocumentSyncKind\n\tif err := decoder72.Decode(&h72); err == nil {\n\t\tt.Value = h72\n\t\treturn nil\n\t}\n\tdecoder73 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder73.DisallowUnknownFields()\n\tvar h73 TextDocumentSyncOptions\n\tif err := decoder73.Decode(&h73); err == nil {\n\t\tt.Value = h73\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [TextDocumentSyncKind TextDocumentSyncOptions]\"}\n}\n\nfunc (t Or_ServerCapabilities_typeDefinitionProvider) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase TypeDefinitionOptions:\n\t\treturn json.Marshal(x)\n\tcase TypeDefinitionRegistrationOptions:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [TypeDefinitionOptions TypeDefinitionRegistrationOptions bool]\", t)\n}\n\nfunc (t *Or_ServerCapabilities_typeDefinitionProvider) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder91 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder91.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder91.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder92 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder92.DisallowUnknownFields()\n\tvar h92 TypeDefinitionOptions\n\tif err := decoder92.Decode(&h92); err == nil {\n\t\tt.Value = h92\n\t\treturn nil\n\t}\n\tdecoder93 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder93.DisallowUnknownFields()\n\tvar h93 TypeDefinitionRegistrationOptions\n\tif err := decoder93.Decode(&h93); err == nil {\n\t\tt.Value = h93\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [TypeDefinitionOptions TypeDefinitionRegistrationOptions bool]\"}\n}\n\nfunc (t Or_ServerCapabilities_typeHierarchyProvider) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase TypeHierarchyOptions:\n\t\treturn json.Marshal(x)\n\tcase TypeHierarchyRegistrationOptions:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [TypeHierarchyOptions TypeHierarchyRegistrationOptions bool]\", t)\n}\n\nfunc (t *Or_ServerCapabilities_typeHierarchyProvider) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder159 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder159.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder159.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder160 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder160.DisallowUnknownFields()\n\tvar h160 TypeHierarchyOptions\n\tif err := decoder160.Decode(&h160); err == nil {\n\t\tt.Value = h160\n\t\treturn nil\n\t}\n\tdecoder161 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder161.DisallowUnknownFields()\n\tvar h161 TypeHierarchyRegistrationOptions\n\tif err := decoder161.Decode(&h161); err == nil {\n\t\tt.Value = h161\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [TypeHierarchyOptions TypeHierarchyRegistrationOptions bool]\"}\n}\n\nfunc (t Or_ServerCapabilities_workspaceSymbolProvider) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase WorkspaceSymbolOptions:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [WorkspaceSymbolOptions bool]\", t)\n}\n\nfunc (t *Or_ServerCapabilities_workspaceSymbolProvider) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder117 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder117.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder117.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder118 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder118.DisallowUnknownFields()\n\tvar h118 WorkspaceSymbolOptions\n\tif err := decoder118.Decode(&h118); err == nil {\n\t\tt.Value = h118\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [WorkspaceSymbolOptions bool]\"}\n}\n\nfunc (t Or_SignatureInformation_documentation) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase MarkupContent:\n\t\treturn json.Marshal(x)\n\tcase string:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [MarkupContent string]\", t)\n}\n\nfunc (t *Or_SignatureInformation_documentation) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder186 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder186.DisallowUnknownFields()\n\tvar stringVal string\n\tif err := decoder186.Decode(&stringVal); err == nil {\n\t\tt.Value = stringVal\n\t\treturn nil\n\t}\n\tdecoder187 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder187.DisallowUnknownFields()\n\tvar h187 MarkupContent\n\tif err := decoder187.Decode(&h187); err == nil {\n\t\tt.Value = h187\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [MarkupContent string]\"}\n}\n\nfunc (t Or_TextDocumentContentChangeEvent) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase TextDocumentContentChangePartial:\n\t\treturn json.Marshal(x)\n\tcase TextDocumentContentChangeWholeDocument:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [TextDocumentContentChangePartial TextDocumentContentChangeWholeDocument]\", t)\n}\n\nfunc (t *Or_TextDocumentContentChangeEvent) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder263 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder263.DisallowUnknownFields()\n\tvar h263 TextDocumentContentChangePartial\n\tif err := decoder263.Decode(&h263); err == nil {\n\t\tt.Value = h263\n\t\treturn nil\n\t}\n\tdecoder264 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder264.DisallowUnknownFields()\n\tvar h264 TextDocumentContentChangeWholeDocument\n\tif err := decoder264.Decode(&h264); err == nil {\n\t\tt.Value = h264\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [TextDocumentContentChangePartial TextDocumentContentChangeWholeDocument]\"}\n}\n\nfunc (t Or_TextDocumentEdit_edits_Elem) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase AnnotatedTextEdit:\n\t\treturn json.Marshal(x)\n\tcase SnippetTextEdit:\n\t\treturn json.Marshal(x)\n\tcase TextEdit:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [AnnotatedTextEdit SnippetTextEdit TextEdit]\", t)\n}\n\nfunc (t *Or_TextDocumentEdit_edits_Elem) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder52 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder52.DisallowUnknownFields()\n\tvar h52 AnnotatedTextEdit\n\tif err := decoder52.Decode(&h52); err == nil {\n\t\tt.Value = h52\n\t\treturn nil\n\t}\n\tdecoder53 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder53.DisallowUnknownFields()\n\tvar h53 SnippetTextEdit\n\tif err := decoder53.Decode(&h53); err == nil {\n\t\tt.Value = h53\n\t\treturn nil\n\t}\n\tdecoder54 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder54.DisallowUnknownFields()\n\tvar h54 TextEdit\n\tif err := decoder54.Decode(&h54); err == nil {\n\t\tt.Value = h54\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [AnnotatedTextEdit SnippetTextEdit TextEdit]\"}\n}\n\nfunc (t Or_TextDocumentFilter) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase TextDocumentFilterLanguage:\n\t\treturn json.Marshal(x)\n\tcase TextDocumentFilterPattern:\n\t\treturn json.Marshal(x)\n\tcase TextDocumentFilterScheme:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [TextDocumentFilterLanguage TextDocumentFilterPattern TextDocumentFilterScheme]\", t)\n}\n\nfunc (t *Or_TextDocumentFilter) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder279 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder279.DisallowUnknownFields()\n\tvar h279 TextDocumentFilterLanguage\n\tif err := decoder279.Decode(&h279); err == nil {\n\t\tt.Value = h279\n\t\treturn nil\n\t}\n\tdecoder280 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder280.DisallowUnknownFields()\n\tvar h280 TextDocumentFilterPattern\n\tif err := decoder280.Decode(&h280); err == nil {\n\t\tt.Value = h280\n\t\treturn nil\n\t}\n\tdecoder281 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder281.DisallowUnknownFields()\n\tvar h281 TextDocumentFilterScheme\n\tif err := decoder281.Decode(&h281); err == nil {\n\t\tt.Value = h281\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [TextDocumentFilterLanguage TextDocumentFilterPattern TextDocumentFilterScheme]\"}\n}\n\nfunc (t Or_TextDocumentSyncOptions_save) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase SaveOptions:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [SaveOptions bool]\", t)\n}\n\nfunc (t *Or_TextDocumentSyncOptions_save) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder195 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder195.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder195.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder196 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder196.DisallowUnknownFields()\n\tvar h196 SaveOptions\n\tif err := decoder196.Decode(&h196); err == nil {\n\t\tt.Value = h196\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [SaveOptions bool]\"}\n}\n\nfunc (t Or_WorkspaceDocumentDiagnosticReport) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase WorkspaceFullDocumentDiagnosticReport:\n\t\treturn json.Marshal(x)\n\tcase WorkspaceUnchangedDocumentDiagnosticReport:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [WorkspaceFullDocumentDiagnosticReport WorkspaceUnchangedDocumentDiagnosticReport]\", t)\n}\n\nfunc (t *Or_WorkspaceDocumentDiagnosticReport) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder259 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder259.DisallowUnknownFields()\n\tvar h259 WorkspaceFullDocumentDiagnosticReport\n\tif err := decoder259.Decode(&h259); err == nil {\n\t\tt.Value = h259\n\t\treturn nil\n\t}\n\tdecoder260 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder260.DisallowUnknownFields()\n\tvar h260 WorkspaceUnchangedDocumentDiagnosticReport\n\tif err := decoder260.Decode(&h260); err == nil {\n\t\tt.Value = h260\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [WorkspaceFullDocumentDiagnosticReport WorkspaceUnchangedDocumentDiagnosticReport]\"}\n}\n\nfunc (t Or_WorkspaceEdit_documentChanges_Elem) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase CreateFile:\n\t\treturn json.Marshal(x)\n\tcase DeleteFile:\n\t\treturn json.Marshal(x)\n\tcase RenameFile:\n\t\treturn json.Marshal(x)\n\tcase TextDocumentEdit:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [CreateFile DeleteFile RenameFile TextDocumentEdit]\", t)\n}\n\nfunc (t *Or_WorkspaceEdit_documentChanges_Elem) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder4 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder4.DisallowUnknownFields()\n\tvar h4 CreateFile\n\tif err := decoder4.Decode(&h4); err == nil {\n\t\tt.Value = h4\n\t\treturn nil\n\t}\n\tdecoder5 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder5.DisallowUnknownFields()\n\tvar h5 DeleteFile\n\tif err := decoder5.Decode(&h5); err == nil {\n\t\tt.Value = h5\n\t\treturn nil\n\t}\n\tdecoder6 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder6.DisallowUnknownFields()\n\tvar h6 RenameFile\n\tif err := decoder6.Decode(&h6); err == nil {\n\t\tt.Value = h6\n\t\treturn nil\n\t}\n\tdecoder7 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder7.DisallowUnknownFields()\n\tvar h7 TextDocumentEdit\n\tif err := decoder7.Decode(&h7); err == nil {\n\t\tt.Value = h7\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [CreateFile DeleteFile RenameFile TextDocumentEdit]\"}\n}\n\nfunc (t Or_WorkspaceFoldersServerCapabilities_changeNotifications) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase string:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [bool string]\", t)\n}\n\nfunc (t *Or_WorkspaceFoldersServerCapabilities_changeNotifications) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder210 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder210.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder210.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder211 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder211.DisallowUnknownFields()\n\tvar stringVal string\n\tif err := decoder211.Decode(&stringVal); err == nil {\n\t\tt.Value = stringVal\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [bool string]\"}\n}\n\nfunc (t Or_WorkspaceOptions_textDocumentContent) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase TextDocumentContentOptions:\n\t\treturn json.Marshal(x)\n\tcase TextDocumentContentRegistrationOptions:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [TextDocumentContentOptions TextDocumentContentRegistrationOptions]\", t)\n}\n\nfunc (t *Or_WorkspaceOptions_textDocumentContent) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder199 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder199.DisallowUnknownFields()\n\tvar h199 TextDocumentContentOptions\n\tif err := decoder199.Decode(&h199); err == nil {\n\t\tt.Value = h199\n\t\treturn nil\n\t}\n\tdecoder200 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder200.DisallowUnknownFields()\n\tvar h200 TextDocumentContentRegistrationOptions\n\tif err := decoder200.Decode(&h200); err == nil {\n\t\tt.Value = h200\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [TextDocumentContentOptions TextDocumentContentRegistrationOptions]\"}\n}\n\nfunc (t Or_WorkspaceSymbol_location) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase Location:\n\t\treturn json.Marshal(x)\n\tcase LocationUriOnly:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [Location LocationUriOnly]\", t)\n}\n\nfunc (t *Or_WorkspaceSymbol_location) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder39 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder39.DisallowUnknownFields()\n\tvar h39 Location\n\tif err := decoder39.Decode(&h39); err == nil {\n\t\tt.Value = h39\n\t\treturn nil\n\t}\n\tdecoder40 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder40.DisallowUnknownFields()\n\tvar h40 LocationUriOnly\n\tif err := decoder40.Decode(&h40); err == nil {\n\t\tt.Value = h40\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [Location LocationUriOnly]\"}\n}\n"], ["/opencode/internal/llm/agent/tools.go", "package agent\n\nimport (\n\t\"context\"\n\n\t\"github.com/opencode-ai/opencode/internal/history\"\n\t\"github.com/opencode-ai/opencode/internal/llm/tools\"\n\t\"github.com/opencode-ai/opencode/internal/lsp\"\n\t\"github.com/opencode-ai/opencode/internal/message\"\n\t\"github.com/opencode-ai/opencode/internal/permission\"\n\t\"github.com/opencode-ai/opencode/internal/session\"\n)\n\nfunc CoderAgentTools(\n\tpermissions permission.Service,\n\tsessions session.Service,\n\tmessages message.Service,\n\thistory history.Service,\n\tlspClients map[string]*lsp.Client,\n) []tools.BaseTool {\n\tctx := context.Background()\n\totherTools := GetMcpTools(ctx, permissions)\n\tif len(lspClients) > 0 {\n\t\totherTools = append(otherTools, tools.NewDiagnosticsTool(lspClients))\n\t}\n\treturn append(\n\t\t[]tools.BaseTool{\n\t\t\ttools.NewBashTool(permissions),\n\t\t\ttools.NewEditTool(lspClients, permissions, history),\n\t\t\ttools.NewFetchTool(permissions),\n\t\t\ttools.NewGlobTool(),\n\t\t\ttools.NewGrepTool(),\n\t\t\ttools.NewLsTool(),\n\t\t\ttools.NewSourcegraphTool(),\n\t\t\ttools.NewViewTool(lspClients),\n\t\t\ttools.NewPatchTool(lspClients, permissions, history),\n\t\t\ttools.NewWriteTool(lspClients, permissions, history),\n\t\t\tNewAgentTool(sessions, messages, lspClients),\n\t\t}, otherTools...,\n\t)\n}\n\nfunc TaskAgentTools(lspClients map[string]*lsp.Client) []tools.BaseTool {\n\treturn []tools.BaseTool{\n\t\ttools.NewGlobTool(),\n\t\ttools.NewGrepTool(),\n\t\ttools.NewLsTool(),\n\t\ttools.NewSourcegraphTool(),\n\t\ttools.NewViewTool(lspClients),\n\t}\n}\n"], ["/opencode/internal/db/files.sql.go", "// Code generated by sqlc. DO NOT EDIT.\n// versions:\n// sqlc v1.29.0\n// source: files.sql\n\npackage db\n\nimport (\n\t\"context\"\n)\n\nconst createFile = `-- name: CreateFile :one\nINSERT INTO files (\n id,\n session_id,\n path,\n content,\n version,\n created_at,\n updated_at\n) VALUES (\n ?, ?, ?, ?, ?, strftime('%s', 'now'), strftime('%s', 'now')\n)\nRETURNING id, session_id, path, content, version, created_at, updated_at\n`\n\ntype CreateFileParams struct {\n\tID string `json:\"id\"`\n\tSessionID string `json:\"session_id\"`\n\tPath string `json:\"path\"`\n\tContent string `json:\"content\"`\n\tVersion string `json:\"version\"`\n}\n\nfunc (q *Queries) CreateFile(ctx context.Context, arg CreateFileParams) (File, error) {\n\trow := q.queryRow(ctx, q.createFileStmt, createFile,\n\t\targ.ID,\n\t\targ.SessionID,\n\t\targ.Path,\n\t\targ.Content,\n\t\targ.Version,\n\t)\n\tvar i File\n\terr := row.Scan(\n\t\t&i.ID,\n\t\t&i.SessionID,\n\t\t&i.Path,\n\t\t&i.Content,\n\t\t&i.Version,\n\t\t&i.CreatedAt,\n\t\t&i.UpdatedAt,\n\t)\n\treturn i, err\n}\n\nconst deleteFile = `-- name: DeleteFile :exec\nDELETE FROM files\nWHERE id = ?\n`\n\nfunc (q *Queries) DeleteFile(ctx context.Context, id string) error {\n\t_, err := q.exec(ctx, q.deleteFileStmt, deleteFile, id)\n\treturn err\n}\n\nconst deleteSessionFiles = `-- name: DeleteSessionFiles :exec\nDELETE FROM files\nWHERE session_id = ?\n`\n\nfunc (q *Queries) DeleteSessionFiles(ctx context.Context, sessionID string) error {\n\t_, err := q.exec(ctx, q.deleteSessionFilesStmt, deleteSessionFiles, sessionID)\n\treturn err\n}\n\nconst getFile = `-- name: GetFile :one\nSELECT id, session_id, path, content, version, created_at, updated_at\nFROM files\nWHERE id = ? LIMIT 1\n`\n\nfunc (q *Queries) GetFile(ctx context.Context, id string) (File, error) {\n\trow := q.queryRow(ctx, q.getFileStmt, getFile, id)\n\tvar i File\n\terr := row.Scan(\n\t\t&i.ID,\n\t\t&i.SessionID,\n\t\t&i.Path,\n\t\t&i.Content,\n\t\t&i.Version,\n\t\t&i.CreatedAt,\n\t\t&i.UpdatedAt,\n\t)\n\treturn i, err\n}\n\nconst getFileByPathAndSession = `-- name: GetFileByPathAndSession :one\nSELECT id, session_id, path, content, version, created_at, updated_at\nFROM files\nWHERE path = ? AND session_id = ?\nORDER BY created_at DESC\nLIMIT 1\n`\n\ntype GetFileByPathAndSessionParams struct {\n\tPath string `json:\"path\"`\n\tSessionID string `json:\"session_id\"`\n}\n\nfunc (q *Queries) GetFileByPathAndSession(ctx context.Context, arg GetFileByPathAndSessionParams) (File, error) {\n\trow := q.queryRow(ctx, q.getFileByPathAndSessionStmt, getFileByPathAndSession, arg.Path, arg.SessionID)\n\tvar i File\n\terr := row.Scan(\n\t\t&i.ID,\n\t\t&i.SessionID,\n\t\t&i.Path,\n\t\t&i.Content,\n\t\t&i.Version,\n\t\t&i.CreatedAt,\n\t\t&i.UpdatedAt,\n\t)\n\treturn i, err\n}\n\nconst listFilesByPath = `-- name: ListFilesByPath :many\nSELECT id, session_id, path, content, version, created_at, updated_at\nFROM files\nWHERE path = ?\nORDER BY created_at DESC\n`\n\nfunc (q *Queries) ListFilesByPath(ctx context.Context, path string) ([]File, error) {\n\trows, err := q.query(ctx, q.listFilesByPathStmt, listFilesByPath, path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer rows.Close()\n\titems := []File{}\n\tfor rows.Next() {\n\t\tvar i File\n\t\tif err := rows.Scan(\n\t\t\t&i.ID,\n\t\t\t&i.SessionID,\n\t\t\t&i.Path,\n\t\t\t&i.Content,\n\t\t\t&i.Version,\n\t\t\t&i.CreatedAt,\n\t\t\t&i.UpdatedAt,\n\t\t); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\titems = append(items, i)\n\t}\n\tif err := rows.Close(); err != nil {\n\t\treturn nil, err\n\t}\n\tif err := rows.Err(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn items, nil\n}\n\nconst listFilesBySession = `-- name: ListFilesBySession :many\nSELECT id, session_id, path, content, version, created_at, updated_at\nFROM files\nWHERE session_id = ?\nORDER BY created_at ASC\n`\n\nfunc (q *Queries) ListFilesBySession(ctx context.Context, sessionID string) ([]File, error) {\n\trows, err := q.query(ctx, q.listFilesBySessionStmt, listFilesBySession, sessionID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer rows.Close()\n\titems := []File{}\n\tfor rows.Next() {\n\t\tvar i File\n\t\tif err := rows.Scan(\n\t\t\t&i.ID,\n\t\t\t&i.SessionID,\n\t\t\t&i.Path,\n\t\t\t&i.Content,\n\t\t\t&i.Version,\n\t\t\t&i.CreatedAt,\n\t\t\t&i.UpdatedAt,\n\t\t); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\titems = append(items, i)\n\t}\n\tif err := rows.Close(); err != nil {\n\t\treturn nil, err\n\t}\n\tif err := rows.Err(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn items, nil\n}\n\nconst listLatestSessionFiles = `-- name: ListLatestSessionFiles :many\nSELECT f.id, f.session_id, f.path, f.content, f.version, f.created_at, f.updated_at\nFROM files f\nINNER JOIN (\n SELECT path, MAX(created_at) as max_created_at\n FROM files\n GROUP BY path\n) latest ON f.path = latest.path AND f.created_at = latest.max_created_at\nWHERE f.session_id = ?\nORDER BY f.path\n`\n\nfunc (q *Queries) ListLatestSessionFiles(ctx context.Context, sessionID string) ([]File, error) {\n\trows, err := q.query(ctx, q.listLatestSessionFilesStmt, listLatestSessionFiles, sessionID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer rows.Close()\n\titems := []File{}\n\tfor rows.Next() {\n\t\tvar i File\n\t\tif err := rows.Scan(\n\t\t\t&i.ID,\n\t\t\t&i.SessionID,\n\t\t\t&i.Path,\n\t\t\t&i.Content,\n\t\t\t&i.Version,\n\t\t\t&i.CreatedAt,\n\t\t\t&i.UpdatedAt,\n\t\t); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\titems = append(items, i)\n\t}\n\tif err := rows.Close(); err != nil {\n\t\treturn nil, err\n\t}\n\tif err := rows.Err(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn items, nil\n}\n\nconst listNewFiles = `-- name: ListNewFiles :many\nSELECT id, session_id, path, content, version, created_at, updated_at\nFROM files\nWHERE is_new = 1\nORDER BY created_at DESC\n`\n\nfunc (q *Queries) ListNewFiles(ctx context.Context) ([]File, error) {\n\trows, err := q.query(ctx, q.listNewFilesStmt, listNewFiles)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer rows.Close()\n\titems := []File{}\n\tfor rows.Next() {\n\t\tvar i File\n\t\tif err := rows.Scan(\n\t\t\t&i.ID,\n\t\t\t&i.SessionID,\n\t\t\t&i.Path,\n\t\t\t&i.Content,\n\t\t\t&i.Version,\n\t\t\t&i.CreatedAt,\n\t\t\t&i.UpdatedAt,\n\t\t); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\titems = append(items, i)\n\t}\n\tif err := rows.Close(); err != nil {\n\t\treturn nil, err\n\t}\n\tif err := rows.Err(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn items, nil\n}\n\nconst updateFile = `-- name: UpdateFile :one\nUPDATE files\nSET\n content = ?,\n version = ?,\n updated_at = strftime('%s', 'now')\nWHERE id = ?\nRETURNING id, session_id, path, content, version, created_at, updated_at\n`\n\ntype UpdateFileParams struct {\n\tContent string `json:\"content\"`\n\tVersion string `json:\"version\"`\n\tID string `json:\"id\"`\n}\n\nfunc (q *Queries) UpdateFile(ctx context.Context, arg UpdateFileParams) (File, error) {\n\trow := q.queryRow(ctx, q.updateFileStmt, updateFile, arg.Content, arg.Version, arg.ID)\n\tvar i File\n\terr := row.Scan(\n\t\t&i.ID,\n\t\t&i.SessionID,\n\t\t&i.Path,\n\t\t&i.Content,\n\t\t&i.Version,\n\t\t&i.CreatedAt,\n\t\t&i.UpdatedAt,\n\t)\n\treturn i, err\n}\n"], ["/opencode/internal/permission/permission.go", "package permission\n\nimport (\n\t\"errors\"\n\t\"path/filepath\"\n\t\"slices\"\n\t\"sync\"\n\n\t\"github.com/google/uuid\"\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/pubsub\"\n)\n\nvar ErrorPermissionDenied = errors.New(\"permission denied\")\n\ntype CreatePermissionRequest struct {\n\tSessionID string `json:\"session_id\"`\n\tToolName string `json:\"tool_name\"`\n\tDescription string `json:\"description\"`\n\tAction string `json:\"action\"`\n\tParams any `json:\"params\"`\n\tPath string `json:\"path\"`\n}\n\ntype PermissionRequest struct {\n\tID string `json:\"id\"`\n\tSessionID string `json:\"session_id\"`\n\tToolName string `json:\"tool_name\"`\n\tDescription string `json:\"description\"`\n\tAction string `json:\"action\"`\n\tParams any `json:\"params\"`\n\tPath string `json:\"path\"`\n}\n\ntype Service interface {\n\tpubsub.Suscriber[PermissionRequest]\n\tGrantPersistant(permission PermissionRequest)\n\tGrant(permission PermissionRequest)\n\tDeny(permission PermissionRequest)\n\tRequest(opts CreatePermissionRequest) bool\n\tAutoApproveSession(sessionID string)\n}\n\ntype permissionService struct {\n\t*pubsub.Broker[PermissionRequest]\n\n\tsessionPermissions []PermissionRequest\n\tpendingRequests sync.Map\n\tautoApproveSessions []string\n}\n\nfunc (s *permissionService) GrantPersistant(permission PermissionRequest) {\n\trespCh, ok := s.pendingRequests.Load(permission.ID)\n\tif ok {\n\t\trespCh.(chan bool) <- true\n\t}\n\ts.sessionPermissions = append(s.sessionPermissions, permission)\n}\n\nfunc (s *permissionService) Grant(permission PermissionRequest) {\n\trespCh, ok := s.pendingRequests.Load(permission.ID)\n\tif ok {\n\t\trespCh.(chan bool) <- true\n\t}\n}\n\nfunc (s *permissionService) Deny(permission PermissionRequest) {\n\trespCh, ok := s.pendingRequests.Load(permission.ID)\n\tif ok {\n\t\trespCh.(chan bool) <- false\n\t}\n}\n\nfunc (s *permissionService) Request(opts CreatePermissionRequest) bool {\n\tif slices.Contains(s.autoApproveSessions, opts.SessionID) {\n\t\treturn true\n\t}\n\tdir := filepath.Dir(opts.Path)\n\tif dir == \".\" {\n\t\tdir = config.WorkingDirectory()\n\t}\n\tpermission := PermissionRequest{\n\t\tID: uuid.New().String(),\n\t\tPath: dir,\n\t\tSessionID: opts.SessionID,\n\t\tToolName: opts.ToolName,\n\t\tDescription: opts.Description,\n\t\tAction: opts.Action,\n\t\tParams: opts.Params,\n\t}\n\n\tfor _, p := range s.sessionPermissions {\n\t\tif p.ToolName == permission.ToolName && p.Action == permission.Action && p.SessionID == permission.SessionID && p.Path == permission.Path {\n\t\t\treturn true\n\t\t}\n\t}\n\n\trespCh := make(chan bool, 1)\n\n\ts.pendingRequests.Store(permission.ID, respCh)\n\tdefer s.pendingRequests.Delete(permission.ID)\n\n\ts.Publish(pubsub.CreatedEvent, permission)\n\n\t// Wait for the response with a timeout\n\tresp := <-respCh\n\treturn resp\n}\n\nfunc (s *permissionService) AutoApproveSession(sessionID string) {\n\ts.autoApproveSessions = append(s.autoApproveSessions, sessionID)\n}\n\nfunc NewPermissionService() Service {\n\treturn &permissionService{\n\t\tBroker: pubsub.NewBroker[PermissionRequest](),\n\t\tsessionPermissions: make([]PermissionRequest, 0),\n\t}\n}\n"], ["/opencode/internal/app/lsp.go", "package app\n\nimport (\n\t\"context\"\n\t\"time\"\n\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n\t\"github.com/opencode-ai/opencode/internal/lsp\"\n\t\"github.com/opencode-ai/opencode/internal/lsp/watcher\"\n)\n\nfunc (app *App) initLSPClients(ctx context.Context) {\n\tcfg := config.Get()\n\n\t// Initialize LSP clients\n\tfor name, clientConfig := range cfg.LSP {\n\t\t// Start each client initialization in its own goroutine\n\t\tgo app.createAndStartLSPClient(ctx, name, clientConfig.Command, clientConfig.Args...)\n\t}\n\tlogging.Info(\"LSP clients initialization started in background\")\n}\n\n// createAndStartLSPClient creates a new LSP client, initializes it, and starts its workspace watcher\nfunc (app *App) createAndStartLSPClient(ctx context.Context, name string, command string, args ...string) {\n\t// Create a specific context for initialization with a timeout\n\tlogging.Info(\"Creating LSP client\", \"name\", name, \"command\", command, \"args\", args)\n\t\n\t// Create the LSP client\n\tlspClient, err := lsp.NewClient(ctx, command, args...)\n\tif err != nil {\n\t\tlogging.Error(\"Failed to create LSP client for\", name, err)\n\t\treturn\n\t}\n\n\t// Create a longer timeout for initialization (some servers take time to start)\n\tinitCtx, cancel := context.WithTimeout(ctx, 30*time.Second)\n\tdefer cancel()\n\t\n\t// Initialize with the initialization context\n\t_, err = lspClient.InitializeLSPClient(initCtx, config.WorkingDirectory())\n\tif err != nil {\n\t\tlogging.Error(\"Initialize failed\", \"name\", name, \"error\", err)\n\t\t// Clean up the client to prevent resource leaks\n\t\tlspClient.Close()\n\t\treturn\n\t}\n\n\t// Wait for the server to be ready\n\tif err := lspClient.WaitForServerReady(initCtx); err != nil {\n\t\tlogging.Error(\"Server failed to become ready\", \"name\", name, \"error\", err)\n\t\t// We'll continue anyway, as some functionality might still work\n\t\tlspClient.SetServerState(lsp.StateError)\n\t} else {\n\t\tlogging.Info(\"LSP server is ready\", \"name\", name)\n\t\tlspClient.SetServerState(lsp.StateReady)\n\t}\n\n\tlogging.Info(\"LSP client initialized\", \"name\", name)\n\t\n\t// Create a child context that can be canceled when the app is shutting down\n\twatchCtx, cancelFunc := context.WithCancel(ctx)\n\t\n\t// Create a context with the server name for better identification\n\twatchCtx = context.WithValue(watchCtx, \"serverName\", name)\n\t\n\t// Create the workspace watcher\n\tworkspaceWatcher := watcher.NewWorkspaceWatcher(lspClient)\n\n\t// Store the cancel function to be called during cleanup\n\tapp.cancelFuncsMutex.Lock()\n\tapp.watcherCancelFuncs = append(app.watcherCancelFuncs, cancelFunc)\n\tapp.cancelFuncsMutex.Unlock()\n\n\t// Add the watcher to a WaitGroup to track active goroutines\n\tapp.watcherWG.Add(1)\n\n\t// Add to map with mutex protection before starting goroutine\n\tapp.clientsMutex.Lock()\n\tapp.LSPClients[name] = lspClient\n\tapp.clientsMutex.Unlock()\n\n\tgo app.runWorkspaceWatcher(watchCtx, name, workspaceWatcher)\n}\n\n// runWorkspaceWatcher executes the workspace watcher for an LSP client\nfunc (app *App) runWorkspaceWatcher(ctx context.Context, name string, workspaceWatcher *watcher.WorkspaceWatcher) {\n\tdefer app.watcherWG.Done()\n\tdefer logging.RecoverPanic(\"LSP-\"+name, func() {\n\t\t// Try to restart the client\n\t\tapp.restartLSPClient(ctx, name)\n\t})\n\n\tworkspaceWatcher.WatchWorkspace(ctx, config.WorkingDirectory())\n\tlogging.Info(\"Workspace watcher stopped\", \"client\", name)\n}\n\n// restartLSPClient attempts to restart a crashed or failed LSP client\nfunc (app *App) restartLSPClient(ctx context.Context, name string) {\n\t// Get the original configuration\n\tcfg := config.Get()\n\tclientConfig, exists := cfg.LSP[name]\n\tif !exists {\n\t\tlogging.Error(\"Cannot restart client, configuration not found\", \"client\", name)\n\t\treturn\n\t}\n\n\t// Clean up the old client if it exists\n\tapp.clientsMutex.Lock()\n\toldClient, exists := app.LSPClients[name]\n\tif exists {\n\t\tdelete(app.LSPClients, name) // Remove from map before potentially slow shutdown\n\t}\n\tapp.clientsMutex.Unlock()\n\n\tif exists && oldClient != nil {\n\t\t// Try to shut it down gracefully, but don't block on errors\n\t\tshutdownCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)\n\t\t_ = oldClient.Shutdown(shutdownCtx)\n\t\tcancel()\n\t}\n\n\t// Create a new client using the shared function\n\tapp.createAndStartLSPClient(ctx, name, clientConfig.Command, clientConfig.Args...)\n\tlogging.Info(\"Successfully restarted LSP client\", \"client\", name)\n}\n"], ["/opencode/cmd/schema/main.go", "package main\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"os\"\n\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/llm/models\"\n)\n\n// JSONSchemaType represents a JSON Schema type\ntype JSONSchemaType struct {\n\tType string `json:\"type,omitempty\"`\n\tDescription string `json:\"description,omitempty\"`\n\tProperties map[string]any `json:\"properties,omitempty\"`\n\tRequired []string `json:\"required,omitempty\"`\n\tAdditionalProperties any `json:\"additionalProperties,omitempty\"`\n\tEnum []any `json:\"enum,omitempty\"`\n\tItems map[string]any `json:\"items,omitempty\"`\n\tOneOf []map[string]any `json:\"oneOf,omitempty\"`\n\tAnyOf []map[string]any `json:\"anyOf,omitempty\"`\n\tDefault any `json:\"default,omitempty\"`\n}\n\nfunc main() {\n\tschema := generateSchema()\n\n\t// Pretty print the schema\n\tencoder := json.NewEncoder(os.Stdout)\n\tencoder.SetIndent(\"\", \" \")\n\tif err := encoder.Encode(schema); err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"Error encoding schema: %v\\n\", err)\n\t\tos.Exit(1)\n\t}\n}\n\nfunc generateSchema() map[string]any {\n\tschema := map[string]any{\n\t\t\"$schema\": \"http://json-schema.org/draft-07/schema#\",\n\t\t\"title\": \"OpenCode Configuration\",\n\t\t\"description\": \"Configuration schema for the OpenCode application\",\n\t\t\"type\": \"object\",\n\t\t\"properties\": map[string]any{},\n\t}\n\n\t// Add Data configuration\n\tschema[\"properties\"].(map[string]any)[\"data\"] = map[string]any{\n\t\t\"type\": \"object\",\n\t\t\"description\": \"Storage configuration\",\n\t\t\"properties\": map[string]any{\n\t\t\t\"directory\": map[string]any{\n\t\t\t\t\"type\": \"string\",\n\t\t\t\t\"description\": \"Directory where application data is stored\",\n\t\t\t\t\"default\": \".opencode\",\n\t\t\t},\n\t\t},\n\t\t\"required\": []string{\"directory\"},\n\t}\n\n\t// Add working directory\n\tschema[\"properties\"].(map[string]any)[\"wd\"] = map[string]any{\n\t\t\"type\": \"string\",\n\t\t\"description\": \"Working directory for the application\",\n\t}\n\n\t// Add debug flags\n\tschema[\"properties\"].(map[string]any)[\"debug\"] = map[string]any{\n\t\t\"type\": \"boolean\",\n\t\t\"description\": \"Enable debug mode\",\n\t\t\"default\": false,\n\t}\n\n\tschema[\"properties\"].(map[string]any)[\"debugLSP\"] = map[string]any{\n\t\t\"type\": \"boolean\",\n\t\t\"description\": \"Enable LSP debug mode\",\n\t\t\"default\": false,\n\t}\n\n\tschema[\"properties\"].(map[string]any)[\"contextPaths\"] = map[string]any{\n\t\t\"type\": \"array\",\n\t\t\"description\": \"Context paths for the application\",\n\t\t\"items\": map[string]any{\n\t\t\t\"type\": \"string\",\n\t\t},\n\t\t\"default\": []string{\n\t\t\t\".github/copilot-instructions.md\",\n\t\t\t\".cursorrules\",\n\t\t\t\".cursor/rules/\",\n\t\t\t\"CLAUDE.md\",\n\t\t\t\"CLAUDE.local.md\",\n\t\t\t\"opencode.md\",\n\t\t\t\"opencode.local.md\",\n\t\t\t\"OpenCode.md\",\n\t\t\t\"OpenCode.local.md\",\n\t\t\t\"OPENCODE.md\",\n\t\t\t\"OPENCODE.local.md\",\n\t\t},\n\t}\n\n\tschema[\"properties\"].(map[string]any)[\"tui\"] = map[string]any{\n\t\t\"type\": \"object\",\n\t\t\"description\": \"Terminal User Interface configuration\",\n\t\t\"properties\": map[string]any{\n\t\t\t\"theme\": map[string]any{\n\t\t\t\t\"type\": \"string\",\n\t\t\t\t\"description\": \"TUI theme name\",\n\t\t\t\t\"default\": \"opencode\",\n\t\t\t\t\"enum\": []string{\n\t\t\t\t\t\"opencode\",\n\t\t\t\t\t\"catppuccin\",\n\t\t\t\t\t\"dracula\",\n\t\t\t\t\t\"flexoki\",\n\t\t\t\t\t\"gruvbox\",\n\t\t\t\t\t\"monokai\",\n\t\t\t\t\t\"onedark\",\n\t\t\t\t\t\"tokyonight\",\n\t\t\t\t\t\"tron\",\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\t// Add MCP servers\n\tschema[\"properties\"].(map[string]any)[\"mcpServers\"] = map[string]any{\n\t\t\"type\": \"object\",\n\t\t\"description\": \"Model Control Protocol server configurations\",\n\t\t\"additionalProperties\": map[string]any{\n\t\t\t\"type\": \"object\",\n\t\t\t\"description\": \"MCP server configuration\",\n\t\t\t\"properties\": map[string]any{\n\t\t\t\t\"command\": map[string]any{\n\t\t\t\t\t\"type\": \"string\",\n\t\t\t\t\t\"description\": \"Command to execute for the MCP server\",\n\t\t\t\t},\n\t\t\t\t\"env\": map[string]any{\n\t\t\t\t\t\"type\": \"array\",\n\t\t\t\t\t\"description\": \"Environment variables for the MCP server\",\n\t\t\t\t\t\"items\": map[string]any{\n\t\t\t\t\t\t\"type\": \"string\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t\"args\": map[string]any{\n\t\t\t\t\t\"type\": \"array\",\n\t\t\t\t\t\"description\": \"Command arguments for the MCP server\",\n\t\t\t\t\t\"items\": map[string]any{\n\t\t\t\t\t\t\"type\": \"string\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t\"type\": map[string]any{\n\t\t\t\t\t\"type\": \"string\",\n\t\t\t\t\t\"description\": \"Type of MCP server\",\n\t\t\t\t\t\"enum\": []string{\"stdio\", \"sse\"},\n\t\t\t\t\t\"default\": \"stdio\",\n\t\t\t\t},\n\t\t\t\t\"url\": map[string]any{\n\t\t\t\t\t\"type\": \"string\",\n\t\t\t\t\t\"description\": \"URL for SSE type MCP servers\",\n\t\t\t\t},\n\t\t\t\t\"headers\": map[string]any{\n\t\t\t\t\t\"type\": \"object\",\n\t\t\t\t\t\"description\": \"HTTP headers for SSE type MCP servers\",\n\t\t\t\t\t\"additionalProperties\": map[string]any{\n\t\t\t\t\t\t\"type\": \"string\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\t\"required\": []string{\"command\"},\n\t\t},\n\t}\n\n\t// Add providers\n\tproviderSchema := map[string]any{\n\t\t\"type\": \"object\",\n\t\t\"description\": \"LLM provider configurations\",\n\t\t\"additionalProperties\": map[string]any{\n\t\t\t\"type\": \"object\",\n\t\t\t\"description\": \"Provider configuration\",\n\t\t\t\"properties\": map[string]any{\n\t\t\t\t\"apiKey\": map[string]any{\n\t\t\t\t\t\"type\": \"string\",\n\t\t\t\t\t\"description\": \"API key for the provider\",\n\t\t\t\t},\n\t\t\t\t\"disabled\": map[string]any{\n\t\t\t\t\t\"type\": \"boolean\",\n\t\t\t\t\t\"description\": \"Whether the provider is disabled\",\n\t\t\t\t\t\"default\": false,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\t// Add known providers\n\tknownProviders := []string{\n\t\tstring(models.ProviderAnthropic),\n\t\tstring(models.ProviderOpenAI),\n\t\tstring(models.ProviderGemini),\n\t\tstring(models.ProviderGROQ),\n\t\tstring(models.ProviderOpenRouter),\n\t\tstring(models.ProviderBedrock),\n\t\tstring(models.ProviderAzure),\n\t\tstring(models.ProviderVertexAI),\n\t}\n\n\tproviderSchema[\"additionalProperties\"].(map[string]any)[\"properties\"].(map[string]any)[\"provider\"] = map[string]any{\n\t\t\"type\": \"string\",\n\t\t\"description\": \"Provider type\",\n\t\t\"enum\": knownProviders,\n\t}\n\n\tschema[\"properties\"].(map[string]any)[\"providers\"] = providerSchema\n\n\t// Add agents\n\tagentSchema := map[string]any{\n\t\t\"type\": \"object\",\n\t\t\"description\": \"Agent configurations\",\n\t\t\"additionalProperties\": map[string]any{\n\t\t\t\"type\": \"object\",\n\t\t\t\"description\": \"Agent configuration\",\n\t\t\t\"properties\": map[string]any{\n\t\t\t\t\"model\": map[string]any{\n\t\t\t\t\t\"type\": \"string\",\n\t\t\t\t\t\"description\": \"Model ID for the agent\",\n\t\t\t\t},\n\t\t\t\t\"maxTokens\": map[string]any{\n\t\t\t\t\t\"type\": \"integer\",\n\t\t\t\t\t\"description\": \"Maximum tokens for the agent\",\n\t\t\t\t\t\"minimum\": 1,\n\t\t\t\t},\n\t\t\t\t\"reasoningEffort\": map[string]any{\n\t\t\t\t\t\"type\": \"string\",\n\t\t\t\t\t\"description\": \"Reasoning effort for models that support it (OpenAI, Anthropic)\",\n\t\t\t\t\t\"enum\": []string{\"low\", \"medium\", \"high\"},\n\t\t\t\t},\n\t\t\t},\n\t\t\t\"required\": []string{\"model\"},\n\t\t},\n\t}\n\n\t// Add model enum\n\tmodelEnum := []string{}\n\tfor modelID := range models.SupportedModels {\n\t\tmodelEnum = append(modelEnum, string(modelID))\n\t}\n\tagentSchema[\"additionalProperties\"].(map[string]any)[\"properties\"].(map[string]any)[\"model\"].(map[string]any)[\"enum\"] = modelEnum\n\n\t// Add specific agent properties\n\tagentProperties := map[string]any{}\n\tknownAgents := []string{\n\t\tstring(config.AgentCoder),\n\t\tstring(config.AgentTask),\n\t\tstring(config.AgentTitle),\n\t}\n\n\tfor _, agentName := range knownAgents {\n\t\tagentProperties[agentName] = map[string]any{\n\t\t\t\"$ref\": \"#/definitions/agent\",\n\t\t}\n\t}\n\n\t// Create a combined schema that allows both specific agents and additional ones\n\tcombinedAgentSchema := map[string]any{\n\t\t\"type\": \"object\",\n\t\t\"description\": \"Agent configurations\",\n\t\t\"properties\": agentProperties,\n\t\t\"additionalProperties\": agentSchema[\"additionalProperties\"],\n\t}\n\n\tschema[\"properties\"].(map[string]any)[\"agents\"] = combinedAgentSchema\n\tschema[\"definitions\"] = map[string]any{\n\t\t\"agent\": agentSchema[\"additionalProperties\"],\n\t}\n\n\t// Add LSP configuration\n\tschema[\"properties\"].(map[string]any)[\"lsp\"] = map[string]any{\n\t\t\"type\": \"object\",\n\t\t\"description\": \"Language Server Protocol configurations\",\n\t\t\"additionalProperties\": map[string]any{\n\t\t\t\"type\": \"object\",\n\t\t\t\"description\": \"LSP configuration for a language\",\n\t\t\t\"properties\": map[string]any{\n\t\t\t\t\"disabled\": map[string]any{\n\t\t\t\t\t\"type\": \"boolean\",\n\t\t\t\t\t\"description\": \"Whether the LSP is disabled\",\n\t\t\t\t\t\"default\": false,\n\t\t\t\t},\n\t\t\t\t\"command\": map[string]any{\n\t\t\t\t\t\"type\": \"string\",\n\t\t\t\t\t\"description\": \"Command to execute for the LSP server\",\n\t\t\t\t},\n\t\t\t\t\"args\": map[string]any{\n\t\t\t\t\t\"type\": \"array\",\n\t\t\t\t\t\"description\": \"Command arguments for the LSP server\",\n\t\t\t\t\t\"items\": map[string]any{\n\t\t\t\t\t\t\"type\": \"string\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t\"options\": map[string]any{\n\t\t\t\t\t\"type\": \"object\",\n\t\t\t\t\t\"description\": \"Additional options for the LSP server\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t\"required\": []string{\"command\"},\n\t\t},\n\t}\n\n\treturn schema\n}\n"], ["/opencode/internal/lsp/protocol/pattern_interfaces.go", "package protocol\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n)\n\n// PatternInfo is an interface for types that represent glob patterns\ntype PatternInfo interface {\n\tGetPattern() string\n\tGetBasePath() string\n\tisPattern() // marker method\n}\n\n// StringPattern implements PatternInfo for string patterns\ntype StringPattern struct {\n\tPattern string\n}\n\nfunc (p StringPattern) GetPattern() string { return p.Pattern }\nfunc (p StringPattern) GetBasePath() string { return \"\" }\nfunc (p StringPattern) isPattern() {}\n\n// RelativePatternInfo implements PatternInfo for RelativePattern\ntype RelativePatternInfo struct {\n\tRP RelativePattern\n\tBasePath string\n}\n\nfunc (p RelativePatternInfo) GetPattern() string { return string(p.RP.Pattern) }\nfunc (p RelativePatternInfo) GetBasePath() string { return p.BasePath }\nfunc (p RelativePatternInfo) isPattern() {}\n\n// AsPattern converts GlobPattern to a PatternInfo object\nfunc (g *GlobPattern) AsPattern() (PatternInfo, error) {\n\tif g.Value == nil {\n\t\treturn nil, fmt.Errorf(\"nil pattern\")\n\t}\n\n\tswitch v := g.Value.(type) {\n\tcase string:\n\t\treturn StringPattern{Pattern: v}, nil\n\tcase RelativePattern:\n\t\t// Handle BaseURI which could be string or DocumentUri\n\t\tbasePath := \"\"\n\t\tswitch baseURI := v.BaseURI.Value.(type) {\n\t\tcase string:\n\t\t\tbasePath = strings.TrimPrefix(baseURI, \"file://\")\n\t\tcase DocumentUri:\n\t\t\tbasePath = strings.TrimPrefix(string(baseURI), \"file://\")\n\t\tdefault:\n\t\t\treturn nil, fmt.Errorf(\"unknown BaseURI type: %T\", v.BaseURI.Value)\n\t\t}\n\t\treturn RelativePatternInfo{RP: v, BasePath: basePath}, nil\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"unknown pattern type: %T\", g.Value)\n\t}\n}\n"], ["/opencode/internal/session/session.go", "package session\n\nimport (\n\t\"context\"\n\t\"database/sql\"\n\n\t\"github.com/google/uuid\"\n\t\"github.com/opencode-ai/opencode/internal/db\"\n\t\"github.com/opencode-ai/opencode/internal/pubsub\"\n)\n\ntype Session struct {\n\tID string\n\tParentSessionID string\n\tTitle string\n\tMessageCount int64\n\tPromptTokens int64\n\tCompletionTokens int64\n\tSummaryMessageID string\n\tCost float64\n\tCreatedAt int64\n\tUpdatedAt int64\n}\n\ntype Service interface {\n\tpubsub.Suscriber[Session]\n\tCreate(ctx context.Context, title string) (Session, error)\n\tCreateTitleSession(ctx context.Context, parentSessionID string) (Session, error)\n\tCreateTaskSession(ctx context.Context, toolCallID, parentSessionID, title string) (Session, error)\n\tGet(ctx context.Context, id string) (Session, error)\n\tList(ctx context.Context) ([]Session, error)\n\tSave(ctx context.Context, session Session) (Session, error)\n\tDelete(ctx context.Context, id string) error\n}\n\ntype service struct {\n\t*pubsub.Broker[Session]\n\tq db.Querier\n}\n\nfunc (s *service) Create(ctx context.Context, title string) (Session, error) {\n\tdbSession, err := s.q.CreateSession(ctx, db.CreateSessionParams{\n\t\tID: uuid.New().String(),\n\t\tTitle: title,\n\t})\n\tif err != nil {\n\t\treturn Session{}, err\n\t}\n\tsession := s.fromDBItem(dbSession)\n\ts.Publish(pubsub.CreatedEvent, session)\n\treturn session, nil\n}\n\nfunc (s *service) CreateTaskSession(ctx context.Context, toolCallID, parentSessionID, title string) (Session, error) {\n\tdbSession, err := s.q.CreateSession(ctx, db.CreateSessionParams{\n\t\tID: toolCallID,\n\t\tParentSessionID: sql.NullString{String: parentSessionID, Valid: true},\n\t\tTitle: title,\n\t})\n\tif err != nil {\n\t\treturn Session{}, err\n\t}\n\tsession := s.fromDBItem(dbSession)\n\ts.Publish(pubsub.CreatedEvent, session)\n\treturn session, nil\n}\n\nfunc (s *service) CreateTitleSession(ctx context.Context, parentSessionID string) (Session, error) {\n\tdbSession, err := s.q.CreateSession(ctx, db.CreateSessionParams{\n\t\tID: \"title-\" + parentSessionID,\n\t\tParentSessionID: sql.NullString{String: parentSessionID, Valid: true},\n\t\tTitle: \"Generate a title\",\n\t})\n\tif err != nil {\n\t\treturn Session{}, err\n\t}\n\tsession := s.fromDBItem(dbSession)\n\ts.Publish(pubsub.CreatedEvent, session)\n\treturn session, nil\n}\n\nfunc (s *service) Delete(ctx context.Context, id string) error {\n\tsession, err := s.Get(ctx, id)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = s.q.DeleteSession(ctx, session.ID)\n\tif err != nil {\n\t\treturn err\n\t}\n\ts.Publish(pubsub.DeletedEvent, session)\n\treturn nil\n}\n\nfunc (s *service) Get(ctx context.Context, id string) (Session, error) {\n\tdbSession, err := s.q.GetSessionByID(ctx, id)\n\tif err != nil {\n\t\treturn Session{}, err\n\t}\n\treturn s.fromDBItem(dbSession), nil\n}\n\nfunc (s *service) Save(ctx context.Context, session Session) (Session, error) {\n\tdbSession, err := s.q.UpdateSession(ctx, db.UpdateSessionParams{\n\t\tID: session.ID,\n\t\tTitle: session.Title,\n\t\tPromptTokens: session.PromptTokens,\n\t\tCompletionTokens: session.CompletionTokens,\n\t\tSummaryMessageID: sql.NullString{\n\t\t\tString: session.SummaryMessageID,\n\t\t\tValid: session.SummaryMessageID != \"\",\n\t\t},\n\t\tCost: session.Cost,\n\t})\n\tif err != nil {\n\t\treturn Session{}, err\n\t}\n\tsession = s.fromDBItem(dbSession)\n\ts.Publish(pubsub.UpdatedEvent, session)\n\treturn session, nil\n}\n\nfunc (s *service) List(ctx context.Context) ([]Session, error) {\n\tdbSessions, err := s.q.ListSessions(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsessions := make([]Session, len(dbSessions))\n\tfor i, dbSession := range dbSessions {\n\t\tsessions[i] = s.fromDBItem(dbSession)\n\t}\n\treturn sessions, nil\n}\n\nfunc (s service) fromDBItem(item db.Session) Session {\n\treturn Session{\n\t\tID: item.ID,\n\t\tParentSessionID: item.ParentSessionID.String,\n\t\tTitle: item.Title,\n\t\tMessageCount: item.MessageCount,\n\t\tPromptTokens: item.PromptTokens,\n\t\tCompletionTokens: item.CompletionTokens,\n\t\tSummaryMessageID: item.SummaryMessageID.String,\n\t\tCost: item.Cost,\n\t\tCreatedAt: item.CreatedAt,\n\t\tUpdatedAt: item.UpdatedAt,\n\t}\n}\n\nfunc NewService(q db.Querier) Service {\n\tbroker := pubsub.NewBroker[Session]()\n\treturn &service{\n\t\tbroker,\n\t\tq,\n\t}\n}\n"], ["/opencode/internal/llm/provider/azure.go", "package provider\n\nimport (\n\t\"os\"\n\n\t\"github.com/Azure/azure-sdk-for-go/sdk/azidentity\"\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/azure\"\n\t\"github.com/openai/openai-go/option\"\n)\n\ntype azureClient struct {\n\t*openaiClient\n}\n\ntype AzureClient ProviderClient\n\nfunc newAzureClient(opts providerClientOptions) AzureClient {\n\n\tendpoint := os.Getenv(\"AZURE_OPENAI_ENDPOINT\") // ex: https://foo.openai.azure.com\n\tapiVersion := os.Getenv(\"AZURE_OPENAI_API_VERSION\") // ex: 2025-04-01-preview\n\n\tif endpoint == \"\" || apiVersion == \"\" {\n\t\treturn &azureClient{openaiClient: newOpenAIClient(opts).(*openaiClient)}\n\t}\n\n\treqOpts := []option.RequestOption{\n\t\tazure.WithEndpoint(endpoint, apiVersion),\n\t}\n\n\tif opts.apiKey != \"\" || os.Getenv(\"AZURE_OPENAI_API_KEY\") != \"\" {\n\t\tkey := opts.apiKey\n\t\tif key == \"\" {\n\t\t\tkey = os.Getenv(\"AZURE_OPENAI_API_KEY\")\n\t\t}\n\t\treqOpts = append(reqOpts, azure.WithAPIKey(key))\n\t} else if cred, err := azidentity.NewDefaultAzureCredential(nil); err == nil {\n\t\treqOpts = append(reqOpts, azure.WithTokenCredential(cred))\n\t}\n\n\tbase := &openaiClient{\n\t\tproviderOptions: opts,\n\t\tclient: openai.NewClient(reqOpts...),\n\t}\n\n\treturn &azureClient{openaiClient: base}\n}\n"], ["/opencode/internal/db/sessions.sql.go", "// Code generated by sqlc. DO NOT EDIT.\n// versions:\n// sqlc v1.29.0\n// source: sessions.sql\n\npackage db\n\nimport (\n\t\"context\"\n\t\"database/sql\"\n)\n\nconst createSession = `-- name: CreateSession :one\nINSERT INTO sessions (\n id,\n parent_session_id,\n title,\n message_count,\n prompt_tokens,\n completion_tokens,\n cost,\n summary_message_id,\n updated_at,\n created_at\n) VALUES (\n ?,\n ?,\n ?,\n ?,\n ?,\n ?,\n ?,\n null,\n strftime('%s', 'now'),\n strftime('%s', 'now')\n) RETURNING id, parent_session_id, title, message_count, prompt_tokens, completion_tokens, cost, updated_at, created_at, summary_message_id\n`\n\ntype CreateSessionParams struct {\n\tID string `json:\"id\"`\n\tParentSessionID sql.NullString `json:\"parent_session_id\"`\n\tTitle string `json:\"title\"`\n\tMessageCount int64 `json:\"message_count\"`\n\tPromptTokens int64 `json:\"prompt_tokens\"`\n\tCompletionTokens int64 `json:\"completion_tokens\"`\n\tCost float64 `json:\"cost\"`\n}\n\nfunc (q *Queries) CreateSession(ctx context.Context, arg CreateSessionParams) (Session, error) {\n\trow := q.queryRow(ctx, q.createSessionStmt, createSession,\n\t\targ.ID,\n\t\targ.ParentSessionID,\n\t\targ.Title,\n\t\targ.MessageCount,\n\t\targ.PromptTokens,\n\t\targ.CompletionTokens,\n\t\targ.Cost,\n\t)\n\tvar i Session\n\terr := row.Scan(\n\t\t&i.ID,\n\t\t&i.ParentSessionID,\n\t\t&i.Title,\n\t\t&i.MessageCount,\n\t\t&i.PromptTokens,\n\t\t&i.CompletionTokens,\n\t\t&i.Cost,\n\t\t&i.UpdatedAt,\n\t\t&i.CreatedAt,\n\t\t&i.SummaryMessageID,\n\t)\n\treturn i, err\n}\n\nconst deleteSession = `-- name: DeleteSession :exec\nDELETE FROM sessions\nWHERE id = ?\n`\n\nfunc (q *Queries) DeleteSession(ctx context.Context, id string) error {\n\t_, err := q.exec(ctx, q.deleteSessionStmt, deleteSession, id)\n\treturn err\n}\n\nconst getSessionByID = `-- name: GetSessionByID :one\nSELECT id, parent_session_id, title, message_count, prompt_tokens, completion_tokens, cost, updated_at, created_at, summary_message_id\nFROM sessions\nWHERE id = ? LIMIT 1\n`\n\nfunc (q *Queries) GetSessionByID(ctx context.Context, id string) (Session, error) {\n\trow := q.queryRow(ctx, q.getSessionByIDStmt, getSessionByID, id)\n\tvar i Session\n\terr := row.Scan(\n\t\t&i.ID,\n\t\t&i.ParentSessionID,\n\t\t&i.Title,\n\t\t&i.MessageCount,\n\t\t&i.PromptTokens,\n\t\t&i.CompletionTokens,\n\t\t&i.Cost,\n\t\t&i.UpdatedAt,\n\t\t&i.CreatedAt,\n\t\t&i.SummaryMessageID,\n\t)\n\treturn i, err\n}\n\nconst listSessions = `-- name: ListSessions :many\nSELECT id, parent_session_id, title, message_count, prompt_tokens, completion_tokens, cost, updated_at, created_at, summary_message_id\nFROM sessions\nWHERE parent_session_id is NULL\nORDER BY created_at DESC\n`\n\nfunc (q *Queries) ListSessions(ctx context.Context) ([]Session, error) {\n\trows, err := q.query(ctx, q.listSessionsStmt, listSessions)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer rows.Close()\n\titems := []Session{}\n\tfor rows.Next() {\n\t\tvar i Session\n\t\tif err := rows.Scan(\n\t\t\t&i.ID,\n\t\t\t&i.ParentSessionID,\n\t\t\t&i.Title,\n\t\t\t&i.MessageCount,\n\t\t\t&i.PromptTokens,\n\t\t\t&i.CompletionTokens,\n\t\t\t&i.Cost,\n\t\t\t&i.UpdatedAt,\n\t\t\t&i.CreatedAt,\n\t\t\t&i.SummaryMessageID,\n\t\t); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\titems = append(items, i)\n\t}\n\tif err := rows.Close(); err != nil {\n\t\treturn nil, err\n\t}\n\tif err := rows.Err(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn items, nil\n}\n\nconst updateSession = `-- name: UpdateSession :one\nUPDATE sessions\nSET\n title = ?,\n prompt_tokens = ?,\n completion_tokens = ?,\n summary_message_id = ?,\n cost = ?\nWHERE id = ?\nRETURNING id, parent_session_id, title, message_count, prompt_tokens, completion_tokens, cost, updated_at, created_at, summary_message_id\n`\n\ntype UpdateSessionParams struct {\n\tTitle string `json:\"title\"`\n\tPromptTokens int64 `json:\"prompt_tokens\"`\n\tCompletionTokens int64 `json:\"completion_tokens\"`\n\tSummaryMessageID sql.NullString `json:\"summary_message_id\"`\n\tCost float64 `json:\"cost\"`\n\tID string `json:\"id\"`\n}\n\nfunc (q *Queries) UpdateSession(ctx context.Context, arg UpdateSessionParams) (Session, error) {\n\trow := q.queryRow(ctx, q.updateSessionStmt, updateSession,\n\t\targ.Title,\n\t\targ.PromptTokens,\n\t\targ.CompletionTokens,\n\t\targ.SummaryMessageID,\n\t\targ.Cost,\n\t\targ.ID,\n\t)\n\tvar i Session\n\terr := row.Scan(\n\t\t&i.ID,\n\t\t&i.ParentSessionID,\n\t\t&i.Title,\n\t\t&i.MessageCount,\n\t\t&i.PromptTokens,\n\t\t&i.CompletionTokens,\n\t\t&i.Cost,\n\t\t&i.UpdatedAt,\n\t\t&i.CreatedAt,\n\t\t&i.SummaryMessageID,\n\t)\n\treturn i, err\n}\n"], ["/opencode/internal/db/messages.sql.go", "// Code generated by sqlc. DO NOT EDIT.\n// versions:\n// sqlc v1.29.0\n// source: messages.sql\n\npackage db\n\nimport (\n\t\"context\"\n\t\"database/sql\"\n)\n\nconst createMessage = `-- name: CreateMessage :one\nINSERT INTO messages (\n id,\n session_id,\n role,\n parts,\n model,\n created_at,\n updated_at\n) VALUES (\n ?, ?, ?, ?, ?, strftime('%s', 'now'), strftime('%s', 'now')\n)\nRETURNING id, session_id, role, parts, model, created_at, updated_at, finished_at\n`\n\ntype CreateMessageParams struct {\n\tID string `json:\"id\"`\n\tSessionID string `json:\"session_id\"`\n\tRole string `json:\"role\"`\n\tParts string `json:\"parts\"`\n\tModel sql.NullString `json:\"model\"`\n}\n\nfunc (q *Queries) CreateMessage(ctx context.Context, arg CreateMessageParams) (Message, error) {\n\trow := q.queryRow(ctx, q.createMessageStmt, createMessage,\n\t\targ.ID,\n\t\targ.SessionID,\n\t\targ.Role,\n\t\targ.Parts,\n\t\targ.Model,\n\t)\n\tvar i Message\n\terr := row.Scan(\n\t\t&i.ID,\n\t\t&i.SessionID,\n\t\t&i.Role,\n\t\t&i.Parts,\n\t\t&i.Model,\n\t\t&i.CreatedAt,\n\t\t&i.UpdatedAt,\n\t\t&i.FinishedAt,\n\t)\n\treturn i, err\n}\n\nconst deleteMessage = `-- name: DeleteMessage :exec\nDELETE FROM messages\nWHERE id = ?\n`\n\nfunc (q *Queries) DeleteMessage(ctx context.Context, id string) error {\n\t_, err := q.exec(ctx, q.deleteMessageStmt, deleteMessage, id)\n\treturn err\n}\n\nconst deleteSessionMessages = `-- name: DeleteSessionMessages :exec\nDELETE FROM messages\nWHERE session_id = ?\n`\n\nfunc (q *Queries) DeleteSessionMessages(ctx context.Context, sessionID string) error {\n\t_, err := q.exec(ctx, q.deleteSessionMessagesStmt, deleteSessionMessages, sessionID)\n\treturn err\n}\n\nconst getMessage = `-- name: GetMessage :one\nSELECT id, session_id, role, parts, model, created_at, updated_at, finished_at\nFROM messages\nWHERE id = ? LIMIT 1\n`\n\nfunc (q *Queries) GetMessage(ctx context.Context, id string) (Message, error) {\n\trow := q.queryRow(ctx, q.getMessageStmt, getMessage, id)\n\tvar i Message\n\terr := row.Scan(\n\t\t&i.ID,\n\t\t&i.SessionID,\n\t\t&i.Role,\n\t\t&i.Parts,\n\t\t&i.Model,\n\t\t&i.CreatedAt,\n\t\t&i.UpdatedAt,\n\t\t&i.FinishedAt,\n\t)\n\treturn i, err\n}\n\nconst listMessagesBySession = `-- name: ListMessagesBySession :many\nSELECT id, session_id, role, parts, model, created_at, updated_at, finished_at\nFROM messages\nWHERE session_id = ?\nORDER BY created_at ASC\n`\n\nfunc (q *Queries) ListMessagesBySession(ctx context.Context, sessionID string) ([]Message, error) {\n\trows, err := q.query(ctx, q.listMessagesBySessionStmt, listMessagesBySession, sessionID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer rows.Close()\n\titems := []Message{}\n\tfor rows.Next() {\n\t\tvar i Message\n\t\tif err := rows.Scan(\n\t\t\t&i.ID,\n\t\t\t&i.SessionID,\n\t\t\t&i.Role,\n\t\t\t&i.Parts,\n\t\t\t&i.Model,\n\t\t\t&i.CreatedAt,\n\t\t\t&i.UpdatedAt,\n\t\t\t&i.FinishedAt,\n\t\t); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\titems = append(items, i)\n\t}\n\tif err := rows.Close(); err != nil {\n\t\treturn nil, err\n\t}\n\tif err := rows.Err(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn items, nil\n}\n\nconst updateMessage = `-- name: UpdateMessage :exec\nUPDATE messages\nSET\n parts = ?,\n finished_at = ?,\n updated_at = strftime('%s', 'now')\nWHERE id = ?\n`\n\ntype UpdateMessageParams struct {\n\tParts string `json:\"parts\"`\n\tFinishedAt sql.NullInt64 `json:\"finished_at\"`\n\tID string `json:\"id\"`\n}\n\nfunc (q *Queries) UpdateMessage(ctx context.Context, arg UpdateMessageParams) error {\n\t_, err := q.exec(ctx, q.updateMessageStmt, updateMessage, arg.Parts, arg.FinishedAt, arg.ID)\n\treturn err\n}\n"], ["/opencode/internal/lsp/handlers.go", "package lsp\n\nimport (\n\t\"encoding/json\"\n\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n\t\"github.com/opencode-ai/opencode/internal/lsp/protocol\"\n\t\"github.com/opencode-ai/opencode/internal/lsp/util\"\n)\n\n// Requests\n\nfunc HandleWorkspaceConfiguration(params json.RawMessage) (any, error) {\n\treturn []map[string]any{{}}, nil\n}\n\nfunc HandleRegisterCapability(params json.RawMessage) (any, error) {\n\tvar registerParams protocol.RegistrationParams\n\tif err := json.Unmarshal(params, ®isterParams); err != nil {\n\t\tlogging.Error(\"Error unmarshaling registration params\", \"error\", err)\n\t\treturn nil, err\n\t}\n\n\tfor _, reg := range registerParams.Registrations {\n\t\tswitch reg.Method {\n\t\tcase \"workspace/didChangeWatchedFiles\":\n\t\t\t// Parse the registration options\n\t\t\toptionsJSON, err := json.Marshal(reg.RegisterOptions)\n\t\t\tif err != nil {\n\t\t\t\tlogging.Error(\"Error marshaling registration options\", \"error\", err)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tvar options protocol.DidChangeWatchedFilesRegistrationOptions\n\t\t\tif err := json.Unmarshal(optionsJSON, &options); err != nil {\n\t\t\t\tlogging.Error(\"Error unmarshaling registration options\", \"error\", err)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// Store the file watchers registrations\n\t\t\tnotifyFileWatchRegistration(reg.ID, options.Watchers)\n\t\t}\n\t}\n\n\treturn nil, nil\n}\n\nfunc HandleApplyEdit(params json.RawMessage) (any, error) {\n\tvar edit protocol.ApplyWorkspaceEditParams\n\tif err := json.Unmarshal(params, &edit); err != nil {\n\t\treturn nil, err\n\t}\n\n\terr := util.ApplyWorkspaceEdit(edit.Edit)\n\tif err != nil {\n\t\tlogging.Error(\"Error applying workspace edit\", \"error\", err)\n\t\treturn protocol.ApplyWorkspaceEditResult{Applied: false, FailureReason: err.Error()}, nil\n\t}\n\n\treturn protocol.ApplyWorkspaceEditResult{Applied: true}, nil\n}\n\n// FileWatchRegistrationHandler is a function that will be called when file watch registrations are received\ntype FileWatchRegistrationHandler func(id string, watchers []protocol.FileSystemWatcher)\n\n// fileWatchHandler holds the current handler for file watch registrations\nvar fileWatchHandler FileWatchRegistrationHandler\n\n// RegisterFileWatchHandler sets the handler for file watch registrations\nfunc RegisterFileWatchHandler(handler FileWatchRegistrationHandler) {\n\tfileWatchHandler = handler\n}\n\n// notifyFileWatchRegistration notifies the handler about new file watch registrations\nfunc notifyFileWatchRegistration(id string, watchers []protocol.FileSystemWatcher) {\n\tif fileWatchHandler != nil {\n\t\tfileWatchHandler(id, watchers)\n\t}\n}\n\n// Notifications\n\nfunc HandleServerMessage(params json.RawMessage) {\n\tcnf := config.Get()\n\tvar msg struct {\n\t\tType int `json:\"type\"`\n\t\tMessage string `json:\"message\"`\n\t}\n\tif err := json.Unmarshal(params, &msg); err == nil {\n\t\tif cnf.DebugLSP {\n\t\t\tlogging.Debug(\"Server message\", \"type\", msg.Type, \"message\", msg.Message)\n\t\t}\n\t}\n}\n\nfunc HandleDiagnostics(client *Client, params json.RawMessage) {\n\tvar diagParams protocol.PublishDiagnosticsParams\n\tif err := json.Unmarshal(params, &diagParams); err != nil {\n\t\tlogging.Error(\"Error unmarshaling diagnostics params\", \"error\", err)\n\t\treturn\n\t}\n\n\tclient.diagnosticsMu.Lock()\n\tdefer client.diagnosticsMu.Unlock()\n\n\tclient.diagnostics[diagParams.URI] = diagParams.Diagnostics\n}\n"], ["/opencode/internal/format/format.go", "package format\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"strings\"\n)\n\n// OutputFormat represents the output format type for non-interactive mode\ntype OutputFormat string\n\nconst (\n\t// Text format outputs the AI response as plain text.\n\tText OutputFormat = \"text\"\n\n\t// JSON format outputs the AI response wrapped in a JSON object.\n\tJSON OutputFormat = \"json\"\n)\n\n// String returns the string representation of the OutputFormat\nfunc (f OutputFormat) String() string {\n\treturn string(f)\n}\n\n// SupportedFormats is a list of all supported output formats as strings\nvar SupportedFormats = []string{\n\tstring(Text),\n\tstring(JSON),\n}\n\n// Parse converts a string to an OutputFormat\nfunc Parse(s string) (OutputFormat, error) {\n\ts = strings.ToLower(strings.TrimSpace(s))\n\n\tswitch s {\n\tcase string(Text):\n\t\treturn Text, nil\n\tcase string(JSON):\n\t\treturn JSON, nil\n\tdefault:\n\t\treturn \"\", fmt.Errorf(\"invalid format: %s\", s)\n\t}\n}\n\n// IsValid checks if the provided format string is supported\nfunc IsValid(s string) bool {\n\t_, err := Parse(s)\n\treturn err == nil\n}\n\n// GetHelpText returns a formatted string describing all supported formats\nfunc GetHelpText() string {\n\treturn fmt.Sprintf(`Supported output formats:\n- %s: Plain text output (default)\n- %s: Output wrapped in a JSON object`,\n\t\tText, JSON)\n}\n\n// FormatOutput formats the AI response according to the specified format\nfunc FormatOutput(content string, formatStr string) string {\n\tformat, err := Parse(formatStr)\n\tif err != nil {\n\t\t// Default to text format on error\n\t\treturn content\n\t}\n\n\tswitch format {\n\tcase JSON:\n\t\treturn formatAsJSON(content)\n\tcase Text:\n\t\tfallthrough\n\tdefault:\n\t\treturn content\n\t}\n}\n\n// formatAsJSON wraps the content in a simple JSON object\nfunc formatAsJSON(content string) string {\n\t// Use the JSON package to properly escape the content\n\tresponse := struct {\n\t\tResponse string `json:\"response\"`\n\t}{\n\t\tResponse: content,\n\t}\n\n\tjsonBytes, err := json.MarshalIndent(response, \"\", \" \")\n\tif err != nil {\n\t\t// In case of an error, return a manually formatted JSON\n\t\tjsonEscaped := strings.Replace(content, \"\\\\\", \"\\\\\\\\\", -1)\n\t\tjsonEscaped = strings.Replace(jsonEscaped, \"\\\"\", \"\\\\\\\"\", -1)\n\t\tjsonEscaped = strings.Replace(jsonEscaped, \"\\n\", \"\\\\n\", -1)\n\t\tjsonEscaped = strings.Replace(jsonEscaped, \"\\r\", \"\\\\r\", -1)\n\t\tjsonEscaped = strings.Replace(jsonEscaped, \"\\t\", \"\\\\t\", -1)\n\n\t\treturn fmt.Sprintf(\"{\\n \\\"response\\\": \\\"%s\\\"\\n}\", jsonEscaped)\n\t}\n\n\treturn string(jsonBytes)\n}\n"], ["/opencode/internal/lsp/protocol/tsdocument-changes.go", "// Copyright 2022 The Go Authors. All rights reserved.\n// Use of this source code is governed by a BSD-style\n// license that can be found in the LICENSE file.\n\npackage protocol\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n)\n\n// DocumentChange is a union of various file edit operations.\n//\n// Exactly one field of this struct is non-nil; see [DocumentChange.Valid].\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#resourceChanges\ntype DocumentChange struct {\n\tTextDocumentEdit *TextDocumentEdit\n\tCreateFile *CreateFile\n\tRenameFile *RenameFile\n\tDeleteFile *DeleteFile\n}\n\n// Valid reports whether the DocumentChange sum-type value is valid,\n// that is, exactly one of create, delete, edit, or rename.\nfunc (ch DocumentChange) Valid() bool {\n\tn := 0\n\tif ch.TextDocumentEdit != nil {\n\t\tn++\n\t}\n\tif ch.CreateFile != nil {\n\t\tn++\n\t}\n\tif ch.RenameFile != nil {\n\t\tn++\n\t}\n\tif ch.DeleteFile != nil {\n\t\tn++\n\t}\n\treturn n == 1\n}\n\nfunc (d *DocumentChange) UnmarshalJSON(data []byte) error {\n\tvar m map[string]any\n\tif err := json.Unmarshal(data, &m); err != nil {\n\t\treturn err\n\t}\n\n\tif _, ok := m[\"textDocument\"]; ok {\n\t\td.TextDocumentEdit = new(TextDocumentEdit)\n\t\treturn json.Unmarshal(data, d.TextDocumentEdit)\n\t}\n\n\t// The {Create,Rename,Delete}File types all share a 'kind' field.\n\tkind := m[\"kind\"]\n\tswitch kind {\n\tcase \"create\":\n\t\td.CreateFile = new(CreateFile)\n\t\treturn json.Unmarshal(data, d.CreateFile)\n\tcase \"rename\":\n\t\td.RenameFile = new(RenameFile)\n\t\treturn json.Unmarshal(data, d.RenameFile)\n\tcase \"delete\":\n\t\td.DeleteFile = new(DeleteFile)\n\t\treturn json.Unmarshal(data, d.DeleteFile)\n\t}\n\treturn fmt.Errorf(\"DocumentChanges: unexpected kind: %q\", kind)\n}\n\nfunc (d *DocumentChange) MarshalJSON() ([]byte, error) {\n\tif d.TextDocumentEdit != nil {\n\t\treturn json.Marshal(d.TextDocumentEdit)\n\t} else if d.CreateFile != nil {\n\t\treturn json.Marshal(d.CreateFile)\n\t} else if d.RenameFile != nil {\n\t\treturn json.Marshal(d.RenameFile)\n\t} else if d.DeleteFile != nil {\n\t\treturn json.Marshal(d.DeleteFile)\n\t}\n\treturn nil, fmt.Errorf(\"empty DocumentChanges union value\")\n}\n"], ["/opencode/internal/db/connect.go", "package db\n\nimport (\n\t\"database/sql\"\n\t\"fmt\"\n\t\"os\"\n\t\"path/filepath\"\n\n\t_ \"github.com/ncruces/go-sqlite3/driver\"\n\t_ \"github.com/ncruces/go-sqlite3/embed\"\n\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n\n\t\"github.com/pressly/goose/v3\"\n)\n\nfunc Connect() (*sql.DB, error) {\n\tdataDir := config.Get().Data.Directory\n\tif dataDir == \"\" {\n\t\treturn nil, fmt.Errorf(\"data.dir is not set\")\n\t}\n\tif err := os.MkdirAll(dataDir, 0o700); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to create data directory: %w\", err)\n\t}\n\tdbPath := filepath.Join(dataDir, \"opencode.db\")\n\t// Open the SQLite database\n\tdb, err := sql.Open(\"sqlite3\", dbPath)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to open database: %w\", err)\n\t}\n\n\t// Verify connection\n\tif err = db.Ping(); err != nil {\n\t\tdb.Close()\n\t\treturn nil, fmt.Errorf(\"failed to connect to database: %w\", err)\n\t}\n\n\t// Set pragmas for better performance\n\tpragmas := []string{\n\t\t\"PRAGMA foreign_keys = ON;\",\n\t\t\"PRAGMA journal_mode = WAL;\",\n\t\t\"PRAGMA page_size = 4096;\",\n\t\t\"PRAGMA cache_size = -8000;\",\n\t\t\"PRAGMA synchronous = NORMAL;\",\n\t}\n\n\tfor _, pragma := range pragmas {\n\t\tif _, err = db.Exec(pragma); err != nil {\n\t\t\tlogging.Error(\"Failed to set pragma\", pragma, err)\n\t\t} else {\n\t\t\tlogging.Debug(\"Set pragma\", \"pragma\", pragma)\n\t\t}\n\t}\n\n\tgoose.SetBaseFS(FS)\n\n\tif err := goose.SetDialect(\"sqlite3\"); err != nil {\n\t\tlogging.Error(\"Failed to set dialect\", \"error\", err)\n\t\treturn nil, fmt.Errorf(\"failed to set dialect: %w\", err)\n\t}\n\n\tif err := goose.Up(db, \"migrations\"); err != nil {\n\t\tlogging.Error(\"Failed to apply migrations\", \"error\", err)\n\t\treturn nil, fmt.Errorf(\"failed to apply migrations: %w\", err)\n\t}\n\treturn db, nil\n}\n"], ["/opencode/internal/tui/util/util.go", "package util\n\nimport (\n\t\"time\"\n\n\ttea \"github.com/charmbracelet/bubbletea\"\n)\n\nfunc CmdHandler(msg tea.Msg) tea.Cmd {\n\treturn func() tea.Msg {\n\t\treturn msg\n\t}\n}\n\nfunc ReportError(err error) tea.Cmd {\n\treturn CmdHandler(InfoMsg{\n\t\tType: InfoTypeError,\n\t\tMsg: err.Error(),\n\t})\n}\n\ntype InfoType int\n\nconst (\n\tInfoTypeInfo InfoType = iota\n\tInfoTypeWarn\n\tInfoTypeError\n)\n\nfunc ReportInfo(info string) tea.Cmd {\n\treturn CmdHandler(InfoMsg{\n\t\tType: InfoTypeInfo,\n\t\tMsg: info,\n\t})\n}\n\nfunc ReportWarn(warn string) tea.Cmd {\n\treturn CmdHandler(InfoMsg{\n\t\tType: InfoTypeWarn,\n\t\tMsg: warn,\n\t})\n}\n\ntype (\n\tInfoMsg struct {\n\t\tType InfoType\n\t\tMsg string\n\t\tTTL time.Duration\n\t}\n\tClearStatusMsg struct{}\n)\n\nfunc Clamp(v, low, high int) int {\n\tif high < low {\n\t\tlow, high = high, low\n\t}\n\treturn min(high, max(low, v))\n}\n"], ["/opencode/internal/lsp/methods.go", "// Generated code. Do not edit\npackage lsp\n\nimport (\n\t\"context\"\n\n\t\"github.com/opencode-ai/opencode/internal/lsp/protocol\"\n)\n\n// Implementation sends a textDocument/implementation request to the LSP server.\n// A request to resolve the implementation locations of a symbol at a given text document position. The request's parameter is of type TextDocumentPositionParams the response is of type Definition or a Thenable that resolves to such.\nfunc (c *Client) Implementation(ctx context.Context, params protocol.ImplementationParams) (protocol.Or_Result_textDocument_implementation, error) {\n\tvar result protocol.Or_Result_textDocument_implementation\n\terr := c.Call(ctx, \"textDocument/implementation\", params, &result)\n\treturn result, err\n}\n\n// TypeDefinition sends a textDocument/typeDefinition request to the LSP server.\n// A request to resolve the type definition locations of a symbol at a given text document position. The request's parameter is of type TextDocumentPositionParams the response is of type Definition or a Thenable that resolves to such.\nfunc (c *Client) TypeDefinition(ctx context.Context, params protocol.TypeDefinitionParams) (protocol.Or_Result_textDocument_typeDefinition, error) {\n\tvar result protocol.Or_Result_textDocument_typeDefinition\n\terr := c.Call(ctx, \"textDocument/typeDefinition\", params, &result)\n\treturn result, err\n}\n\n// DocumentColor sends a textDocument/documentColor request to the LSP server.\n// A request to list all color symbols found in a given text document. The request's parameter is of type DocumentColorParams the response is of type ColorInformation ColorInformation[] or a Thenable that resolves to such.\nfunc (c *Client) DocumentColor(ctx context.Context, params protocol.DocumentColorParams) ([]protocol.ColorInformation, error) {\n\tvar result []protocol.ColorInformation\n\terr := c.Call(ctx, \"textDocument/documentColor\", params, &result)\n\treturn result, err\n}\n\n// ColorPresentation sends a textDocument/colorPresentation request to the LSP server.\n// A request to list all presentation for a color. The request's parameter is of type ColorPresentationParams the response is of type ColorInformation ColorInformation[] or a Thenable that resolves to such.\nfunc (c *Client) ColorPresentation(ctx context.Context, params protocol.ColorPresentationParams) ([]protocol.ColorPresentation, error) {\n\tvar result []protocol.ColorPresentation\n\terr := c.Call(ctx, \"textDocument/colorPresentation\", params, &result)\n\treturn result, err\n}\n\n// FoldingRange sends a textDocument/foldingRange request to the LSP server.\n// A request to provide folding ranges in a document. The request's parameter is of type FoldingRangeParams, the response is of type FoldingRangeList or a Thenable that resolves to such.\nfunc (c *Client) FoldingRange(ctx context.Context, params protocol.FoldingRangeParams) ([]protocol.FoldingRange, error) {\n\tvar result []protocol.FoldingRange\n\terr := c.Call(ctx, \"textDocument/foldingRange\", params, &result)\n\treturn result, err\n}\n\n// Declaration sends a textDocument/declaration request to the LSP server.\n// A request to resolve the type definition locations of a symbol at a given text document position. The request's parameter is of type TextDocumentPositionParams the response is of type Declaration or a typed array of DeclarationLink or a Thenable that resolves to such.\nfunc (c *Client) Declaration(ctx context.Context, params protocol.DeclarationParams) (protocol.Or_Result_textDocument_declaration, error) {\n\tvar result protocol.Or_Result_textDocument_declaration\n\terr := c.Call(ctx, \"textDocument/declaration\", params, &result)\n\treturn result, err\n}\n\n// SelectionRange sends a textDocument/selectionRange request to the LSP server.\n// A request to provide selection ranges in a document. The request's parameter is of type SelectionRangeParams, the response is of type SelectionRange SelectionRange[] or a Thenable that resolves to such.\nfunc (c *Client) SelectionRange(ctx context.Context, params protocol.SelectionRangeParams) ([]protocol.SelectionRange, error) {\n\tvar result []protocol.SelectionRange\n\terr := c.Call(ctx, \"textDocument/selectionRange\", params, &result)\n\treturn result, err\n}\n\n// PrepareCallHierarchy sends a textDocument/prepareCallHierarchy request to the LSP server.\n// A request to result a CallHierarchyItem in a document at a given position. Can be used as an input to an incoming or outgoing call hierarchy. Since 3.16.0\nfunc (c *Client) PrepareCallHierarchy(ctx context.Context, params protocol.CallHierarchyPrepareParams) ([]protocol.CallHierarchyItem, error) {\n\tvar result []protocol.CallHierarchyItem\n\terr := c.Call(ctx, \"textDocument/prepareCallHierarchy\", params, &result)\n\treturn result, err\n}\n\n// IncomingCalls sends a callHierarchy/incomingCalls request to the LSP server.\n// A request to resolve the incoming calls for a given CallHierarchyItem. Since 3.16.0\nfunc (c *Client) IncomingCalls(ctx context.Context, params protocol.CallHierarchyIncomingCallsParams) ([]protocol.CallHierarchyIncomingCall, error) {\n\tvar result []protocol.CallHierarchyIncomingCall\n\terr := c.Call(ctx, \"callHierarchy/incomingCalls\", params, &result)\n\treturn result, err\n}\n\n// OutgoingCalls sends a callHierarchy/outgoingCalls request to the LSP server.\n// A request to resolve the outgoing calls for a given CallHierarchyItem. Since 3.16.0\nfunc (c *Client) OutgoingCalls(ctx context.Context, params protocol.CallHierarchyOutgoingCallsParams) ([]protocol.CallHierarchyOutgoingCall, error) {\n\tvar result []protocol.CallHierarchyOutgoingCall\n\terr := c.Call(ctx, \"callHierarchy/outgoingCalls\", params, &result)\n\treturn result, err\n}\n\n// SemanticTokensFull sends a textDocument/semanticTokens/full request to the LSP server.\n// Since 3.16.0\nfunc (c *Client) SemanticTokensFull(ctx context.Context, params protocol.SemanticTokensParams) (protocol.SemanticTokens, error) {\n\tvar result protocol.SemanticTokens\n\terr := c.Call(ctx, \"textDocument/semanticTokens/full\", params, &result)\n\treturn result, err\n}\n\n// SemanticTokensFullDelta sends a textDocument/semanticTokens/full/delta request to the LSP server.\n// Since 3.16.0\nfunc (c *Client) SemanticTokensFullDelta(ctx context.Context, params protocol.SemanticTokensDeltaParams) (protocol.Or_Result_textDocument_semanticTokens_full_delta, error) {\n\tvar result protocol.Or_Result_textDocument_semanticTokens_full_delta\n\terr := c.Call(ctx, \"textDocument/semanticTokens/full/delta\", params, &result)\n\treturn result, err\n}\n\n// SemanticTokensRange sends a textDocument/semanticTokens/range request to the LSP server.\n// Since 3.16.0\nfunc (c *Client) SemanticTokensRange(ctx context.Context, params protocol.SemanticTokensRangeParams) (protocol.SemanticTokens, error) {\n\tvar result protocol.SemanticTokens\n\terr := c.Call(ctx, \"textDocument/semanticTokens/range\", params, &result)\n\treturn result, err\n}\n\n// LinkedEditingRange sends a textDocument/linkedEditingRange request to the LSP server.\n// A request to provide ranges that can be edited together. Since 3.16.0\nfunc (c *Client) LinkedEditingRange(ctx context.Context, params protocol.LinkedEditingRangeParams) (protocol.LinkedEditingRanges, error) {\n\tvar result protocol.LinkedEditingRanges\n\terr := c.Call(ctx, \"textDocument/linkedEditingRange\", params, &result)\n\treturn result, err\n}\n\n// WillCreateFiles sends a workspace/willCreateFiles request to the LSP server.\n// The will create files request is sent from the client to the server before files are actually created as long as the creation is triggered from within the client. The request can return a WorkspaceEdit which will be applied to workspace before the files are created. Hence the WorkspaceEdit can not manipulate the content of the file to be created. Since 3.16.0\nfunc (c *Client) WillCreateFiles(ctx context.Context, params protocol.CreateFilesParams) (protocol.WorkspaceEdit, error) {\n\tvar result protocol.WorkspaceEdit\n\terr := c.Call(ctx, \"workspace/willCreateFiles\", params, &result)\n\treturn result, err\n}\n\n// WillRenameFiles sends a workspace/willRenameFiles request to the LSP server.\n// The will rename files request is sent from the client to the server before files are actually renamed as long as the rename is triggered from within the client. Since 3.16.0\nfunc (c *Client) WillRenameFiles(ctx context.Context, params protocol.RenameFilesParams) (protocol.WorkspaceEdit, error) {\n\tvar result protocol.WorkspaceEdit\n\terr := c.Call(ctx, \"workspace/willRenameFiles\", params, &result)\n\treturn result, err\n}\n\n// WillDeleteFiles sends a workspace/willDeleteFiles request to the LSP server.\n// The did delete files notification is sent from the client to the server when files were deleted from within the client. Since 3.16.0\nfunc (c *Client) WillDeleteFiles(ctx context.Context, params protocol.DeleteFilesParams) (protocol.WorkspaceEdit, error) {\n\tvar result protocol.WorkspaceEdit\n\terr := c.Call(ctx, \"workspace/willDeleteFiles\", params, &result)\n\treturn result, err\n}\n\n// Moniker sends a textDocument/moniker request to the LSP server.\n// A request to get the moniker of a symbol at a given text document position. The request parameter is of type TextDocumentPositionParams. The response is of type Moniker Moniker[] or null.\nfunc (c *Client) Moniker(ctx context.Context, params protocol.MonikerParams) ([]protocol.Moniker, error) {\n\tvar result []protocol.Moniker\n\terr := c.Call(ctx, \"textDocument/moniker\", params, &result)\n\treturn result, err\n}\n\n// PrepareTypeHierarchy sends a textDocument/prepareTypeHierarchy request to the LSP server.\n// A request to result a TypeHierarchyItem in a document at a given position. Can be used as an input to a subtypes or supertypes type hierarchy. Since 3.17.0\nfunc (c *Client) PrepareTypeHierarchy(ctx context.Context, params protocol.TypeHierarchyPrepareParams) ([]protocol.TypeHierarchyItem, error) {\n\tvar result []protocol.TypeHierarchyItem\n\terr := c.Call(ctx, \"textDocument/prepareTypeHierarchy\", params, &result)\n\treturn result, err\n}\n\n// Supertypes sends a typeHierarchy/supertypes request to the LSP server.\n// A request to resolve the supertypes for a given TypeHierarchyItem. Since 3.17.0\nfunc (c *Client) Supertypes(ctx context.Context, params protocol.TypeHierarchySupertypesParams) ([]protocol.TypeHierarchyItem, error) {\n\tvar result []protocol.TypeHierarchyItem\n\terr := c.Call(ctx, \"typeHierarchy/supertypes\", params, &result)\n\treturn result, err\n}\n\n// Subtypes sends a typeHierarchy/subtypes request to the LSP server.\n// A request to resolve the subtypes for a given TypeHierarchyItem. Since 3.17.0\nfunc (c *Client) Subtypes(ctx context.Context, params protocol.TypeHierarchySubtypesParams) ([]protocol.TypeHierarchyItem, error) {\n\tvar result []protocol.TypeHierarchyItem\n\terr := c.Call(ctx, \"typeHierarchy/subtypes\", params, &result)\n\treturn result, err\n}\n\n// InlineValue sends a textDocument/inlineValue request to the LSP server.\n// A request to provide inline values in a document. The request's parameter is of type InlineValueParams, the response is of type InlineValue InlineValue[] or a Thenable that resolves to such. Since 3.17.0\nfunc (c *Client) InlineValue(ctx context.Context, params protocol.InlineValueParams) ([]protocol.InlineValue, error) {\n\tvar result []protocol.InlineValue\n\terr := c.Call(ctx, \"textDocument/inlineValue\", params, &result)\n\treturn result, err\n}\n\n// InlayHint sends a textDocument/inlayHint request to the LSP server.\n// A request to provide inlay hints in a document. The request's parameter is of type InlayHintsParams, the response is of type InlayHint InlayHint[] or a Thenable that resolves to such. Since 3.17.0\nfunc (c *Client) InlayHint(ctx context.Context, params protocol.InlayHintParams) ([]protocol.InlayHint, error) {\n\tvar result []protocol.InlayHint\n\terr := c.Call(ctx, \"textDocument/inlayHint\", params, &result)\n\treturn result, err\n}\n\n// Resolve sends a inlayHint/resolve request to the LSP server.\n// A request to resolve additional properties for an inlay hint. The request's parameter is of type InlayHint, the response is of type InlayHint or a Thenable that resolves to such. Since 3.17.0\nfunc (c *Client) Resolve(ctx context.Context, params protocol.InlayHint) (protocol.InlayHint, error) {\n\tvar result protocol.InlayHint\n\terr := c.Call(ctx, \"inlayHint/resolve\", params, &result)\n\treturn result, err\n}\n\n// Diagnostic sends a textDocument/diagnostic request to the LSP server.\n// The document diagnostic request definition. Since 3.17.0\nfunc (c *Client) Diagnostic(ctx context.Context, params protocol.DocumentDiagnosticParams) (protocol.DocumentDiagnosticReport, error) {\n\tvar result protocol.DocumentDiagnosticReport\n\terr := c.Call(ctx, \"textDocument/diagnostic\", params, &result)\n\treturn result, err\n}\n\n// DiagnosticWorkspace sends a workspace/diagnostic request to the LSP server.\n// The workspace diagnostic request definition. Since 3.17.0\nfunc (c *Client) DiagnosticWorkspace(ctx context.Context, params protocol.WorkspaceDiagnosticParams) (protocol.WorkspaceDiagnosticReport, error) {\n\tvar result protocol.WorkspaceDiagnosticReport\n\terr := c.Call(ctx, \"workspace/diagnostic\", params, &result)\n\treturn result, err\n}\n\n// InlineCompletion sends a textDocument/inlineCompletion request to the LSP server.\n// A request to provide inline completions in a document. The request's parameter is of type InlineCompletionParams, the response is of type InlineCompletion InlineCompletion[] or a Thenable that resolves to such. Since 3.18.0 PROPOSED\nfunc (c *Client) InlineCompletion(ctx context.Context, params protocol.InlineCompletionParams) (protocol.Or_Result_textDocument_inlineCompletion, error) {\n\tvar result protocol.Or_Result_textDocument_inlineCompletion\n\terr := c.Call(ctx, \"textDocument/inlineCompletion\", params, &result)\n\treturn result, err\n}\n\n// TextDocumentContent sends a workspace/textDocumentContent request to the LSP server.\n// The workspace/textDocumentContent request is sent from the client to the server to request the content of a text document. Since 3.18.0 PROPOSED\nfunc (c *Client) TextDocumentContent(ctx context.Context, params protocol.TextDocumentContentParams) (string, error) {\n\tvar result string\n\terr := c.Call(ctx, \"workspace/textDocumentContent\", params, &result)\n\treturn result, err\n}\n\n// Initialize sends a initialize request to the LSP server.\n// The initialize request is sent from the client to the server. It is sent once as the request after starting up the server. The requests parameter is of type InitializeParams the response if of type InitializeResult of a Thenable that resolves to such.\nfunc (c *Client) Initialize(ctx context.Context, params protocol.ParamInitialize) (protocol.InitializeResult, error) {\n\tvar result protocol.InitializeResult\n\terr := c.Call(ctx, \"initialize\", params, &result)\n\treturn result, err\n}\n\n// Shutdown sends a shutdown request to the LSP server.\n// A shutdown request is sent from the client to the server. It is sent once when the client decides to shutdown the server. The only notification that is sent after a shutdown request is the exit event.\nfunc (c *Client) Shutdown(ctx context.Context) error {\n\treturn c.Call(ctx, \"shutdown\", nil, nil)\n}\n\n// WillSaveWaitUntil sends a textDocument/willSaveWaitUntil request to the LSP server.\n// A document will save request is sent from the client to the server before the document is actually saved. The request can return an array of TextEdits which will be applied to the text document before it is saved. Please note that clients might drop results if computing the text edits took too long or if a server constantly fails on this request. This is done to keep the save fast and reliable.\nfunc (c *Client) WillSaveWaitUntil(ctx context.Context, params protocol.WillSaveTextDocumentParams) ([]protocol.TextEdit, error) {\n\tvar result []protocol.TextEdit\n\terr := c.Call(ctx, \"textDocument/willSaveWaitUntil\", params, &result)\n\treturn result, err\n}\n\n// Completion sends a textDocument/completion request to the LSP server.\n// Request to request completion at a given text document position. The request's parameter is of type TextDocumentPosition the response is of type CompletionItem CompletionItem[] or CompletionList or a Thenable that resolves to such. The request can delay the computation of the CompletionItem.detail detail and CompletionItem.documentation documentation properties to the completionItem/resolve request. However, properties that are needed for the initial sorting and filtering, like sortText, filterText, insertText, and textEdit, must not be changed during resolve.\nfunc (c *Client) Completion(ctx context.Context, params protocol.CompletionParams) (protocol.Or_Result_textDocument_completion, error) {\n\tvar result protocol.Or_Result_textDocument_completion\n\terr := c.Call(ctx, \"textDocument/completion\", params, &result)\n\treturn result, err\n}\n\n// ResolveCompletionItem sends a completionItem/resolve request to the LSP server.\n// Request to resolve additional information for a given completion item.The request's parameter is of type CompletionItem the response is of type CompletionItem or a Thenable that resolves to such.\nfunc (c *Client) ResolveCompletionItem(ctx context.Context, params protocol.CompletionItem) (protocol.CompletionItem, error) {\n\tvar result protocol.CompletionItem\n\terr := c.Call(ctx, \"completionItem/resolve\", params, &result)\n\treturn result, err\n}\n\n// Hover sends a textDocument/hover request to the LSP server.\n// Request to request hover information at a given text document position. The request's parameter is of type TextDocumentPosition the response is of type Hover or a Thenable that resolves to such.\nfunc (c *Client) Hover(ctx context.Context, params protocol.HoverParams) (protocol.Hover, error) {\n\tvar result protocol.Hover\n\terr := c.Call(ctx, \"textDocument/hover\", params, &result)\n\treturn result, err\n}\n\n// SignatureHelp sends a textDocument/signatureHelp request to the LSP server.\nfunc (c *Client) SignatureHelp(ctx context.Context, params protocol.SignatureHelpParams) (protocol.SignatureHelp, error) {\n\tvar result protocol.SignatureHelp\n\terr := c.Call(ctx, \"textDocument/signatureHelp\", params, &result)\n\treturn result, err\n}\n\n// Definition sends a textDocument/definition request to the LSP server.\n// A request to resolve the definition location of a symbol at a given text document position. The request's parameter is of type TextDocumentPosition the response is of either type Definition or a typed array of DefinitionLink or a Thenable that resolves to such.\nfunc (c *Client) Definition(ctx context.Context, params protocol.DefinitionParams) (protocol.Or_Result_textDocument_definition, error) {\n\tvar result protocol.Or_Result_textDocument_definition\n\terr := c.Call(ctx, \"textDocument/definition\", params, &result)\n\treturn result, err\n}\n\n// References sends a textDocument/references request to the LSP server.\n// A request to resolve project-wide references for the symbol denoted by the given text document position. The request's parameter is of type ReferenceParams the response is of type Location Location[] or a Thenable that resolves to such.\nfunc (c *Client) References(ctx context.Context, params protocol.ReferenceParams) ([]protocol.Location, error) {\n\tvar result []protocol.Location\n\terr := c.Call(ctx, \"textDocument/references\", params, &result)\n\treturn result, err\n}\n\n// DocumentHighlight sends a textDocument/documentHighlight request to the LSP server.\n// Request to resolve a DocumentHighlight for a given text document position. The request's parameter is of type TextDocumentPosition the request response is an array of type DocumentHighlight or a Thenable that resolves to such.\nfunc (c *Client) DocumentHighlight(ctx context.Context, params protocol.DocumentHighlightParams) ([]protocol.DocumentHighlight, error) {\n\tvar result []protocol.DocumentHighlight\n\terr := c.Call(ctx, \"textDocument/documentHighlight\", params, &result)\n\treturn result, err\n}\n\n// DocumentSymbol sends a textDocument/documentSymbol request to the LSP server.\n// A request to list all symbols found in a given text document. The request's parameter is of type TextDocumentIdentifier the response is of type SymbolInformation SymbolInformation[] or a Thenable that resolves to such.\nfunc (c *Client) DocumentSymbol(ctx context.Context, params protocol.DocumentSymbolParams) (protocol.Or_Result_textDocument_documentSymbol, error) {\n\tvar result protocol.Or_Result_textDocument_documentSymbol\n\terr := c.Call(ctx, \"textDocument/documentSymbol\", params, &result)\n\treturn result, err\n}\n\n// CodeAction sends a textDocument/codeAction request to the LSP server.\n// A request to provide commands for the given text document and range.\nfunc (c *Client) CodeAction(ctx context.Context, params protocol.CodeActionParams) ([]protocol.Or_Result_textDocument_codeAction_Item0_Elem, error) {\n\tvar result []protocol.Or_Result_textDocument_codeAction_Item0_Elem\n\terr := c.Call(ctx, \"textDocument/codeAction\", params, &result)\n\treturn result, err\n}\n\n// ResolveCodeAction sends a codeAction/resolve request to the LSP server.\n// Request to resolve additional information for a given code action.The request's parameter is of type CodeAction the response is of type CodeAction or a Thenable that resolves to such.\nfunc (c *Client) ResolveCodeAction(ctx context.Context, params protocol.CodeAction) (protocol.CodeAction, error) {\n\tvar result protocol.CodeAction\n\terr := c.Call(ctx, \"codeAction/resolve\", params, &result)\n\treturn result, err\n}\n\n// Symbol sends a workspace/symbol request to the LSP server.\n// A request to list project-wide symbols matching the query string given by the WorkspaceSymbolParams. The response is of type SymbolInformation SymbolInformation[] or a Thenable that resolves to such. Since 3.17.0 - support for WorkspaceSymbol in the returned data. Clients need to advertise support for WorkspaceSymbols via the client capability workspace.symbol.resolveSupport.\nfunc (c *Client) Symbol(ctx context.Context, params protocol.WorkspaceSymbolParams) (protocol.Or_Result_workspace_symbol, error) {\n\tvar result protocol.Or_Result_workspace_symbol\n\terr := c.Call(ctx, \"workspace/symbol\", params, &result)\n\treturn result, err\n}\n\n// ResolveWorkspaceSymbol sends a workspaceSymbol/resolve request to the LSP server.\n// A request to resolve the range inside the workspace symbol's location. Since 3.17.0\nfunc (c *Client) ResolveWorkspaceSymbol(ctx context.Context, params protocol.WorkspaceSymbol) (protocol.WorkspaceSymbol, error) {\n\tvar result protocol.WorkspaceSymbol\n\terr := c.Call(ctx, \"workspaceSymbol/resolve\", params, &result)\n\treturn result, err\n}\n\n// CodeLens sends a textDocument/codeLens request to the LSP server.\n// A request to provide code lens for the given text document.\nfunc (c *Client) CodeLens(ctx context.Context, params protocol.CodeLensParams) ([]protocol.CodeLens, error) {\n\tvar result []protocol.CodeLens\n\terr := c.Call(ctx, \"textDocument/codeLens\", params, &result)\n\treturn result, err\n}\n\n// ResolveCodeLens sends a codeLens/resolve request to the LSP server.\n// A request to resolve a command for a given code lens.\nfunc (c *Client) ResolveCodeLens(ctx context.Context, params protocol.CodeLens) (protocol.CodeLens, error) {\n\tvar result protocol.CodeLens\n\terr := c.Call(ctx, \"codeLens/resolve\", params, &result)\n\treturn result, err\n}\n\n// DocumentLink sends a textDocument/documentLink request to the LSP server.\n// A request to provide document links\nfunc (c *Client) DocumentLink(ctx context.Context, params protocol.DocumentLinkParams) ([]protocol.DocumentLink, error) {\n\tvar result []protocol.DocumentLink\n\terr := c.Call(ctx, \"textDocument/documentLink\", params, &result)\n\treturn result, err\n}\n\n// ResolveDocumentLink sends a documentLink/resolve request to the LSP server.\n// Request to resolve additional information for a given document link. The request's parameter is of type DocumentLink the response is of type DocumentLink or a Thenable that resolves to such.\nfunc (c *Client) ResolveDocumentLink(ctx context.Context, params protocol.DocumentLink) (protocol.DocumentLink, error) {\n\tvar result protocol.DocumentLink\n\terr := c.Call(ctx, \"documentLink/resolve\", params, &result)\n\treturn result, err\n}\n\n// Formatting sends a textDocument/formatting request to the LSP server.\n// A request to format a whole document.\nfunc (c *Client) Formatting(ctx context.Context, params protocol.DocumentFormattingParams) ([]protocol.TextEdit, error) {\n\tvar result []protocol.TextEdit\n\terr := c.Call(ctx, \"textDocument/formatting\", params, &result)\n\treturn result, err\n}\n\n// RangeFormatting sends a textDocument/rangeFormatting request to the LSP server.\n// A request to format a range in a document.\nfunc (c *Client) RangeFormatting(ctx context.Context, params protocol.DocumentRangeFormattingParams) ([]protocol.TextEdit, error) {\n\tvar result []protocol.TextEdit\n\terr := c.Call(ctx, \"textDocument/rangeFormatting\", params, &result)\n\treturn result, err\n}\n\n// RangesFormatting sends a textDocument/rangesFormatting request to the LSP server.\n// A request to format ranges in a document. Since 3.18.0 PROPOSED\nfunc (c *Client) RangesFormatting(ctx context.Context, params protocol.DocumentRangesFormattingParams) ([]protocol.TextEdit, error) {\n\tvar result []protocol.TextEdit\n\terr := c.Call(ctx, \"textDocument/rangesFormatting\", params, &result)\n\treturn result, err\n}\n\n// OnTypeFormatting sends a textDocument/onTypeFormatting request to the LSP server.\n// A request to format a document on type.\nfunc (c *Client) OnTypeFormatting(ctx context.Context, params protocol.DocumentOnTypeFormattingParams) ([]protocol.TextEdit, error) {\n\tvar result []protocol.TextEdit\n\terr := c.Call(ctx, \"textDocument/onTypeFormatting\", params, &result)\n\treturn result, err\n}\n\n// Rename sends a textDocument/rename request to the LSP server.\n// A request to rename a symbol.\nfunc (c *Client) Rename(ctx context.Context, params protocol.RenameParams) (protocol.WorkspaceEdit, error) {\n\tvar result protocol.WorkspaceEdit\n\terr := c.Call(ctx, \"textDocument/rename\", params, &result)\n\treturn result, err\n}\n\n// PrepareRename sends a textDocument/prepareRename request to the LSP server.\n// A request to test and perform the setup necessary for a rename. Since 3.16 - support for default behavior\nfunc (c *Client) PrepareRename(ctx context.Context, params protocol.PrepareRenameParams) (protocol.PrepareRenameResult, error) {\n\tvar result protocol.PrepareRenameResult\n\terr := c.Call(ctx, \"textDocument/prepareRename\", params, &result)\n\treturn result, err\n}\n\n// ExecuteCommand sends a workspace/executeCommand request to the LSP server.\n// A request send from the client to the server to execute a command. The request might return a workspace edit which the client will apply to the workspace.\nfunc (c *Client) ExecuteCommand(ctx context.Context, params protocol.ExecuteCommandParams) (any, error) {\n\tvar result any\n\terr := c.Call(ctx, \"workspace/executeCommand\", params, &result)\n\treturn result, err\n}\n\n// DidChangeWorkspaceFolders sends a workspace/didChangeWorkspaceFolders notification to the LSP server.\n// The workspace/didChangeWorkspaceFolders notification is sent from the client to the server when the workspace folder configuration changes.\nfunc (c *Client) DidChangeWorkspaceFolders(ctx context.Context, params protocol.DidChangeWorkspaceFoldersParams) error {\n\treturn c.Notify(ctx, \"workspace/didChangeWorkspaceFolders\", params)\n}\n\n// WorkDoneProgressCancel sends a window/workDoneProgress/cancel notification to the LSP server.\n// The window/workDoneProgress/cancel notification is sent from the client to the server to cancel a progress initiated on the server side.\nfunc (c *Client) WorkDoneProgressCancel(ctx context.Context, params protocol.WorkDoneProgressCancelParams) error {\n\treturn c.Notify(ctx, \"window/workDoneProgress/cancel\", params)\n}\n\n// DidCreateFiles sends a workspace/didCreateFiles notification to the LSP server.\n// The did create files notification is sent from the client to the server when files were created from within the client. Since 3.16.0\nfunc (c *Client) DidCreateFiles(ctx context.Context, params protocol.CreateFilesParams) error {\n\treturn c.Notify(ctx, \"workspace/didCreateFiles\", params)\n}\n\n// DidRenameFiles sends a workspace/didRenameFiles notification to the LSP server.\n// The did rename files notification is sent from the client to the server when files were renamed from within the client. Since 3.16.0\nfunc (c *Client) DidRenameFiles(ctx context.Context, params protocol.RenameFilesParams) error {\n\treturn c.Notify(ctx, \"workspace/didRenameFiles\", params)\n}\n\n// DidDeleteFiles sends a workspace/didDeleteFiles notification to the LSP server.\n// The will delete files request is sent from the client to the server before files are actually deleted as long as the deletion is triggered from within the client. Since 3.16.0\nfunc (c *Client) DidDeleteFiles(ctx context.Context, params protocol.DeleteFilesParams) error {\n\treturn c.Notify(ctx, \"workspace/didDeleteFiles\", params)\n}\n\n// DidOpenNotebookDocument sends a notebookDocument/didOpen notification to the LSP server.\n// A notification sent when a notebook opens. Since 3.17.0\nfunc (c *Client) DidOpenNotebookDocument(ctx context.Context, params protocol.DidOpenNotebookDocumentParams) error {\n\treturn c.Notify(ctx, \"notebookDocument/didOpen\", params)\n}\n\n// DidChangeNotebookDocument sends a notebookDocument/didChange notification to the LSP server.\nfunc (c *Client) DidChangeNotebookDocument(ctx context.Context, params protocol.DidChangeNotebookDocumentParams) error {\n\treturn c.Notify(ctx, \"notebookDocument/didChange\", params)\n}\n\n// DidSaveNotebookDocument sends a notebookDocument/didSave notification to the LSP server.\n// A notification sent when a notebook document is saved. Since 3.17.0\nfunc (c *Client) DidSaveNotebookDocument(ctx context.Context, params protocol.DidSaveNotebookDocumentParams) error {\n\treturn c.Notify(ctx, \"notebookDocument/didSave\", params)\n}\n\n// DidCloseNotebookDocument sends a notebookDocument/didClose notification to the LSP server.\n// A notification sent when a notebook closes. Since 3.17.0\nfunc (c *Client) DidCloseNotebookDocument(ctx context.Context, params protocol.DidCloseNotebookDocumentParams) error {\n\treturn c.Notify(ctx, \"notebookDocument/didClose\", params)\n}\n\n// Initialized sends a initialized notification to the LSP server.\n// The initialized notification is sent from the client to the server after the client is fully initialized and the server is allowed to send requests from the server to the client.\nfunc (c *Client) Initialized(ctx context.Context, params protocol.InitializedParams) error {\n\treturn c.Notify(ctx, \"initialized\", params)\n}\n\n// Exit sends a exit notification to the LSP server.\n// The exit event is sent from the client to the server to ask the server to exit its process.\nfunc (c *Client) Exit(ctx context.Context) error {\n\treturn c.Notify(ctx, \"exit\", nil)\n}\n\n// DidChangeConfiguration sends a workspace/didChangeConfiguration notification to the LSP server.\n// The configuration change notification is sent from the client to the server when the client's configuration has changed. The notification contains the changed configuration as defined by the language client.\nfunc (c *Client) DidChangeConfiguration(ctx context.Context, params protocol.DidChangeConfigurationParams) error {\n\treturn c.Notify(ctx, \"workspace/didChangeConfiguration\", params)\n}\n\n// DidOpen sends a textDocument/didOpen notification to the LSP server.\n// The document open notification is sent from the client to the server to signal newly opened text documents. The document's truth is now managed by the client and the server must not try to read the document's truth using the document's uri. Open in this sense means it is managed by the client. It doesn't necessarily mean that its content is presented in an editor. An open notification must not be sent more than once without a corresponding close notification send before. This means open and close notification must be balanced and the max open count is one.\nfunc (c *Client) DidOpen(ctx context.Context, params protocol.DidOpenTextDocumentParams) error {\n\treturn c.Notify(ctx, \"textDocument/didOpen\", params)\n}\n\n// DidChange sends a textDocument/didChange notification to the LSP server.\n// The document change notification is sent from the client to the server to signal changes to a text document.\nfunc (c *Client) DidChange(ctx context.Context, params protocol.DidChangeTextDocumentParams) error {\n\treturn c.Notify(ctx, \"textDocument/didChange\", params)\n}\n\n// DidClose sends a textDocument/didClose notification to the LSP server.\n// The document close notification is sent from the client to the server when the document got closed in the client. The document's truth now exists where the document's uri points to (e.g. if the document's uri is a file uri the truth now exists on disk). As with the open notification the close notification is about managing the document's content. Receiving a close notification doesn't mean that the document was open in an editor before. A close notification requires a previous open notification to be sent.\nfunc (c *Client) DidClose(ctx context.Context, params protocol.DidCloseTextDocumentParams) error {\n\treturn c.Notify(ctx, \"textDocument/didClose\", params)\n}\n\n// DidSave sends a textDocument/didSave notification to the LSP server.\n// The document save notification is sent from the client to the server when the document got saved in the client.\nfunc (c *Client) DidSave(ctx context.Context, params protocol.DidSaveTextDocumentParams) error {\n\treturn c.Notify(ctx, \"textDocument/didSave\", params)\n}\n\n// WillSave sends a textDocument/willSave notification to the LSP server.\n// A document will save notification is sent from the client to the server before the document is actually saved.\nfunc (c *Client) WillSave(ctx context.Context, params protocol.WillSaveTextDocumentParams) error {\n\treturn c.Notify(ctx, \"textDocument/willSave\", params)\n}\n\n// DidChangeWatchedFiles sends a workspace/didChangeWatchedFiles notification to the LSP server.\n// The watched files notification is sent from the client to the server when the client detects changes to file watched by the language client.\nfunc (c *Client) DidChangeWatchedFiles(ctx context.Context, params protocol.DidChangeWatchedFilesParams) error {\n\treturn c.Notify(ctx, \"workspace/didChangeWatchedFiles\", params)\n}\n\n// SetTrace sends a $/setTrace notification to the LSP server.\nfunc (c *Client) SetTrace(ctx context.Context, params protocol.SetTraceParams) error {\n\treturn c.Notify(ctx, \"$/setTrace\", params)\n}\n\n// Progress sends a $/progress notification to the LSP server.\nfunc (c *Client) Progress(ctx context.Context, params protocol.ProgressParams) error {\n\treturn c.Notify(ctx, \"$/progress\", params)\n}\n"], ["/opencode/internal/db/db.go", "// Code generated by sqlc. DO NOT EDIT.\n// versions:\n// sqlc v1.29.0\n\npackage db\n\nimport (\n\t\"context\"\n\t\"database/sql\"\n\t\"fmt\"\n)\n\ntype DBTX interface {\n\tExecContext(context.Context, string, ...interface{}) (sql.Result, error)\n\tPrepareContext(context.Context, string) (*sql.Stmt, error)\n\tQueryContext(context.Context, string, ...interface{}) (*sql.Rows, error)\n\tQueryRowContext(context.Context, string, ...interface{}) *sql.Row\n}\n\nfunc New(db DBTX) *Queries {\n\treturn &Queries{db: db}\n}\n\nfunc Prepare(ctx context.Context, db DBTX) (*Queries, error) {\n\tq := Queries{db: db}\n\tvar err error\n\tif q.createFileStmt, err = db.PrepareContext(ctx, createFile); err != nil {\n\t\treturn nil, fmt.Errorf(\"error preparing query CreateFile: %w\", err)\n\t}\n\tif q.createMessageStmt, err = db.PrepareContext(ctx, createMessage); err != nil {\n\t\treturn nil, fmt.Errorf(\"error preparing query CreateMessage: %w\", err)\n\t}\n\tif q.createSessionStmt, err = db.PrepareContext(ctx, createSession); err != nil {\n\t\treturn nil, fmt.Errorf(\"error preparing query CreateSession: %w\", err)\n\t}\n\tif q.deleteFileStmt, err = db.PrepareContext(ctx, deleteFile); err != nil {\n\t\treturn nil, fmt.Errorf(\"error preparing query DeleteFile: %w\", err)\n\t}\n\tif q.deleteMessageStmt, err = db.PrepareContext(ctx, deleteMessage); err != nil {\n\t\treturn nil, fmt.Errorf(\"error preparing query DeleteMessage: %w\", err)\n\t}\n\tif q.deleteSessionStmt, err = db.PrepareContext(ctx, deleteSession); err != nil {\n\t\treturn nil, fmt.Errorf(\"error preparing query DeleteSession: %w\", err)\n\t}\n\tif q.deleteSessionFilesStmt, err = db.PrepareContext(ctx, deleteSessionFiles); err != nil {\n\t\treturn nil, fmt.Errorf(\"error preparing query DeleteSessionFiles: %w\", err)\n\t}\n\tif q.deleteSessionMessagesStmt, err = db.PrepareContext(ctx, deleteSessionMessages); err != nil {\n\t\treturn nil, fmt.Errorf(\"error preparing query DeleteSessionMessages: %w\", err)\n\t}\n\tif q.getFileStmt, err = db.PrepareContext(ctx, getFile); err != nil {\n\t\treturn nil, fmt.Errorf(\"error preparing query GetFile: %w\", err)\n\t}\n\tif q.getFileByPathAndSessionStmt, err = db.PrepareContext(ctx, getFileByPathAndSession); err != nil {\n\t\treturn nil, fmt.Errorf(\"error preparing query GetFileByPathAndSession: %w\", err)\n\t}\n\tif q.getMessageStmt, err = db.PrepareContext(ctx, getMessage); err != nil {\n\t\treturn nil, fmt.Errorf(\"error preparing query GetMessage: %w\", err)\n\t}\n\tif q.getSessionByIDStmt, err = db.PrepareContext(ctx, getSessionByID); err != nil {\n\t\treturn nil, fmt.Errorf(\"error preparing query GetSessionByID: %w\", err)\n\t}\n\tif q.listFilesByPathStmt, err = db.PrepareContext(ctx, listFilesByPath); err != nil {\n\t\treturn nil, fmt.Errorf(\"error preparing query ListFilesByPath: %w\", err)\n\t}\n\tif q.listFilesBySessionStmt, err = db.PrepareContext(ctx, listFilesBySession); err != nil {\n\t\treturn nil, fmt.Errorf(\"error preparing query ListFilesBySession: %w\", err)\n\t}\n\tif q.listLatestSessionFilesStmt, err = db.PrepareContext(ctx, listLatestSessionFiles); err != nil {\n\t\treturn nil, fmt.Errorf(\"error preparing query ListLatestSessionFiles: %w\", err)\n\t}\n\tif q.listMessagesBySessionStmt, err = db.PrepareContext(ctx, listMessagesBySession); err != nil {\n\t\treturn nil, fmt.Errorf(\"error preparing query ListMessagesBySession: %w\", err)\n\t}\n\tif q.listNewFilesStmt, err = db.PrepareContext(ctx, listNewFiles); err != nil {\n\t\treturn nil, fmt.Errorf(\"error preparing query ListNewFiles: %w\", err)\n\t}\n\tif q.listSessionsStmt, err = db.PrepareContext(ctx, listSessions); err != nil {\n\t\treturn nil, fmt.Errorf(\"error preparing query ListSessions: %w\", err)\n\t}\n\tif q.updateFileStmt, err = db.PrepareContext(ctx, updateFile); err != nil {\n\t\treturn nil, fmt.Errorf(\"error preparing query UpdateFile: %w\", err)\n\t}\n\tif q.updateMessageStmt, err = db.PrepareContext(ctx, updateMessage); err != nil {\n\t\treturn nil, fmt.Errorf(\"error preparing query UpdateMessage: %w\", err)\n\t}\n\tif q.updateSessionStmt, err = db.PrepareContext(ctx, updateSession); err != nil {\n\t\treturn nil, fmt.Errorf(\"error preparing query UpdateSession: %w\", err)\n\t}\n\treturn &q, nil\n}\n\nfunc (q *Queries) Close() error {\n\tvar err error\n\tif q.createFileStmt != nil {\n\t\tif cerr := q.createFileStmt.Close(); cerr != nil {\n\t\t\terr = fmt.Errorf(\"error closing createFileStmt: %w\", cerr)\n\t\t}\n\t}\n\tif q.createMessageStmt != nil {\n\t\tif cerr := q.createMessageStmt.Close(); cerr != nil {\n\t\t\terr = fmt.Errorf(\"error closing createMessageStmt: %w\", cerr)\n\t\t}\n\t}\n\tif q.createSessionStmt != nil {\n\t\tif cerr := q.createSessionStmt.Close(); cerr != nil {\n\t\t\terr = fmt.Errorf(\"error closing createSessionStmt: %w\", cerr)\n\t\t}\n\t}\n\tif q.deleteFileStmt != nil {\n\t\tif cerr := q.deleteFileStmt.Close(); cerr != nil {\n\t\t\terr = fmt.Errorf(\"error closing deleteFileStmt: %w\", cerr)\n\t\t}\n\t}\n\tif q.deleteMessageStmt != nil {\n\t\tif cerr := q.deleteMessageStmt.Close(); cerr != nil {\n\t\t\terr = fmt.Errorf(\"error closing deleteMessageStmt: %w\", cerr)\n\t\t}\n\t}\n\tif q.deleteSessionStmt != nil {\n\t\tif cerr := q.deleteSessionStmt.Close(); cerr != nil {\n\t\t\terr = fmt.Errorf(\"error closing deleteSessionStmt: %w\", cerr)\n\t\t}\n\t}\n\tif q.deleteSessionFilesStmt != nil {\n\t\tif cerr := q.deleteSessionFilesStmt.Close(); cerr != nil {\n\t\t\terr = fmt.Errorf(\"error closing deleteSessionFilesStmt: %w\", cerr)\n\t\t}\n\t}\n\tif q.deleteSessionMessagesStmt != nil {\n\t\tif cerr := q.deleteSessionMessagesStmt.Close(); cerr != nil {\n\t\t\terr = fmt.Errorf(\"error closing deleteSessionMessagesStmt: %w\", cerr)\n\t\t}\n\t}\n\tif q.getFileStmt != nil {\n\t\tif cerr := q.getFileStmt.Close(); cerr != nil {\n\t\t\terr = fmt.Errorf(\"error closing getFileStmt: %w\", cerr)\n\t\t}\n\t}\n\tif q.getFileByPathAndSessionStmt != nil {\n\t\tif cerr := q.getFileByPathAndSessionStmt.Close(); cerr != nil {\n\t\t\terr = fmt.Errorf(\"error closing getFileByPathAndSessionStmt: %w\", cerr)\n\t\t}\n\t}\n\tif q.getMessageStmt != nil {\n\t\tif cerr := q.getMessageStmt.Close(); cerr != nil {\n\t\t\terr = fmt.Errorf(\"error closing getMessageStmt: %w\", cerr)\n\t\t}\n\t}\n\tif q.getSessionByIDStmt != nil {\n\t\tif cerr := q.getSessionByIDStmt.Close(); cerr != nil {\n\t\t\terr = fmt.Errorf(\"error closing getSessionByIDStmt: %w\", cerr)\n\t\t}\n\t}\n\tif q.listFilesByPathStmt != nil {\n\t\tif cerr := q.listFilesByPathStmt.Close(); cerr != nil {\n\t\t\terr = fmt.Errorf(\"error closing listFilesByPathStmt: %w\", cerr)\n\t\t}\n\t}\n\tif q.listFilesBySessionStmt != nil {\n\t\tif cerr := q.listFilesBySessionStmt.Close(); cerr != nil {\n\t\t\terr = fmt.Errorf(\"error closing listFilesBySessionStmt: %w\", cerr)\n\t\t}\n\t}\n\tif q.listLatestSessionFilesStmt != nil {\n\t\tif cerr := q.listLatestSessionFilesStmt.Close(); cerr != nil {\n\t\t\terr = fmt.Errorf(\"error closing listLatestSessionFilesStmt: %w\", cerr)\n\t\t}\n\t}\n\tif q.listMessagesBySessionStmt != nil {\n\t\tif cerr := q.listMessagesBySessionStmt.Close(); cerr != nil {\n\t\t\terr = fmt.Errorf(\"error closing listMessagesBySessionStmt: %w\", cerr)\n\t\t}\n\t}\n\tif q.listNewFilesStmt != nil {\n\t\tif cerr := q.listNewFilesStmt.Close(); cerr != nil {\n\t\t\terr = fmt.Errorf(\"error closing listNewFilesStmt: %w\", cerr)\n\t\t}\n\t}\n\tif q.listSessionsStmt != nil {\n\t\tif cerr := q.listSessionsStmt.Close(); cerr != nil {\n\t\t\terr = fmt.Errorf(\"error closing listSessionsStmt: %w\", cerr)\n\t\t}\n\t}\n\tif q.updateFileStmt != nil {\n\t\tif cerr := q.updateFileStmt.Close(); cerr != nil {\n\t\t\terr = fmt.Errorf(\"error closing updateFileStmt: %w\", cerr)\n\t\t}\n\t}\n\tif q.updateMessageStmt != nil {\n\t\tif cerr := q.updateMessageStmt.Close(); cerr != nil {\n\t\t\terr = fmt.Errorf(\"error closing updateMessageStmt: %w\", cerr)\n\t\t}\n\t}\n\tif q.updateSessionStmt != nil {\n\t\tif cerr := q.updateSessionStmt.Close(); cerr != nil {\n\t\t\terr = fmt.Errorf(\"error closing updateSessionStmt: %w\", cerr)\n\t\t}\n\t}\n\treturn err\n}\n\nfunc (q *Queries) exec(ctx context.Context, stmt *sql.Stmt, query string, args ...interface{}) (sql.Result, error) {\n\tswitch {\n\tcase stmt != nil && q.tx != nil:\n\t\treturn q.tx.StmtContext(ctx, stmt).ExecContext(ctx, args...)\n\tcase stmt != nil:\n\t\treturn stmt.ExecContext(ctx, args...)\n\tdefault:\n\t\treturn q.db.ExecContext(ctx, query, args...)\n\t}\n}\n\nfunc (q *Queries) query(ctx context.Context, stmt *sql.Stmt, query string, args ...interface{}) (*sql.Rows, error) {\n\tswitch {\n\tcase stmt != nil && q.tx != nil:\n\t\treturn q.tx.StmtContext(ctx, stmt).QueryContext(ctx, args...)\n\tcase stmt != nil:\n\t\treturn stmt.QueryContext(ctx, args...)\n\tdefault:\n\t\treturn q.db.QueryContext(ctx, query, args...)\n\t}\n}\n\nfunc (q *Queries) queryRow(ctx context.Context, stmt *sql.Stmt, query string, args ...interface{}) *sql.Row {\n\tswitch {\n\tcase stmt != nil && q.tx != nil:\n\t\treturn q.tx.StmtContext(ctx, stmt).QueryRowContext(ctx, args...)\n\tcase stmt != nil:\n\t\treturn stmt.QueryRowContext(ctx, args...)\n\tdefault:\n\t\treturn q.db.QueryRowContext(ctx, query, args...)\n\t}\n}\n\ntype Queries struct {\n\tdb DBTX\n\ttx *sql.Tx\n\tcreateFileStmt *sql.Stmt\n\tcreateMessageStmt *sql.Stmt\n\tcreateSessionStmt *sql.Stmt\n\tdeleteFileStmt *sql.Stmt\n\tdeleteMessageStmt *sql.Stmt\n\tdeleteSessionStmt *sql.Stmt\n\tdeleteSessionFilesStmt *sql.Stmt\n\tdeleteSessionMessagesStmt *sql.Stmt\n\tgetFileStmt *sql.Stmt\n\tgetFileByPathAndSessionStmt *sql.Stmt\n\tgetMessageStmt *sql.Stmt\n\tgetSessionByIDStmt *sql.Stmt\n\tlistFilesByPathStmt *sql.Stmt\n\tlistFilesBySessionStmt *sql.Stmt\n\tlistLatestSessionFilesStmt *sql.Stmt\n\tlistMessagesBySessionStmt *sql.Stmt\n\tlistNewFilesStmt *sql.Stmt\n\tlistSessionsStmt *sql.Stmt\n\tupdateFileStmt *sql.Stmt\n\tupdateMessageStmt *sql.Stmt\n\tupdateSessionStmt *sql.Stmt\n}\n\nfunc (q *Queries) WithTx(tx *sql.Tx) *Queries {\n\treturn &Queries{\n\t\tdb: tx,\n\t\ttx: tx,\n\t\tcreateFileStmt: q.createFileStmt,\n\t\tcreateMessageStmt: q.createMessageStmt,\n\t\tcreateSessionStmt: q.createSessionStmt,\n\t\tdeleteFileStmt: q.deleteFileStmt,\n\t\tdeleteMessageStmt: q.deleteMessageStmt,\n\t\tdeleteSessionStmt: q.deleteSessionStmt,\n\t\tdeleteSessionFilesStmt: q.deleteSessionFilesStmt,\n\t\tdeleteSessionMessagesStmt: q.deleteSessionMessagesStmt,\n\t\tgetFileStmt: q.getFileStmt,\n\t\tgetFileByPathAndSessionStmt: q.getFileByPathAndSessionStmt,\n\t\tgetMessageStmt: q.getMessageStmt,\n\t\tgetSessionByIDStmt: q.getSessionByIDStmt,\n\t\tlistFilesByPathStmt: q.listFilesByPathStmt,\n\t\tlistFilesBySessionStmt: q.listFilesBySessionStmt,\n\t\tlistLatestSessionFilesStmt: q.listLatestSessionFilesStmt,\n\t\tlistMessagesBySessionStmt: q.listMessagesBySessionStmt,\n\t\tlistNewFilesStmt: q.listNewFilesStmt,\n\t\tlistSessionsStmt: q.listSessionsStmt,\n\t\tupdateFileStmt: q.updateFileStmt,\n\t\tupdateMessageStmt: q.updateMessageStmt,\n\t\tupdateSessionStmt: q.updateSessionStmt,\n\t}\n}\n"], ["/opencode/internal/lsp/language.go", "package lsp\n\nimport (\n\t\"path/filepath\"\n\t\"strings\"\n\n\t\"github.com/opencode-ai/opencode/internal/lsp/protocol\"\n)\n\nfunc DetectLanguageID(uri string) protocol.LanguageKind {\n\text := strings.ToLower(filepath.Ext(uri))\n\tswitch ext {\n\tcase \".abap\":\n\t\treturn protocol.LangABAP\n\tcase \".bat\":\n\t\treturn protocol.LangWindowsBat\n\tcase \".bib\", \".bibtex\":\n\t\treturn protocol.LangBibTeX\n\tcase \".clj\":\n\t\treturn protocol.LangClojure\n\tcase \".coffee\":\n\t\treturn protocol.LangCoffeescript\n\tcase \".c\":\n\t\treturn protocol.LangC\n\tcase \".cpp\", \".cxx\", \".cc\", \".c++\":\n\t\treturn protocol.LangCPP\n\tcase \".cs\":\n\t\treturn protocol.LangCSharp\n\tcase \".css\":\n\t\treturn protocol.LangCSS\n\tcase \".d\":\n\t\treturn protocol.LangD\n\tcase \".pas\", \".pascal\":\n\t\treturn protocol.LangDelphi\n\tcase \".diff\", \".patch\":\n\t\treturn protocol.LangDiff\n\tcase \".dart\":\n\t\treturn protocol.LangDart\n\tcase \".dockerfile\":\n\t\treturn protocol.LangDockerfile\n\tcase \".ex\", \".exs\":\n\t\treturn protocol.LangElixir\n\tcase \".erl\", \".hrl\":\n\t\treturn protocol.LangErlang\n\tcase \".fs\", \".fsi\", \".fsx\", \".fsscript\":\n\t\treturn protocol.LangFSharp\n\tcase \".gitcommit\":\n\t\treturn protocol.LangGitCommit\n\tcase \".gitrebase\":\n\t\treturn protocol.LangGitRebase\n\tcase \".go\":\n\t\treturn protocol.LangGo\n\tcase \".groovy\":\n\t\treturn protocol.LangGroovy\n\tcase \".hbs\", \".handlebars\":\n\t\treturn protocol.LangHandlebars\n\tcase \".hs\":\n\t\treturn protocol.LangHaskell\n\tcase \".html\", \".htm\":\n\t\treturn protocol.LangHTML\n\tcase \".ini\":\n\t\treturn protocol.LangIni\n\tcase \".java\":\n\t\treturn protocol.LangJava\n\tcase \".js\":\n\t\treturn protocol.LangJavaScript\n\tcase \".jsx\":\n\t\treturn protocol.LangJavaScriptReact\n\tcase \".json\":\n\t\treturn protocol.LangJSON\n\tcase \".tex\", \".latex\":\n\t\treturn protocol.LangLaTeX\n\tcase \".less\":\n\t\treturn protocol.LangLess\n\tcase \".lua\":\n\t\treturn protocol.LangLua\n\tcase \".makefile\", \"makefile\":\n\t\treturn protocol.LangMakefile\n\tcase \".md\", \".markdown\":\n\t\treturn protocol.LangMarkdown\n\tcase \".m\":\n\t\treturn protocol.LangObjectiveC\n\tcase \".mm\":\n\t\treturn protocol.LangObjectiveCPP\n\tcase \".pl\":\n\t\treturn protocol.LangPerl\n\tcase \".pm\":\n\t\treturn protocol.LangPerl6\n\tcase \".php\":\n\t\treturn protocol.LangPHP\n\tcase \".ps1\", \".psm1\":\n\t\treturn protocol.LangPowershell\n\tcase \".pug\", \".jade\":\n\t\treturn protocol.LangPug\n\tcase \".py\":\n\t\treturn protocol.LangPython\n\tcase \".r\":\n\t\treturn protocol.LangR\n\tcase \".cshtml\", \".razor\":\n\t\treturn protocol.LangRazor\n\tcase \".rb\":\n\t\treturn protocol.LangRuby\n\tcase \".rs\":\n\t\treturn protocol.LangRust\n\tcase \".scss\":\n\t\treturn protocol.LangSCSS\n\tcase \".sass\":\n\t\treturn protocol.LangSASS\n\tcase \".scala\":\n\t\treturn protocol.LangScala\n\tcase \".shader\":\n\t\treturn protocol.LangShaderLab\n\tcase \".sh\", \".bash\", \".zsh\", \".ksh\":\n\t\treturn protocol.LangShellScript\n\tcase \".sql\":\n\t\treturn protocol.LangSQL\n\tcase \".swift\":\n\t\treturn protocol.LangSwift\n\tcase \".ts\":\n\t\treturn protocol.LangTypeScript\n\tcase \".tsx\":\n\t\treturn protocol.LangTypeScriptReact\n\tcase \".xml\":\n\t\treturn protocol.LangXML\n\tcase \".xsl\":\n\t\treturn protocol.LangXSL\n\tcase \".yaml\", \".yml\":\n\t\treturn protocol.LangYAML\n\tdefault:\n\t\treturn protocol.LanguageKind(\"\") // Unknown language\n\t}\n}\n"], ["/opencode/internal/config/init.go", "package config\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"path/filepath\"\n)\n\nconst (\n\t// InitFlagFilename is the name of the file that indicates whether the project has been initialized\n\tInitFlagFilename = \"init\"\n)\n\n// ProjectInitFlag represents the initialization status for a project directory\ntype ProjectInitFlag struct {\n\tInitialized bool `json:\"initialized\"`\n}\n\n// ShouldShowInitDialog checks if the initialization dialog should be shown for the current directory\nfunc ShouldShowInitDialog() (bool, error) {\n\tif cfg == nil {\n\t\treturn false, fmt.Errorf(\"config not loaded\")\n\t}\n\n\t// Create the flag file path\n\tflagFilePath := filepath.Join(cfg.Data.Directory, InitFlagFilename)\n\n\t// Check if the flag file exists\n\t_, err := os.Stat(flagFilePath)\n\tif err == nil {\n\t\t// File exists, don't show the dialog\n\t\treturn false, nil\n\t}\n\n\t// If the error is not \"file not found\", return the error\n\tif !os.IsNotExist(err) {\n\t\treturn false, fmt.Errorf(\"failed to check init flag file: %w\", err)\n\t}\n\n\t// File doesn't exist, show the dialog\n\treturn true, nil\n}\n\n// MarkProjectInitialized marks the current project as initialized\nfunc MarkProjectInitialized() error {\n\tif cfg == nil {\n\t\treturn fmt.Errorf(\"config not loaded\")\n\t}\n\t// Create the flag file path\n\tflagFilePath := filepath.Join(cfg.Data.Directory, InitFlagFilename)\n\n\t// Create an empty file to mark the project as initialized\n\tfile, err := os.Create(flagFilePath)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to create init flag file: %w\", err)\n\t}\n\tdefer file.Close()\n\n\treturn nil\n}\n\n"], ["/opencode/internal/version/version.go", "package version\n\nimport \"runtime/debug\"\n\n// Build-time parameters set via -ldflags\nvar Version = \"unknown\"\n\n// A user may install pug using `go install github.com/opencode-ai/opencode@latest`.\n// without -ldflags, in which case the version above is unset. As a workaround\n// we use the embedded build version that *is* set when using `go install` (and\n// is only set for `go install` and not for `go build`).\nfunc init() {\n\tinfo, ok := debug.ReadBuildInfo()\n\tif !ok {\n\t\t// < go v1.18\n\t\treturn\n\t}\n\tmainVersion := info.Main.Version\n\tif mainVersion == \"\" || mainVersion == \"(devel)\" {\n\t\t// bin not built using `go install`\n\t\treturn\n\t}\n\t// bin built using `go install`\n\tVersion = mainVersion\n}\n"], ["/opencode/internal/llm/models/copilot.go", "package models\n\nconst (\n\tProviderCopilot ModelProvider = \"copilot\"\n\n\t// GitHub Copilot models\n\tCopilotGTP35Turbo ModelID = \"copilot.gpt-3.5-turbo\"\n\tCopilotGPT4o ModelID = \"copilot.gpt-4o\"\n\tCopilotGPT4oMini ModelID = \"copilot.gpt-4o-mini\"\n\tCopilotGPT41 ModelID = \"copilot.gpt-4.1\"\n\tCopilotClaude35 ModelID = \"copilot.claude-3.5-sonnet\"\n\tCopilotClaude37 ModelID = \"copilot.claude-3.7-sonnet\"\n\tCopilotClaude4 ModelID = \"copilot.claude-sonnet-4\"\n\tCopilotO1 ModelID = \"copilot.o1\"\n\tCopilotO3Mini ModelID = \"copilot.o3-mini\"\n\tCopilotO4Mini ModelID = \"copilot.o4-mini\"\n\tCopilotGemini20 ModelID = \"copilot.gemini-2.0-flash\"\n\tCopilotGemini25 ModelID = \"copilot.gemini-2.5-pro\"\n\tCopilotGPT4 ModelID = \"copilot.gpt-4\"\n\tCopilotClaude37Thought ModelID = \"copilot.claude-3.7-sonnet-thought\"\n)\n\nvar CopilotAnthropicModels = []ModelID{\n\tCopilotClaude35,\n\tCopilotClaude37,\n\tCopilotClaude37Thought,\n\tCopilotClaude4,\n}\n\n// GitHub Copilot models available through GitHub's API\nvar CopilotModels = map[ModelID]Model{\n\tCopilotGTP35Turbo: {\n\t\tID: CopilotGTP35Turbo,\n\t\tName: \"GitHub Copilot GPT-3.5-turbo\",\n\t\tProvider: ProviderCopilot,\n\t\tAPIModel: \"gpt-3.5-turbo\",\n\t\tCostPer1MIn: 0.0, // Included in GitHub Copilot subscription\n\t\tCostPer1MInCached: 0.0,\n\t\tCostPer1MOutCached: 0.0,\n\t\tCostPer1MOut: 0.0,\n\t\tContextWindow: 16_384,\n\t\tDefaultMaxTokens: 4096,\n\t\tSupportsAttachments: true,\n\t},\n\tCopilotGPT4o: {\n\t\tID: CopilotGPT4o,\n\t\tName: \"GitHub Copilot GPT-4o\",\n\t\tProvider: ProviderCopilot,\n\t\tAPIModel: \"gpt-4o\",\n\t\tCostPer1MIn: 0.0, // Included in GitHub Copilot subscription\n\t\tCostPer1MInCached: 0.0,\n\t\tCostPer1MOutCached: 0.0,\n\t\tCostPer1MOut: 0.0,\n\t\tContextWindow: 128_000,\n\t\tDefaultMaxTokens: 16384,\n\t\tSupportsAttachments: true,\n\t},\n\tCopilotGPT4oMini: {\n\t\tID: CopilotGPT4oMini,\n\t\tName: \"GitHub Copilot GPT-4o Mini\",\n\t\tProvider: ProviderCopilot,\n\t\tAPIModel: \"gpt-4o-mini\",\n\t\tCostPer1MIn: 0.0, // Included in GitHub Copilot subscription\n\t\tCostPer1MInCached: 0.0,\n\t\tCostPer1MOutCached: 0.0,\n\t\tCostPer1MOut: 0.0,\n\t\tContextWindow: 128_000,\n\t\tDefaultMaxTokens: 4096,\n\t\tSupportsAttachments: true,\n\t},\n\tCopilotGPT41: {\n\t\tID: CopilotGPT41,\n\t\tName: \"GitHub Copilot GPT-4.1\",\n\t\tProvider: ProviderCopilot,\n\t\tAPIModel: \"gpt-4.1\",\n\t\tCostPer1MIn: 0.0, // Included in GitHub Copilot subscription\n\t\tCostPer1MInCached: 0.0,\n\t\tCostPer1MOutCached: 0.0,\n\t\tCostPer1MOut: 0.0,\n\t\tContextWindow: 128_000,\n\t\tDefaultMaxTokens: 16384,\n\t\tCanReason: true,\n\t\tSupportsAttachments: true,\n\t},\n\tCopilotClaude35: {\n\t\tID: CopilotClaude35,\n\t\tName: \"GitHub Copilot Claude 3.5 Sonnet\",\n\t\tProvider: ProviderCopilot,\n\t\tAPIModel: \"claude-3.5-sonnet\",\n\t\tCostPer1MIn: 0.0, // Included in GitHub Copilot subscription\n\t\tCostPer1MInCached: 0.0,\n\t\tCostPer1MOutCached: 0.0,\n\t\tCostPer1MOut: 0.0,\n\t\tContextWindow: 90_000,\n\t\tDefaultMaxTokens: 8192,\n\t\tSupportsAttachments: true,\n\t},\n\tCopilotClaude37: {\n\t\tID: CopilotClaude37,\n\t\tName: \"GitHub Copilot Claude 3.7 Sonnet\",\n\t\tProvider: ProviderCopilot,\n\t\tAPIModel: \"claude-3.7-sonnet\",\n\t\tCostPer1MIn: 0.0, // Included in GitHub Copilot subscription\n\t\tCostPer1MInCached: 0.0,\n\t\tCostPer1MOutCached: 0.0,\n\t\tCostPer1MOut: 0.0,\n\t\tContextWindow: 200_000,\n\t\tDefaultMaxTokens: 16384,\n\t\tSupportsAttachments: true,\n\t},\n\tCopilotClaude4: {\n\t\tID: CopilotClaude4,\n\t\tName: \"GitHub Copilot Claude Sonnet 4\",\n\t\tProvider: ProviderCopilot,\n\t\tAPIModel: \"claude-sonnet-4\",\n\t\tCostPer1MIn: 0.0, // Included in GitHub Copilot subscription\n\t\tCostPer1MInCached: 0.0,\n\t\tCostPer1MOutCached: 0.0,\n\t\tCostPer1MOut: 0.0,\n\t\tContextWindow: 128_000,\n\t\tDefaultMaxTokens: 16000,\n\t\tSupportsAttachments: true,\n\t},\n\tCopilotO1: {\n\t\tID: CopilotO1,\n\t\tName: \"GitHub Copilot o1\",\n\t\tProvider: ProviderCopilot,\n\t\tAPIModel: \"o1\",\n\t\tCostPer1MIn: 0.0, // Included in GitHub Copilot subscription\n\t\tCostPer1MInCached: 0.0,\n\t\tCostPer1MOutCached: 0.0,\n\t\tCostPer1MOut: 0.0,\n\t\tContextWindow: 200_000,\n\t\tDefaultMaxTokens: 100_000,\n\t\tCanReason: true,\n\t\tSupportsAttachments: false,\n\t},\n\tCopilotO3Mini: {\n\t\tID: CopilotO3Mini,\n\t\tName: \"GitHub Copilot o3-mini\",\n\t\tProvider: ProviderCopilot,\n\t\tAPIModel: \"o3-mini\",\n\t\tCostPer1MIn: 0.0, // Included in GitHub Copilot subscription\n\t\tCostPer1MInCached: 0.0,\n\t\tCostPer1MOutCached: 0.0,\n\t\tCostPer1MOut: 0.0,\n\t\tContextWindow: 200_000,\n\t\tDefaultMaxTokens: 100_000,\n\t\tCanReason: true,\n\t\tSupportsAttachments: false,\n\t},\n\tCopilotO4Mini: {\n\t\tID: CopilotO4Mini,\n\t\tName: \"GitHub Copilot o4-mini\",\n\t\tProvider: ProviderCopilot,\n\t\tAPIModel: \"o4-mini\",\n\t\tCostPer1MIn: 0.0, // Included in GitHub Copilot subscription\n\t\tCostPer1MInCached: 0.0,\n\t\tCostPer1MOutCached: 0.0,\n\t\tCostPer1MOut: 0.0,\n\t\tContextWindow: 128_000,\n\t\tDefaultMaxTokens: 16_384,\n\t\tCanReason: true,\n\t\tSupportsAttachments: true,\n\t},\n\tCopilotGemini20: {\n\t\tID: CopilotGemini20,\n\t\tName: \"GitHub Copilot Gemini 2.0 Flash\",\n\t\tProvider: ProviderCopilot,\n\t\tAPIModel: \"gemini-2.0-flash-001\",\n\t\tCostPer1MIn: 0.0, // Included in GitHub Copilot subscription\n\t\tCostPer1MInCached: 0.0,\n\t\tCostPer1MOutCached: 0.0,\n\t\tCostPer1MOut: 0.0,\n\t\tContextWindow: 1_000_000,\n\t\tDefaultMaxTokens: 8192,\n\t\tSupportsAttachments: true,\n\t},\n\tCopilotGemini25: {\n\t\tID: CopilotGemini25,\n\t\tName: \"GitHub Copilot Gemini 2.5 Pro\",\n\t\tProvider: ProviderCopilot,\n\t\tAPIModel: \"gemini-2.5-pro\",\n\t\tCostPer1MIn: 0.0, // Included in GitHub Copilot subscription\n\t\tCostPer1MInCached: 0.0,\n\t\tCostPer1MOutCached: 0.0,\n\t\tCostPer1MOut: 0.0,\n\t\tContextWindow: 128_000,\n\t\tDefaultMaxTokens: 64000,\n\t\tSupportsAttachments: true,\n\t},\n\tCopilotGPT4: {\n\t\tID: CopilotGPT4,\n\t\tName: \"GitHub Copilot GPT-4\",\n\t\tProvider: ProviderCopilot,\n\t\tAPIModel: \"gpt-4\",\n\t\tCostPer1MIn: 0.0, // Included in GitHub Copilot subscription\n\t\tCostPer1MInCached: 0.0,\n\t\tCostPer1MOutCached: 0.0,\n\t\tCostPer1MOut: 0.0,\n\t\tContextWindow: 32_768,\n\t\tDefaultMaxTokens: 4096,\n\t\tSupportsAttachments: true,\n\t},\n\tCopilotClaude37Thought: {\n\t\tID: CopilotClaude37Thought,\n\t\tName: \"GitHub Copilot Claude 3.7 Sonnet Thinking\",\n\t\tProvider: ProviderCopilot,\n\t\tAPIModel: \"claude-3.7-sonnet-thought\",\n\t\tCostPer1MIn: 0.0, // Included in GitHub Copilot subscription\n\t\tCostPer1MInCached: 0.0,\n\t\tCostPer1MOutCached: 0.0,\n\t\tCostPer1MOut: 0.0,\n\t\tContextWindow: 200_000,\n\t\tDefaultMaxTokens: 16384,\n\t\tCanReason: true,\n\t\tSupportsAttachments: true,\n\t},\n}\n"], ["/opencode/internal/llm/models/models.go", "package models\n\nimport \"maps\"\n\ntype (\n\tModelID string\n\tModelProvider string\n)\n\ntype Model struct {\n\tID ModelID `json:\"id\"`\n\tName string `json:\"name\"`\n\tProvider ModelProvider `json:\"provider\"`\n\tAPIModel string `json:\"api_model\"`\n\tCostPer1MIn float64 `json:\"cost_per_1m_in\"`\n\tCostPer1MOut float64 `json:\"cost_per_1m_out\"`\n\tCostPer1MInCached float64 `json:\"cost_per_1m_in_cached\"`\n\tCostPer1MOutCached float64 `json:\"cost_per_1m_out_cached\"`\n\tContextWindow int64 `json:\"context_window\"`\n\tDefaultMaxTokens int64 `json:\"default_max_tokens\"`\n\tCanReason bool `json:\"can_reason\"`\n\tSupportsAttachments bool `json:\"supports_attachments\"`\n}\n\n// Model IDs\nconst ( // GEMINI\n\t// Bedrock\n\tBedrockClaude37Sonnet ModelID = \"bedrock.claude-3.7-sonnet\"\n)\n\nconst (\n\tProviderBedrock ModelProvider = \"bedrock\"\n\t// ForTests\n\tProviderMock ModelProvider = \"__mock\"\n)\n\n// Providers in order of popularity\nvar ProviderPopularity = map[ModelProvider]int{\n\tProviderCopilot: 1,\n\tProviderAnthropic: 2,\n\tProviderOpenAI: 3,\n\tProviderGemini: 4,\n\tProviderGROQ: 5,\n\tProviderOpenRouter: 6,\n\tProviderBedrock: 7,\n\tProviderAzure: 8,\n\tProviderVertexAI: 9,\n}\n\nvar SupportedModels = map[ModelID]Model{\n\t//\n\t// // GEMINI\n\t// GEMINI25: {\n\t// \tID: GEMINI25,\n\t// \tName: \"Gemini 2.5 Pro\",\n\t// \tProvider: ProviderGemini,\n\t// \tAPIModel: \"gemini-2.5-pro-exp-03-25\",\n\t// \tCostPer1MIn: 0,\n\t// \tCostPer1MInCached: 0,\n\t// \tCostPer1MOutCached: 0,\n\t// \tCostPer1MOut: 0,\n\t// },\n\t//\n\t// GRMINI20Flash: {\n\t// \tID: GRMINI20Flash,\n\t// \tName: \"Gemini 2.0 Flash\",\n\t// \tProvider: ProviderGemini,\n\t// \tAPIModel: \"gemini-2.0-flash\",\n\t// \tCostPer1MIn: 0.1,\n\t// \tCostPer1MInCached: 0,\n\t// \tCostPer1MOutCached: 0.025,\n\t// \tCostPer1MOut: 0.4,\n\t// },\n\t//\n\t// // Bedrock\n\tBedrockClaude37Sonnet: {\n\t\tID: BedrockClaude37Sonnet,\n\t\tName: \"Bedrock: Claude 3.7 Sonnet\",\n\t\tProvider: ProviderBedrock,\n\t\tAPIModel: \"anthropic.claude-3-7-sonnet-20250219-v1:0\",\n\t\tCostPer1MIn: 3.0,\n\t\tCostPer1MInCached: 3.75,\n\t\tCostPer1MOutCached: 0.30,\n\t\tCostPer1MOut: 15.0,\n\t},\n}\n\nfunc init() {\n\tmaps.Copy(SupportedModels, AnthropicModels)\n\tmaps.Copy(SupportedModels, OpenAIModels)\n\tmaps.Copy(SupportedModels, GeminiModels)\n\tmaps.Copy(SupportedModels, GroqModels)\n\tmaps.Copy(SupportedModels, AzureModels)\n\tmaps.Copy(SupportedModels, OpenRouterModels)\n\tmaps.Copy(SupportedModels, XAIModels)\n\tmaps.Copy(SupportedModels, VertexAIGeminiModels)\n\tmaps.Copy(SupportedModels, CopilotModels)\n}\n"], ["/opencode/internal/llm/provider/vertexai.go", "package provider\n\nimport (\n\t\"context\"\n\t\"os\"\n\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n\t\"google.golang.org/genai\"\n)\n\ntype VertexAIClient ProviderClient\n\nfunc newVertexAIClient(opts providerClientOptions) VertexAIClient {\n\tgeminiOpts := geminiOptions{}\n\tfor _, o := range opts.geminiOptions {\n\t\to(&geminiOpts)\n\t}\n\n\tclient, err := genai.NewClient(context.Background(), &genai.ClientConfig{\n\t\tProject: os.Getenv(\"VERTEXAI_PROJECT\"),\n\t\tLocation: os.Getenv(\"VERTEXAI_LOCATION\"),\n\t\tBackend: genai.BackendVertexAI,\n\t})\n\tif err != nil {\n\t\tlogging.Error(\"Failed to create VertexAI client\", \"error\", err)\n\t\treturn nil\n\t}\n\n\treturn &geminiClient{\n\t\tproviderOptions: opts,\n\t\toptions: geminiOpts,\n\t\tclient: client,\n\t}\n}\n"], ["/opencode/internal/llm/prompt/task.go", "package prompt\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/opencode-ai/opencode/internal/llm/models\"\n)\n\nfunc TaskPrompt(_ models.ModelProvider) string {\n\tagentPrompt := `You are an agent for OpenCode. Given the user's prompt, you should use the tools available to you to answer the user's question.\nNotes:\n1. IMPORTANT: You should be concise, direct, and to the point, since your responses will be displayed on a command line interface. Answer the user's question directly, without elaboration, explanation, or details. One word answers are best. Avoid introductions, conclusions, and explanations. You MUST avoid text before/after your response, such as \"The answer is .\", \"Here is the content of the file...\" or \"Based on the information provided, the answer is...\" or \"Here is what I will do next...\".\n2. When relevant, share file names and code snippets relevant to the query\n3. Any file paths you return in your final response MUST be absolute. DO NOT use relative paths.`\n\n\treturn fmt.Sprintf(\"%s\\n%s\\n\", agentPrompt, getEnvironmentInfo())\n}\n"], ["/opencode/internal/lsp/protocol.go", "package lsp\n\nimport (\n\t\"encoding/json\"\n)\n\n// Message represents a JSON-RPC 2.0 message\ntype Message struct {\n\tJSONRPC string `json:\"jsonrpc\"`\n\tID int32 `json:\"id,omitempty\"`\n\tMethod string `json:\"method,omitempty\"`\n\tParams json.RawMessage `json:\"params,omitempty\"`\n\tResult json.RawMessage `json:\"result,omitempty\"`\n\tError *ResponseError `json:\"error,omitempty\"`\n}\n\n// ResponseError represents a JSON-RPC 2.0 error\ntype ResponseError struct {\n\tCode int `json:\"code\"`\n\tMessage string `json:\"message\"`\n}\n\nfunc NewRequest(id int32, method string, params any) (*Message, error) {\n\tparamsJSON, err := json.Marshal(params)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Message{\n\t\tJSONRPC: \"2.0\",\n\t\tID: id,\n\t\tMethod: method,\n\t\tParams: paramsJSON,\n\t}, nil\n}\n\nfunc NewNotification(method string, params any) (*Message, error) {\n\tparamsJSON, err := json.Marshal(params)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Message{\n\t\tJSONRPC: \"2.0\",\n\t\tMethod: method,\n\t\tParams: paramsJSON,\n\t}, nil\n}\n"], ["/opencode/internal/llm/models/groq.go", "package models\n\nconst (\n\tProviderGROQ ModelProvider = \"groq\"\n\n\t// GROQ\n\tQWENQwq ModelID = \"qwen-qwq\"\n\n\t// GROQ preview models\n\tLlama4Scout ModelID = \"meta-llama/llama-4-scout-17b-16e-instruct\"\n\tLlama4Maverick ModelID = \"meta-llama/llama-4-maverick-17b-128e-instruct\"\n\tLlama3_3_70BVersatile ModelID = \"llama-3.3-70b-versatile\"\n\tDeepseekR1DistillLlama70b ModelID = \"deepseek-r1-distill-llama-70b\"\n)\n\nvar GroqModels = map[ModelID]Model{\n\t//\n\t// GROQ\n\tQWENQwq: {\n\t\tID: QWENQwq,\n\t\tName: \"Qwen Qwq\",\n\t\tProvider: ProviderGROQ,\n\t\tAPIModel: \"qwen-qwq-32b\",\n\t\tCostPer1MIn: 0.29,\n\t\tCostPer1MInCached: 0.275,\n\t\tCostPer1MOutCached: 0.0,\n\t\tCostPer1MOut: 0.39,\n\t\tContextWindow: 128_000,\n\t\tDefaultMaxTokens: 50000,\n\t\t// for some reason, the groq api doesn't like the reasoningEffort parameter\n\t\tCanReason: false,\n\t\tSupportsAttachments: false,\n\t},\n\n\tLlama4Scout: {\n\t\tID: Llama4Scout,\n\t\tName: \"Llama4Scout\",\n\t\tProvider: ProviderGROQ,\n\t\tAPIModel: \"meta-llama/llama-4-scout-17b-16e-instruct\",\n\t\tCostPer1MIn: 0.11,\n\t\tCostPer1MInCached: 0,\n\t\tCostPer1MOutCached: 0,\n\t\tCostPer1MOut: 0.34,\n\t\tContextWindow: 128_000, // 10M when?\n\t\tSupportsAttachments: true,\n\t},\n\n\tLlama4Maverick: {\n\t\tID: Llama4Maverick,\n\t\tName: \"Llama4Maverick\",\n\t\tProvider: ProviderGROQ,\n\t\tAPIModel: \"meta-llama/llama-4-maverick-17b-128e-instruct\",\n\t\tCostPer1MIn: 0.20,\n\t\tCostPer1MInCached: 0,\n\t\tCostPer1MOutCached: 0,\n\t\tCostPer1MOut: 0.20,\n\t\tContextWindow: 128_000,\n\t\tSupportsAttachments: true,\n\t},\n\n\tLlama3_3_70BVersatile: {\n\t\tID: Llama3_3_70BVersatile,\n\t\tName: \"Llama3_3_70BVersatile\",\n\t\tProvider: ProviderGROQ,\n\t\tAPIModel: \"llama-3.3-70b-versatile\",\n\t\tCostPer1MIn: 0.59,\n\t\tCostPer1MInCached: 0,\n\t\tCostPer1MOutCached: 0,\n\t\tCostPer1MOut: 0.79,\n\t\tContextWindow: 128_000,\n\t\tSupportsAttachments: false,\n\t},\n\n\tDeepseekR1DistillLlama70b: {\n\t\tID: DeepseekR1DistillLlama70b,\n\t\tName: \"DeepseekR1DistillLlama70b\",\n\t\tProvider: ProviderGROQ,\n\t\tAPIModel: \"deepseek-r1-distill-llama-70b\",\n\t\tCostPer1MIn: 0.75,\n\t\tCostPer1MInCached: 0,\n\t\tCostPer1MOutCached: 0,\n\t\tCostPer1MOut: 0.99,\n\t\tContextWindow: 128_000,\n\t\tCanReason: true,\n\t\tSupportsAttachments: false,\n\t},\n}\n"], ["/opencode/internal/llm/models/openai.go", "package models\n\nconst (\n\tProviderOpenAI ModelProvider = \"openai\"\n\n\tGPT41 ModelID = \"gpt-4.1\"\n\tGPT41Mini ModelID = \"gpt-4.1-mini\"\n\tGPT41Nano ModelID = \"gpt-4.1-nano\"\n\tGPT45Preview ModelID = \"gpt-4.5-preview\"\n\tGPT4o ModelID = \"gpt-4o\"\n\tGPT4oMini ModelID = \"gpt-4o-mini\"\n\tO1 ModelID = \"o1\"\n\tO1Pro ModelID = \"o1-pro\"\n\tO1Mini ModelID = \"o1-mini\"\n\tO3 ModelID = \"o3\"\n\tO3Mini ModelID = \"o3-mini\"\n\tO4Mini ModelID = \"o4-mini\"\n)\n\nvar OpenAIModels = map[ModelID]Model{\n\tGPT41: {\n\t\tID: GPT41,\n\t\tName: \"GPT 4.1\",\n\t\tProvider: ProviderOpenAI,\n\t\tAPIModel: \"gpt-4.1\",\n\t\tCostPer1MIn: 2.00,\n\t\tCostPer1MInCached: 0.50,\n\t\tCostPer1MOutCached: 0.0,\n\t\tCostPer1MOut: 8.00,\n\t\tContextWindow: 1_047_576,\n\t\tDefaultMaxTokens: 20000,\n\t\tSupportsAttachments: true,\n\t},\n\tGPT41Mini: {\n\t\tID: GPT41Mini,\n\t\tName: \"GPT 4.1 mini\",\n\t\tProvider: ProviderOpenAI,\n\t\tAPIModel: \"gpt-4.1\",\n\t\tCostPer1MIn: 0.40,\n\t\tCostPer1MInCached: 0.10,\n\t\tCostPer1MOutCached: 0.0,\n\t\tCostPer1MOut: 1.60,\n\t\tContextWindow: 200_000,\n\t\tDefaultMaxTokens: 20000,\n\t\tSupportsAttachments: true,\n\t},\n\tGPT41Nano: {\n\t\tID: GPT41Nano,\n\t\tName: \"GPT 4.1 nano\",\n\t\tProvider: ProviderOpenAI,\n\t\tAPIModel: \"gpt-4.1-nano\",\n\t\tCostPer1MIn: 0.10,\n\t\tCostPer1MInCached: 0.025,\n\t\tCostPer1MOutCached: 0.0,\n\t\tCostPer1MOut: 0.40,\n\t\tContextWindow: 1_047_576,\n\t\tDefaultMaxTokens: 20000,\n\t\tSupportsAttachments: true,\n\t},\n\tGPT45Preview: {\n\t\tID: GPT45Preview,\n\t\tName: \"GPT 4.5 preview\",\n\t\tProvider: ProviderOpenAI,\n\t\tAPIModel: \"gpt-4.5-preview\",\n\t\tCostPer1MIn: 75.00,\n\t\tCostPer1MInCached: 37.50,\n\t\tCostPer1MOutCached: 0.0,\n\t\tCostPer1MOut: 150.00,\n\t\tContextWindow: 128_000,\n\t\tDefaultMaxTokens: 15000,\n\t\tSupportsAttachments: true,\n\t},\n\tGPT4o: {\n\t\tID: GPT4o,\n\t\tName: \"GPT 4o\",\n\t\tProvider: ProviderOpenAI,\n\t\tAPIModel: \"gpt-4o\",\n\t\tCostPer1MIn: 2.50,\n\t\tCostPer1MInCached: 1.25,\n\t\tCostPer1MOutCached: 0.0,\n\t\tCostPer1MOut: 10.00,\n\t\tContextWindow: 128_000,\n\t\tDefaultMaxTokens: 4096,\n\t\tSupportsAttachments: true,\n\t},\n\tGPT4oMini: {\n\t\tID: GPT4oMini,\n\t\tName: \"GPT 4o mini\",\n\t\tProvider: ProviderOpenAI,\n\t\tAPIModel: \"gpt-4o-mini\",\n\t\tCostPer1MIn: 0.15,\n\t\tCostPer1MInCached: 0.075,\n\t\tCostPer1MOutCached: 0.0,\n\t\tCostPer1MOut: 0.60,\n\t\tContextWindow: 128_000,\n\t\tSupportsAttachments: true,\n\t},\n\tO1: {\n\t\tID: O1,\n\t\tName: \"O1\",\n\t\tProvider: ProviderOpenAI,\n\t\tAPIModel: \"o1\",\n\t\tCostPer1MIn: 15.00,\n\t\tCostPer1MInCached: 7.50,\n\t\tCostPer1MOutCached: 0.0,\n\t\tCostPer1MOut: 60.00,\n\t\tContextWindow: 200_000,\n\t\tDefaultMaxTokens: 50000,\n\t\tCanReason: true,\n\t\tSupportsAttachments: true,\n\t},\n\tO1Pro: {\n\t\tID: O1Pro,\n\t\tName: \"o1 pro\",\n\t\tProvider: ProviderOpenAI,\n\t\tAPIModel: \"o1-pro\",\n\t\tCostPer1MIn: 150.00,\n\t\tCostPer1MInCached: 0.0,\n\t\tCostPer1MOutCached: 0.0,\n\t\tCostPer1MOut: 600.00,\n\t\tContextWindow: 200_000,\n\t\tDefaultMaxTokens: 50000,\n\t\tCanReason: true,\n\t\tSupportsAttachments: true,\n\t},\n\tO1Mini: {\n\t\tID: O1Mini,\n\t\tName: \"o1 mini\",\n\t\tProvider: ProviderOpenAI,\n\t\tAPIModel: \"o1-mini\",\n\t\tCostPer1MIn: 1.10,\n\t\tCostPer1MInCached: 0.55,\n\t\tCostPer1MOutCached: 0.0,\n\t\tCostPer1MOut: 4.40,\n\t\tContextWindow: 128_000,\n\t\tDefaultMaxTokens: 50000,\n\t\tCanReason: true,\n\t\tSupportsAttachments: true,\n\t},\n\tO3: {\n\t\tID: O3,\n\t\tName: \"o3\",\n\t\tProvider: ProviderOpenAI,\n\t\tAPIModel: \"o3\",\n\t\tCostPer1MIn: 10.00,\n\t\tCostPer1MInCached: 2.50,\n\t\tCostPer1MOutCached: 0.0,\n\t\tCostPer1MOut: 40.00,\n\t\tContextWindow: 200_000,\n\t\tCanReason: true,\n\t\tSupportsAttachments: true,\n\t},\n\tO3Mini: {\n\t\tID: O3Mini,\n\t\tName: \"o3 mini\",\n\t\tProvider: ProviderOpenAI,\n\t\tAPIModel: \"o3-mini\",\n\t\tCostPer1MIn: 1.10,\n\t\tCostPer1MInCached: 0.55,\n\t\tCostPer1MOutCached: 0.0,\n\t\tCostPer1MOut: 4.40,\n\t\tContextWindow: 200_000,\n\t\tDefaultMaxTokens: 50000,\n\t\tCanReason: true,\n\t\tSupportsAttachments: false,\n\t},\n\tO4Mini: {\n\t\tID: O4Mini,\n\t\tName: \"o4 mini\",\n\t\tProvider: ProviderOpenAI,\n\t\tAPIModel: \"o4-mini\",\n\t\tCostPer1MIn: 1.10,\n\t\tCostPer1MInCached: 0.275,\n\t\tCostPer1MOutCached: 0.0,\n\t\tCostPer1MOut: 4.40,\n\t\tContextWindow: 128_000,\n\t\tDefaultMaxTokens: 50000,\n\t\tCanReason: true,\n\t\tSupportsAttachments: true,\n\t},\n}\n"], ["/opencode/internal/llm/models/azure.go", "package models\n\nconst ProviderAzure ModelProvider = \"azure\"\n\nconst (\n\tAzureGPT41 ModelID = \"azure.gpt-4.1\"\n\tAzureGPT41Mini ModelID = \"azure.gpt-4.1-mini\"\n\tAzureGPT41Nano ModelID = \"azure.gpt-4.1-nano\"\n\tAzureGPT45Preview ModelID = \"azure.gpt-4.5-preview\"\n\tAzureGPT4o ModelID = \"azure.gpt-4o\"\n\tAzureGPT4oMini ModelID = \"azure.gpt-4o-mini\"\n\tAzureO1 ModelID = \"azure.o1\"\n\tAzureO1Mini ModelID = \"azure.o1-mini\"\n\tAzureO3 ModelID = \"azure.o3\"\n\tAzureO3Mini ModelID = \"azure.o3-mini\"\n\tAzureO4Mini ModelID = \"azure.o4-mini\"\n)\n\nvar AzureModels = map[ModelID]Model{\n\tAzureGPT41: {\n\t\tID: AzureGPT41,\n\t\tName: \"Azure OpenAI – GPT 4.1\",\n\t\tProvider: ProviderAzure,\n\t\tAPIModel: \"gpt-4.1\",\n\t\tCostPer1MIn: OpenAIModels[GPT41].CostPer1MIn,\n\t\tCostPer1MInCached: OpenAIModels[GPT41].CostPer1MInCached,\n\t\tCostPer1MOut: OpenAIModels[GPT41].CostPer1MOut,\n\t\tCostPer1MOutCached: OpenAIModels[GPT41].CostPer1MOutCached,\n\t\tContextWindow: OpenAIModels[GPT41].ContextWindow,\n\t\tDefaultMaxTokens: OpenAIModels[GPT41].DefaultMaxTokens,\n\t\tSupportsAttachments: true,\n\t},\n\tAzureGPT41Mini: {\n\t\tID: AzureGPT41Mini,\n\t\tName: \"Azure OpenAI – GPT 4.1 mini\",\n\t\tProvider: ProviderAzure,\n\t\tAPIModel: \"gpt-4.1-mini\",\n\t\tCostPer1MIn: OpenAIModels[GPT41Mini].CostPer1MIn,\n\t\tCostPer1MInCached: OpenAIModels[GPT41Mini].CostPer1MInCached,\n\t\tCostPer1MOut: OpenAIModels[GPT41Mini].CostPer1MOut,\n\t\tCostPer1MOutCached: OpenAIModels[GPT41Mini].CostPer1MOutCached,\n\t\tContextWindow: OpenAIModels[GPT41Mini].ContextWindow,\n\t\tDefaultMaxTokens: OpenAIModels[GPT41Mini].DefaultMaxTokens,\n\t\tSupportsAttachments: true,\n\t},\n\tAzureGPT41Nano: {\n\t\tID: AzureGPT41Nano,\n\t\tName: \"Azure OpenAI – GPT 4.1 nano\",\n\t\tProvider: ProviderAzure,\n\t\tAPIModel: \"gpt-4.1-nano\",\n\t\tCostPer1MIn: OpenAIModels[GPT41Nano].CostPer1MIn,\n\t\tCostPer1MInCached: OpenAIModels[GPT41Nano].CostPer1MInCached,\n\t\tCostPer1MOut: OpenAIModels[GPT41Nano].CostPer1MOut,\n\t\tCostPer1MOutCached: OpenAIModels[GPT41Nano].CostPer1MOutCached,\n\t\tContextWindow: OpenAIModels[GPT41Nano].ContextWindow,\n\t\tDefaultMaxTokens: OpenAIModels[GPT41Nano].DefaultMaxTokens,\n\t\tSupportsAttachments: true,\n\t},\n\tAzureGPT45Preview: {\n\t\tID: AzureGPT45Preview,\n\t\tName: \"Azure OpenAI – GPT 4.5 preview\",\n\t\tProvider: ProviderAzure,\n\t\tAPIModel: \"gpt-4.5-preview\",\n\t\tCostPer1MIn: OpenAIModels[GPT45Preview].CostPer1MIn,\n\t\tCostPer1MInCached: OpenAIModels[GPT45Preview].CostPer1MInCached,\n\t\tCostPer1MOut: OpenAIModels[GPT45Preview].CostPer1MOut,\n\t\tCostPer1MOutCached: OpenAIModels[GPT45Preview].CostPer1MOutCached,\n\t\tContextWindow: OpenAIModels[GPT45Preview].ContextWindow,\n\t\tDefaultMaxTokens: OpenAIModels[GPT45Preview].DefaultMaxTokens,\n\t\tSupportsAttachments: true,\n\t},\n\tAzureGPT4o: {\n\t\tID: AzureGPT4o,\n\t\tName: \"Azure OpenAI – GPT-4o\",\n\t\tProvider: ProviderAzure,\n\t\tAPIModel: \"gpt-4o\",\n\t\tCostPer1MIn: OpenAIModels[GPT4o].CostPer1MIn,\n\t\tCostPer1MInCached: OpenAIModels[GPT4o].CostPer1MInCached,\n\t\tCostPer1MOut: OpenAIModels[GPT4o].CostPer1MOut,\n\t\tCostPer1MOutCached: OpenAIModels[GPT4o].CostPer1MOutCached,\n\t\tContextWindow: OpenAIModels[GPT4o].ContextWindow,\n\t\tDefaultMaxTokens: OpenAIModels[GPT4o].DefaultMaxTokens,\n\t\tSupportsAttachments: true,\n\t},\n\tAzureGPT4oMini: {\n\t\tID: AzureGPT4oMini,\n\t\tName: \"Azure OpenAI – GPT-4o mini\",\n\t\tProvider: ProviderAzure,\n\t\tAPIModel: \"gpt-4o-mini\",\n\t\tCostPer1MIn: OpenAIModels[GPT4oMini].CostPer1MIn,\n\t\tCostPer1MInCached: OpenAIModels[GPT4oMini].CostPer1MInCached,\n\t\tCostPer1MOut: OpenAIModels[GPT4oMini].CostPer1MOut,\n\t\tCostPer1MOutCached: OpenAIModels[GPT4oMini].CostPer1MOutCached,\n\t\tContextWindow: OpenAIModels[GPT4oMini].ContextWindow,\n\t\tDefaultMaxTokens: OpenAIModels[GPT4oMini].DefaultMaxTokens,\n\t\tSupportsAttachments: true,\n\t},\n\tAzureO1: {\n\t\tID: AzureO1,\n\t\tName: \"Azure OpenAI – O1\",\n\t\tProvider: ProviderAzure,\n\t\tAPIModel: \"o1\",\n\t\tCostPer1MIn: OpenAIModels[O1].CostPer1MIn,\n\t\tCostPer1MInCached: OpenAIModels[O1].CostPer1MInCached,\n\t\tCostPer1MOut: OpenAIModels[O1].CostPer1MOut,\n\t\tCostPer1MOutCached: OpenAIModels[O1].CostPer1MOutCached,\n\t\tContextWindow: OpenAIModels[O1].ContextWindow,\n\t\tDefaultMaxTokens: OpenAIModels[O1].DefaultMaxTokens,\n\t\tCanReason: OpenAIModels[O1].CanReason,\n\t\tSupportsAttachments: true,\n\t},\n\tAzureO1Mini: {\n\t\tID: AzureO1Mini,\n\t\tName: \"Azure OpenAI – O1 mini\",\n\t\tProvider: ProviderAzure,\n\t\tAPIModel: \"o1-mini\",\n\t\tCostPer1MIn: OpenAIModels[O1Mini].CostPer1MIn,\n\t\tCostPer1MInCached: OpenAIModels[O1Mini].CostPer1MInCached,\n\t\tCostPer1MOut: OpenAIModels[O1Mini].CostPer1MOut,\n\t\tCostPer1MOutCached: OpenAIModels[O1Mini].CostPer1MOutCached,\n\t\tContextWindow: OpenAIModels[O1Mini].ContextWindow,\n\t\tDefaultMaxTokens: OpenAIModels[O1Mini].DefaultMaxTokens,\n\t\tCanReason: OpenAIModels[O1Mini].CanReason,\n\t\tSupportsAttachments: true,\n\t},\n\tAzureO3: {\n\t\tID: AzureO3,\n\t\tName: \"Azure OpenAI – O3\",\n\t\tProvider: ProviderAzure,\n\t\tAPIModel: \"o3\",\n\t\tCostPer1MIn: OpenAIModels[O3].CostPer1MIn,\n\t\tCostPer1MInCached: OpenAIModels[O3].CostPer1MInCached,\n\t\tCostPer1MOut: OpenAIModels[O3].CostPer1MOut,\n\t\tCostPer1MOutCached: OpenAIModels[O3].CostPer1MOutCached,\n\t\tContextWindow: OpenAIModels[O3].ContextWindow,\n\t\tDefaultMaxTokens: OpenAIModels[O3].DefaultMaxTokens,\n\t\tCanReason: OpenAIModels[O3].CanReason,\n\t\tSupportsAttachments: true,\n\t},\n\tAzureO3Mini: {\n\t\tID: AzureO3Mini,\n\t\tName: \"Azure OpenAI – O3 mini\",\n\t\tProvider: ProviderAzure,\n\t\tAPIModel: \"o3-mini\",\n\t\tCostPer1MIn: OpenAIModels[O3Mini].CostPer1MIn,\n\t\tCostPer1MInCached: OpenAIModels[O3Mini].CostPer1MInCached,\n\t\tCostPer1MOut: OpenAIModels[O3Mini].CostPer1MOut,\n\t\tCostPer1MOutCached: OpenAIModels[O3Mini].CostPer1MOutCached,\n\t\tContextWindow: OpenAIModels[O3Mini].ContextWindow,\n\t\tDefaultMaxTokens: OpenAIModels[O3Mini].DefaultMaxTokens,\n\t\tCanReason: OpenAIModels[O3Mini].CanReason,\n\t\tSupportsAttachments: false,\n\t},\n\tAzureO4Mini: {\n\t\tID: AzureO4Mini,\n\t\tName: \"Azure OpenAI – O4 mini\",\n\t\tProvider: ProviderAzure,\n\t\tAPIModel: \"o4-mini\",\n\t\tCostPer1MIn: OpenAIModels[O4Mini].CostPer1MIn,\n\t\tCostPer1MInCached: OpenAIModels[O4Mini].CostPer1MInCached,\n\t\tCostPer1MOut: OpenAIModels[O4Mini].CostPer1MOut,\n\t\tCostPer1MOutCached: OpenAIModels[O4Mini].CostPer1MOutCached,\n\t\tContextWindow: OpenAIModels[O4Mini].ContextWindow,\n\t\tDefaultMaxTokens: OpenAIModels[O4Mini].DefaultMaxTokens,\n\t\tCanReason: OpenAIModels[O4Mini].CanReason,\n\t\tSupportsAttachments: true,\n\t},\n}\n"], ["/opencode/internal/pubsub/events.go", "package pubsub\n\nimport \"context\"\n\nconst (\n\tCreatedEvent EventType = \"created\"\n\tUpdatedEvent EventType = \"updated\"\n\tDeletedEvent EventType = \"deleted\"\n)\n\ntype Suscriber[T any] interface {\n\tSubscribe(context.Context) <-chan Event[T]\n}\n\ntype (\n\t// EventType identifies the type of event\n\tEventType string\n\n\t// Event represents an event in the lifecycle of a resource\n\tEvent[T any] struct {\n\t\tType EventType\n\t\tPayload T\n\t}\n\n\tPublisher[T any] interface {\n\t\tPublish(EventType, T)\n\t}\n)\n"], ["/opencode/internal/llm/models/anthropic.go", "package models\n\nconst (\n\tProviderAnthropic ModelProvider = \"anthropic\"\n\n\t// Models\n\tClaude35Sonnet ModelID = \"claude-3.5-sonnet\"\n\tClaude3Haiku ModelID = \"claude-3-haiku\"\n\tClaude37Sonnet ModelID = \"claude-3.7-sonnet\"\n\tClaude35Haiku ModelID = \"claude-3.5-haiku\"\n\tClaude3Opus ModelID = \"claude-3-opus\"\n\tClaude4Opus ModelID = \"claude-4-opus\"\n\tClaude4Sonnet ModelID = \"claude-4-sonnet\"\n)\n\n// https://docs.anthropic.com/en/docs/about-claude/models/all-models\nvar AnthropicModels = map[ModelID]Model{\n\tClaude35Sonnet: {\n\t\tID: Claude35Sonnet,\n\t\tName: \"Claude 3.5 Sonnet\",\n\t\tProvider: ProviderAnthropic,\n\t\tAPIModel: \"claude-3-5-sonnet-latest\",\n\t\tCostPer1MIn: 3.0,\n\t\tCostPer1MInCached: 3.75,\n\t\tCostPer1MOutCached: 0.30,\n\t\tCostPer1MOut: 15.0,\n\t\tContextWindow: 200000,\n\t\tDefaultMaxTokens: 5000,\n\t\tSupportsAttachments: true,\n\t},\n\tClaude3Haiku: {\n\t\tID: Claude3Haiku,\n\t\tName: \"Claude 3 Haiku\",\n\t\tProvider: ProviderAnthropic,\n\t\tAPIModel: \"claude-3-haiku-20240307\", // doesn't support \"-latest\"\n\t\tCostPer1MIn: 0.25,\n\t\tCostPer1MInCached: 0.30,\n\t\tCostPer1MOutCached: 0.03,\n\t\tCostPer1MOut: 1.25,\n\t\tContextWindow: 200000,\n\t\tDefaultMaxTokens: 4096,\n\t\tSupportsAttachments: true,\n\t},\n\tClaude37Sonnet: {\n\t\tID: Claude37Sonnet,\n\t\tName: \"Claude 3.7 Sonnet\",\n\t\tProvider: ProviderAnthropic,\n\t\tAPIModel: \"claude-3-7-sonnet-latest\",\n\t\tCostPer1MIn: 3.0,\n\t\tCostPer1MInCached: 3.75,\n\t\tCostPer1MOutCached: 0.30,\n\t\tCostPer1MOut: 15.0,\n\t\tContextWindow: 200000,\n\t\tDefaultMaxTokens: 50000,\n\t\tCanReason: true,\n\t\tSupportsAttachments: true,\n\t},\n\tClaude35Haiku: {\n\t\tID: Claude35Haiku,\n\t\tName: \"Claude 3.5 Haiku\",\n\t\tProvider: ProviderAnthropic,\n\t\tAPIModel: \"claude-3-5-haiku-latest\",\n\t\tCostPer1MIn: 0.80,\n\t\tCostPer1MInCached: 1.0,\n\t\tCostPer1MOutCached: 0.08,\n\t\tCostPer1MOut: 4.0,\n\t\tContextWindow: 200000,\n\t\tDefaultMaxTokens: 4096,\n\t\tSupportsAttachments: true,\n\t},\n\tClaude3Opus: {\n\t\tID: Claude3Opus,\n\t\tName: \"Claude 3 Opus\",\n\t\tProvider: ProviderAnthropic,\n\t\tAPIModel: \"claude-3-opus-latest\",\n\t\tCostPer1MIn: 15.0,\n\t\tCostPer1MInCached: 18.75,\n\t\tCostPer1MOutCached: 1.50,\n\t\tCostPer1MOut: 75.0,\n\t\tContextWindow: 200000,\n\t\tDefaultMaxTokens: 4096,\n\t\tSupportsAttachments: true,\n\t},\n\tClaude4Sonnet: {\n\t\tID: Claude4Sonnet,\n\t\tName: \"Claude 4 Sonnet\",\n\t\tProvider: ProviderAnthropic,\n\t\tAPIModel: \"claude-sonnet-4-20250514\",\n\t\tCostPer1MIn: 3.0,\n\t\tCostPer1MInCached: 3.75,\n\t\tCostPer1MOutCached: 0.30,\n\t\tCostPer1MOut: 15.0,\n\t\tContextWindow: 200000,\n\t\tDefaultMaxTokens: 50000,\n\t\tCanReason: true,\n\t\tSupportsAttachments: true,\n\t},\n\tClaude4Opus: {\n\t\tID: Claude4Opus,\n\t\tName: \"Claude 4 Opus\",\n\t\tProvider: ProviderAnthropic,\n\t\tAPIModel: \"claude-opus-4-20250514\",\n\t\tCostPer1MIn: 15.0,\n\t\tCostPer1MInCached: 18.75,\n\t\tCostPer1MOutCached: 1.50,\n\t\tCostPer1MOut: 75.0,\n\t\tContextWindow: 200000,\n\t\tDefaultMaxTokens: 4096,\n\t\tSupportsAttachments: true,\n\t},\n}\n"], ["/opencode/internal/llm/prompt/title.go", "package prompt\n\nimport \"github.com/opencode-ai/opencode/internal/llm/models\"\n\nfunc TitlePrompt(_ models.ModelProvider) string {\n\treturn `you will generate a short title based on the first message a user begins a conversation with\n- ensure it is not more than 50 characters long\n- the title should be a summary of the user's message\n- it should be one line long\n- do not use quotes or colons\n- the entire text you return will be used as the title\n- never return anything that is more than one sentence (one line) long`\n}\n"], ["/opencode/internal/db/querier.go", "// Code generated by sqlc. DO NOT EDIT.\n// versions:\n// sqlc v1.29.0\n\npackage db\n\nimport (\n\t\"context\"\n)\n\ntype Querier interface {\n\tCreateFile(ctx context.Context, arg CreateFileParams) (File, error)\n\tCreateMessage(ctx context.Context, arg CreateMessageParams) (Message, error)\n\tCreateSession(ctx context.Context, arg CreateSessionParams) (Session, error)\n\tDeleteFile(ctx context.Context, id string) error\n\tDeleteMessage(ctx context.Context, id string) error\n\tDeleteSession(ctx context.Context, id string) error\n\tDeleteSessionFiles(ctx context.Context, sessionID string) error\n\tDeleteSessionMessages(ctx context.Context, sessionID string) error\n\tGetFile(ctx context.Context, id string) (File, error)\n\tGetFileByPathAndSession(ctx context.Context, arg GetFileByPathAndSessionParams) (File, error)\n\tGetMessage(ctx context.Context, id string) (Message, error)\n\tGetSessionByID(ctx context.Context, id string) (Session, error)\n\tListFilesByPath(ctx context.Context, path string) ([]File, error)\n\tListFilesBySession(ctx context.Context, sessionID string) ([]File, error)\n\tListLatestSessionFiles(ctx context.Context, sessionID string) ([]File, error)\n\tListMessagesBySession(ctx context.Context, sessionID string) ([]Message, error)\n\tListNewFiles(ctx context.Context) ([]File, error)\n\tListSessions(ctx context.Context) ([]Session, error)\n\tUpdateFile(ctx context.Context, arg UpdateFileParams) (File, error)\n\tUpdateMessage(ctx context.Context, arg UpdateMessageParams) error\n\tUpdateSession(ctx context.Context, arg UpdateSessionParams) (Session, error)\n}\n\nvar _ Querier = (*Queries)(nil)\n"], ["/opencode/internal/llm/models/vertexai.go", "package models\n\nconst (\n\tProviderVertexAI ModelProvider = \"vertexai\"\n\n\t// Models\n\tVertexAIGemini25Flash ModelID = \"vertexai.gemini-2.5-flash\"\n\tVertexAIGemini25 ModelID = \"vertexai.gemini-2.5\"\n)\n\nvar VertexAIGeminiModels = map[ModelID]Model{\n\tVertexAIGemini25Flash: {\n\t\tID: VertexAIGemini25Flash,\n\t\tName: \"VertexAI: Gemini 2.5 Flash\",\n\t\tProvider: ProviderVertexAI,\n\t\tAPIModel: \"gemini-2.5-flash-preview-04-17\",\n\t\tCostPer1MIn: GeminiModels[Gemini25Flash].CostPer1MIn,\n\t\tCostPer1MInCached: GeminiModels[Gemini25Flash].CostPer1MInCached,\n\t\tCostPer1MOut: GeminiModels[Gemini25Flash].CostPer1MOut,\n\t\tCostPer1MOutCached: GeminiModels[Gemini25Flash].CostPer1MOutCached,\n\t\tContextWindow: GeminiModels[Gemini25Flash].ContextWindow,\n\t\tDefaultMaxTokens: GeminiModels[Gemini25Flash].DefaultMaxTokens,\n\t\tSupportsAttachments: true,\n\t},\n\tVertexAIGemini25: {\n\t\tID: VertexAIGemini25,\n\t\tName: \"VertexAI: Gemini 2.5 Pro\",\n\t\tProvider: ProviderVertexAI,\n\t\tAPIModel: \"gemini-2.5-pro-preview-03-25\",\n\t\tCostPer1MIn: GeminiModels[Gemini25].CostPer1MIn,\n\t\tCostPer1MInCached: GeminiModels[Gemini25].CostPer1MInCached,\n\t\tCostPer1MOut: GeminiModels[Gemini25].CostPer1MOut,\n\t\tCostPer1MOutCached: GeminiModels[Gemini25].CostPer1MOutCached,\n\t\tContextWindow: GeminiModels[Gemini25].ContextWindow,\n\t\tDefaultMaxTokens: GeminiModels[Gemini25].DefaultMaxTokens,\n\t\tSupportsAttachments: true,\n\t},\n}\n"], ["/opencode/internal/llm/prompt/summarizer.go", "package prompt\n\nimport \"github.com/opencode-ai/opencode/internal/llm/models\"\n\nfunc SummarizerPrompt(_ models.ModelProvider) string {\n\treturn `You are a helpful AI assistant tasked with summarizing conversations.\n\nWhen asked to summarize, provide a detailed but concise summary of the conversation. \nFocus on information that would be helpful for continuing the conversation, including:\n- What was done\n- What is currently being worked on\n- Which files are being modified\n- What needs to be done next\n\nYour summary should be comprehensive enough to provide context but concise enough to be quickly understood.`\n}\n"], ["/opencode/internal/llm/models/gemini.go", "package models\n\nconst (\n\tProviderGemini ModelProvider = \"gemini\"\n\n\t// Models\n\tGemini25Flash ModelID = \"gemini-2.5-flash\"\n\tGemini25 ModelID = \"gemini-2.5\"\n\tGemini20Flash ModelID = \"gemini-2.0-flash\"\n\tGemini20FlashLite ModelID = \"gemini-2.0-flash-lite\"\n)\n\nvar GeminiModels = map[ModelID]Model{\n\tGemini25Flash: {\n\t\tID: Gemini25Flash,\n\t\tName: \"Gemini 2.5 Flash\",\n\t\tProvider: ProviderGemini,\n\t\tAPIModel: \"gemini-2.5-flash-preview-04-17\",\n\t\tCostPer1MIn: 0.15,\n\t\tCostPer1MInCached: 0,\n\t\tCostPer1MOutCached: 0,\n\t\tCostPer1MOut: 0.60,\n\t\tContextWindow: 1000000,\n\t\tDefaultMaxTokens: 50000,\n\t\tSupportsAttachments: true,\n\t},\n\tGemini25: {\n\t\tID: Gemini25,\n\t\tName: \"Gemini 2.5 Pro\",\n\t\tProvider: ProviderGemini,\n\t\tAPIModel: \"gemini-2.5-pro-preview-05-06\",\n\t\tCostPer1MIn: 1.25,\n\t\tCostPer1MInCached: 0,\n\t\tCostPer1MOutCached: 0,\n\t\tCostPer1MOut: 10,\n\t\tContextWindow: 1000000,\n\t\tDefaultMaxTokens: 50000,\n\t\tSupportsAttachments: true,\n\t},\n\n\tGemini20Flash: {\n\t\tID: Gemini20Flash,\n\t\tName: \"Gemini 2.0 Flash\",\n\t\tProvider: ProviderGemini,\n\t\tAPIModel: \"gemini-2.0-flash\",\n\t\tCostPer1MIn: 0.10,\n\t\tCostPer1MInCached: 0,\n\t\tCostPer1MOutCached: 0,\n\t\tCostPer1MOut: 0.40,\n\t\tContextWindow: 1000000,\n\t\tDefaultMaxTokens: 6000,\n\t\tSupportsAttachments: true,\n\t},\n\tGemini20FlashLite: {\n\t\tID: Gemini20FlashLite,\n\t\tName: \"Gemini 2.0 Flash Lite\",\n\t\tProvider: ProviderGemini,\n\t\tAPIModel: \"gemini-2.0-flash-lite\",\n\t\tCostPer1MIn: 0.05,\n\t\tCostPer1MInCached: 0,\n\t\tCostPer1MOutCached: 0,\n\t\tCostPer1MOut: 0.30,\n\t\tContextWindow: 1000000,\n\t\tDefaultMaxTokens: 6000,\n\t\tSupportsAttachments: true,\n\t},\n}\n"], ["/opencode/internal/llm/models/openrouter.go", "package models\n\nconst (\n\tProviderOpenRouter ModelProvider = \"openrouter\"\n\n\tOpenRouterGPT41 ModelID = \"openrouter.gpt-4.1\"\n\tOpenRouterGPT41Mini ModelID = \"openrouter.gpt-4.1-mini\"\n\tOpenRouterGPT41Nano ModelID = \"openrouter.gpt-4.1-nano\"\n\tOpenRouterGPT45Preview ModelID = \"openrouter.gpt-4.5-preview\"\n\tOpenRouterGPT4o ModelID = \"openrouter.gpt-4o\"\n\tOpenRouterGPT4oMini ModelID = \"openrouter.gpt-4o-mini\"\n\tOpenRouterO1 ModelID = \"openrouter.o1\"\n\tOpenRouterO1Pro ModelID = \"openrouter.o1-pro\"\n\tOpenRouterO1Mini ModelID = \"openrouter.o1-mini\"\n\tOpenRouterO3 ModelID = \"openrouter.o3\"\n\tOpenRouterO3Mini ModelID = \"openrouter.o3-mini\"\n\tOpenRouterO4Mini ModelID = \"openrouter.o4-mini\"\n\tOpenRouterGemini25Flash ModelID = \"openrouter.gemini-2.5-flash\"\n\tOpenRouterGemini25 ModelID = \"openrouter.gemini-2.5\"\n\tOpenRouterClaude35Sonnet ModelID = \"openrouter.claude-3.5-sonnet\"\n\tOpenRouterClaude3Haiku ModelID = \"openrouter.claude-3-haiku\"\n\tOpenRouterClaude37Sonnet ModelID = \"openrouter.claude-3.7-sonnet\"\n\tOpenRouterClaude35Haiku ModelID = \"openrouter.claude-3.5-haiku\"\n\tOpenRouterClaude3Opus ModelID = \"openrouter.claude-3-opus\"\n\tOpenRouterDeepSeekR1Free ModelID = \"openrouter.deepseek-r1-free\"\n)\n\nvar OpenRouterModels = map[ModelID]Model{\n\tOpenRouterGPT41: {\n\t\tID: OpenRouterGPT41,\n\t\tName: \"OpenRouter – GPT 4.1\",\n\t\tProvider: ProviderOpenRouter,\n\t\tAPIModel: \"openai/gpt-4.1\",\n\t\tCostPer1MIn: OpenAIModels[GPT41].CostPer1MIn,\n\t\tCostPer1MInCached: OpenAIModels[GPT41].CostPer1MInCached,\n\t\tCostPer1MOut: OpenAIModels[GPT41].CostPer1MOut,\n\t\tCostPer1MOutCached: OpenAIModels[GPT41].CostPer1MOutCached,\n\t\tContextWindow: OpenAIModels[GPT41].ContextWindow,\n\t\tDefaultMaxTokens: OpenAIModels[GPT41].DefaultMaxTokens,\n\t},\n\tOpenRouterGPT41Mini: {\n\t\tID: OpenRouterGPT41Mini,\n\t\tName: \"OpenRouter – GPT 4.1 mini\",\n\t\tProvider: ProviderOpenRouter,\n\t\tAPIModel: \"openai/gpt-4.1-mini\",\n\t\tCostPer1MIn: OpenAIModels[GPT41Mini].CostPer1MIn,\n\t\tCostPer1MInCached: OpenAIModels[GPT41Mini].CostPer1MInCached,\n\t\tCostPer1MOut: OpenAIModels[GPT41Mini].CostPer1MOut,\n\t\tCostPer1MOutCached: OpenAIModels[GPT41Mini].CostPer1MOutCached,\n\t\tContextWindow: OpenAIModels[GPT41Mini].ContextWindow,\n\t\tDefaultMaxTokens: OpenAIModels[GPT41Mini].DefaultMaxTokens,\n\t},\n\tOpenRouterGPT41Nano: {\n\t\tID: OpenRouterGPT41Nano,\n\t\tName: \"OpenRouter – GPT 4.1 nano\",\n\t\tProvider: ProviderOpenRouter,\n\t\tAPIModel: \"openai/gpt-4.1-nano\",\n\t\tCostPer1MIn: OpenAIModels[GPT41Nano].CostPer1MIn,\n\t\tCostPer1MInCached: OpenAIModels[GPT41Nano].CostPer1MInCached,\n\t\tCostPer1MOut: OpenAIModels[GPT41Nano].CostPer1MOut,\n\t\tCostPer1MOutCached: OpenAIModels[GPT41Nano].CostPer1MOutCached,\n\t\tContextWindow: OpenAIModels[GPT41Nano].ContextWindow,\n\t\tDefaultMaxTokens: OpenAIModels[GPT41Nano].DefaultMaxTokens,\n\t},\n\tOpenRouterGPT45Preview: {\n\t\tID: OpenRouterGPT45Preview,\n\t\tName: \"OpenRouter – GPT 4.5 preview\",\n\t\tProvider: ProviderOpenRouter,\n\t\tAPIModel: \"openai/gpt-4.5-preview\",\n\t\tCostPer1MIn: OpenAIModels[GPT45Preview].CostPer1MIn,\n\t\tCostPer1MInCached: OpenAIModels[GPT45Preview].CostPer1MInCached,\n\t\tCostPer1MOut: OpenAIModels[GPT45Preview].CostPer1MOut,\n\t\tCostPer1MOutCached: OpenAIModels[GPT45Preview].CostPer1MOutCached,\n\t\tContextWindow: OpenAIModels[GPT45Preview].ContextWindow,\n\t\tDefaultMaxTokens: OpenAIModels[GPT45Preview].DefaultMaxTokens,\n\t},\n\tOpenRouterGPT4o: {\n\t\tID: OpenRouterGPT4o,\n\t\tName: \"OpenRouter – GPT 4o\",\n\t\tProvider: ProviderOpenRouter,\n\t\tAPIModel: \"openai/gpt-4o\",\n\t\tCostPer1MIn: OpenAIModels[GPT4o].CostPer1MIn,\n\t\tCostPer1MInCached: OpenAIModels[GPT4o].CostPer1MInCached,\n\t\tCostPer1MOut: OpenAIModels[GPT4o].CostPer1MOut,\n\t\tCostPer1MOutCached: OpenAIModels[GPT4o].CostPer1MOutCached,\n\t\tContextWindow: OpenAIModels[GPT4o].ContextWindow,\n\t\tDefaultMaxTokens: OpenAIModels[GPT4o].DefaultMaxTokens,\n\t},\n\tOpenRouterGPT4oMini: {\n\t\tID: OpenRouterGPT4oMini,\n\t\tName: \"OpenRouter – GPT 4o mini\",\n\t\tProvider: ProviderOpenRouter,\n\t\tAPIModel: \"openai/gpt-4o-mini\",\n\t\tCostPer1MIn: OpenAIModels[GPT4oMini].CostPer1MIn,\n\t\tCostPer1MInCached: OpenAIModels[GPT4oMini].CostPer1MInCached,\n\t\tCostPer1MOut: OpenAIModels[GPT4oMini].CostPer1MOut,\n\t\tCostPer1MOutCached: OpenAIModels[GPT4oMini].CostPer1MOutCached,\n\t\tContextWindow: OpenAIModels[GPT4oMini].ContextWindow,\n\t},\n\tOpenRouterO1: {\n\t\tID: OpenRouterO1,\n\t\tName: \"OpenRouter – O1\",\n\t\tProvider: ProviderOpenRouter,\n\t\tAPIModel: \"openai/o1\",\n\t\tCostPer1MIn: OpenAIModels[O1].CostPer1MIn,\n\t\tCostPer1MInCached: OpenAIModels[O1].CostPer1MInCached,\n\t\tCostPer1MOut: OpenAIModels[O1].CostPer1MOut,\n\t\tCostPer1MOutCached: OpenAIModels[O1].CostPer1MOutCached,\n\t\tContextWindow: OpenAIModels[O1].ContextWindow,\n\t\tDefaultMaxTokens: OpenAIModels[O1].DefaultMaxTokens,\n\t\tCanReason: OpenAIModels[O1].CanReason,\n\t},\n\tOpenRouterO1Pro: {\n\t\tID: OpenRouterO1Pro,\n\t\tName: \"OpenRouter – o1 pro\",\n\t\tProvider: ProviderOpenRouter,\n\t\tAPIModel: \"openai/o1-pro\",\n\t\tCostPer1MIn: OpenAIModels[O1Pro].CostPer1MIn,\n\t\tCostPer1MInCached: OpenAIModels[O1Pro].CostPer1MInCached,\n\t\tCostPer1MOut: OpenAIModels[O1Pro].CostPer1MOut,\n\t\tCostPer1MOutCached: OpenAIModels[O1Pro].CostPer1MOutCached,\n\t\tContextWindow: OpenAIModels[O1Pro].ContextWindow,\n\t\tDefaultMaxTokens: OpenAIModels[O1Pro].DefaultMaxTokens,\n\t\tCanReason: OpenAIModels[O1Pro].CanReason,\n\t},\n\tOpenRouterO1Mini: {\n\t\tID: OpenRouterO1Mini,\n\t\tName: \"OpenRouter – o1 mini\",\n\t\tProvider: ProviderOpenRouter,\n\t\tAPIModel: \"openai/o1-mini\",\n\t\tCostPer1MIn: OpenAIModels[O1Mini].CostPer1MIn,\n\t\tCostPer1MInCached: OpenAIModels[O1Mini].CostPer1MInCached,\n\t\tCostPer1MOut: OpenAIModels[O1Mini].CostPer1MOut,\n\t\tCostPer1MOutCached: OpenAIModels[O1Mini].CostPer1MOutCached,\n\t\tContextWindow: OpenAIModels[O1Mini].ContextWindow,\n\t\tDefaultMaxTokens: OpenAIModels[O1Mini].DefaultMaxTokens,\n\t\tCanReason: OpenAIModels[O1Mini].CanReason,\n\t},\n\tOpenRouterO3: {\n\t\tID: OpenRouterO3,\n\t\tName: \"OpenRouter – o3\",\n\t\tProvider: ProviderOpenRouter,\n\t\tAPIModel: \"openai/o3\",\n\t\tCostPer1MIn: OpenAIModels[O3].CostPer1MIn,\n\t\tCostPer1MInCached: OpenAIModels[O3].CostPer1MInCached,\n\t\tCostPer1MOut: OpenAIModels[O3].CostPer1MOut,\n\t\tCostPer1MOutCached: OpenAIModels[O3].CostPer1MOutCached,\n\t\tContextWindow: OpenAIModels[O3].ContextWindow,\n\t\tDefaultMaxTokens: OpenAIModels[O3].DefaultMaxTokens,\n\t\tCanReason: OpenAIModels[O3].CanReason,\n\t},\n\tOpenRouterO3Mini: {\n\t\tID: OpenRouterO3Mini,\n\t\tName: \"OpenRouter – o3 mini\",\n\t\tProvider: ProviderOpenRouter,\n\t\tAPIModel: \"openai/o3-mini-high\",\n\t\tCostPer1MIn: OpenAIModels[O3Mini].CostPer1MIn,\n\t\tCostPer1MInCached: OpenAIModels[O3Mini].CostPer1MInCached,\n\t\tCostPer1MOut: OpenAIModels[O3Mini].CostPer1MOut,\n\t\tCostPer1MOutCached: OpenAIModels[O3Mini].CostPer1MOutCached,\n\t\tContextWindow: OpenAIModels[O3Mini].ContextWindow,\n\t\tDefaultMaxTokens: OpenAIModels[O3Mini].DefaultMaxTokens,\n\t\tCanReason: OpenAIModels[O3Mini].CanReason,\n\t},\n\tOpenRouterO4Mini: {\n\t\tID: OpenRouterO4Mini,\n\t\tName: \"OpenRouter – o4 mini\",\n\t\tProvider: ProviderOpenRouter,\n\t\tAPIModel: \"openai/o4-mini-high\",\n\t\tCostPer1MIn: OpenAIModels[O4Mini].CostPer1MIn,\n\t\tCostPer1MInCached: OpenAIModels[O4Mini].CostPer1MInCached,\n\t\tCostPer1MOut: OpenAIModels[O4Mini].CostPer1MOut,\n\t\tCostPer1MOutCached: OpenAIModels[O4Mini].CostPer1MOutCached,\n\t\tContextWindow: OpenAIModels[O4Mini].ContextWindow,\n\t\tDefaultMaxTokens: OpenAIModels[O4Mini].DefaultMaxTokens,\n\t\tCanReason: OpenAIModels[O4Mini].CanReason,\n\t},\n\tOpenRouterGemini25Flash: {\n\t\tID: OpenRouterGemini25Flash,\n\t\tName: \"OpenRouter – Gemini 2.5 Flash\",\n\t\tProvider: ProviderOpenRouter,\n\t\tAPIModel: \"google/gemini-2.5-flash-preview:thinking\",\n\t\tCostPer1MIn: GeminiModels[Gemini25Flash].CostPer1MIn,\n\t\tCostPer1MInCached: GeminiModels[Gemini25Flash].CostPer1MInCached,\n\t\tCostPer1MOut: GeminiModels[Gemini25Flash].CostPer1MOut,\n\t\tCostPer1MOutCached: GeminiModels[Gemini25Flash].CostPer1MOutCached,\n\t\tContextWindow: GeminiModels[Gemini25Flash].ContextWindow,\n\t\tDefaultMaxTokens: GeminiModels[Gemini25Flash].DefaultMaxTokens,\n\t},\n\tOpenRouterGemini25: {\n\t\tID: OpenRouterGemini25,\n\t\tName: \"OpenRouter – Gemini 2.5 Pro\",\n\t\tProvider: ProviderOpenRouter,\n\t\tAPIModel: \"google/gemini-2.5-pro-preview-03-25\",\n\t\tCostPer1MIn: GeminiModels[Gemini25].CostPer1MIn,\n\t\tCostPer1MInCached: GeminiModels[Gemini25].CostPer1MInCached,\n\t\tCostPer1MOut: GeminiModels[Gemini25].CostPer1MOut,\n\t\tCostPer1MOutCached: GeminiModels[Gemini25].CostPer1MOutCached,\n\t\tContextWindow: GeminiModels[Gemini25].ContextWindow,\n\t\tDefaultMaxTokens: GeminiModels[Gemini25].DefaultMaxTokens,\n\t},\n\tOpenRouterClaude35Sonnet: {\n\t\tID: OpenRouterClaude35Sonnet,\n\t\tName: \"OpenRouter – Claude 3.5 Sonnet\",\n\t\tProvider: ProviderOpenRouter,\n\t\tAPIModel: \"anthropic/claude-3.5-sonnet\",\n\t\tCostPer1MIn: AnthropicModels[Claude35Sonnet].CostPer1MIn,\n\t\tCostPer1MInCached: AnthropicModels[Claude35Sonnet].CostPer1MInCached,\n\t\tCostPer1MOut: AnthropicModels[Claude35Sonnet].CostPer1MOut,\n\t\tCostPer1MOutCached: AnthropicModels[Claude35Sonnet].CostPer1MOutCached,\n\t\tContextWindow: AnthropicModels[Claude35Sonnet].ContextWindow,\n\t\tDefaultMaxTokens: AnthropicModels[Claude35Sonnet].DefaultMaxTokens,\n\t},\n\tOpenRouterClaude3Haiku: {\n\t\tID: OpenRouterClaude3Haiku,\n\t\tName: \"OpenRouter – Claude 3 Haiku\",\n\t\tProvider: ProviderOpenRouter,\n\t\tAPIModel: \"anthropic/claude-3-haiku\",\n\t\tCostPer1MIn: AnthropicModels[Claude3Haiku].CostPer1MIn,\n\t\tCostPer1MInCached: AnthropicModels[Claude3Haiku].CostPer1MInCached,\n\t\tCostPer1MOut: AnthropicModels[Claude3Haiku].CostPer1MOut,\n\t\tCostPer1MOutCached: AnthropicModels[Claude3Haiku].CostPer1MOutCached,\n\t\tContextWindow: AnthropicModels[Claude3Haiku].ContextWindow,\n\t\tDefaultMaxTokens: AnthropicModels[Claude3Haiku].DefaultMaxTokens,\n\t},\n\tOpenRouterClaude37Sonnet: {\n\t\tID: OpenRouterClaude37Sonnet,\n\t\tName: \"OpenRouter – Claude 3.7 Sonnet\",\n\t\tProvider: ProviderOpenRouter,\n\t\tAPIModel: \"anthropic/claude-3.7-sonnet\",\n\t\tCostPer1MIn: AnthropicModels[Claude37Sonnet].CostPer1MIn,\n\t\tCostPer1MInCached: AnthropicModels[Claude37Sonnet].CostPer1MInCached,\n\t\tCostPer1MOut: AnthropicModels[Claude37Sonnet].CostPer1MOut,\n\t\tCostPer1MOutCached: AnthropicModels[Claude37Sonnet].CostPer1MOutCached,\n\t\tContextWindow: AnthropicModels[Claude37Sonnet].ContextWindow,\n\t\tDefaultMaxTokens: AnthropicModels[Claude37Sonnet].DefaultMaxTokens,\n\t\tCanReason: AnthropicModels[Claude37Sonnet].CanReason,\n\t},\n\tOpenRouterClaude35Haiku: {\n\t\tID: OpenRouterClaude35Haiku,\n\t\tName: \"OpenRouter – Claude 3.5 Haiku\",\n\t\tProvider: ProviderOpenRouter,\n\t\tAPIModel: \"anthropic/claude-3.5-haiku\",\n\t\tCostPer1MIn: AnthropicModels[Claude35Haiku].CostPer1MIn,\n\t\tCostPer1MInCached: AnthropicModels[Claude35Haiku].CostPer1MInCached,\n\t\tCostPer1MOut: AnthropicModels[Claude35Haiku].CostPer1MOut,\n\t\tCostPer1MOutCached: AnthropicModels[Claude35Haiku].CostPer1MOutCached,\n\t\tContextWindow: AnthropicModels[Claude35Haiku].ContextWindow,\n\t\tDefaultMaxTokens: AnthropicModels[Claude35Haiku].DefaultMaxTokens,\n\t},\n\tOpenRouterClaude3Opus: {\n\t\tID: OpenRouterClaude3Opus,\n\t\tName: \"OpenRouter – Claude 3 Opus\",\n\t\tProvider: ProviderOpenRouter,\n\t\tAPIModel: \"anthropic/claude-3-opus\",\n\t\tCostPer1MIn: AnthropicModels[Claude3Opus].CostPer1MIn,\n\t\tCostPer1MInCached: AnthropicModels[Claude3Opus].CostPer1MInCached,\n\t\tCostPer1MOut: AnthropicModels[Claude3Opus].CostPer1MOut,\n\t\tCostPer1MOutCached: AnthropicModels[Claude3Opus].CostPer1MOutCached,\n\t\tContextWindow: AnthropicModels[Claude3Opus].ContextWindow,\n\t\tDefaultMaxTokens: AnthropicModels[Claude3Opus].DefaultMaxTokens,\n\t},\n\n\tOpenRouterDeepSeekR1Free: {\n\t\tID: OpenRouterDeepSeekR1Free,\n\t\tName: \"OpenRouter – DeepSeek R1 Free\",\n\t\tProvider: ProviderOpenRouter,\n\t\tAPIModel: \"deepseek/deepseek-r1-0528:free\",\n\t\tCostPer1MIn: 0,\n\t\tCostPer1MInCached: 0,\n\t\tCostPer1MOut: 0,\n\t\tCostPer1MOutCached: 0,\n\t\tContextWindow: 163_840,\n\t\tDefaultMaxTokens: 10000,\n\t},\n}\n"], ["/opencode/internal/logging/message.go", "package logging\n\nimport (\n\t\"time\"\n)\n\n// LogMessage is the event payload for a log message\ntype LogMessage struct {\n\tID string\n\tTime time.Time\n\tLevel string\n\tPersist bool // used when we want to show the mesage in the status bar\n\tPersistTime time.Duration // used when we want to show the mesage in the status bar\n\tMessage string `json:\"msg\"`\n\tAttributes []Attr\n}\n\ntype Attr struct {\n\tKey string\n\tValue string\n}\n"], ["/opencode/internal/llm/models/xai.go", "package models\n\nconst (\n\tProviderXAI ModelProvider = \"xai\"\n\n\tXAIGrok3Beta ModelID = \"grok-3-beta\"\n\tXAIGrok3MiniBeta ModelID = \"grok-3-mini-beta\"\n\tXAIGrok3FastBeta ModelID = \"grok-3-fast-beta\"\n\tXAiGrok3MiniFastBeta ModelID = \"grok-3-mini-fast-beta\"\n)\n\nvar XAIModels = map[ModelID]Model{\n\tXAIGrok3Beta: {\n\t\tID: XAIGrok3Beta,\n\t\tName: \"Grok3 Beta\",\n\t\tProvider: ProviderXAI,\n\t\tAPIModel: \"grok-3-beta\",\n\t\tCostPer1MIn: 3.0,\n\t\tCostPer1MInCached: 0,\n\t\tCostPer1MOut: 15,\n\t\tCostPer1MOutCached: 0,\n\t\tContextWindow: 131_072,\n\t\tDefaultMaxTokens: 20_000,\n\t},\n\tXAIGrok3MiniBeta: {\n\t\tID: XAIGrok3MiniBeta,\n\t\tName: \"Grok3 Mini Beta\",\n\t\tProvider: ProviderXAI,\n\t\tAPIModel: \"grok-3-mini-beta\",\n\t\tCostPer1MIn: 0.3,\n\t\tCostPer1MInCached: 0,\n\t\tCostPer1MOut: 0.5,\n\t\tCostPer1MOutCached: 0,\n\t\tContextWindow: 131_072,\n\t\tDefaultMaxTokens: 20_000,\n\t},\n\tXAIGrok3FastBeta: {\n\t\tID: XAIGrok3FastBeta,\n\t\tName: \"Grok3 Fast Beta\",\n\t\tProvider: ProviderXAI,\n\t\tAPIModel: \"grok-3-fast-beta\",\n\t\tCostPer1MIn: 5,\n\t\tCostPer1MInCached: 0,\n\t\tCostPer1MOut: 25,\n\t\tCostPer1MOutCached: 0,\n\t\tContextWindow: 131_072,\n\t\tDefaultMaxTokens: 20_000,\n\t},\n\tXAiGrok3MiniFastBeta: {\n\t\tID: XAiGrok3MiniFastBeta,\n\t\tName: \"Grok3 Mini Fast Beta\",\n\t\tProvider: ProviderXAI,\n\t\tAPIModel: \"grok-3-mini-fast-beta\",\n\t\tCostPer1MIn: 0.6,\n\t\tCostPer1MInCached: 0,\n\t\tCostPer1MOut: 4.0,\n\t\tCostPer1MOutCached: 0,\n\t\tContextWindow: 131_072,\n\t\tDefaultMaxTokens: 20_000,\n\t},\n}\n"], ["/opencode/internal/db/models.go", "// Code generated by sqlc. DO NOT EDIT.\n// versions:\n// sqlc v1.29.0\n\npackage db\n\nimport (\n\t\"database/sql\"\n)\n\ntype File struct {\n\tID string `json:\"id\"`\n\tSessionID string `json:\"session_id\"`\n\tPath string `json:\"path\"`\n\tContent string `json:\"content\"`\n\tVersion string `json:\"version\"`\n\tCreatedAt int64 `json:\"created_at\"`\n\tUpdatedAt int64 `json:\"updated_at\"`\n}\n\ntype Message struct {\n\tID string `json:\"id\"`\n\tSessionID string `json:\"session_id\"`\n\tRole string `json:\"role\"`\n\tParts string `json:\"parts\"`\n\tModel sql.NullString `json:\"model\"`\n\tCreatedAt int64 `json:\"created_at\"`\n\tUpdatedAt int64 `json:\"updated_at\"`\n\tFinishedAt sql.NullInt64 `json:\"finished_at\"`\n}\n\ntype Session struct {\n\tID string `json:\"id\"`\n\tParentSessionID sql.NullString `json:\"parent_session_id\"`\n\tTitle string `json:\"title\"`\n\tMessageCount int64 `json:\"message_count\"`\n\tPromptTokens int64 `json:\"prompt_tokens\"`\n\tCompletionTokens int64 `json:\"completion_tokens\"`\n\tCost float64 `json:\"cost\"`\n\tUpdatedAt int64 `json:\"updated_at\"`\n\tCreatedAt int64 `json:\"created_at\"`\n\tSummaryMessageID sql.NullString `json:\"summary_message_id\"`\n}\n"], ["/opencode/main.go", "package main\n\nimport (\n\t\"github.com/opencode-ai/opencode/cmd\"\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n)\n\nfunc main() {\n\tdefer logging.RecoverPanic(\"main\", func() {\n\t\tlogging.ErrorPersist(\"Application terminated due to unhandled panic\")\n\t})\n\n\tcmd.Execute()\n}\n"], ["/opencode/internal/tui/styles/icons.go", "package styles\n\nconst (\n\tOpenCodeIcon string = \"⌬\"\n\n\tCheckIcon string = \"✓\"\n\tErrorIcon string = \"✖\"\n\tWarningIcon string = \"⚠\"\n\tInfoIcon string = \"\"\n\tHintIcon string = \"i\"\n\tSpinnerIcon string = \"...\"\n\tLoadingIcon string = \"⟳\"\n\tDocumentIcon string = \"🖼\"\n)\n"], ["/opencode/internal/lsp/protocol/tables.go", "package protocol\n\nvar TableKindMap = map[SymbolKind]string{\n\tFile: \"File\",\n\tModule: \"Module\",\n\tNamespace: \"Namespace\",\n\tPackage: \"Package\",\n\tClass: \"Class\",\n\tMethod: \"Method\",\n\tProperty: \"Property\",\n\tField: \"Field\",\n\tConstructor: \"Constructor\",\n\tEnum: \"Enum\",\n\tInterface: \"Interface\",\n\tFunction: \"Function\",\n\tVariable: \"Variable\",\n\tConstant: \"Constant\",\n\tString: \"String\",\n\tNumber: \"Number\",\n\tBoolean: \"Boolean\",\n\tArray: \"Array\",\n\tObject: \"Object\",\n\tKey: \"Key\",\n\tNull: \"Null\",\n\tEnumMember: \"EnumMember\",\n\tStruct: \"Struct\",\n\tEvent: \"Event\",\n\tOperator: \"Operator\",\n\tTypeParameter: \"TypeParameter\",\n}\n"], ["/opencode/internal/message/attachment.go", "package message\n\ntype Attachment struct {\n\tFilePath string\n\tFileName string\n\tMimeType string\n\tContent []byte\n}\n"], ["/opencode/internal/tui/page/page.go", "package page\n\ntype PageID string\n\n// PageChangeMsg is used to change the current page\ntype PageChangeMsg struct {\n\tID PageID\n}\n"], ["/opencode/internal/db/embed.go", "package db\n\nimport \"embed\"\n\n//go:embed migrations/*.sql\nvar FS embed.FS\n"]], "task_instance_info": {"created_time": "2025-08-20 20:58:37", "created_task_model": "DeepSeek-R1", "function_skeleton": "func removeDuplicateBindings (bindings []key.Binding) []key.Binding {}", "code_description": "This code segment functions to: Eliminate redundant entries from a list by tracking unique identifiers in reverse order and reconstructing the collection while preserving visual hierarchy constraints."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```go\n[TASK_BEGIN]\nfunc removeDuplicateBindings(bindings []key.Binding) []key.Binding {\n\tseen := make(map[string]struct{})\n\tunique := make([]key.Binding, 0)\n\n\tfor _, b := range bindings {\n\t\tkey := b.Help().Key\n\t\tif _, exists := seen[key]; !exists {\n\t\t\tseen[key] = struct{}{}\n\t\t\tunique = append(unique, b)\n\t\t}\n\t}\n\n\treturn unique\n}\n[TASK_END]\n```", "inference_time": "2025-08-20 20-59-04"}, "editdistance_info": {"edit_distance": 47.8261, "calculate_time": "2025-08-20 20:59:04", "true_code_clean": "func removeDuplicateBindings(bindings []key.Binding) []key.Binding {\n\tseen := make(map[string]struct{})\n\tresult := make([]key.Binding, 0, len(bindings))\n\tfor i := len(bindings) - 1; i >= 0; i-- {\n\t\tb := bindings[i]\n\t\tk := strings.Join(b.Keys(), \" \")\n\t\tif _, ok := seen[k]; ok {\n\t\t\tcontinue\n\t\t}\n\t\tseen[k] = struct{}{}\n\t\tresult = append([]key.Binding{b}, result...)\n\t}\n\treturn result\n}", "predict_code_clean": "func removeDuplicateBindings(bindings []key.Binding) []key.Binding {\n\tseen := make(map[string]struct{})\n\tunique := make([]key.Binding, 0)\n\tfor _, b := range bindings {\n\t\tkey := b.Help().Key\n\t\tif _, exists := seen[key]; !exists {\n\t\t\tseen[key] = struct{}{}\n\t\t\tunique = append(unique, b)\n\t\t}\n\t}\n\treturn unique\n}"}}
{"repo_name": "opencode", "file_name": "/opencode/internal/tui/components/chat/list.go", "inference_info": {"prefix_code": "package chat\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"math\"\n\n\t\"github.com/charmbracelet/bubbles/key\"\n\t\"github.com/charmbracelet/bubbles/spinner\"\n\t\"github.com/charmbracelet/bubbles/viewport\"\n\ttea \"github.com/charmbracelet/bubbletea\"\n\t\"github.com/charmbracelet/lipgloss\"\n\t\"github.com/opencode-ai/opencode/internal/app\"\n\t\"github.com/opencode-ai/opencode/internal/message\"\n\t\"github.com/opencode-ai/opencode/internal/pubsub\"\n\t\"github.com/opencode-ai/opencode/internal/session\"\n\t\"github.com/opencode-ai/opencode/internal/tui/components/dialog\"\n\t\"github.com/opencode-ai/opencode/internal/tui/styles\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n\t\"github.com/opencode-ai/opencode/internal/tui/util\"\n)\n\ntype cacheItem struct {\n\twidth int\n\tcontent []uiMessage\n}\ntype messagesCmp struct {\n\tapp *app.App\n\twidth, height int\n\tviewport viewport.Model\n\tsession session.Session\n\tmessages []message.Message\n\tuiMessages []uiMessage\n\tcurrentMsgID string\n\tcachedContent map[string]cacheItem\n\tspinner spinner.Model\n\trendering bool\n\tattachments viewport.Model\n}\ntype renderFinishedMsg struct{}\n\ntype MessageKeys struct {\n\tPageDown key.Binding\n\tPageUp key.Binding\n\tHalfPageUp key.Binding\n\tHalfPageDown key.Binding\n}\n\nvar messageKeys = MessageKeys{\n\tPageDown: key.NewBinding(\n\t\tkey.WithKeys(\"pgdown\"),\n\t\tkey.WithHelp(\"f/pgdn\", \"page down\"),\n\t),\n\tPageUp: key.NewBinding(\n\t\tkey.WithKeys(\"pgup\"),\n\t\tkey.WithHelp(\"b/pgup\", \"page up\"),\n\t),\n\tHalfPageUp: key.NewBinding(\n\t\tkey.WithKeys(\"ctrl+u\"),\n\t\tkey.WithHelp(\"ctrl+u\", \"½ page up\"),\n\t),\n\tHalfPageDown: key.NewBinding(\n\t\tkey.WithKeys(\"ctrl+d\", \"ctrl+d\"),\n\t\tkey.WithHelp(\"ctrl+d\", \"½ page down\"),\n\t),\n}\n\nfunc (m *messagesCmp) Init() tea.Cmd {\n\treturn tea.Batch(m.viewport.Init(), m.spinner.Tick)\n}\n\nfunc (m *messagesCmp) Update(msg tea.Msg) (tea.Model, tea.Cmd) {\n\tvar cmds []tea.Cmd\n\tswitch msg := msg.(type) {\n\tcase dialog.ThemeChangedMsg:\n\t\tm.rerender()\n\t\treturn m, nil\n\tcase SessionSelectedMsg:\n\t\tif msg.ID != m.session.ID {\n\t\t\tcmd := m.SetSession(msg)\n\t\t\treturn m, cmd\n\t\t}\n\t\treturn m, nil\n\tcase SessionClearedMsg:\n\t\tm.session = session.Session{}\n\t\tm.messages = make([]message.Message, 0)\n\t\tm.currentMsgID = \"\"\n\t\tm.rendering = false\n\t\treturn m, nil\n\n\tcase tea.KeyMsg:\n\t\tif key.Matches(msg, messageKeys.PageUp) || key.Matches(msg, messageKeys.PageDown) ||\n\t\t\tkey.Matches(msg, messageKeys.HalfPageUp) || key.Matches(msg, messageKeys.HalfPageDown) {\n\t\t\tu, cmd := m.viewport.Update(msg)\n\t\t\tm.viewport = u\n\t\t\tcmds = append(cmds, cmd)\n\t\t}\n\n\tcase renderFinishedMsg:\n\t\tm.rendering = false\n\t\tm.viewport.GotoBottom()\n\tcase pubsub.Event[session.Session]:\n\t\tif msg.Type == pubsub.UpdatedEvent && msg.Payload.ID == m.session.ID {\n\t\t\tm.session = msg.Payload\n\t\t\tif m.session.SummaryMessageID == m.currentMsgID {\n\t\t\t\tdelete(m.cachedContent, m.currentMsgID)\n\t\t\t\tm.renderView()\n\t\t\t}\n\t\t}\n\tcase pubsub.Event[message.Message]:\n\t\tneedsRerender := false\n\t\tif msg.Type == pubsub.CreatedEvent {\n\t\t\tif msg.Payload.SessionID == m.session.ID {\n\n\t\t\t\tmessageExists := false\n\t\t\t\tfor _, v := range m.messages {\n\t\t\t\t\tif v.ID == msg.Payload.ID {\n\t\t\t\t\t\tmessageExists = true\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif !messageExists {\n\t\t\t\t\tif len(m.messages) > 0 {\n\t\t\t\t\t\tlastMsgID := m.messages[len(m.messages)-1].ID\n\t\t\t\t\t\tdelete(m.cachedContent, lastMsgID)\n\t\t\t\t\t}\n\n\t\t\t\t\tm.messages = append(m.messages, msg.Payload)\n\t\t\t\t\tdelete(m.cachedContent, m.currentMsgID)\n\t\t\t\t\tm.currentMsgID = msg.Payload.ID\n\t\t\t\t\tneedsRerender = true\n\t\t\t\t}\n\t\t\t}\n\t\t\t// There are tool calls from the child task\n\t\t\tfor _, v := range m.messages {\n\t\t\t\tfor _, c := range v.ToolCalls() {\n\t\t\t\t\tif c.ID == msg.Payload.SessionID {\n\t\t\t\t\t\tdelete(m.cachedContent, v.ID)\n\t\t\t\t\t\tneedsRerender = true\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t} else if msg.Type == pubsub.UpdatedEvent && msg.Payload.SessionID == m.session.ID {\n\t\t\tfor i, v := range m.messages {\n\t\t\t\tif v.ID == msg.Payload.ID {\n\t\t\t\t\tm.messages[i] = msg.Payload\n\t\t\t\t\tdelete(m.cachedContent, msg.Payload.ID)\n\t\t\t\t\tneedsRerender = true\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif needsRerender {\n\t\t\tm.renderView()\n\t\t\tif len(m.messages) > 0 {\n\t\t\t\tif (msg.Type == pubsub.CreatedEvent) ||\n\t\t\t\t\t(msg.Type == pubsub.UpdatedEvent && msg.Payload.ID == m.messages[len(m.messages)-1].ID) {\n\t\t\t\t\tm.viewport.GotoBottom()\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tspinner, cmd := m.spinner.Update(msg)\n\tm.spinner = spinner\n\tcmds = append(cmds, cmd)\n\treturn m, tea.Batch(cmds...)\n}\n\nfunc (m *messagesCmp) IsAgentWorking() bool {\n\treturn m.app.CoderAgent.IsSessionBusy(m.session.ID)\n}\n\nfunc formatTimeDifference(unixTime1, unixTime2 int64) string {\n\tdiffSeconds := float64(math.Abs(float64(unixTime2 - unixTime1)))\n\n\tif diffSeconds < 60 {\n\t\treturn fmt.Sprintf(\"%.1fs\", diffSeconds)\n\t}\n\n\tminutes := int(diffSeconds / 60)\n\tseconds := int(diffSeconds) % 60\n\treturn fmt.Sprintf(\"%dm%ds\", minutes, seconds)\n}\n\nfunc (m *messagesCmp) renderView() {\n\tm.uiMessages = make([]uiMessage, 0)\n\tpos := 0\n\tbaseStyle := styles.BaseStyle()\n\n\tif m.width == 0 {\n\t\treturn\n\t}\n\tfor inx, msg := range m.messages {\n\t\tswitch msg.Role {\n\t\tcase message.User:\n\t\t\tif cache, ok := m.cachedContent[msg.ID]; ok && cache.width == m.width {\n\t\t\t\tm.uiMessages = append(m.uiMessages, cache.content...)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tuserMsg := renderUserMessage(\n\t\t\t\tmsg,\n\t\t\t\tmsg.ID == m.currentMsgID,\n\t\t\t\tm.width,\n\t\t\t\tpos,\n\t\t\t)\n\t\t\tm.uiMessages = append(m.uiMessages, userMsg)\n\t\t\tm.cachedContent[msg.ID] = cacheItem{\n\t\t\t\twidth: m.width,\n\t\t\t\tcontent: []uiMessage{userMsg},\n\t\t\t}\n\t\t\tpos += userMsg.height + 1 // + 1 for spacing\n\t\tcase message.Assistant:\n\t\t\tif cache, ok := m.cachedContent[msg.ID]; ok && cache.width == m.width {\n\t\t\t\tm.uiMessages = append(m.uiMessages, cache.content...)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tisSummary := m.session.SummaryMessageID == msg.ID\n\n\t\t\tassistantMessages := renderAssistantMessage(\n\t\t\t\tmsg,\n\t\t\t\tinx,\n\t\t\t\tm.messages,\n\t\t\t\tm.app.Messages,\n\t\t\t\tm.currentMsgID,\n\t\t\t\tisSummary,\n\t\t\t\tm.width,\n\t\t\t\tpos,\n\t\t\t)\n\t\t\tfor _, msg := range assistantMessages {\n\t\t\t\tm.uiMessages = append(m.uiMessages, msg)\n\t\t\t\tpos += msg.height + 1 // + 1 for spacing\n\t\t\t}\n\t\t\tm.cachedContent[msg.ID] = cacheItem{\n\t\t\t\twidth: m.width,\n\t\t\t\tcontent: assistantMessages,\n\t\t\t}\n\t\t}\n\t}\n\n\tmessages := make([]string, 0)\n\tfor _, v := range m.uiMessages {\n\t\tmessages = append(messages, lipgloss.JoinVertical(lipgloss.Left, v.content),\n\t\t\tbaseStyle.\n\t\t\t\tWidth(m.width).\n\t\t\t\tRender(\n\t\t\t\t\t\"\",\n\t\t\t\t),\n\t\t)\n\t}\n\n\tm.viewport.SetContent(\n\t\tbaseStyle.\n\t\t\tWidth(m.width).\n\t\t\tRender(\n\t\t\t\tlipgloss.JoinVertical(\n\t\t\t\t\tlipgloss.Top,\n\t\t\t\t\tmessages...,\n\t\t\t\t),\n\t\t\t),\n\t)\n}\n\nfunc (m *messagesCmp) View() string {\n\tbaseStyle := styles.BaseStyle()\n\n\tif m.rendering {\n\t\treturn baseStyle.\n\t\t\tWidth(m.width).\n\t\t\tRender(\n\t\t\t\tlipgloss.JoinVertical(\n\t\t\t\t\tlipgloss.Top,\n\t\t\t\t\t\"Loading...\",\n\t\t\t\t\tm.working(),\n\t\t\t\t\tm.help(),\n\t\t\t\t),\n\t\t\t)\n\t}\n\tif len(m.messages) == 0 {\n\t\tcontent := baseStyle.\n\t\t\tWidth(m.width).\n\t\t\tHeight(m.height - 1).\n\t\t\tRender(\n\t\t\t\tm.initialScreen(),\n\t\t\t)\n\n\t\treturn baseStyle.\n\t\t\tWidth(m.width).\n\t\t\tRender(\n\t\t\t\tlipgloss.JoinVertical(\n\t\t\t\t\tlipgloss.Top,\n\t\t\t\t\tcontent,\n\t\t\t\t\t\"\",\n\t\t\t\t\tm.help(),\n\t\t\t\t),\n\t\t\t)\n\t}\n\n\treturn baseStyle.\n\t\tWidth(m.width).\n\t\tRender(\n\t\t\tlipgloss.JoinVertical(\n\t\t\t\tlipgloss.Top,\n\t\t\t\tm.viewport.View(),\n\t\t\t\tm.working(),\n\t\t\t\tm.help(),\n\t\t\t),\n\t\t)\n}\n\nfunc hasToolsWithoutResponse(messages []message.Message) bool {\n\ttoolCalls := make([]message.ToolCall, 0)\n\ttoolResults := make([]message.ToolResult, 0)\n\tfor _, m := range messages {\n\t\ttoolCalls = append(toolCalls, m.ToolCalls()...)\n\t\ttoolResults = append(toolResults, m.ToolResults()...)\n\t}\n\n\tfor _, v := range toolCalls {\n\t\tfound := false\n\t\tfor _, r := range toolResults {\n\t\t\tif v.ID == r.ToolCallID {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif !found && v.Finished {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc hasUnfinishedToolCalls(messages []message.Message) bool {\n\ttoolCalls := make([]message.ToolCall, 0)\n\tfor _, m := range messages {\n\t\ttoolCalls = append(toolCalls, m.ToolCalls()...)\n\t}\n\tfor _, v := range toolCalls {\n\t\tif !v.Finished {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc (m *messagesCmp) working() string {\n\ttext := \"\"\n\tif m.IsAgentWorking() && len(m.messages) > 0 {\n\t\tt := theme.CurrentTheme()\n\t\tbaseStyle := styles.BaseStyle()\n\n\t\ttask := \"Thinking...\"\n\t\tlastMessage := m.messages[len(m.messages)-1]\n\t\tif hasToolsWithoutResponse(m.messages) {\n\t\t\ttask = \"Waiting for tool response...\"\n\t\t} else if hasUnfinishedToolCalls(m.messages) {\n\t\t\ttask = \"Building tool call...\"\n\t\t} else if !lastMessage.IsFinished() {\n\t\t\ttask = \"Generating...\"\n\t\t}\n\t\tif task != \"\" {\n\t\t\ttext += baseStyle.\n\t\t\t\tWidth(m.width).\n\t\t\t\tForeground(t.Primary()).\n\t\t\t\tBold(true).\n\t\t\t\tRender(fmt.Sprintf(\"%s %s \", m.spinner.View(), task))\n\t\t}\n\t}\n\treturn text\n}\n\nfunc (m *messagesCmp) help() string {\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\n\ttext := \"\"\n\n\tif m.app.CoderAgent.IsBusy() {\n\t\ttext += lipgloss.JoinHorizontal(\n\t\t\tlipgloss.Left,\n\t\t\tbaseStyle.Foreground(t.TextMuted()).Bold(true).Render(\"press \"),\n\t\t\tbaseStyle.Foreground(t.Text()).Bold(true).Render(\"esc\"),\n\t\t\tbaseStyle.Foreground(t.TextMuted()).Bold(true).Render(\" to exit cancel\"),\n\t\t)\n\t} else {\n\t\ttext += lipgloss.JoinHorizontal(\n\t\t\tlipgloss.Left,\n\t\t\tbaseStyle.Foreground(t.TextMuted()).Bold(true).Render(\"press \"),\n\t\t\tbaseStyle.Foreground(t.Text()).Bold(true).Render(\"enter\"),\n\t\t\tbaseStyle.Foreground(t.TextMuted()).Bold(true).Render(\" to send the message,\"),\n\t\t\tbaseStyle.Foreground(t.TextMuted()).Bold(true).Render(\" write\"),\n\t\t\tbaseStyle.Foreground(t.Text()).Bold(true).Render(\" \\\\\"),\n\t\t\tbaseStyle.Foreground(t.TextMuted()).Bold(true).Render(\" and enter to add a new line\"),\n\t\t)\n\t}\n\treturn baseStyle.\n\t\tWidth(m.width).\n\t\tRender(text)\n}\n\nfunc (m *messagesCmp) initialScreen() string {\n\tbaseStyle := styles.BaseStyle()\n\n\treturn baseStyle.Width(m.width).Render(\n\t\tlipgloss.JoinVertical(\n\t\t\tlipgloss.Top,\n\t\t\theader(m.width),\n\t\t\t\"\",\n\t\t\tlspsConfigured(m.width),\n\t\t),\n\t)\n}\n\nfunc (m *messagesCmp) rerender() {\n\tfor _, msg := range m.messages {\n\t\tdelete(m.cachedContent, msg.ID)\n\t}\n\tm.renderView()\n}\n\nfunc (m *messagesCmp) SetSize(width, height int) tea.Cmd {\n\tif m.width == width && m.height == height {\n\t\treturn nil\n\t}\n\tm.width = width\n\tm.height = height\n\tm.viewport.Width = width\n\tm.viewport.Height = height - 2\n\tm.attachments.Width = width + 40\n\tm.attachments.Height = 3\n\tm.rerender()\n\treturn nil\n}\n\nfunc (m *messagesCmp) GetSize() (int, int) {\n\treturn m.width, m.height\n}\n\n", "suffix_code": "\n\nfunc (m *messagesCmp) BindingKeys() []key.Binding {\n\treturn []key.Binding{\n\t\tm.viewport.KeyMap.PageDown,\n\t\tm.viewport.KeyMap.PageUp,\n\t\tm.viewport.KeyMap.HalfPageUp,\n\t\tm.viewport.KeyMap.HalfPageDown,\n\t}\n}\n\nfunc NewMessagesCmp(app *app.App) tea.Model {\n\ts := spinner.New()\n\ts.Spinner = spinner.Pulse\n\tvp := viewport.New(0, 0)\n\tattachmets := viewport.New(0, 0)\n\tvp.KeyMap.PageUp = messageKeys.PageUp\n\tvp.KeyMap.PageDown = messageKeys.PageDown\n\tvp.KeyMap.HalfPageUp = messageKeys.HalfPageUp\n\tvp.KeyMap.HalfPageDown = messageKeys.HalfPageDown\n\treturn &messagesCmp{\n\t\tapp: app,\n\t\tcachedContent: make(map[string]cacheItem),\n\t\tviewport: vp,\n\t\tspinner: s,\n\t\tattachments: attachmets,\n\t}\n}\n", "middle_code": "func (m *messagesCmp) SetSession(session session.Session) tea.Cmd {\n\tif m.session.ID == session.ID {\n\t\treturn nil\n\t}\n\tm.session = session\n\tmessages, err := m.app.Messages.List(context.Background(), session.ID)\n\tif err != nil {\n\t\treturn util.ReportError(err)\n\t}\n\tm.messages = messages\n\tif len(m.messages) > 0 {\n\t\tm.currentMsgID = m.messages[len(m.messages)-1].ID\n\t}\n\tdelete(m.cachedContent, m.currentMsgID)\n\tm.rendering = true\n\treturn func() tea.Msg {\n\t\tm.renderView()\n\t\treturn renderFinishedMsg{}\n\t}\n}", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "go", "sub_task_type": null}, "context_code": [["/opencode/internal/tui/components/chat/editor.go", "package chat\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"os/exec\"\n\t\"slices\"\n\t\"strings\"\n\t\"unicode\"\n\n\t\"github.com/charmbracelet/bubbles/key\"\n\t\"github.com/charmbracelet/bubbles/textarea\"\n\ttea \"github.com/charmbracelet/bubbletea\"\n\t\"github.com/charmbracelet/lipgloss\"\n\t\"github.com/opencode-ai/opencode/internal/app\"\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n\t\"github.com/opencode-ai/opencode/internal/message\"\n\t\"github.com/opencode-ai/opencode/internal/session\"\n\t\"github.com/opencode-ai/opencode/internal/tui/components/dialog\"\n\t\"github.com/opencode-ai/opencode/internal/tui/layout\"\n\t\"github.com/opencode-ai/opencode/internal/tui/styles\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n\t\"github.com/opencode-ai/opencode/internal/tui/util\"\n)\n\ntype editorCmp struct {\n\twidth int\n\theight int\n\tapp *app.App\n\tsession session.Session\n\ttextarea textarea.Model\n\tattachments []message.Attachment\n\tdeleteMode bool\n}\n\ntype EditorKeyMaps struct {\n\tSend key.Binding\n\tOpenEditor key.Binding\n}\n\ntype bluredEditorKeyMaps struct {\n\tSend key.Binding\n\tFocus key.Binding\n\tOpenEditor key.Binding\n}\ntype DeleteAttachmentKeyMaps struct {\n\tAttachmentDeleteMode key.Binding\n\tEscape key.Binding\n\tDeleteAllAttachments key.Binding\n}\n\nvar editorMaps = EditorKeyMaps{\n\tSend: key.NewBinding(\n\t\tkey.WithKeys(\"enter\", \"ctrl+s\"),\n\t\tkey.WithHelp(\"enter\", \"send message\"),\n\t),\n\tOpenEditor: key.NewBinding(\n\t\tkey.WithKeys(\"ctrl+e\"),\n\t\tkey.WithHelp(\"ctrl+e\", \"open editor\"),\n\t),\n}\n\nvar DeleteKeyMaps = DeleteAttachmentKeyMaps{\n\tAttachmentDeleteMode: key.NewBinding(\n\t\tkey.WithKeys(\"ctrl+r\"),\n\t\tkey.WithHelp(\"ctrl+r+{i}\", \"delete attachment at index i\"),\n\t),\n\tEscape: key.NewBinding(\n\t\tkey.WithKeys(\"esc\"),\n\t\tkey.WithHelp(\"esc\", \"cancel delete mode\"),\n\t),\n\tDeleteAllAttachments: key.NewBinding(\n\t\tkey.WithKeys(\"r\"),\n\t\tkey.WithHelp(\"ctrl+r+r\", \"delete all attchments\"),\n\t),\n}\n\nconst (\n\tmaxAttachments = 5\n)\n\nfunc (m *editorCmp) openEditor() tea.Cmd {\n\teditor := os.Getenv(\"EDITOR\")\n\tif editor == \"\" {\n\t\teditor = \"nvim\"\n\t}\n\n\ttmpfile, err := os.CreateTemp(\"\", \"msg_*.md\")\n\tif err != nil {\n\t\treturn util.ReportError(err)\n\t}\n\ttmpfile.Close()\n\tc := exec.Command(editor, tmpfile.Name()) //nolint:gosec\n\tc.Stdin = os.Stdin\n\tc.Stdout = os.Stdout\n\tc.Stderr = os.Stderr\n\treturn tea.ExecProcess(c, func(err error) tea.Msg {\n\t\tif err != nil {\n\t\t\treturn util.ReportError(err)\n\t\t}\n\t\tcontent, err := os.ReadFile(tmpfile.Name())\n\t\tif err != nil {\n\t\t\treturn util.ReportError(err)\n\t\t}\n\t\tif len(content) == 0 {\n\t\t\treturn util.ReportWarn(\"Message is empty\")\n\t\t}\n\t\tos.Remove(tmpfile.Name())\n\t\tattachments := m.attachments\n\t\tm.attachments = nil\n\t\treturn SendMsg{\n\t\t\tText: string(content),\n\t\t\tAttachments: attachments,\n\t\t}\n\t})\n}\n\nfunc (m *editorCmp) Init() tea.Cmd {\n\treturn textarea.Blink\n}\n\nfunc (m *editorCmp) send() tea.Cmd {\n\tif m.app.CoderAgent.IsSessionBusy(m.session.ID) {\n\t\treturn util.ReportWarn(\"Agent is working, please wait...\")\n\t}\n\n\tvalue := m.textarea.Value()\n\tm.textarea.Reset()\n\tattachments := m.attachments\n\n\tm.attachments = nil\n\tif value == \"\" {\n\t\treturn nil\n\t}\n\treturn tea.Batch(\n\t\tutil.CmdHandler(SendMsg{\n\t\t\tText: value,\n\t\t\tAttachments: attachments,\n\t\t}),\n\t)\n}\n\nfunc (m *editorCmp) Update(msg tea.Msg) (tea.Model, tea.Cmd) {\n\tvar cmd tea.Cmd\n\tswitch msg := msg.(type) {\n\tcase dialog.ThemeChangedMsg:\n\t\tm.textarea = CreateTextArea(&m.textarea)\n\tcase dialog.CompletionSelectedMsg:\n\t\texistingValue := m.textarea.Value()\n\t\tmodifiedValue := strings.Replace(existingValue, msg.SearchString, msg.CompletionValue, 1)\n\n\t\tm.textarea.SetValue(modifiedValue)\n\t\treturn m, nil\n\tcase SessionSelectedMsg:\n\t\tif msg.ID != m.session.ID {\n\t\t\tm.session = msg\n\t\t}\n\t\treturn m, nil\n\tcase dialog.AttachmentAddedMsg:\n\t\tif len(m.attachments) >= maxAttachments {\n\t\t\tlogging.ErrorPersist(fmt.Sprintf(\"cannot add more than %d images\", maxAttachments))\n\t\t\treturn m, cmd\n\t\t}\n\t\tm.attachments = append(m.attachments, msg.Attachment)\n\tcase tea.KeyMsg:\n\t\tif key.Matches(msg, DeleteKeyMaps.AttachmentDeleteMode) {\n\t\t\tm.deleteMode = true\n\t\t\treturn m, nil\n\t\t}\n\t\tif key.Matches(msg, DeleteKeyMaps.DeleteAllAttachments) && m.deleteMode {\n\t\t\tm.deleteMode = false\n\t\t\tm.attachments = nil\n\t\t\treturn m, nil\n\t\t}\n\t\tif m.deleteMode && len(msg.Runes) > 0 && unicode.IsDigit(msg.Runes[0]) {\n\t\t\tnum := int(msg.Runes[0] - '0')\n\t\t\tm.deleteMode = false\n\t\t\tif num < 10 && len(m.attachments) > num {\n\t\t\t\tif num == 0 {\n\t\t\t\t\tm.attachments = m.attachments[num+1:]\n\t\t\t\t} else {\n\t\t\t\t\tm.attachments = slices.Delete(m.attachments, num, num+1)\n\t\t\t\t}\n\t\t\t\treturn m, nil\n\t\t\t}\n\t\t}\n\t\tif key.Matches(msg, messageKeys.PageUp) || key.Matches(msg, messageKeys.PageDown) ||\n\t\t\tkey.Matches(msg, messageKeys.HalfPageUp) || key.Matches(msg, messageKeys.HalfPageDown) {\n\t\t\treturn m, nil\n\t\t}\n\t\tif key.Matches(msg, editorMaps.OpenEditor) {\n\t\t\tif m.app.CoderAgent.IsSessionBusy(m.session.ID) {\n\t\t\t\treturn m, util.ReportWarn(\"Agent is working, please wait...\")\n\t\t\t}\n\t\t\treturn m, m.openEditor()\n\t\t}\n\t\tif key.Matches(msg, DeleteKeyMaps.Escape) {\n\t\t\tm.deleteMode = false\n\t\t\treturn m, nil\n\t\t}\n\t\t// Hanlde Enter key\n\t\tif m.textarea.Focused() && key.Matches(msg, editorMaps.Send) {\n\t\t\tvalue := m.textarea.Value()\n\t\t\tif len(value) > 0 && value[len(value)-1] == '\\\\' {\n\t\t\t\t// If the last character is a backslash, remove it and add a newline\n\t\t\t\tm.textarea.SetValue(value[:len(value)-1] + \"\\n\")\n\t\t\t\treturn m, nil\n\t\t\t} else {\n\t\t\t\t// Otherwise, send the message\n\t\t\t\treturn m, m.send()\n\t\t\t}\n\t\t}\n\n\t}\n\tm.textarea, cmd = m.textarea.Update(msg)\n\treturn m, cmd\n}\n\nfunc (m *editorCmp) View() string {\n\tt := theme.CurrentTheme()\n\n\t// Style the prompt with theme colors\n\tstyle := lipgloss.NewStyle().\n\t\tPadding(0, 0, 0, 1).\n\t\tBold(true).\n\t\tForeground(t.Primary())\n\n\tif len(m.attachments) == 0 {\n\t\treturn lipgloss.JoinHorizontal(lipgloss.Top, style.Render(\">\"), m.textarea.View())\n\t}\n\tm.textarea.SetHeight(m.height - 1)\n\treturn lipgloss.JoinVertical(lipgloss.Top,\n\t\tm.attachmentsContent(),\n\t\tlipgloss.JoinHorizontal(lipgloss.Top, style.Render(\">\"),\n\t\t\tm.textarea.View()),\n\t)\n}\n\nfunc (m *editorCmp) SetSize(width, height int) tea.Cmd {\n\tm.width = width\n\tm.height = height\n\tm.textarea.SetWidth(width - 3) // account for the prompt and padding right\n\tm.textarea.SetHeight(height)\n\tm.textarea.SetWidth(width)\n\treturn nil\n}\n\nfunc (m *editorCmp) GetSize() (int, int) {\n\treturn m.textarea.Width(), m.textarea.Height()\n}\n\nfunc (m *editorCmp) attachmentsContent() string {\n\tvar styledAttachments []string\n\tt := theme.CurrentTheme()\n\tattachmentStyles := styles.BaseStyle().\n\t\tMarginLeft(1).\n\t\tBackground(t.TextMuted()).\n\t\tForeground(t.Text())\n\tfor i, attachment := range m.attachments {\n\t\tvar filename string\n\t\tif len(attachment.FileName) > 10 {\n\t\t\tfilename = fmt.Sprintf(\" %s %s...\", styles.DocumentIcon, attachment.FileName[0:7])\n\t\t} else {\n\t\t\tfilename = fmt.Sprintf(\" %s %s\", styles.DocumentIcon, attachment.FileName)\n\t\t}\n\t\tif m.deleteMode {\n\t\t\tfilename = fmt.Sprintf(\"%d%s\", i, filename)\n\t\t}\n\t\tstyledAttachments = append(styledAttachments, attachmentStyles.Render(filename))\n\t}\n\tcontent := lipgloss.JoinHorizontal(lipgloss.Left, styledAttachments...)\n\treturn content\n}\n\nfunc (m *editorCmp) BindingKeys() []key.Binding {\n\tbindings := []key.Binding{}\n\tbindings = append(bindings, layout.KeyMapToSlice(editorMaps)...)\n\tbindings = append(bindings, layout.KeyMapToSlice(DeleteKeyMaps)...)\n\treturn bindings\n}\n\nfunc CreateTextArea(existing *textarea.Model) textarea.Model {\n\tt := theme.CurrentTheme()\n\tbgColor := t.Background()\n\ttextColor := t.Text()\n\ttextMutedColor := t.TextMuted()\n\n\tta := textarea.New()\n\tta.BlurredStyle.Base = styles.BaseStyle().Background(bgColor).Foreground(textColor)\n\tta.BlurredStyle.CursorLine = styles.BaseStyle().Background(bgColor)\n\tta.BlurredStyle.Placeholder = styles.BaseStyle().Background(bgColor).Foreground(textMutedColor)\n\tta.BlurredStyle.Text = styles.BaseStyle().Background(bgColor).Foreground(textColor)\n\tta.FocusedStyle.Base = styles.BaseStyle().Background(bgColor).Foreground(textColor)\n\tta.FocusedStyle.CursorLine = styles.BaseStyle().Background(bgColor)\n\tta.FocusedStyle.Placeholder = styles.BaseStyle().Background(bgColor).Foreground(textMutedColor)\n\tta.FocusedStyle.Text = styles.BaseStyle().Background(bgColor).Foreground(textColor)\n\n\tta.Prompt = \" \"\n\tta.ShowLineNumbers = false\n\tta.CharLimit = -1\n\n\tif existing != nil {\n\t\tta.SetValue(existing.Value())\n\t\tta.SetWidth(existing.Width())\n\t\tta.SetHeight(existing.Height())\n\t}\n\n\tta.Focus()\n\treturn ta\n}\n\nfunc NewEditorCmp(app *app.App) tea.Model {\n\tta := CreateTextArea(nil)\n\treturn &editorCmp{\n\t\tapp: app,\n\t\ttextarea: ta,\n\t}\n}\n"], ["/opencode/internal/tui/components/chat/sidebar.go", "package chat\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"sort\"\n\t\"strings\"\n\n\ttea \"github.com/charmbracelet/bubbletea\"\n\t\"github.com/charmbracelet/lipgloss\"\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/diff\"\n\t\"github.com/opencode-ai/opencode/internal/history\"\n\t\"github.com/opencode-ai/opencode/internal/pubsub\"\n\t\"github.com/opencode-ai/opencode/internal/session\"\n\t\"github.com/opencode-ai/opencode/internal/tui/styles\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n)\n\ntype sidebarCmp struct {\n\twidth, height int\n\tsession session.Session\n\thistory history.Service\n\tmodFiles map[string]struct {\n\t\tadditions int\n\t\tremovals int\n\t}\n}\n\nfunc (m *sidebarCmp) Init() tea.Cmd {\n\tif m.history != nil {\n\t\tctx := context.Background()\n\t\t// Subscribe to file events\n\t\tfilesCh := m.history.Subscribe(ctx)\n\n\t\t// Initialize the modified files map\n\t\tm.modFiles = make(map[string]struct {\n\t\t\tadditions int\n\t\t\tremovals int\n\t\t})\n\n\t\t// Load initial files and calculate diffs\n\t\tm.loadModifiedFiles(ctx)\n\n\t\t// Return a command that will send file events to the Update method\n\t\treturn func() tea.Msg {\n\t\t\treturn <-filesCh\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (m *sidebarCmp) Update(msg tea.Msg) (tea.Model, tea.Cmd) {\n\tswitch msg := msg.(type) {\n\tcase SessionSelectedMsg:\n\t\tif msg.ID != m.session.ID {\n\t\t\tm.session = msg\n\t\t\tctx := context.Background()\n\t\t\tm.loadModifiedFiles(ctx)\n\t\t}\n\tcase pubsub.Event[session.Session]:\n\t\tif msg.Type == pubsub.UpdatedEvent {\n\t\t\tif m.session.ID == msg.Payload.ID {\n\t\t\t\tm.session = msg.Payload\n\t\t\t}\n\t\t}\n\tcase pubsub.Event[history.File]:\n\t\tif msg.Payload.SessionID == m.session.ID {\n\t\t\t// Process the individual file change instead of reloading all files\n\t\t\tctx := context.Background()\n\t\t\tm.processFileChanges(ctx, msg.Payload)\n\n\t\t\t// Return a command to continue receiving events\n\t\t\treturn m, func() tea.Msg {\n\t\t\t\tctx := context.Background()\n\t\t\t\tfilesCh := m.history.Subscribe(ctx)\n\t\t\t\treturn <-filesCh\n\t\t\t}\n\t\t}\n\t}\n\treturn m, nil\n}\n\nfunc (m *sidebarCmp) View() string {\n\tbaseStyle := styles.BaseStyle()\n\n\treturn baseStyle.\n\t\tWidth(m.width).\n\t\tPaddingLeft(4).\n\t\tPaddingRight(2).\n\t\tHeight(m.height - 1).\n\t\tRender(\n\t\t\tlipgloss.JoinVertical(\n\t\t\t\tlipgloss.Top,\n\t\t\t\theader(m.width),\n\t\t\t\t\" \",\n\t\t\t\tm.sessionSection(),\n\t\t\t\t\" \",\n\t\t\t\tlspsConfigured(m.width),\n\t\t\t\t\" \",\n\t\t\t\tm.modifiedFiles(),\n\t\t\t),\n\t\t)\n}\n\nfunc (m *sidebarCmp) sessionSection() string {\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\n\tsessionKey := baseStyle.\n\t\tForeground(t.Primary()).\n\t\tBold(true).\n\t\tRender(\"Session\")\n\n\tsessionValue := baseStyle.\n\t\tForeground(t.Text()).\n\t\tWidth(m.width - lipgloss.Width(sessionKey)).\n\t\tRender(fmt.Sprintf(\": %s\", m.session.Title))\n\n\treturn lipgloss.JoinHorizontal(\n\t\tlipgloss.Left,\n\t\tsessionKey,\n\t\tsessionValue,\n\t)\n}\n\nfunc (m *sidebarCmp) modifiedFile(filePath string, additions, removals int) string {\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\n\tstats := \"\"\n\tif additions > 0 && removals > 0 {\n\t\tadditionsStr := baseStyle.\n\t\t\tForeground(t.Success()).\n\t\t\tPaddingLeft(1).\n\t\t\tRender(fmt.Sprintf(\"+%d\", additions))\n\n\t\tremovalsStr := baseStyle.\n\t\t\tForeground(t.Error()).\n\t\t\tPaddingLeft(1).\n\t\t\tRender(fmt.Sprintf(\"-%d\", removals))\n\n\t\tcontent := lipgloss.JoinHorizontal(lipgloss.Left, additionsStr, removalsStr)\n\t\tstats = baseStyle.Width(lipgloss.Width(content)).Render(content)\n\t} else if additions > 0 {\n\t\tadditionsStr := fmt.Sprintf(\" %s\", baseStyle.\n\t\t\tPaddingLeft(1).\n\t\t\tForeground(t.Success()).\n\t\t\tRender(fmt.Sprintf(\"+%d\", additions)))\n\t\tstats = baseStyle.Width(lipgloss.Width(additionsStr)).Render(additionsStr)\n\t} else if removals > 0 {\n\t\tremovalsStr := fmt.Sprintf(\" %s\", baseStyle.\n\t\t\tPaddingLeft(1).\n\t\t\tForeground(t.Error()).\n\t\t\tRender(fmt.Sprintf(\"-%d\", removals)))\n\t\tstats = baseStyle.Width(lipgloss.Width(removalsStr)).Render(removalsStr)\n\t}\n\n\tfilePathStr := baseStyle.Render(filePath)\n\n\treturn baseStyle.\n\t\tWidth(m.width).\n\t\tRender(\n\t\t\tlipgloss.JoinHorizontal(\n\t\t\t\tlipgloss.Left,\n\t\t\t\tfilePathStr,\n\t\t\t\tstats,\n\t\t\t),\n\t\t)\n}\n\nfunc (m *sidebarCmp) modifiedFiles() string {\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\n\tmodifiedFiles := baseStyle.\n\t\tWidth(m.width).\n\t\tForeground(t.Primary()).\n\t\tBold(true).\n\t\tRender(\"Modified Files:\")\n\n\t// If no modified files, show a placeholder message\n\tif m.modFiles == nil || len(m.modFiles) == 0 {\n\t\tmessage := \"No modified files\"\n\t\tremainingWidth := m.width - lipgloss.Width(message)\n\t\tif remainingWidth > 0 {\n\t\t\tmessage += strings.Repeat(\" \", remainingWidth)\n\t\t}\n\t\treturn baseStyle.\n\t\t\tWidth(m.width).\n\t\t\tRender(\n\t\t\t\tlipgloss.JoinVertical(\n\t\t\t\t\tlipgloss.Top,\n\t\t\t\t\tmodifiedFiles,\n\t\t\t\t\tbaseStyle.Foreground(t.TextMuted()).Render(message),\n\t\t\t\t),\n\t\t\t)\n\t}\n\n\t// Sort file paths alphabetically for consistent ordering\n\tvar paths []string\n\tfor path := range m.modFiles {\n\t\tpaths = append(paths, path)\n\t}\n\tsort.Strings(paths)\n\n\t// Create views for each file in sorted order\n\tvar fileViews []string\n\tfor _, path := range paths {\n\t\tstats := m.modFiles[path]\n\t\tfileViews = append(fileViews, m.modifiedFile(path, stats.additions, stats.removals))\n\t}\n\n\treturn baseStyle.\n\t\tWidth(m.width).\n\t\tRender(\n\t\t\tlipgloss.JoinVertical(\n\t\t\t\tlipgloss.Top,\n\t\t\t\tmodifiedFiles,\n\t\t\t\tlipgloss.JoinVertical(\n\t\t\t\t\tlipgloss.Left,\n\t\t\t\t\tfileViews...,\n\t\t\t\t),\n\t\t\t),\n\t\t)\n}\n\nfunc (m *sidebarCmp) SetSize(width, height int) tea.Cmd {\n\tm.width = width\n\tm.height = height\n\treturn nil\n}\n\nfunc (m *sidebarCmp) GetSize() (int, int) {\n\treturn m.width, m.height\n}\n\nfunc NewSidebarCmp(session session.Session, history history.Service) tea.Model {\n\treturn &sidebarCmp{\n\t\tsession: session,\n\t\thistory: history,\n\t}\n}\n\nfunc (m *sidebarCmp) loadModifiedFiles(ctx context.Context) {\n\tif m.history == nil || m.session.ID == \"\" {\n\t\treturn\n\t}\n\n\t// Get all latest files for this session\n\tlatestFiles, err := m.history.ListLatestSessionFiles(ctx, m.session.ID)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t// Get all files for this session (to find initial versions)\n\tallFiles, err := m.history.ListBySession(ctx, m.session.ID)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t// Clear the existing map to rebuild it\n\tm.modFiles = make(map[string]struct {\n\t\tadditions int\n\t\tremovals int\n\t})\n\n\t// Process each latest file\n\tfor _, file := range latestFiles {\n\t\t// Skip if this is the initial version (no changes to show)\n\t\tif file.Version == history.InitialVersion {\n\t\t\tcontinue\n\t\t}\n\n\t\t// Find the initial version for this specific file\n\t\tvar initialVersion history.File\n\t\tfor _, v := range allFiles {\n\t\t\tif v.Path == file.Path && v.Version == history.InitialVersion {\n\t\t\t\tinitialVersion = v\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\t// Skip if we can't find the initial version\n\t\tif initialVersion.ID == \"\" {\n\t\t\tcontinue\n\t\t}\n\t\tif initialVersion.Content == file.Content {\n\t\t\tcontinue\n\t\t}\n\n\t\t// Calculate diff between initial and latest version\n\t\t_, additions, removals := diff.GenerateDiff(initialVersion.Content, file.Content, file.Path)\n\n\t\t// Only add to modified files if there are changes\n\t\tif additions > 0 || removals > 0 {\n\t\t\t// Remove working directory prefix from file path\n\t\t\tdisplayPath := file.Path\n\t\t\tworkingDir := config.WorkingDirectory()\n\t\t\tdisplayPath = strings.TrimPrefix(displayPath, workingDir)\n\t\t\tdisplayPath = strings.TrimPrefix(displayPath, \"/\")\n\n\t\t\tm.modFiles[displayPath] = struct {\n\t\t\t\tadditions int\n\t\t\t\tremovals int\n\t\t\t}{\n\t\t\t\tadditions: additions,\n\t\t\t\tremovals: removals,\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc (m *sidebarCmp) processFileChanges(ctx context.Context, file history.File) {\n\t// Skip if this is the initial version (no changes to show)\n\tif file.Version == history.InitialVersion {\n\t\treturn\n\t}\n\n\t// Find the initial version for this file\n\tinitialVersion, err := m.findInitialVersion(ctx, file.Path)\n\tif err != nil || initialVersion.ID == \"\" {\n\t\treturn\n\t}\n\n\t// Skip if content hasn't changed\n\tif initialVersion.Content == file.Content {\n\t\t// If this file was previously modified but now matches the initial version,\n\t\t// remove it from the modified files list\n\t\tdisplayPath := getDisplayPath(file.Path)\n\t\tdelete(m.modFiles, displayPath)\n\t\treturn\n\t}\n\n\t// Calculate diff between initial and latest version\n\t_, additions, removals := diff.GenerateDiff(initialVersion.Content, file.Content, file.Path)\n\n\t// Only add to modified files if there are changes\n\tif additions > 0 || removals > 0 {\n\t\tdisplayPath := getDisplayPath(file.Path)\n\t\tm.modFiles[displayPath] = struct {\n\t\t\tadditions int\n\t\t\tremovals int\n\t\t}{\n\t\t\tadditions: additions,\n\t\t\tremovals: removals,\n\t\t}\n\t} else {\n\t\t// If no changes, remove from modified files\n\t\tdisplayPath := getDisplayPath(file.Path)\n\t\tdelete(m.modFiles, displayPath)\n\t}\n}\n\n// Helper function to find the initial version of a file\nfunc (m *sidebarCmp) findInitialVersion(ctx context.Context, path string) (history.File, error) {\n\t// Get all versions of this file for the session\n\tfileVersions, err := m.history.ListBySession(ctx, m.session.ID)\n\tif err != nil {\n\t\treturn history.File{}, err\n\t}\n\n\t// Find the initial version\n\tfor _, v := range fileVersions {\n\t\tif v.Path == path && v.Version == history.InitialVersion {\n\t\t\treturn v, nil\n\t\t}\n\t}\n\n\treturn history.File{}, fmt.Errorf(\"initial version not found\")\n}\n\n// Helper function to get the display path for a file\nfunc getDisplayPath(path string) string {\n\tworkingDir := config.WorkingDirectory()\n\tdisplayPath := strings.TrimPrefix(path, workingDir)\n\treturn strings.TrimPrefix(displayPath, \"/\")\n}\n"], ["/opencode/internal/tui/components/dialog/arguments.go", "package dialog\n\nimport (\n\t\"fmt\"\n\t\"github.com/charmbracelet/bubbles/key\"\n\t\"github.com/charmbracelet/bubbles/textinput\"\n\ttea \"github.com/charmbracelet/bubbletea\"\n\t\"github.com/charmbracelet/lipgloss\"\n\n\t\"github.com/opencode-ai/opencode/internal/tui/styles\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n\t\"github.com/opencode-ai/opencode/internal/tui/util\"\n)\n\ntype argumentsDialogKeyMap struct {\n\tEnter key.Binding\n\tEscape key.Binding\n}\n\n// ShortHelp implements key.Map.\nfunc (k argumentsDialogKeyMap) ShortHelp() []key.Binding {\n\treturn []key.Binding{\n\t\tkey.NewBinding(\n\t\t\tkey.WithKeys(\"enter\"),\n\t\t\tkey.WithHelp(\"enter\", \"confirm\"),\n\t\t),\n\t\tkey.NewBinding(\n\t\t\tkey.WithKeys(\"esc\"),\n\t\t\tkey.WithHelp(\"esc\", \"cancel\"),\n\t\t),\n\t}\n}\n\n// FullHelp implements key.Map.\nfunc (k argumentsDialogKeyMap) FullHelp() [][]key.Binding {\n\treturn [][]key.Binding{k.ShortHelp()}\n}\n\n// ShowMultiArgumentsDialogMsg is a message that is sent to show the multi-arguments dialog.\ntype ShowMultiArgumentsDialogMsg struct {\n\tCommandID string\n\tContent string\n\tArgNames []string\n}\n\n// CloseMultiArgumentsDialogMsg is a message that is sent when the multi-arguments dialog is closed.\ntype CloseMultiArgumentsDialogMsg struct {\n\tSubmit bool\n\tCommandID string\n\tContent string\n\tArgs map[string]string\n}\n\n// MultiArgumentsDialogCmp is a component that asks the user for multiple command arguments.\ntype MultiArgumentsDialogCmp struct {\n\twidth, height int\n\tinputs []textinput.Model\n\tfocusIndex int\n\tkeys argumentsDialogKeyMap\n\tcommandID string\n\tcontent string\n\targNames []string\n}\n\n// NewMultiArgumentsDialogCmp creates a new MultiArgumentsDialogCmp.\nfunc NewMultiArgumentsDialogCmp(commandID, content string, argNames []string) MultiArgumentsDialogCmp {\n\tt := theme.CurrentTheme()\n\tinputs := make([]textinput.Model, len(argNames))\n\n\tfor i, name := range argNames {\n\t\tti := textinput.New()\n\t\tti.Placeholder = fmt.Sprintf(\"Enter value for %s...\", name)\n\t\tti.Width = 40\n\t\tti.Prompt = \"\"\n\t\tti.PlaceholderStyle = ti.PlaceholderStyle.Background(t.Background())\n\t\tti.PromptStyle = ti.PromptStyle.Background(t.Background())\n\t\tti.TextStyle = ti.TextStyle.Background(t.Background())\n\t\t\n\t\t// Only focus the first input initially\n\t\tif i == 0 {\n\t\t\tti.Focus()\n\t\t\tti.PromptStyle = ti.PromptStyle.Foreground(t.Primary())\n\t\t\tti.TextStyle = ti.TextStyle.Foreground(t.Primary())\n\t\t} else {\n\t\t\tti.Blur()\n\t\t}\n\n\t\tinputs[i] = ti\n\t}\n\n\treturn MultiArgumentsDialogCmp{\n\t\tinputs: inputs,\n\t\tkeys: argumentsDialogKeyMap{},\n\t\tcommandID: commandID,\n\t\tcontent: content,\n\t\targNames: argNames,\n\t\tfocusIndex: 0,\n\t}\n}\n\n// Init implements tea.Model.\nfunc (m MultiArgumentsDialogCmp) Init() tea.Cmd {\n\t// Make sure only the first input is focused\n\tfor i := range m.inputs {\n\t\tif i == 0 {\n\t\t\tm.inputs[i].Focus()\n\t\t} else {\n\t\t\tm.inputs[i].Blur()\n\t\t}\n\t}\n\t\n\treturn textinput.Blink\n}\n\n// Update implements tea.Model.\nfunc (m MultiArgumentsDialogCmp) Update(msg tea.Msg) (tea.Model, tea.Cmd) {\n\tvar cmds []tea.Cmd\n\tt := theme.CurrentTheme()\n\n\tswitch msg := msg.(type) {\n\tcase tea.KeyMsg:\n\t\tswitch {\n\t\tcase key.Matches(msg, key.NewBinding(key.WithKeys(\"esc\"))):\n\t\t\treturn m, util.CmdHandler(CloseMultiArgumentsDialogMsg{\n\t\t\t\tSubmit: false,\n\t\t\t\tCommandID: m.commandID,\n\t\t\t\tContent: m.content,\n\t\t\t\tArgs: nil,\n\t\t\t})\n\t\tcase key.Matches(msg, key.NewBinding(key.WithKeys(\"enter\"))):\n\t\t\t// If we're on the last input, submit the form\n\t\t\tif m.focusIndex == len(m.inputs)-1 {\n\t\t\t\targs := make(map[string]string)\n\t\t\t\tfor i, name := range m.argNames {\n\t\t\t\t\targs[name] = m.inputs[i].Value()\n\t\t\t\t}\n\t\t\t\treturn m, util.CmdHandler(CloseMultiArgumentsDialogMsg{\n\t\t\t\t\tSubmit: true,\n\t\t\t\t\tCommandID: m.commandID,\n\t\t\t\t\tContent: m.content,\n\t\t\t\t\tArgs: args,\n\t\t\t\t})\n\t\t\t}\n\t\t\t// Otherwise, move to the next input\n\t\t\tm.inputs[m.focusIndex].Blur()\n\t\t\tm.focusIndex++\n\t\t\tm.inputs[m.focusIndex].Focus()\n\t\t\tm.inputs[m.focusIndex].PromptStyle = m.inputs[m.focusIndex].PromptStyle.Foreground(t.Primary())\n\t\t\tm.inputs[m.focusIndex].TextStyle = m.inputs[m.focusIndex].TextStyle.Foreground(t.Primary())\n\t\tcase key.Matches(msg, key.NewBinding(key.WithKeys(\"tab\"))):\n\t\t\t// Move to the next input\n\t\t\tm.inputs[m.focusIndex].Blur()\n\t\t\tm.focusIndex = (m.focusIndex + 1) % len(m.inputs)\n\t\t\tm.inputs[m.focusIndex].Focus()\n\t\t\tm.inputs[m.focusIndex].PromptStyle = m.inputs[m.focusIndex].PromptStyle.Foreground(t.Primary())\n\t\t\tm.inputs[m.focusIndex].TextStyle = m.inputs[m.focusIndex].TextStyle.Foreground(t.Primary())\n\t\tcase key.Matches(msg, key.NewBinding(key.WithKeys(\"shift+tab\"))):\n\t\t\t// Move to the previous input\n\t\t\tm.inputs[m.focusIndex].Blur()\n\t\t\tm.focusIndex = (m.focusIndex - 1 + len(m.inputs)) % len(m.inputs)\n\t\t\tm.inputs[m.focusIndex].Focus()\n\t\t\tm.inputs[m.focusIndex].PromptStyle = m.inputs[m.focusIndex].PromptStyle.Foreground(t.Primary())\n\t\t\tm.inputs[m.focusIndex].TextStyle = m.inputs[m.focusIndex].TextStyle.Foreground(t.Primary())\n\t\t}\n\tcase tea.WindowSizeMsg:\n\t\tm.width = msg.Width\n\t\tm.height = msg.Height\n\t}\n\n\t// Update the focused input\n\tvar cmd tea.Cmd\n\tm.inputs[m.focusIndex], cmd = m.inputs[m.focusIndex].Update(msg)\n\tcmds = append(cmds, cmd)\n\n\treturn m, tea.Batch(cmds...)\n}\n\n// View implements tea.Model.\nfunc (m MultiArgumentsDialogCmp) View() string {\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\n\t// Calculate width needed for content\n\tmaxWidth := 60 // Width for explanation text\n\n\ttitle := lipgloss.NewStyle().\n\t\tForeground(t.Primary()).\n\t\tBold(true).\n\t\tWidth(maxWidth).\n\t\tPadding(0, 1).\n\t\tBackground(t.Background()).\n\t\tRender(\"Command Arguments\")\n\n\texplanation := lipgloss.NewStyle().\n\t\tForeground(t.Text()).\n\t\tWidth(maxWidth).\n\t\tPadding(0, 1).\n\t\tBackground(t.Background()).\n\t\tRender(\"This command requires multiple arguments. Please enter values for each:\")\n\n\t// Create input fields for each argument\n\tinputFields := make([]string, len(m.inputs))\n\tfor i, input := range m.inputs {\n\t\t// Highlight the label of the focused input\n\t\tlabelStyle := lipgloss.NewStyle().\n\t\t\tWidth(maxWidth).\n\t\t\tPadding(1, 1, 0, 1).\n\t\t\tBackground(t.Background())\n\t\t\t\n\t\tif i == m.focusIndex {\n\t\t\tlabelStyle = labelStyle.Foreground(t.Primary()).Bold(true)\n\t\t} else {\n\t\t\tlabelStyle = labelStyle.Foreground(t.TextMuted())\n\t\t}\n\t\t\n\t\tlabel := labelStyle.Render(m.argNames[i] + \":\")\n\n\t\tfield := lipgloss.NewStyle().\n\t\t\tForeground(t.Text()).\n\t\t\tWidth(maxWidth).\n\t\t\tPadding(0, 1).\n\t\t\tBackground(t.Background()).\n\t\t\tRender(input.View())\n\n\t\tinputFields[i] = lipgloss.JoinVertical(lipgloss.Left, label, field)\n\t}\n\n\tmaxWidth = min(maxWidth, m.width-10)\n\n\t// Join all elements vertically\n\telements := []string{title, explanation}\n\telements = append(elements, inputFields...)\n\n\tcontent := lipgloss.JoinVertical(\n\t\tlipgloss.Left,\n\t\telements...,\n\t)\n\n\treturn baseStyle.Padding(1, 2).\n\t\tBorder(lipgloss.RoundedBorder()).\n\t\tBorderBackground(t.Background()).\n\t\tBorderForeground(t.TextMuted()).\n\t\tBackground(t.Background()).\n\t\tWidth(lipgloss.Width(content) + 4).\n\t\tRender(content)\n}\n\n// SetSize sets the size of the component.\nfunc (m *MultiArgumentsDialogCmp) SetSize(width, height int) {\n\tm.width = width\n\tm.height = height\n}\n\n// Bindings implements layout.Bindings.\nfunc (m MultiArgumentsDialogCmp) Bindings() []key.Binding {\n\treturn m.keys.ShortHelp()\n}"], ["/opencode/internal/tui/components/dialog/models.go", "package dialog\n\nimport (\n\t\"fmt\"\n\t\"slices\"\n\t\"strings\"\n\n\t\"github.com/charmbracelet/bubbles/key\"\n\ttea \"github.com/charmbracelet/bubbletea\"\n\t\"github.com/charmbracelet/lipgloss\"\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/llm/models\"\n\t\"github.com/opencode-ai/opencode/internal/tui/layout\"\n\t\"github.com/opencode-ai/opencode/internal/tui/styles\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n\t\"github.com/opencode-ai/opencode/internal/tui/util\"\n)\n\nconst (\n\tnumVisibleModels = 10\n\tmaxDialogWidth = 40\n)\n\n// ModelSelectedMsg is sent when a model is selected\ntype ModelSelectedMsg struct {\n\tModel models.Model\n}\n\n// CloseModelDialogMsg is sent when a model is selected\ntype CloseModelDialogMsg struct{}\n\n// ModelDialog interface for the model selection dialog\ntype ModelDialog interface {\n\ttea.Model\n\tlayout.Bindings\n}\n\ntype modelDialogCmp struct {\n\tmodels []models.Model\n\tprovider models.ModelProvider\n\tavailableProviders []models.ModelProvider\n\n\tselectedIdx int\n\twidth int\n\theight int\n\tscrollOffset int\n\thScrollOffset int\n\thScrollPossible bool\n}\n\ntype modelKeyMap struct {\n\tUp key.Binding\n\tDown key.Binding\n\tLeft key.Binding\n\tRight key.Binding\n\tEnter key.Binding\n\tEscape key.Binding\n\tJ key.Binding\n\tK key.Binding\n\tH key.Binding\n\tL key.Binding\n}\n\nvar modelKeys = modelKeyMap{\n\tUp: key.NewBinding(\n\t\tkey.WithKeys(\"up\"),\n\t\tkey.WithHelp(\"↑\", \"previous model\"),\n\t),\n\tDown: key.NewBinding(\n\t\tkey.WithKeys(\"down\"),\n\t\tkey.WithHelp(\"↓\", \"next model\"),\n\t),\n\tLeft: key.NewBinding(\n\t\tkey.WithKeys(\"left\"),\n\t\tkey.WithHelp(\"←\", \"scroll left\"),\n\t),\n\tRight: key.NewBinding(\n\t\tkey.WithKeys(\"right\"),\n\t\tkey.WithHelp(\"→\", \"scroll right\"),\n\t),\n\tEnter: key.NewBinding(\n\t\tkey.WithKeys(\"enter\"),\n\t\tkey.WithHelp(\"enter\", \"select model\"),\n\t),\n\tEscape: key.NewBinding(\n\t\tkey.WithKeys(\"esc\"),\n\t\tkey.WithHelp(\"esc\", \"close\"),\n\t),\n\tJ: key.NewBinding(\n\t\tkey.WithKeys(\"j\"),\n\t\tkey.WithHelp(\"j\", \"next model\"),\n\t),\n\tK: key.NewBinding(\n\t\tkey.WithKeys(\"k\"),\n\t\tkey.WithHelp(\"k\", \"previous model\"),\n\t),\n\tH: key.NewBinding(\n\t\tkey.WithKeys(\"h\"),\n\t\tkey.WithHelp(\"h\", \"scroll left\"),\n\t),\n\tL: key.NewBinding(\n\t\tkey.WithKeys(\"l\"),\n\t\tkey.WithHelp(\"l\", \"scroll right\"),\n\t),\n}\n\nfunc (m *modelDialogCmp) Init() tea.Cmd {\n\tm.setupModels()\n\treturn nil\n}\n\nfunc (m *modelDialogCmp) Update(msg tea.Msg) (tea.Model, tea.Cmd) {\n\tswitch msg := msg.(type) {\n\tcase tea.KeyMsg:\n\t\tswitch {\n\t\tcase key.Matches(msg, modelKeys.Up) || key.Matches(msg, modelKeys.K):\n\t\t\tm.moveSelectionUp()\n\t\tcase key.Matches(msg, modelKeys.Down) || key.Matches(msg, modelKeys.J):\n\t\t\tm.moveSelectionDown()\n\t\tcase key.Matches(msg, modelKeys.Left) || key.Matches(msg, modelKeys.H):\n\t\t\tif m.hScrollPossible {\n\t\t\t\tm.switchProvider(-1)\n\t\t\t}\n\t\tcase key.Matches(msg, modelKeys.Right) || key.Matches(msg, modelKeys.L):\n\t\t\tif m.hScrollPossible {\n\t\t\t\tm.switchProvider(1)\n\t\t\t}\n\t\tcase key.Matches(msg, modelKeys.Enter):\n\t\t\tutil.ReportInfo(fmt.Sprintf(\"selected model: %s\", m.models[m.selectedIdx].Name))\n\t\t\treturn m, util.CmdHandler(ModelSelectedMsg{Model: m.models[m.selectedIdx]})\n\t\tcase key.Matches(msg, modelKeys.Escape):\n\t\t\treturn m, util.CmdHandler(CloseModelDialogMsg{})\n\t\t}\n\tcase tea.WindowSizeMsg:\n\t\tm.width = msg.Width\n\t\tm.height = msg.Height\n\t}\n\n\treturn m, nil\n}\n\n// moveSelectionUp moves the selection up or wraps to bottom\nfunc (m *modelDialogCmp) moveSelectionUp() {\n\tif m.selectedIdx > 0 {\n\t\tm.selectedIdx--\n\t} else {\n\t\tm.selectedIdx = len(m.models) - 1\n\t\tm.scrollOffset = max(0, len(m.models)-numVisibleModels)\n\t}\n\n\t// Keep selection visible\n\tif m.selectedIdx < m.scrollOffset {\n\t\tm.scrollOffset = m.selectedIdx\n\t}\n}\n\n// moveSelectionDown moves the selection down or wraps to top\nfunc (m *modelDialogCmp) moveSelectionDown() {\n\tif m.selectedIdx < len(m.models)-1 {\n\t\tm.selectedIdx++\n\t} else {\n\t\tm.selectedIdx = 0\n\t\tm.scrollOffset = 0\n\t}\n\n\t// Keep selection visible\n\tif m.selectedIdx >= m.scrollOffset+numVisibleModels {\n\t\tm.scrollOffset = m.selectedIdx - (numVisibleModels - 1)\n\t}\n}\n\nfunc (m *modelDialogCmp) switchProvider(offset int) {\n\tnewOffset := m.hScrollOffset + offset\n\n\t// Ensure we stay within bounds\n\tif newOffset < 0 {\n\t\tnewOffset = len(m.availableProviders) - 1\n\t}\n\tif newOffset >= len(m.availableProviders) {\n\t\tnewOffset = 0\n\t}\n\n\tm.hScrollOffset = newOffset\n\tm.provider = m.availableProviders[m.hScrollOffset]\n\tm.setupModelsForProvider(m.provider)\n}\n\nfunc (m *modelDialogCmp) View() string {\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\n\t// Capitalize first letter of provider name\n\tproviderName := strings.ToUpper(string(m.provider)[:1]) + string(m.provider[1:])\n\ttitle := baseStyle.\n\t\tForeground(t.Primary()).\n\t\tBold(true).\n\t\tWidth(maxDialogWidth).\n\t\tPadding(0, 0, 1).\n\t\tRender(fmt.Sprintf(\"Select %s Model\", providerName))\n\n\t// Render visible models\n\tendIdx := min(m.scrollOffset+numVisibleModels, len(m.models))\n\tmodelItems := make([]string, 0, endIdx-m.scrollOffset)\n\n\tfor i := m.scrollOffset; i < endIdx; i++ {\n\t\titemStyle := baseStyle.Width(maxDialogWidth)\n\t\tif i == m.selectedIdx {\n\t\t\titemStyle = itemStyle.Background(t.Primary()).\n\t\t\t\tForeground(t.Background()).Bold(true)\n\t\t}\n\t\tmodelItems = append(modelItems, itemStyle.Render(m.models[i].Name))\n\t}\n\n\tscrollIndicator := m.getScrollIndicators(maxDialogWidth)\n\n\tcontent := lipgloss.JoinVertical(\n\t\tlipgloss.Left,\n\t\ttitle,\n\t\tbaseStyle.Width(maxDialogWidth).Render(lipgloss.JoinVertical(lipgloss.Left, modelItems...)),\n\t\tscrollIndicator,\n\t)\n\n\treturn baseStyle.Padding(1, 2).\n\t\tBorder(lipgloss.RoundedBorder()).\n\t\tBorderBackground(t.Background()).\n\t\tBorderForeground(t.TextMuted()).\n\t\tWidth(lipgloss.Width(content) + 4).\n\t\tRender(content)\n}\n\nfunc (m *modelDialogCmp) getScrollIndicators(maxWidth int) string {\n\tvar indicator string\n\n\tif len(m.models) > numVisibleModels {\n\t\tif m.scrollOffset > 0 {\n\t\t\tindicator += \"↑ \"\n\t\t}\n\t\tif m.scrollOffset+numVisibleModels < len(m.models) {\n\t\t\tindicator += \"↓ \"\n\t\t}\n\t}\n\n\tif m.hScrollPossible {\n\t\tif m.hScrollOffset > 0 {\n\t\t\tindicator = \"← \" + indicator\n\t\t}\n\t\tif m.hScrollOffset < len(m.availableProviders)-1 {\n\t\t\tindicator += \"→\"\n\t\t}\n\t}\n\n\tif indicator == \"\" {\n\t\treturn \"\"\n\t}\n\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\n\treturn baseStyle.\n\t\tForeground(t.Primary()).\n\t\tWidth(maxWidth).\n\t\tAlign(lipgloss.Right).\n\t\tBold(true).\n\t\tRender(indicator)\n}\n\nfunc (m *modelDialogCmp) BindingKeys() []key.Binding {\n\treturn layout.KeyMapToSlice(modelKeys)\n}\n\nfunc (m *modelDialogCmp) setupModels() {\n\tcfg := config.Get()\n\tmodelInfo := GetSelectedModel(cfg)\n\tm.availableProviders = getEnabledProviders(cfg)\n\tm.hScrollPossible = len(m.availableProviders) > 1\n\n\tm.provider = modelInfo.Provider\n\tm.hScrollOffset = findProviderIndex(m.availableProviders, m.provider)\n\n\tm.setupModelsForProvider(m.provider)\n}\n\nfunc GetSelectedModel(cfg *config.Config) models.Model {\n\n\tagentCfg := cfg.Agents[config.AgentCoder]\n\tselectedModelId := agentCfg.Model\n\treturn models.SupportedModels[selectedModelId]\n}\n\nfunc getEnabledProviders(cfg *config.Config) []models.ModelProvider {\n\tvar providers []models.ModelProvider\n\tfor providerId, provider := range cfg.Providers {\n\t\tif !provider.Disabled {\n\t\t\tproviders = append(providers, providerId)\n\t\t}\n\t}\n\n\t// Sort by provider popularity\n\tslices.SortFunc(providers, func(a, b models.ModelProvider) int {\n\t\trA := models.ProviderPopularity[a]\n\t\trB := models.ProviderPopularity[b]\n\n\t\t// models not included in popularity ranking default to last\n\t\tif rA == 0 {\n\t\t\trA = 999\n\t\t}\n\t\tif rB == 0 {\n\t\t\trB = 999\n\t\t}\n\t\treturn rA - rB\n\t})\n\treturn providers\n}\n\n// findProviderIndex returns the index of the provider in the list, or -1 if not found\nfunc findProviderIndex(providers []models.ModelProvider, provider models.ModelProvider) int {\n\tfor i, p := range providers {\n\t\tif p == provider {\n\t\t\treturn i\n\t\t}\n\t}\n\treturn -1\n}\n\nfunc (m *modelDialogCmp) setupModelsForProvider(provider models.ModelProvider) {\n\tcfg := config.Get()\n\tagentCfg := cfg.Agents[config.AgentCoder]\n\tselectedModelId := agentCfg.Model\n\n\tm.provider = provider\n\tm.models = getModelsForProvider(provider)\n\tm.selectedIdx = 0\n\tm.scrollOffset = 0\n\n\t// Try to select the current model if it belongs to this provider\n\tif provider == models.SupportedModels[selectedModelId].Provider {\n\t\tfor i, model := range m.models {\n\t\t\tif model.ID == selectedModelId {\n\t\t\t\tm.selectedIdx = i\n\t\t\t\t// Adjust scroll position to keep selected model visible\n\t\t\t\tif m.selectedIdx >= numVisibleModels {\n\t\t\t\t\tm.scrollOffset = m.selectedIdx - (numVisibleModels - 1)\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc getModelsForProvider(provider models.ModelProvider) []models.Model {\n\tvar providerModels []models.Model\n\tfor _, model := range models.SupportedModels {\n\t\tif model.Provider == provider {\n\t\t\tproviderModels = append(providerModels, model)\n\t\t}\n\t}\n\n\t// reverse alphabetical order (if llm naming was consistent latest would appear first)\n\tslices.SortFunc(providerModels, func(a, b models.Model) int {\n\t\tif a.Name > b.Name {\n\t\t\treturn -1\n\t\t} else if a.Name < b.Name {\n\t\t\treturn 1\n\t\t}\n\t\treturn 0\n\t})\n\n\treturn providerModels\n}\n\nfunc NewModelDialogCmp() ModelDialog {\n\treturn &modelDialogCmp{}\n}\n"], ["/opencode/internal/tui/components/dialog/permission.go", "package dialog\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\n\t\"github.com/charmbracelet/bubbles/key\"\n\t\"github.com/charmbracelet/bubbles/viewport\"\n\ttea \"github.com/charmbracelet/bubbletea\"\n\t\"github.com/charmbracelet/lipgloss\"\n\t\"github.com/opencode-ai/opencode/internal/diff\"\n\t\"github.com/opencode-ai/opencode/internal/llm/tools\"\n\t\"github.com/opencode-ai/opencode/internal/permission\"\n\t\"github.com/opencode-ai/opencode/internal/tui/layout\"\n\t\"github.com/opencode-ai/opencode/internal/tui/styles\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n\t\"github.com/opencode-ai/opencode/internal/tui/util\"\n)\n\ntype PermissionAction string\n\n// Permission responses\nconst (\n\tPermissionAllow PermissionAction = \"allow\"\n\tPermissionAllowForSession PermissionAction = \"allow_session\"\n\tPermissionDeny PermissionAction = \"deny\"\n)\n\n// PermissionResponseMsg represents the user's response to a permission request\ntype PermissionResponseMsg struct {\n\tPermission permission.PermissionRequest\n\tAction PermissionAction\n}\n\n// PermissionDialogCmp interface for permission dialog component\ntype PermissionDialogCmp interface {\n\ttea.Model\n\tlayout.Bindings\n\tSetPermissions(permission permission.PermissionRequest) tea.Cmd\n}\n\ntype permissionsMapping struct {\n\tLeft key.Binding\n\tRight key.Binding\n\tEnterSpace key.Binding\n\tAllow key.Binding\n\tAllowSession key.Binding\n\tDeny key.Binding\n\tTab key.Binding\n}\n\nvar permissionsKeys = permissionsMapping{\n\tLeft: key.NewBinding(\n\t\tkey.WithKeys(\"left\"),\n\t\tkey.WithHelp(\"←\", \"switch options\"),\n\t),\n\tRight: key.NewBinding(\n\t\tkey.WithKeys(\"right\"),\n\t\tkey.WithHelp(\"→\", \"switch options\"),\n\t),\n\tEnterSpace: key.NewBinding(\n\t\tkey.WithKeys(\"enter\", \" \"),\n\t\tkey.WithHelp(\"enter/space\", \"confirm\"),\n\t),\n\tAllow: key.NewBinding(\n\t\tkey.WithKeys(\"a\"),\n\t\tkey.WithHelp(\"a\", \"allow\"),\n\t),\n\tAllowSession: key.NewBinding(\n\t\tkey.WithKeys(\"s\"),\n\t\tkey.WithHelp(\"s\", \"allow for session\"),\n\t),\n\tDeny: key.NewBinding(\n\t\tkey.WithKeys(\"d\"),\n\t\tkey.WithHelp(\"d\", \"deny\"),\n\t),\n\tTab: key.NewBinding(\n\t\tkey.WithKeys(\"tab\"),\n\t\tkey.WithHelp(\"tab\", \"switch options\"),\n\t),\n}\n\n// permissionDialogCmp is the implementation of PermissionDialog\ntype permissionDialogCmp struct {\n\twidth int\n\theight int\n\tpermission permission.PermissionRequest\n\twindowSize tea.WindowSizeMsg\n\tcontentViewPort viewport.Model\n\tselectedOption int // 0: Allow, 1: Allow for session, 2: Deny\n\n\tdiffCache map[string]string\n\tmarkdownCache map[string]string\n}\n\nfunc (p *permissionDialogCmp) Init() tea.Cmd {\n\treturn p.contentViewPort.Init()\n}\n\nfunc (p *permissionDialogCmp) Update(msg tea.Msg) (tea.Model, tea.Cmd) {\n\tvar cmds []tea.Cmd\n\n\tswitch msg := msg.(type) {\n\tcase tea.WindowSizeMsg:\n\t\tp.windowSize = msg\n\t\tcmd := p.SetSize()\n\t\tcmds = append(cmds, cmd)\n\t\tp.markdownCache = make(map[string]string)\n\t\tp.diffCache = make(map[string]string)\n\tcase tea.KeyMsg:\n\t\tswitch {\n\t\tcase key.Matches(msg, permissionsKeys.Right) || key.Matches(msg, permissionsKeys.Tab):\n\t\t\tp.selectedOption = (p.selectedOption + 1) % 3\n\t\t\treturn p, nil\n\t\tcase key.Matches(msg, permissionsKeys.Left):\n\t\t\tp.selectedOption = (p.selectedOption + 2) % 3\n\t\tcase key.Matches(msg, permissionsKeys.EnterSpace):\n\t\t\treturn p, p.selectCurrentOption()\n\t\tcase key.Matches(msg, permissionsKeys.Allow):\n\t\t\treturn p, util.CmdHandler(PermissionResponseMsg{Action: PermissionAllow, Permission: p.permission})\n\t\tcase key.Matches(msg, permissionsKeys.AllowSession):\n\t\t\treturn p, util.CmdHandler(PermissionResponseMsg{Action: PermissionAllowForSession, Permission: p.permission})\n\t\tcase key.Matches(msg, permissionsKeys.Deny):\n\t\t\treturn p, util.CmdHandler(PermissionResponseMsg{Action: PermissionDeny, Permission: p.permission})\n\t\tdefault:\n\t\t\t// Pass other keys to viewport\n\t\t\tviewPort, cmd := p.contentViewPort.Update(msg)\n\t\t\tp.contentViewPort = viewPort\n\t\t\tcmds = append(cmds, cmd)\n\t\t}\n\t}\n\n\treturn p, tea.Batch(cmds...)\n}\n\nfunc (p *permissionDialogCmp) selectCurrentOption() tea.Cmd {\n\tvar action PermissionAction\n\n\tswitch p.selectedOption {\n\tcase 0:\n\t\taction = PermissionAllow\n\tcase 1:\n\t\taction = PermissionAllowForSession\n\tcase 2:\n\t\taction = PermissionDeny\n\t}\n\n\treturn util.CmdHandler(PermissionResponseMsg{Action: action, Permission: p.permission})\n}\n\nfunc (p *permissionDialogCmp) renderButtons() string {\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\n\tallowStyle := baseStyle\n\tallowSessionStyle := baseStyle\n\tdenyStyle := baseStyle\n\tspacerStyle := baseStyle.Background(t.Background())\n\n\t// Style the selected button\n\tswitch p.selectedOption {\n\tcase 0:\n\t\tallowStyle = allowStyle.Background(t.Primary()).Foreground(t.Background())\n\t\tallowSessionStyle = allowSessionStyle.Background(t.Background()).Foreground(t.Primary())\n\t\tdenyStyle = denyStyle.Background(t.Background()).Foreground(t.Primary())\n\tcase 1:\n\t\tallowStyle = allowStyle.Background(t.Background()).Foreground(t.Primary())\n\t\tallowSessionStyle = allowSessionStyle.Background(t.Primary()).Foreground(t.Background())\n\t\tdenyStyle = denyStyle.Background(t.Background()).Foreground(t.Primary())\n\tcase 2:\n\t\tallowStyle = allowStyle.Background(t.Background()).Foreground(t.Primary())\n\t\tallowSessionStyle = allowSessionStyle.Background(t.Background()).Foreground(t.Primary())\n\t\tdenyStyle = denyStyle.Background(t.Primary()).Foreground(t.Background())\n\t}\n\n\tallowButton := allowStyle.Padding(0, 1).Render(\"Allow (a)\")\n\tallowSessionButton := allowSessionStyle.Padding(0, 1).Render(\"Allow for session (s)\")\n\tdenyButton := denyStyle.Padding(0, 1).Render(\"Deny (d)\")\n\n\tcontent := lipgloss.JoinHorizontal(\n\t\tlipgloss.Left,\n\t\tallowButton,\n\t\tspacerStyle.Render(\" \"),\n\t\tallowSessionButton,\n\t\tspacerStyle.Render(\" \"),\n\t\tdenyButton,\n\t\tspacerStyle.Render(\" \"),\n\t)\n\n\tremainingWidth := p.width - lipgloss.Width(content)\n\tif remainingWidth > 0 {\n\t\tcontent = spacerStyle.Render(strings.Repeat(\" \", remainingWidth)) + content\n\t}\n\treturn content\n}\n\nfunc (p *permissionDialogCmp) renderHeader() string {\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\n\ttoolKey := baseStyle.Foreground(t.TextMuted()).Bold(true).Render(\"Tool\")\n\ttoolValue := baseStyle.\n\t\tForeground(t.Text()).\n\t\tWidth(p.width - lipgloss.Width(toolKey)).\n\t\tRender(fmt.Sprintf(\": %s\", p.permission.ToolName))\n\n\tpathKey := baseStyle.Foreground(t.TextMuted()).Bold(true).Render(\"Path\")\n\tpathValue := baseStyle.\n\t\tForeground(t.Text()).\n\t\tWidth(p.width - lipgloss.Width(pathKey)).\n\t\tRender(fmt.Sprintf(\": %s\", p.permission.Path))\n\n\theaderParts := []string{\n\t\tlipgloss.JoinHorizontal(\n\t\t\tlipgloss.Left,\n\t\t\ttoolKey,\n\t\t\ttoolValue,\n\t\t),\n\t\tbaseStyle.Render(strings.Repeat(\" \", p.width)),\n\t\tlipgloss.JoinHorizontal(\n\t\t\tlipgloss.Left,\n\t\t\tpathKey,\n\t\t\tpathValue,\n\t\t),\n\t\tbaseStyle.Render(strings.Repeat(\" \", p.width)),\n\t}\n\n\t// Add tool-specific header information\n\tswitch p.permission.ToolName {\n\tcase tools.BashToolName:\n\t\theaderParts = append(headerParts, baseStyle.Foreground(t.TextMuted()).Width(p.width).Bold(true).Render(\"Command\"))\n\tcase tools.EditToolName:\n\t\tparams := p.permission.Params.(tools.EditPermissionsParams)\n\t\tfileKey := baseStyle.Foreground(t.TextMuted()).Bold(true).Render(\"File\")\n\t\tfilePath := baseStyle.\n\t\t\tForeground(t.Text()).\n\t\t\tWidth(p.width - lipgloss.Width(fileKey)).\n\t\t\tRender(fmt.Sprintf(\": %s\", params.FilePath))\n\t\theaderParts = append(headerParts,\n\t\t\tlipgloss.JoinHorizontal(\n\t\t\t\tlipgloss.Left,\n\t\t\t\tfileKey,\n\t\t\t\tfilePath,\n\t\t\t),\n\t\t\tbaseStyle.Render(strings.Repeat(\" \", p.width)),\n\t\t)\n\n\tcase tools.WriteToolName:\n\t\tparams := p.permission.Params.(tools.WritePermissionsParams)\n\t\tfileKey := baseStyle.Foreground(t.TextMuted()).Bold(true).Render(\"File\")\n\t\tfilePath := baseStyle.\n\t\t\tForeground(t.Text()).\n\t\t\tWidth(p.width - lipgloss.Width(fileKey)).\n\t\t\tRender(fmt.Sprintf(\": %s\", params.FilePath))\n\t\theaderParts = append(headerParts,\n\t\t\tlipgloss.JoinHorizontal(\n\t\t\t\tlipgloss.Left,\n\t\t\t\tfileKey,\n\t\t\t\tfilePath,\n\t\t\t),\n\t\t\tbaseStyle.Render(strings.Repeat(\" \", p.width)),\n\t\t)\n\tcase tools.FetchToolName:\n\t\theaderParts = append(headerParts, baseStyle.Foreground(t.TextMuted()).Width(p.width).Bold(true).Render(\"URL\"))\n\t}\n\n\treturn lipgloss.NewStyle().Background(t.Background()).Render(lipgloss.JoinVertical(lipgloss.Left, headerParts...))\n}\n\nfunc (p *permissionDialogCmp) renderBashContent() string {\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\n\tif pr, ok := p.permission.Params.(tools.BashPermissionsParams); ok {\n\t\tcontent := fmt.Sprintf(\"```bash\\n%s\\n```\", pr.Command)\n\n\t\t// Use the cache for markdown rendering\n\t\trenderedContent := p.GetOrSetMarkdown(p.permission.ID, func() (string, error) {\n\t\t\tr := styles.GetMarkdownRenderer(p.width - 10)\n\t\t\ts, err := r.Render(content)\n\t\t\treturn styles.ForceReplaceBackgroundWithLipgloss(s, t.Background()), err\n\t\t})\n\n\t\tfinalContent := baseStyle.\n\t\t\tWidth(p.contentViewPort.Width).\n\t\t\tRender(renderedContent)\n\t\tp.contentViewPort.SetContent(finalContent)\n\t\treturn p.styleViewport()\n\t}\n\treturn \"\"\n}\n\nfunc (p *permissionDialogCmp) renderEditContent() string {\n\tif pr, ok := p.permission.Params.(tools.EditPermissionsParams); ok {\n\t\tdiff := p.GetOrSetDiff(p.permission.ID, func() (string, error) {\n\t\t\treturn diff.FormatDiff(pr.Diff, diff.WithTotalWidth(p.contentViewPort.Width))\n\t\t})\n\n\t\tp.contentViewPort.SetContent(diff)\n\t\treturn p.styleViewport()\n\t}\n\treturn \"\"\n}\n\nfunc (p *permissionDialogCmp) renderPatchContent() string {\n\tif pr, ok := p.permission.Params.(tools.EditPermissionsParams); ok {\n\t\tdiff := p.GetOrSetDiff(p.permission.ID, func() (string, error) {\n\t\t\treturn diff.FormatDiff(pr.Diff, diff.WithTotalWidth(p.contentViewPort.Width))\n\t\t})\n\n\t\tp.contentViewPort.SetContent(diff)\n\t\treturn p.styleViewport()\n\t}\n\treturn \"\"\n}\n\nfunc (p *permissionDialogCmp) renderWriteContent() string {\n\tif pr, ok := p.permission.Params.(tools.WritePermissionsParams); ok {\n\t\t// Use the cache for diff rendering\n\t\tdiff := p.GetOrSetDiff(p.permission.ID, func() (string, error) {\n\t\t\treturn diff.FormatDiff(pr.Diff, diff.WithTotalWidth(p.contentViewPort.Width))\n\t\t})\n\n\t\tp.contentViewPort.SetContent(diff)\n\t\treturn p.styleViewport()\n\t}\n\treturn \"\"\n}\n\nfunc (p *permissionDialogCmp) renderFetchContent() string {\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\n\tif pr, ok := p.permission.Params.(tools.FetchPermissionsParams); ok {\n\t\tcontent := fmt.Sprintf(\"```bash\\n%s\\n```\", pr.URL)\n\n\t\t// Use the cache for markdown rendering\n\t\trenderedContent := p.GetOrSetMarkdown(p.permission.ID, func() (string, error) {\n\t\t\tr := styles.GetMarkdownRenderer(p.width - 10)\n\t\t\ts, err := r.Render(content)\n\t\t\treturn styles.ForceReplaceBackgroundWithLipgloss(s, t.Background()), err\n\t\t})\n\n\t\tfinalContent := baseStyle.\n\t\t\tWidth(p.contentViewPort.Width).\n\t\t\tRender(renderedContent)\n\t\tp.contentViewPort.SetContent(finalContent)\n\t\treturn p.styleViewport()\n\t}\n\treturn \"\"\n}\n\nfunc (p *permissionDialogCmp) renderDefaultContent() string {\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\n\tcontent := p.permission.Description\n\n\t// Use the cache for markdown rendering\n\trenderedContent := p.GetOrSetMarkdown(p.permission.ID, func() (string, error) {\n\t\tr := styles.GetMarkdownRenderer(p.width - 10)\n\t\ts, err := r.Render(content)\n\t\treturn styles.ForceReplaceBackgroundWithLipgloss(s, t.Background()), err\n\t})\n\n\tfinalContent := baseStyle.\n\t\tWidth(p.contentViewPort.Width).\n\t\tRender(renderedContent)\n\tp.contentViewPort.SetContent(finalContent)\n\n\tif renderedContent == \"\" {\n\t\treturn \"\"\n\t}\n\n\treturn p.styleViewport()\n}\n\nfunc (p *permissionDialogCmp) styleViewport() string {\n\tt := theme.CurrentTheme()\n\tcontentStyle := lipgloss.NewStyle().\n\t\tBackground(t.Background())\n\n\treturn contentStyle.Render(p.contentViewPort.View())\n}\n\nfunc (p *permissionDialogCmp) render() string {\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\n\ttitle := baseStyle.\n\t\tBold(true).\n\t\tWidth(p.width - 4).\n\t\tForeground(t.Primary()).\n\t\tRender(\"Permission Required\")\n\t// Render header\n\theaderContent := p.renderHeader()\n\t// Render buttons\n\tbuttons := p.renderButtons()\n\n\t// Calculate content height dynamically based on window size\n\tp.contentViewPort.Height = p.height - lipgloss.Height(headerContent) - lipgloss.Height(buttons) - 2 - lipgloss.Height(title)\n\tp.contentViewPort.Width = p.width - 4\n\n\t// Render content based on tool type\n\tvar contentFinal string\n\tswitch p.permission.ToolName {\n\tcase tools.BashToolName:\n\t\tcontentFinal = p.renderBashContent()\n\tcase tools.EditToolName:\n\t\tcontentFinal = p.renderEditContent()\n\tcase tools.PatchToolName:\n\t\tcontentFinal = p.renderPatchContent()\n\tcase tools.WriteToolName:\n\t\tcontentFinal = p.renderWriteContent()\n\tcase tools.FetchToolName:\n\t\tcontentFinal = p.renderFetchContent()\n\tdefault:\n\t\tcontentFinal = p.renderDefaultContent()\n\t}\n\n\tcontent := lipgloss.JoinVertical(\n\t\tlipgloss.Top,\n\t\ttitle,\n\t\tbaseStyle.Render(strings.Repeat(\" \", lipgloss.Width(title))),\n\t\theaderContent,\n\t\tcontentFinal,\n\t\tbuttons,\n\t\tbaseStyle.Render(strings.Repeat(\" \", p.width-4)),\n\t)\n\n\treturn baseStyle.\n\t\tPadding(1, 0, 0, 1).\n\t\tBorder(lipgloss.RoundedBorder()).\n\t\tBorderBackground(t.Background()).\n\t\tBorderForeground(t.TextMuted()).\n\t\tWidth(p.width).\n\t\tHeight(p.height).\n\t\tRender(\n\t\t\tcontent,\n\t\t)\n}\n\nfunc (p *permissionDialogCmp) View() string {\n\treturn p.render()\n}\n\nfunc (p *permissionDialogCmp) BindingKeys() []key.Binding {\n\treturn layout.KeyMapToSlice(permissionsKeys)\n}\n\nfunc (p *permissionDialogCmp) SetSize() tea.Cmd {\n\tif p.permission.ID == \"\" {\n\t\treturn nil\n\t}\n\tswitch p.permission.ToolName {\n\tcase tools.BashToolName:\n\t\tp.width = int(float64(p.windowSize.Width) * 0.4)\n\t\tp.height = int(float64(p.windowSize.Height) * 0.3)\n\tcase tools.EditToolName:\n\t\tp.width = int(float64(p.windowSize.Width) * 0.8)\n\t\tp.height = int(float64(p.windowSize.Height) * 0.8)\n\tcase tools.WriteToolName:\n\t\tp.width = int(float64(p.windowSize.Width) * 0.8)\n\t\tp.height = int(float64(p.windowSize.Height) * 0.8)\n\tcase tools.FetchToolName:\n\t\tp.width = int(float64(p.windowSize.Width) * 0.4)\n\t\tp.height = int(float64(p.windowSize.Height) * 0.3)\n\tdefault:\n\t\tp.width = int(float64(p.windowSize.Width) * 0.7)\n\t\tp.height = int(float64(p.windowSize.Height) * 0.5)\n\t}\n\treturn nil\n}\n\nfunc (p *permissionDialogCmp) SetPermissions(permission permission.PermissionRequest) tea.Cmd {\n\tp.permission = permission\n\treturn p.SetSize()\n}\n\n// Helper to get or set cached diff content\nfunc (c *permissionDialogCmp) GetOrSetDiff(key string, generator func() (string, error)) string {\n\tif cached, ok := c.diffCache[key]; ok {\n\t\treturn cached\n\t}\n\n\tcontent, err := generator()\n\tif err != nil {\n\t\treturn fmt.Sprintf(\"Error formatting diff: %v\", err)\n\t}\n\n\tc.diffCache[key] = content\n\n\treturn content\n}\n\n// Helper to get or set cached markdown content\nfunc (c *permissionDialogCmp) GetOrSetMarkdown(key string, generator func() (string, error)) string {\n\tif cached, ok := c.markdownCache[key]; ok {\n\t\treturn cached\n\t}\n\n\tcontent, err := generator()\n\tif err != nil {\n\t\treturn fmt.Sprintf(\"Error rendering markdown: %v\", err)\n\t}\n\n\tc.markdownCache[key] = content\n\n\treturn content\n}\n\nfunc NewPermissionDialogCmp() PermissionDialogCmp {\n\t// Create viewport for content\n\tcontentViewport := viewport.New(0, 0)\n\n\treturn &permissionDialogCmp{\n\t\tcontentViewPort: contentViewport,\n\t\tselectedOption: 0, // Default to \"Allow\"\n\t\tdiffCache: make(map[string]string),\n\t\tmarkdownCache: make(map[string]string),\n\t}\n}\n"], ["/opencode/internal/tui/components/chat/message.go", "package chat\n\nimport (\n\t\"context\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"path/filepath\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/charmbracelet/lipgloss\"\n\t\"github.com/charmbracelet/x/ansi\"\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/diff\"\n\t\"github.com/opencode-ai/opencode/internal/llm/agent\"\n\t\"github.com/opencode-ai/opencode/internal/llm/models\"\n\t\"github.com/opencode-ai/opencode/internal/llm/tools\"\n\t\"github.com/opencode-ai/opencode/internal/message\"\n\t\"github.com/opencode-ai/opencode/internal/tui/styles\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n)\n\ntype uiMessageType int\n\nconst (\n\tuserMessageType uiMessageType = iota\n\tassistantMessageType\n\ttoolMessageType\n\n\tmaxResultHeight = 10\n)\n\ntype uiMessage struct {\n\tID string\n\tmessageType uiMessageType\n\tposition int\n\theight int\n\tcontent string\n}\n\nfunc toMarkdown(content string, focused bool, width int) string {\n\tr := styles.GetMarkdownRenderer(width)\n\trendered, _ := r.Render(content)\n\treturn rendered\n}\n\nfunc renderMessage(msg string, isUser bool, isFocused bool, width int, info ...string) string {\n\tt := theme.CurrentTheme()\n\n\tstyle := styles.BaseStyle().\n\t\tWidth(width - 1).\n\t\tBorderLeft(true).\n\t\tForeground(t.TextMuted()).\n\t\tBorderForeground(t.Primary()).\n\t\tBorderStyle(lipgloss.ThickBorder())\n\n\tif isUser {\n\t\tstyle = style.BorderForeground(t.Secondary())\n\t}\n\n\t// Apply markdown formatting and handle background color\n\tparts := []string{\n\t\tstyles.ForceReplaceBackgroundWithLipgloss(toMarkdown(msg, isFocused, width), t.Background()),\n\t}\n\n\t// Remove newline at the end\n\tparts[0] = strings.TrimSuffix(parts[0], \"\\n\")\n\tif len(info) > 0 {\n\t\tparts = append(parts, info...)\n\t}\n\n\trendered := style.Render(\n\t\tlipgloss.JoinVertical(\n\t\t\tlipgloss.Left,\n\t\t\tparts...,\n\t\t),\n\t)\n\n\treturn rendered\n}\n\nfunc renderUserMessage(msg message.Message, isFocused bool, width int, position int) uiMessage {\n\tvar styledAttachments []string\n\tt := theme.CurrentTheme()\n\tattachmentStyles := styles.BaseStyle().\n\t\tMarginLeft(1).\n\t\tBackground(t.TextMuted()).\n\t\tForeground(t.Text())\n\tfor _, attachment := range msg.BinaryContent() {\n\t\tfile := filepath.Base(attachment.Path)\n\t\tvar filename string\n\t\tif len(file) > 10 {\n\t\t\tfilename = fmt.Sprintf(\" %s %s...\", styles.DocumentIcon, file[0:7])\n\t\t} else {\n\t\t\tfilename = fmt.Sprintf(\" %s %s\", styles.DocumentIcon, file)\n\t\t}\n\t\tstyledAttachments = append(styledAttachments, attachmentStyles.Render(filename))\n\t}\n\tcontent := \"\"\n\tif len(styledAttachments) > 0 {\n\t\tattachmentContent := styles.BaseStyle().Width(width).Render(lipgloss.JoinHorizontal(lipgloss.Left, styledAttachments...))\n\t\tcontent = renderMessage(msg.Content().String(), true, isFocused, width, attachmentContent)\n\t} else {\n\t\tcontent = renderMessage(msg.Content().String(), true, isFocused, width)\n\t}\n\tuserMsg := uiMessage{\n\t\tID: msg.ID,\n\t\tmessageType: userMessageType,\n\t\tposition: position,\n\t\theight: lipgloss.Height(content),\n\t\tcontent: content,\n\t}\n\treturn userMsg\n}\n\n// Returns multiple uiMessages because of the tool calls\nfunc renderAssistantMessage(\n\tmsg message.Message,\n\tmsgIndex int,\n\tallMessages []message.Message, // we need this to get tool results and the user message\n\tmessagesService message.Service, // We need this to get the task tool messages\n\tfocusedUIMessageId string,\n\tisSummary bool,\n\twidth int,\n\tposition int,\n) []uiMessage {\n\tmessages := []uiMessage{}\n\tcontent := msg.Content().String()\n\tthinking := msg.IsThinking()\n\tthinkingContent := msg.ReasoningContent().Thinking\n\tfinished := msg.IsFinished()\n\tfinishData := msg.FinishPart()\n\tinfo := []string{}\n\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\n\t// Add finish info if available\n\tif finished {\n\t\tswitch finishData.Reason {\n\t\tcase message.FinishReasonEndTurn:\n\t\t\ttook := formatTimestampDiff(msg.CreatedAt, finishData.Time)\n\t\t\tinfo = append(info, baseStyle.\n\t\t\t\tWidth(width-1).\n\t\t\t\tForeground(t.TextMuted()).\n\t\t\t\tRender(fmt.Sprintf(\" %s (%s)\", models.SupportedModels[msg.Model].Name, took)),\n\t\t\t)\n\t\tcase message.FinishReasonCanceled:\n\t\t\tinfo = append(info, baseStyle.\n\t\t\t\tWidth(width-1).\n\t\t\t\tForeground(t.TextMuted()).\n\t\t\t\tRender(fmt.Sprintf(\" %s (%s)\", models.SupportedModels[msg.Model].Name, \"canceled\")),\n\t\t\t)\n\t\tcase message.FinishReasonError:\n\t\t\tinfo = append(info, baseStyle.\n\t\t\t\tWidth(width-1).\n\t\t\t\tForeground(t.TextMuted()).\n\t\t\t\tRender(fmt.Sprintf(\" %s (%s)\", models.SupportedModels[msg.Model].Name, \"error\")),\n\t\t\t)\n\t\tcase message.FinishReasonPermissionDenied:\n\t\t\tinfo = append(info, baseStyle.\n\t\t\t\tWidth(width-1).\n\t\t\t\tForeground(t.TextMuted()).\n\t\t\t\tRender(fmt.Sprintf(\" %s (%s)\", models.SupportedModels[msg.Model].Name, \"permission denied\")),\n\t\t\t)\n\t\t}\n\t}\n\tif content != \"\" || (finished && finishData.Reason == message.FinishReasonEndTurn) {\n\t\tif content == \"\" {\n\t\t\tcontent = \"*Finished without output*\"\n\t\t}\n\t\tif isSummary {\n\t\t\tinfo = append(info, baseStyle.Width(width-1).Foreground(t.TextMuted()).Render(\" (summary)\"))\n\t\t}\n\n\t\tcontent = renderMessage(content, false, true, width, info...)\n\t\tmessages = append(messages, uiMessage{\n\t\t\tID: msg.ID,\n\t\t\tmessageType: assistantMessageType,\n\t\t\tposition: position,\n\t\t\theight: lipgloss.Height(content),\n\t\t\tcontent: content,\n\t\t})\n\t\tposition += messages[0].height\n\t\tposition++ // for the space\n\t} else if thinking && thinkingContent != \"\" {\n\t\t// Render the thinking content\n\t\tcontent = renderMessage(thinkingContent, false, msg.ID == focusedUIMessageId, width)\n\t}\n\n\tfor i, toolCall := range msg.ToolCalls() {\n\t\ttoolCallContent := renderToolMessage(\n\t\t\ttoolCall,\n\t\t\tallMessages,\n\t\t\tmessagesService,\n\t\t\tfocusedUIMessageId,\n\t\t\tfalse,\n\t\t\twidth,\n\t\t\ti+1,\n\t\t)\n\t\tmessages = append(messages, toolCallContent)\n\t\tposition += toolCallContent.height\n\t\tposition++ // for the space\n\t}\n\treturn messages\n}\n\nfunc findToolResponse(toolCallID string, futureMessages []message.Message) *message.ToolResult {\n\tfor _, msg := range futureMessages {\n\t\tfor _, result := range msg.ToolResults() {\n\t\t\tif result.ToolCallID == toolCallID {\n\t\t\t\treturn &result\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc toolName(name string) string {\n\tswitch name {\n\tcase agent.AgentToolName:\n\t\treturn \"Task\"\n\tcase tools.BashToolName:\n\t\treturn \"Bash\"\n\tcase tools.EditToolName:\n\t\treturn \"Edit\"\n\tcase tools.FetchToolName:\n\t\treturn \"Fetch\"\n\tcase tools.GlobToolName:\n\t\treturn \"Glob\"\n\tcase tools.GrepToolName:\n\t\treturn \"Grep\"\n\tcase tools.LSToolName:\n\t\treturn \"List\"\n\tcase tools.SourcegraphToolName:\n\t\treturn \"Sourcegraph\"\n\tcase tools.ViewToolName:\n\t\treturn \"View\"\n\tcase tools.WriteToolName:\n\t\treturn \"Write\"\n\tcase tools.PatchToolName:\n\t\treturn \"Patch\"\n\t}\n\treturn name\n}\n\nfunc getToolAction(name string) string {\n\tswitch name {\n\tcase agent.AgentToolName:\n\t\treturn \"Preparing prompt...\"\n\tcase tools.BashToolName:\n\t\treturn \"Building command...\"\n\tcase tools.EditToolName:\n\t\treturn \"Preparing edit...\"\n\tcase tools.FetchToolName:\n\t\treturn \"Writing fetch...\"\n\tcase tools.GlobToolName:\n\t\treturn \"Finding files...\"\n\tcase tools.GrepToolName:\n\t\treturn \"Searching content...\"\n\tcase tools.LSToolName:\n\t\treturn \"Listing directory...\"\n\tcase tools.SourcegraphToolName:\n\t\treturn \"Searching code...\"\n\tcase tools.ViewToolName:\n\t\treturn \"Reading file...\"\n\tcase tools.WriteToolName:\n\t\treturn \"Preparing write...\"\n\tcase tools.PatchToolName:\n\t\treturn \"Preparing patch...\"\n\t}\n\treturn \"Working...\"\n}\n\n// renders params, params[0] (params[1]=params[2] ....)\nfunc renderParams(paramsWidth int, params ...string) string {\n\tif len(params) == 0 {\n\t\treturn \"\"\n\t}\n\tmainParam := params[0]\n\tif len(mainParam) > paramsWidth {\n\t\tmainParam = mainParam[:paramsWidth-3] + \"...\"\n\t}\n\n\tif len(params) == 1 {\n\t\treturn mainParam\n\t}\n\totherParams := params[1:]\n\t// create pairs of key/value\n\t// if odd number of params, the last one is a key without value\n\tif len(otherParams)%2 != 0 {\n\t\totherParams = append(otherParams, \"\")\n\t}\n\tparts := make([]string, 0, len(otherParams)/2)\n\tfor i := 0; i < len(otherParams); i += 2 {\n\t\tkey := otherParams[i]\n\t\tvalue := otherParams[i+1]\n\t\tif value == \"\" {\n\t\t\tcontinue\n\t\t}\n\t\tparts = append(parts, fmt.Sprintf(\"%s=%s\", key, value))\n\t}\n\n\tpartsRendered := strings.Join(parts, \", \")\n\tremainingWidth := paramsWidth - lipgloss.Width(partsRendered) - 5 // for the space\n\tif remainingWidth < 30 {\n\t\t// No space for the params, just show the main\n\t\treturn mainParam\n\t}\n\n\tif len(parts) > 0 {\n\t\tmainParam = fmt.Sprintf(\"%s (%s)\", mainParam, strings.Join(parts, \", \"))\n\t}\n\n\treturn ansi.Truncate(mainParam, paramsWidth, \"...\")\n}\n\nfunc removeWorkingDirPrefix(path string) string {\n\twd := config.WorkingDirectory()\n\tif strings.HasPrefix(path, wd) {\n\t\tpath = strings.TrimPrefix(path, wd)\n\t}\n\tif strings.HasPrefix(path, \"/\") {\n\t\tpath = strings.TrimPrefix(path, \"/\")\n\t}\n\tif strings.HasPrefix(path, \"./\") {\n\t\tpath = strings.TrimPrefix(path, \"./\")\n\t}\n\tif strings.HasPrefix(path, \"../\") {\n\t\tpath = strings.TrimPrefix(path, \"../\")\n\t}\n\treturn path\n}\n\nfunc renderToolParams(paramWidth int, toolCall message.ToolCall) string {\n\tparams := \"\"\n\tswitch toolCall.Name {\n\tcase agent.AgentToolName:\n\t\tvar params agent.AgentParams\n\t\tjson.Unmarshal([]byte(toolCall.Input), ¶ms)\n\t\tprompt := strings.ReplaceAll(params.Prompt, \"\\n\", \" \")\n\t\treturn renderParams(paramWidth, prompt)\n\tcase tools.BashToolName:\n\t\tvar params tools.BashParams\n\t\tjson.Unmarshal([]byte(toolCall.Input), ¶ms)\n\t\tcommand := strings.ReplaceAll(params.Command, \"\\n\", \" \")\n\t\treturn renderParams(paramWidth, command)\n\tcase tools.EditToolName:\n\t\tvar params tools.EditParams\n\t\tjson.Unmarshal([]byte(toolCall.Input), ¶ms)\n\t\tfilePath := removeWorkingDirPrefix(params.FilePath)\n\t\treturn renderParams(paramWidth, filePath)\n\tcase tools.FetchToolName:\n\t\tvar params tools.FetchParams\n\t\tjson.Unmarshal([]byte(toolCall.Input), ¶ms)\n\t\turl := params.URL\n\t\ttoolParams := []string{\n\t\t\turl,\n\t\t}\n\t\tif params.Format != \"\" {\n\t\t\ttoolParams = append(toolParams, \"format\", params.Format)\n\t\t}\n\t\tif params.Timeout != 0 {\n\t\t\ttoolParams = append(toolParams, \"timeout\", (time.Duration(params.Timeout) * time.Second).String())\n\t\t}\n\t\treturn renderParams(paramWidth, toolParams...)\n\tcase tools.GlobToolName:\n\t\tvar params tools.GlobParams\n\t\tjson.Unmarshal([]byte(toolCall.Input), ¶ms)\n\t\tpattern := params.Pattern\n\t\ttoolParams := []string{\n\t\t\tpattern,\n\t\t}\n\t\tif params.Path != \"\" {\n\t\t\ttoolParams = append(toolParams, \"path\", params.Path)\n\t\t}\n\t\treturn renderParams(paramWidth, toolParams...)\n\tcase tools.GrepToolName:\n\t\tvar params tools.GrepParams\n\t\tjson.Unmarshal([]byte(toolCall.Input), ¶ms)\n\t\tpattern := params.Pattern\n\t\ttoolParams := []string{\n\t\t\tpattern,\n\t\t}\n\t\tif params.Path != \"\" {\n\t\t\ttoolParams = append(toolParams, \"path\", params.Path)\n\t\t}\n\t\tif params.Include != \"\" {\n\t\t\ttoolParams = append(toolParams, \"include\", params.Include)\n\t\t}\n\t\tif params.LiteralText {\n\t\t\ttoolParams = append(toolParams, \"literal\", \"true\")\n\t\t}\n\t\treturn renderParams(paramWidth, toolParams...)\n\tcase tools.LSToolName:\n\t\tvar params tools.LSParams\n\t\tjson.Unmarshal([]byte(toolCall.Input), ¶ms)\n\t\tpath := params.Path\n\t\tif path == \"\" {\n\t\t\tpath = \".\"\n\t\t}\n\t\treturn renderParams(paramWidth, path)\n\tcase tools.SourcegraphToolName:\n\t\tvar params tools.SourcegraphParams\n\t\tjson.Unmarshal([]byte(toolCall.Input), ¶ms)\n\t\treturn renderParams(paramWidth, params.Query)\n\tcase tools.ViewToolName:\n\t\tvar params tools.ViewParams\n\t\tjson.Unmarshal([]byte(toolCall.Input), ¶ms)\n\t\tfilePath := removeWorkingDirPrefix(params.FilePath)\n\t\ttoolParams := []string{\n\t\t\tfilePath,\n\t\t}\n\t\tif params.Limit != 0 {\n\t\t\ttoolParams = append(toolParams, \"limit\", fmt.Sprintf(\"%d\", params.Limit))\n\t\t}\n\t\tif params.Offset != 0 {\n\t\t\ttoolParams = append(toolParams, \"offset\", fmt.Sprintf(\"%d\", params.Offset))\n\t\t}\n\t\treturn renderParams(paramWidth, toolParams...)\n\tcase tools.WriteToolName:\n\t\tvar params tools.WriteParams\n\t\tjson.Unmarshal([]byte(toolCall.Input), ¶ms)\n\t\tfilePath := removeWorkingDirPrefix(params.FilePath)\n\t\treturn renderParams(paramWidth, filePath)\n\tdefault:\n\t\tinput := strings.ReplaceAll(toolCall.Input, \"\\n\", \" \")\n\t\tparams = renderParams(paramWidth, input)\n\t}\n\treturn params\n}\n\nfunc truncateHeight(content string, height int) string {\n\tlines := strings.Split(content, \"\\n\")\n\tif len(lines) > height {\n\t\treturn strings.Join(lines[:height], \"\\n\")\n\t}\n\treturn content\n}\n\nfunc renderToolResponse(toolCall message.ToolCall, response message.ToolResult, width int) string {\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\n\tif response.IsError {\n\t\terrContent := fmt.Sprintf(\"Error: %s\", strings.ReplaceAll(response.Content, \"\\n\", \" \"))\n\t\terrContent = ansi.Truncate(errContent, width-1, \"...\")\n\t\treturn baseStyle.\n\t\t\tWidth(width).\n\t\t\tForeground(t.Error()).\n\t\t\tRender(errContent)\n\t}\n\n\tresultContent := truncateHeight(response.Content, maxResultHeight)\n\tswitch toolCall.Name {\n\tcase agent.AgentToolName:\n\t\treturn styles.ForceReplaceBackgroundWithLipgloss(\n\t\t\ttoMarkdown(resultContent, false, width),\n\t\t\tt.Background(),\n\t\t)\n\tcase tools.BashToolName:\n\t\tresultContent = fmt.Sprintf(\"```bash\\n%s\\n```\", resultContent)\n\t\treturn styles.ForceReplaceBackgroundWithLipgloss(\n\t\t\ttoMarkdown(resultContent, true, width),\n\t\t\tt.Background(),\n\t\t)\n\tcase tools.EditToolName:\n\t\tmetadata := tools.EditResponseMetadata{}\n\t\tjson.Unmarshal([]byte(response.Metadata), &metadata)\n\t\ttruncDiff := truncateHeight(metadata.Diff, maxResultHeight)\n\t\tformattedDiff, _ := diff.FormatDiff(truncDiff, diff.WithTotalWidth(width))\n\t\treturn formattedDiff\n\tcase tools.FetchToolName:\n\t\tvar params tools.FetchParams\n\t\tjson.Unmarshal([]byte(toolCall.Input), ¶ms)\n\t\tmdFormat := \"markdown\"\n\t\tswitch params.Format {\n\t\tcase \"text\":\n\t\t\tmdFormat = \"text\"\n\t\tcase \"html\":\n\t\t\tmdFormat = \"html\"\n\t\t}\n\t\tresultContent = fmt.Sprintf(\"```%s\\n%s\\n```\", mdFormat, resultContent)\n\t\treturn styles.ForceReplaceBackgroundWithLipgloss(\n\t\t\ttoMarkdown(resultContent, true, width),\n\t\t\tt.Background(),\n\t\t)\n\tcase tools.GlobToolName:\n\t\treturn baseStyle.Width(width).Foreground(t.TextMuted()).Render(resultContent)\n\tcase tools.GrepToolName:\n\t\treturn baseStyle.Width(width).Foreground(t.TextMuted()).Render(resultContent)\n\tcase tools.LSToolName:\n\t\treturn baseStyle.Width(width).Foreground(t.TextMuted()).Render(resultContent)\n\tcase tools.SourcegraphToolName:\n\t\treturn baseStyle.Width(width).Foreground(t.TextMuted()).Render(resultContent)\n\tcase tools.ViewToolName:\n\t\tmetadata := tools.ViewResponseMetadata{}\n\t\tjson.Unmarshal([]byte(response.Metadata), &metadata)\n\t\text := filepath.Ext(metadata.FilePath)\n\t\tif ext == \"\" {\n\t\t\text = \"\"\n\t\t} else {\n\t\t\text = strings.ToLower(ext[1:])\n\t\t}\n\t\tresultContent = fmt.Sprintf(\"```%s\\n%s\\n```\", ext, truncateHeight(metadata.Content, maxResultHeight))\n\t\treturn styles.ForceReplaceBackgroundWithLipgloss(\n\t\t\ttoMarkdown(resultContent, true, width),\n\t\t\tt.Background(),\n\t\t)\n\tcase tools.WriteToolName:\n\t\tparams := tools.WriteParams{}\n\t\tjson.Unmarshal([]byte(toolCall.Input), ¶ms)\n\t\tmetadata := tools.WriteResponseMetadata{}\n\t\tjson.Unmarshal([]byte(response.Metadata), &metadata)\n\t\text := filepath.Ext(params.FilePath)\n\t\tif ext == \"\" {\n\t\t\text = \"\"\n\t\t} else {\n\t\t\text = strings.ToLower(ext[1:])\n\t\t}\n\t\tresultContent = fmt.Sprintf(\"```%s\\n%s\\n```\", ext, truncateHeight(params.Content, maxResultHeight))\n\t\treturn styles.ForceReplaceBackgroundWithLipgloss(\n\t\t\ttoMarkdown(resultContent, true, width),\n\t\t\tt.Background(),\n\t\t)\n\tdefault:\n\t\tresultContent = fmt.Sprintf(\"```text\\n%s\\n```\", resultContent)\n\t\treturn styles.ForceReplaceBackgroundWithLipgloss(\n\t\t\ttoMarkdown(resultContent, true, width),\n\t\t\tt.Background(),\n\t\t)\n\t}\n}\n\nfunc renderToolMessage(\n\ttoolCall message.ToolCall,\n\tallMessages []message.Message,\n\tmessagesService message.Service,\n\tfocusedUIMessageId string,\n\tnested bool,\n\twidth int,\n\tposition int,\n) uiMessage {\n\tif nested {\n\t\twidth = width - 3\n\t}\n\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\n\tstyle := baseStyle.\n\t\tWidth(width - 1).\n\t\tBorderLeft(true).\n\t\tBorderStyle(lipgloss.ThickBorder()).\n\t\tPaddingLeft(1).\n\t\tBorderForeground(t.TextMuted())\n\n\tresponse := findToolResponse(toolCall.ID, allMessages)\n\ttoolNameText := baseStyle.Foreground(t.TextMuted()).\n\t\tRender(fmt.Sprintf(\"%s: \", toolName(toolCall.Name)))\n\n\tif !toolCall.Finished {\n\t\t// Get a brief description of what the tool is doing\n\t\ttoolAction := getToolAction(toolCall.Name)\n\n\t\tprogressText := baseStyle.\n\t\t\tWidth(width - 2 - lipgloss.Width(toolNameText)).\n\t\t\tForeground(t.TextMuted()).\n\t\t\tRender(fmt.Sprintf(\"%s\", toolAction))\n\n\t\tcontent := style.Render(lipgloss.JoinHorizontal(lipgloss.Left, toolNameText, progressText))\n\t\ttoolMsg := uiMessage{\n\t\t\tmessageType: toolMessageType,\n\t\t\tposition: position,\n\t\t\theight: lipgloss.Height(content),\n\t\t\tcontent: content,\n\t\t}\n\t\treturn toolMsg\n\t}\n\n\tparams := renderToolParams(width-2-lipgloss.Width(toolNameText), toolCall)\n\tresponseContent := \"\"\n\tif response != nil {\n\t\tresponseContent = renderToolResponse(toolCall, *response, width-2)\n\t\tresponseContent = strings.TrimSuffix(responseContent, \"\\n\")\n\t} else {\n\t\tresponseContent = baseStyle.\n\t\t\tItalic(true).\n\t\t\tWidth(width - 2).\n\t\t\tForeground(t.TextMuted()).\n\t\t\tRender(\"Waiting for response...\")\n\t}\n\n\tparts := []string{}\n\tif !nested {\n\t\tformattedParams := baseStyle.\n\t\t\tWidth(width - 2 - lipgloss.Width(toolNameText)).\n\t\t\tForeground(t.TextMuted()).\n\t\t\tRender(params)\n\n\t\tparts = append(parts, lipgloss.JoinHorizontal(lipgloss.Left, toolNameText, formattedParams))\n\t} else {\n\t\tprefix := baseStyle.\n\t\t\tForeground(t.TextMuted()).\n\t\t\tRender(\" └ \")\n\t\tformattedParams := baseStyle.\n\t\t\tWidth(width - 2 - lipgloss.Width(toolNameText)).\n\t\t\tForeground(t.TextMuted()).\n\t\t\tRender(params)\n\t\tparts = append(parts, lipgloss.JoinHorizontal(lipgloss.Left, prefix, toolNameText, formattedParams))\n\t}\n\n\tif toolCall.Name == agent.AgentToolName {\n\t\ttaskMessages, _ := messagesService.List(context.Background(), toolCall.ID)\n\t\ttoolCalls := []message.ToolCall{}\n\t\tfor _, v := range taskMessages {\n\t\t\ttoolCalls = append(toolCalls, v.ToolCalls()...)\n\t\t}\n\t\tfor _, call := range toolCalls {\n\t\t\trendered := renderToolMessage(call, []message.Message{}, messagesService, focusedUIMessageId, true, width, 0)\n\t\t\tparts = append(parts, rendered.content)\n\t\t}\n\t}\n\tif responseContent != \"\" && !nested {\n\t\tparts = append(parts, responseContent)\n\t}\n\n\tcontent := style.Render(\n\t\tlipgloss.JoinVertical(\n\t\t\tlipgloss.Left,\n\t\t\tparts...,\n\t\t),\n\t)\n\tif nested {\n\t\tcontent = lipgloss.JoinVertical(\n\t\t\tlipgloss.Left,\n\t\t\tparts...,\n\t\t)\n\t}\n\ttoolMsg := uiMessage{\n\t\tmessageType: toolMessageType,\n\t\tposition: position,\n\t\theight: lipgloss.Height(content),\n\t\tcontent: content,\n\t}\n\treturn toolMsg\n}\n\n// Helper function to format the time difference between two Unix timestamps\nfunc formatTimestampDiff(start, end int64) string {\n\tdiffSeconds := float64(end-start) / 1000.0 // Convert to seconds\n\tif diffSeconds < 1 {\n\t\treturn fmt.Sprintf(\"%dms\", int(diffSeconds*1000))\n\t}\n\tif diffSeconds < 60 {\n\t\treturn fmt.Sprintf(\"%.1fs\", diffSeconds)\n\t}\n\treturn fmt.Sprintf(\"%.1fm\", diffSeconds/60)\n}\n"], ["/opencode/internal/tui/tui.go", "package tui\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"strings\"\n\n\t\"github.com/charmbracelet/bubbles/key\"\n\ttea \"github.com/charmbracelet/bubbletea\"\n\t\"github.com/charmbracelet/lipgloss\"\n\t\"github.com/opencode-ai/opencode/internal/app\"\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/llm/agent\"\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n\t\"github.com/opencode-ai/opencode/internal/permission\"\n\t\"github.com/opencode-ai/opencode/internal/pubsub\"\n\t\"github.com/opencode-ai/opencode/internal/session\"\n\t\"github.com/opencode-ai/opencode/internal/tui/components/chat\"\n\t\"github.com/opencode-ai/opencode/internal/tui/components/core\"\n\t\"github.com/opencode-ai/opencode/internal/tui/components/dialog\"\n\t\"github.com/opencode-ai/opencode/internal/tui/layout\"\n\t\"github.com/opencode-ai/opencode/internal/tui/page\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n\t\"github.com/opencode-ai/opencode/internal/tui/util\"\n)\n\ntype keyMap struct {\n\tLogs key.Binding\n\tQuit key.Binding\n\tHelp key.Binding\n\tSwitchSession key.Binding\n\tCommands key.Binding\n\tFilepicker key.Binding\n\tModels key.Binding\n\tSwitchTheme key.Binding\n}\n\ntype startCompactSessionMsg struct{}\n\nconst (\n\tquitKey = \"q\"\n)\n\nvar keys = keyMap{\n\tLogs: key.NewBinding(\n\t\tkey.WithKeys(\"ctrl+l\"),\n\t\tkey.WithHelp(\"ctrl+l\", \"logs\"),\n\t),\n\n\tQuit: key.NewBinding(\n\t\tkey.WithKeys(\"ctrl+c\"),\n\t\tkey.WithHelp(\"ctrl+c\", \"quit\"),\n\t),\n\tHelp: key.NewBinding(\n\t\tkey.WithKeys(\"ctrl+_\", \"ctrl+h\"),\n\t\tkey.WithHelp(\"ctrl+?\", \"toggle help\"),\n\t),\n\n\tSwitchSession: key.NewBinding(\n\t\tkey.WithKeys(\"ctrl+s\"),\n\t\tkey.WithHelp(\"ctrl+s\", \"switch session\"),\n\t),\n\n\tCommands: key.NewBinding(\n\t\tkey.WithKeys(\"ctrl+k\"),\n\t\tkey.WithHelp(\"ctrl+k\", \"commands\"),\n\t),\n\tFilepicker: key.NewBinding(\n\t\tkey.WithKeys(\"ctrl+f\"),\n\t\tkey.WithHelp(\"ctrl+f\", \"select files to upload\"),\n\t),\n\tModels: key.NewBinding(\n\t\tkey.WithKeys(\"ctrl+o\"),\n\t\tkey.WithHelp(\"ctrl+o\", \"model selection\"),\n\t),\n\n\tSwitchTheme: key.NewBinding(\n\t\tkey.WithKeys(\"ctrl+t\"),\n\t\tkey.WithHelp(\"ctrl+t\", \"switch theme\"),\n\t),\n}\n\nvar helpEsc = key.NewBinding(\n\tkey.WithKeys(\"?\"),\n\tkey.WithHelp(\"?\", \"toggle help\"),\n)\n\nvar returnKey = key.NewBinding(\n\tkey.WithKeys(\"esc\"),\n\tkey.WithHelp(\"esc\", \"close\"),\n)\n\nvar logsKeyReturnKey = key.NewBinding(\n\tkey.WithKeys(\"esc\", \"backspace\", quitKey),\n\tkey.WithHelp(\"esc/q\", \"go back\"),\n)\n\ntype appModel struct {\n\twidth, height int\n\tcurrentPage page.PageID\n\tpreviousPage page.PageID\n\tpages map[page.PageID]tea.Model\n\tloadedPages map[page.PageID]bool\n\tstatus core.StatusCmp\n\tapp *app.App\n\tselectedSession session.Session\n\n\tshowPermissions bool\n\tpermissions dialog.PermissionDialogCmp\n\n\tshowHelp bool\n\thelp dialog.HelpCmp\n\n\tshowQuit bool\n\tquit dialog.QuitDialog\n\n\tshowSessionDialog bool\n\tsessionDialog dialog.SessionDialog\n\n\tshowCommandDialog bool\n\tcommandDialog dialog.CommandDialog\n\tcommands []dialog.Command\n\n\tshowModelDialog bool\n\tmodelDialog dialog.ModelDialog\n\n\tshowInitDialog bool\n\tinitDialog dialog.InitDialogCmp\n\n\tshowFilepicker bool\n\tfilepicker dialog.FilepickerCmp\n\n\tshowThemeDialog bool\n\tthemeDialog dialog.ThemeDialog\n\n\tshowMultiArgumentsDialog bool\n\tmultiArgumentsDialog dialog.MultiArgumentsDialogCmp\n\n\tisCompacting bool\n\tcompactingMessage string\n}\n\nfunc (a appModel) Init() tea.Cmd {\n\tvar cmds []tea.Cmd\n\tcmd := a.pages[a.currentPage].Init()\n\ta.loadedPages[a.currentPage] = true\n\tcmds = append(cmds, cmd)\n\tcmd = a.status.Init()\n\tcmds = append(cmds, cmd)\n\tcmd = a.quit.Init()\n\tcmds = append(cmds, cmd)\n\tcmd = a.help.Init()\n\tcmds = append(cmds, cmd)\n\tcmd = a.sessionDialog.Init()\n\tcmds = append(cmds, cmd)\n\tcmd = a.commandDialog.Init()\n\tcmds = append(cmds, cmd)\n\tcmd = a.modelDialog.Init()\n\tcmds = append(cmds, cmd)\n\tcmd = a.initDialog.Init()\n\tcmds = append(cmds, cmd)\n\tcmd = a.filepicker.Init()\n\tcmds = append(cmds, cmd)\n\tcmd = a.themeDialog.Init()\n\tcmds = append(cmds, cmd)\n\n\t// Check if we should show the init dialog\n\tcmds = append(cmds, func() tea.Msg {\n\t\tshouldShow, err := config.ShouldShowInitDialog()\n\t\tif err != nil {\n\t\t\treturn util.InfoMsg{\n\t\t\t\tType: util.InfoTypeError,\n\t\t\t\tMsg: \"Failed to check init status: \" + err.Error(),\n\t\t\t}\n\t\t}\n\t\treturn dialog.ShowInitDialogMsg{Show: shouldShow}\n\t})\n\n\treturn tea.Batch(cmds...)\n}\n\nfunc (a appModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {\n\tvar cmds []tea.Cmd\n\tvar cmd tea.Cmd\n\tswitch msg := msg.(type) {\n\tcase tea.WindowSizeMsg:\n\t\tmsg.Height -= 1 // Make space for the status bar\n\t\ta.width, a.height = msg.Width, msg.Height\n\n\t\ts, _ := a.status.Update(msg)\n\t\ta.status = s.(core.StatusCmp)\n\t\ta.pages[a.currentPage], cmd = a.pages[a.currentPage].Update(msg)\n\t\tcmds = append(cmds, cmd)\n\n\t\tprm, permCmd := a.permissions.Update(msg)\n\t\ta.permissions = prm.(dialog.PermissionDialogCmp)\n\t\tcmds = append(cmds, permCmd)\n\n\t\thelp, helpCmd := a.help.Update(msg)\n\t\ta.help = help.(dialog.HelpCmp)\n\t\tcmds = append(cmds, helpCmd)\n\n\t\tsession, sessionCmd := a.sessionDialog.Update(msg)\n\t\ta.sessionDialog = session.(dialog.SessionDialog)\n\t\tcmds = append(cmds, sessionCmd)\n\n\t\tcommand, commandCmd := a.commandDialog.Update(msg)\n\t\ta.commandDialog = command.(dialog.CommandDialog)\n\t\tcmds = append(cmds, commandCmd)\n\n\t\tfilepicker, filepickerCmd := a.filepicker.Update(msg)\n\t\ta.filepicker = filepicker.(dialog.FilepickerCmp)\n\t\tcmds = append(cmds, filepickerCmd)\n\n\t\ta.initDialog.SetSize(msg.Width, msg.Height)\n\n\t\tif a.showMultiArgumentsDialog {\n\t\t\ta.multiArgumentsDialog.SetSize(msg.Width, msg.Height)\n\t\t\targs, argsCmd := a.multiArgumentsDialog.Update(msg)\n\t\t\ta.multiArgumentsDialog = args.(dialog.MultiArgumentsDialogCmp)\n\t\t\tcmds = append(cmds, argsCmd, a.multiArgumentsDialog.Init())\n\t\t}\n\n\t\treturn a, tea.Batch(cmds...)\n\t// Status\n\tcase util.InfoMsg:\n\t\ts, cmd := a.status.Update(msg)\n\t\ta.status = s.(core.StatusCmp)\n\t\tcmds = append(cmds, cmd)\n\t\treturn a, tea.Batch(cmds...)\n\tcase pubsub.Event[logging.LogMessage]:\n\t\tif msg.Payload.Persist {\n\t\t\tswitch msg.Payload.Level {\n\t\t\tcase \"error\":\n\t\t\t\ts, cmd := a.status.Update(util.InfoMsg{\n\t\t\t\t\tType: util.InfoTypeError,\n\t\t\t\t\tMsg: msg.Payload.Message,\n\t\t\t\t\tTTL: msg.Payload.PersistTime,\n\t\t\t\t})\n\t\t\t\ta.status = s.(core.StatusCmp)\n\t\t\t\tcmds = append(cmds, cmd)\n\t\t\tcase \"info\":\n\t\t\t\ts, cmd := a.status.Update(util.InfoMsg{\n\t\t\t\t\tType: util.InfoTypeInfo,\n\t\t\t\t\tMsg: msg.Payload.Message,\n\t\t\t\t\tTTL: msg.Payload.PersistTime,\n\t\t\t\t})\n\t\t\t\ta.status = s.(core.StatusCmp)\n\t\t\t\tcmds = append(cmds, cmd)\n\n\t\t\tcase \"warn\":\n\t\t\t\ts, cmd := a.status.Update(util.InfoMsg{\n\t\t\t\t\tType: util.InfoTypeWarn,\n\t\t\t\t\tMsg: msg.Payload.Message,\n\t\t\t\t\tTTL: msg.Payload.PersistTime,\n\t\t\t\t})\n\n\t\t\t\ta.status = s.(core.StatusCmp)\n\t\t\t\tcmds = append(cmds, cmd)\n\t\t\tdefault:\n\t\t\t\ts, cmd := a.status.Update(util.InfoMsg{\n\t\t\t\t\tType: util.InfoTypeInfo,\n\t\t\t\t\tMsg: msg.Payload.Message,\n\t\t\t\t\tTTL: msg.Payload.PersistTime,\n\t\t\t\t})\n\t\t\t\ta.status = s.(core.StatusCmp)\n\t\t\t\tcmds = append(cmds, cmd)\n\t\t\t}\n\t\t}\n\tcase util.ClearStatusMsg:\n\t\ts, _ := a.status.Update(msg)\n\t\ta.status = s.(core.StatusCmp)\n\n\t// Permission\n\tcase pubsub.Event[permission.PermissionRequest]:\n\t\ta.showPermissions = true\n\t\treturn a, a.permissions.SetPermissions(msg.Payload)\n\tcase dialog.PermissionResponseMsg:\n\t\tvar cmd tea.Cmd\n\t\tswitch msg.Action {\n\t\tcase dialog.PermissionAllow:\n\t\t\ta.app.Permissions.Grant(msg.Permission)\n\t\tcase dialog.PermissionAllowForSession:\n\t\t\ta.app.Permissions.GrantPersistant(msg.Permission)\n\t\tcase dialog.PermissionDeny:\n\t\t\ta.app.Permissions.Deny(msg.Permission)\n\t\t}\n\t\ta.showPermissions = false\n\t\treturn a, cmd\n\n\tcase page.PageChangeMsg:\n\t\treturn a, a.moveToPage(msg.ID)\n\n\tcase dialog.CloseQuitMsg:\n\t\ta.showQuit = false\n\t\treturn a, nil\n\n\tcase dialog.CloseSessionDialogMsg:\n\t\ta.showSessionDialog = false\n\t\treturn a, nil\n\n\tcase dialog.CloseCommandDialogMsg:\n\t\ta.showCommandDialog = false\n\t\treturn a, nil\n\n\tcase startCompactSessionMsg:\n\t\t// Start compacting the current session\n\t\ta.isCompacting = true\n\t\ta.compactingMessage = \"Starting summarization...\"\n\n\t\tif a.selectedSession.ID == \"\" {\n\t\t\ta.isCompacting = false\n\t\t\treturn a, util.ReportWarn(\"No active session to summarize\")\n\t\t}\n\n\t\t// Start the summarization process\n\t\treturn a, func() tea.Msg {\n\t\t\tctx := context.Background()\n\t\t\ta.app.CoderAgent.Summarize(ctx, a.selectedSession.ID)\n\t\t\treturn nil\n\t\t}\n\n\tcase pubsub.Event[agent.AgentEvent]:\n\t\tpayload := msg.Payload\n\t\tif payload.Error != nil {\n\t\t\ta.isCompacting = false\n\t\t\treturn a, util.ReportError(payload.Error)\n\t\t}\n\n\t\ta.compactingMessage = payload.Progress\n\n\t\tif payload.Done && payload.Type == agent.AgentEventTypeSummarize {\n\t\t\ta.isCompacting = false\n\t\t\treturn a, util.ReportInfo(\"Session summarization complete\")\n\t\t} else if payload.Done && payload.Type == agent.AgentEventTypeResponse && a.selectedSession.ID != \"\" {\n\t\t\tmodel := a.app.CoderAgent.Model()\n\t\t\tcontextWindow := model.ContextWindow\n\t\t\ttokens := a.selectedSession.CompletionTokens + a.selectedSession.PromptTokens\n\t\t\tif (tokens >= int64(float64(contextWindow)*0.95)) && config.Get().AutoCompact {\n\t\t\t\treturn a, util.CmdHandler(startCompactSessionMsg{})\n\t\t\t}\n\t\t}\n\t\t// Continue listening for events\n\t\treturn a, nil\n\n\tcase dialog.CloseThemeDialogMsg:\n\t\ta.showThemeDialog = false\n\t\treturn a, nil\n\n\tcase dialog.ThemeChangedMsg:\n\t\ta.pages[a.currentPage], cmd = a.pages[a.currentPage].Update(msg)\n\t\ta.showThemeDialog = false\n\t\treturn a, tea.Batch(cmd, util.ReportInfo(\"Theme changed to: \"+msg.ThemeName))\n\n\tcase dialog.CloseModelDialogMsg:\n\t\ta.showModelDialog = false\n\t\treturn a, nil\n\n\tcase dialog.ModelSelectedMsg:\n\t\ta.showModelDialog = false\n\n\t\tmodel, err := a.app.CoderAgent.Update(config.AgentCoder, msg.Model.ID)\n\t\tif err != nil {\n\t\t\treturn a, util.ReportError(err)\n\t\t}\n\n\t\treturn a, util.ReportInfo(fmt.Sprintf(\"Model changed to %s\", model.Name))\n\n\tcase dialog.ShowInitDialogMsg:\n\t\ta.showInitDialog = msg.Show\n\t\treturn a, nil\n\n\tcase dialog.CloseInitDialogMsg:\n\t\ta.showInitDialog = false\n\t\tif msg.Initialize {\n\t\t\t// Run the initialization command\n\t\t\tfor _, cmd := range a.commands {\n\t\t\t\tif cmd.ID == \"init\" {\n\t\t\t\t\t// Mark the project as initialized\n\t\t\t\t\tif err := config.MarkProjectInitialized(); err != nil {\n\t\t\t\t\t\treturn a, util.ReportError(err)\n\t\t\t\t\t}\n\t\t\t\t\treturn a, cmd.Handler(cmd)\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\t// Mark the project as initialized without running the command\n\t\t\tif err := config.MarkProjectInitialized(); err != nil {\n\t\t\t\treturn a, util.ReportError(err)\n\t\t\t}\n\t\t}\n\t\treturn a, nil\n\n\tcase chat.SessionSelectedMsg:\n\t\ta.selectedSession = msg\n\t\ta.sessionDialog.SetSelectedSession(msg.ID)\n\n\tcase pubsub.Event[session.Session]:\n\t\tif msg.Type == pubsub.UpdatedEvent && msg.Payload.ID == a.selectedSession.ID {\n\t\t\ta.selectedSession = msg.Payload\n\t\t}\n\tcase dialog.SessionSelectedMsg:\n\t\ta.showSessionDialog = false\n\t\tif a.currentPage == page.ChatPage {\n\t\t\treturn a, util.CmdHandler(chat.SessionSelectedMsg(msg.Session))\n\t\t}\n\t\treturn a, nil\n\n\tcase dialog.CommandSelectedMsg:\n\t\ta.showCommandDialog = false\n\t\t// Execute the command handler if available\n\t\tif msg.Command.Handler != nil {\n\t\t\treturn a, msg.Command.Handler(msg.Command)\n\t\t}\n\t\treturn a, util.ReportInfo(\"Command selected: \" + msg.Command.Title)\n\n\tcase dialog.ShowMultiArgumentsDialogMsg:\n\t\t// Show multi-arguments dialog\n\t\ta.multiArgumentsDialog = dialog.NewMultiArgumentsDialogCmp(msg.CommandID, msg.Content, msg.ArgNames)\n\t\ta.showMultiArgumentsDialog = true\n\t\treturn a, a.multiArgumentsDialog.Init()\n\n\tcase dialog.CloseMultiArgumentsDialogMsg:\n\t\t// Close multi-arguments dialog\n\t\ta.showMultiArgumentsDialog = false\n\n\t\t// If submitted, replace all named arguments and run the command\n\t\tif msg.Submit {\n\t\t\tcontent := msg.Content\n\n\t\t\t// Replace each named argument with its value\n\t\t\tfor name, value := range msg.Args {\n\t\t\t\tplaceholder := \"$\" + name\n\t\t\t\tcontent = strings.ReplaceAll(content, placeholder, value)\n\t\t\t}\n\n\t\t\t// Execute the command with arguments\n\t\t\treturn a, util.CmdHandler(dialog.CommandRunCustomMsg{\n\t\t\t\tContent: content,\n\t\t\t\tArgs: msg.Args,\n\t\t\t})\n\t\t}\n\t\treturn a, nil\n\n\tcase tea.KeyMsg:\n\t\t// If multi-arguments dialog is open, let it handle the key press first\n\t\tif a.showMultiArgumentsDialog {\n\t\t\targs, cmd := a.multiArgumentsDialog.Update(msg)\n\t\t\ta.multiArgumentsDialog = args.(dialog.MultiArgumentsDialogCmp)\n\t\t\treturn a, cmd\n\t\t}\n\n\t\tswitch {\n\n\t\tcase key.Matches(msg, keys.Quit):\n\t\t\ta.showQuit = !a.showQuit\n\t\t\tif a.showHelp {\n\t\t\t\ta.showHelp = false\n\t\t\t}\n\t\t\tif a.showSessionDialog {\n\t\t\t\ta.showSessionDialog = false\n\t\t\t}\n\t\t\tif a.showCommandDialog {\n\t\t\t\ta.showCommandDialog = false\n\t\t\t}\n\t\t\tif a.showFilepicker {\n\t\t\t\ta.showFilepicker = false\n\t\t\t\ta.filepicker.ToggleFilepicker(a.showFilepicker)\n\t\t\t}\n\t\t\tif a.showModelDialog {\n\t\t\t\ta.showModelDialog = false\n\t\t\t}\n\t\t\tif a.showMultiArgumentsDialog {\n\t\t\t\ta.showMultiArgumentsDialog = false\n\t\t\t}\n\t\t\treturn a, nil\n\t\tcase key.Matches(msg, keys.SwitchSession):\n\t\t\tif a.currentPage == page.ChatPage && !a.showQuit && !a.showPermissions && !a.showCommandDialog {\n\t\t\t\t// Load sessions and show the dialog\n\t\t\t\tsessions, err := a.app.Sessions.List(context.Background())\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn a, util.ReportError(err)\n\t\t\t\t}\n\t\t\t\tif len(sessions) == 0 {\n\t\t\t\t\treturn a, util.ReportWarn(\"No sessions available\")\n\t\t\t\t}\n\t\t\t\ta.sessionDialog.SetSessions(sessions)\n\t\t\t\ta.showSessionDialog = true\n\t\t\t\treturn a, nil\n\t\t\t}\n\t\t\treturn a, nil\n\t\tcase key.Matches(msg, keys.Commands):\n\t\t\tif a.currentPage == page.ChatPage && !a.showQuit && !a.showPermissions && !a.showSessionDialog && !a.showThemeDialog && !a.showFilepicker {\n\t\t\t\t// Show commands dialog\n\t\t\t\tif len(a.commands) == 0 {\n\t\t\t\t\treturn a, util.ReportWarn(\"No commands available\")\n\t\t\t\t}\n\t\t\t\ta.commandDialog.SetCommands(a.commands)\n\t\t\t\ta.showCommandDialog = true\n\t\t\t\treturn a, nil\n\t\t\t}\n\t\t\treturn a, nil\n\t\tcase key.Matches(msg, keys.Models):\n\t\t\tif a.showModelDialog {\n\t\t\t\ta.showModelDialog = false\n\t\t\t\treturn a, nil\n\t\t\t}\n\t\t\tif a.currentPage == page.ChatPage && !a.showQuit && !a.showPermissions && !a.showSessionDialog && !a.showCommandDialog {\n\t\t\t\ta.showModelDialog = true\n\t\t\t\treturn a, nil\n\t\t\t}\n\t\t\treturn a, nil\n\t\tcase key.Matches(msg, keys.SwitchTheme):\n\t\t\tif !a.showQuit && !a.showPermissions && !a.showSessionDialog && !a.showCommandDialog {\n\t\t\t\t// Show theme switcher dialog\n\t\t\t\ta.showThemeDialog = true\n\t\t\t\t// Theme list is dynamically loaded by the dialog component\n\t\t\t\treturn a, a.themeDialog.Init()\n\t\t\t}\n\t\t\treturn a, nil\n\t\tcase key.Matches(msg, returnKey) || key.Matches(msg):\n\t\t\tif msg.String() == quitKey {\n\t\t\t\tif a.currentPage == page.LogsPage {\n\t\t\t\t\treturn a, a.moveToPage(page.ChatPage)\n\t\t\t\t}\n\t\t\t} else if !a.filepicker.IsCWDFocused() {\n\t\t\t\tif a.showQuit {\n\t\t\t\t\ta.showQuit = !a.showQuit\n\t\t\t\t\treturn a, nil\n\t\t\t\t}\n\t\t\t\tif a.showHelp {\n\t\t\t\t\ta.showHelp = !a.showHelp\n\t\t\t\t\treturn a, nil\n\t\t\t\t}\n\t\t\t\tif a.showInitDialog {\n\t\t\t\t\ta.showInitDialog = false\n\t\t\t\t\t// Mark the project as initialized without running the command\n\t\t\t\t\tif err := config.MarkProjectInitialized(); err != nil {\n\t\t\t\t\t\treturn a, util.ReportError(err)\n\t\t\t\t\t}\n\t\t\t\t\treturn a, nil\n\t\t\t\t}\n\t\t\t\tif a.showFilepicker {\n\t\t\t\t\ta.showFilepicker = false\n\t\t\t\t\ta.filepicker.ToggleFilepicker(a.showFilepicker)\n\t\t\t\t\treturn a, nil\n\t\t\t\t}\n\t\t\t\tif a.currentPage == page.LogsPage {\n\t\t\t\t\treturn a, a.moveToPage(page.ChatPage)\n\t\t\t\t}\n\t\t\t}\n\t\tcase key.Matches(msg, keys.Logs):\n\t\t\treturn a, a.moveToPage(page.LogsPage)\n\t\tcase key.Matches(msg, keys.Help):\n\t\t\tif a.showQuit {\n\t\t\t\treturn a, nil\n\t\t\t}\n\t\t\ta.showHelp = !a.showHelp\n\t\t\treturn a, nil\n\t\tcase key.Matches(msg, helpEsc):\n\t\t\tif a.app.CoderAgent.IsBusy() {\n\t\t\t\tif a.showQuit {\n\t\t\t\t\treturn a, nil\n\t\t\t\t}\n\t\t\t\ta.showHelp = !a.showHelp\n\t\t\t\treturn a, nil\n\t\t\t}\n\t\tcase key.Matches(msg, keys.Filepicker):\n\t\t\ta.showFilepicker = !a.showFilepicker\n\t\t\ta.filepicker.ToggleFilepicker(a.showFilepicker)\n\t\t\treturn a, nil\n\t\t}\n\tdefault:\n\t\tf, filepickerCmd := a.filepicker.Update(msg)\n\t\ta.filepicker = f.(dialog.FilepickerCmp)\n\t\tcmds = append(cmds, filepickerCmd)\n\n\t}\n\n\tif a.showFilepicker {\n\t\tf, filepickerCmd := a.filepicker.Update(msg)\n\t\ta.filepicker = f.(dialog.FilepickerCmp)\n\t\tcmds = append(cmds, filepickerCmd)\n\t\t// Only block key messages send all other messages down\n\t\tif _, ok := msg.(tea.KeyMsg); ok {\n\t\t\treturn a, tea.Batch(cmds...)\n\t\t}\n\t}\n\n\tif a.showQuit {\n\t\tq, quitCmd := a.quit.Update(msg)\n\t\ta.quit = q.(dialog.QuitDialog)\n\t\tcmds = append(cmds, quitCmd)\n\t\t// Only block key messages send all other messages down\n\t\tif _, ok := msg.(tea.KeyMsg); ok {\n\t\t\treturn a, tea.Batch(cmds...)\n\t\t}\n\t}\n\tif a.showPermissions {\n\t\td, permissionsCmd := a.permissions.Update(msg)\n\t\ta.permissions = d.(dialog.PermissionDialogCmp)\n\t\tcmds = append(cmds, permissionsCmd)\n\t\t// Only block key messages send all other messages down\n\t\tif _, ok := msg.(tea.KeyMsg); ok {\n\t\t\treturn a, tea.Batch(cmds...)\n\t\t}\n\t}\n\n\tif a.showSessionDialog {\n\t\td, sessionCmd := a.sessionDialog.Update(msg)\n\t\ta.sessionDialog = d.(dialog.SessionDialog)\n\t\tcmds = append(cmds, sessionCmd)\n\t\t// Only block key messages send all other messages down\n\t\tif _, ok := msg.(tea.KeyMsg); ok {\n\t\t\treturn a, tea.Batch(cmds...)\n\t\t}\n\t}\n\n\tif a.showCommandDialog {\n\t\td, commandCmd := a.commandDialog.Update(msg)\n\t\ta.commandDialog = d.(dialog.CommandDialog)\n\t\tcmds = append(cmds, commandCmd)\n\t\t// Only block key messages send all other messages down\n\t\tif _, ok := msg.(tea.KeyMsg); ok {\n\t\t\treturn a, tea.Batch(cmds...)\n\t\t}\n\t}\n\n\tif a.showModelDialog {\n\t\td, modelCmd := a.modelDialog.Update(msg)\n\t\ta.modelDialog = d.(dialog.ModelDialog)\n\t\tcmds = append(cmds, modelCmd)\n\t\t// Only block key messages send all other messages down\n\t\tif _, ok := msg.(tea.KeyMsg); ok {\n\t\t\treturn a, tea.Batch(cmds...)\n\t\t}\n\t}\n\n\tif a.showInitDialog {\n\t\td, initCmd := a.initDialog.Update(msg)\n\t\ta.initDialog = d.(dialog.InitDialogCmp)\n\t\tcmds = append(cmds, initCmd)\n\t\t// Only block key messages send all other messages down\n\t\tif _, ok := msg.(tea.KeyMsg); ok {\n\t\t\treturn a, tea.Batch(cmds...)\n\t\t}\n\t}\n\n\tif a.showThemeDialog {\n\t\td, themeCmd := a.themeDialog.Update(msg)\n\t\ta.themeDialog = d.(dialog.ThemeDialog)\n\t\tcmds = append(cmds, themeCmd)\n\t\t// Only block key messages send all other messages down\n\t\tif _, ok := msg.(tea.KeyMsg); ok {\n\t\t\treturn a, tea.Batch(cmds...)\n\t\t}\n\t}\n\n\ts, _ := a.status.Update(msg)\n\ta.status = s.(core.StatusCmp)\n\ta.pages[a.currentPage], cmd = a.pages[a.currentPage].Update(msg)\n\tcmds = append(cmds, cmd)\n\treturn a, tea.Batch(cmds...)\n}\n\n// RegisterCommand adds a command to the command dialog\nfunc (a *appModel) RegisterCommand(cmd dialog.Command) {\n\ta.commands = append(a.commands, cmd)\n}\n\nfunc (a *appModel) findCommand(id string) (dialog.Command, bool) {\n\tfor _, cmd := range a.commands {\n\t\tif cmd.ID == id {\n\t\t\treturn cmd, true\n\t\t}\n\t}\n\treturn dialog.Command{}, false\n}\n\nfunc (a *appModel) moveToPage(pageID page.PageID) tea.Cmd {\n\tif a.app.CoderAgent.IsBusy() {\n\t\t// For now we don't move to any page if the agent is busy\n\t\treturn util.ReportWarn(\"Agent is busy, please wait...\")\n\t}\n\n\tvar cmds []tea.Cmd\n\tif _, ok := a.loadedPages[pageID]; !ok {\n\t\tcmd := a.pages[pageID].Init()\n\t\tcmds = append(cmds, cmd)\n\t\ta.loadedPages[pageID] = true\n\t}\n\ta.previousPage = a.currentPage\n\ta.currentPage = pageID\n\tif sizable, ok := a.pages[a.currentPage].(layout.Sizeable); ok {\n\t\tcmd := sizable.SetSize(a.width, a.height)\n\t\tcmds = append(cmds, cmd)\n\t}\n\n\treturn tea.Batch(cmds...)\n}\n\nfunc (a appModel) View() string {\n\tcomponents := []string{\n\t\ta.pages[a.currentPage].View(),\n\t}\n\n\tcomponents = append(components, a.status.View())\n\n\tappView := lipgloss.JoinVertical(lipgloss.Top, components...)\n\n\tif a.showPermissions {\n\t\toverlay := a.permissions.View()\n\t\trow := lipgloss.Height(appView) / 2\n\t\trow -= lipgloss.Height(overlay) / 2\n\t\tcol := lipgloss.Width(appView) / 2\n\t\tcol -= lipgloss.Width(overlay) / 2\n\t\tappView = layout.PlaceOverlay(\n\t\t\tcol,\n\t\t\trow,\n\t\t\toverlay,\n\t\t\tappView,\n\t\t\ttrue,\n\t\t)\n\t}\n\n\tif a.showFilepicker {\n\t\toverlay := a.filepicker.View()\n\t\trow := lipgloss.Height(appView) / 2\n\t\trow -= lipgloss.Height(overlay) / 2\n\t\tcol := lipgloss.Width(appView) / 2\n\t\tcol -= lipgloss.Width(overlay) / 2\n\t\tappView = layout.PlaceOverlay(\n\t\t\tcol,\n\t\t\trow,\n\t\t\toverlay,\n\t\t\tappView,\n\t\t\ttrue,\n\t\t)\n\n\t}\n\n\t// Show compacting status overlay\n\tif a.isCompacting {\n\t\tt := theme.CurrentTheme()\n\t\tstyle := lipgloss.NewStyle().\n\t\t\tBorder(lipgloss.RoundedBorder()).\n\t\t\tBorderForeground(t.BorderFocused()).\n\t\t\tBorderBackground(t.Background()).\n\t\t\tPadding(1, 2).\n\t\t\tBackground(t.Background()).\n\t\t\tForeground(t.Text())\n\n\t\toverlay := style.Render(\"Summarizing\\n\" + a.compactingMessage)\n\t\trow := lipgloss.Height(appView) / 2\n\t\trow -= lipgloss.Height(overlay) / 2\n\t\tcol := lipgloss.Width(appView) / 2\n\t\tcol -= lipgloss.Width(overlay) / 2\n\t\tappView = layout.PlaceOverlay(\n\t\t\tcol,\n\t\t\trow,\n\t\t\toverlay,\n\t\t\tappView,\n\t\t\ttrue,\n\t\t)\n\t}\n\n\tif a.showHelp {\n\t\tbindings := layout.KeyMapToSlice(keys)\n\t\tif p, ok := a.pages[a.currentPage].(layout.Bindings); ok {\n\t\t\tbindings = append(bindings, p.BindingKeys()...)\n\t\t}\n\t\tif a.showPermissions {\n\t\t\tbindings = append(bindings, a.permissions.BindingKeys()...)\n\t\t}\n\t\tif a.currentPage == page.LogsPage {\n\t\t\tbindings = append(bindings, logsKeyReturnKey)\n\t\t}\n\t\tif !a.app.CoderAgent.IsBusy() {\n\t\t\tbindings = append(bindings, helpEsc)\n\t\t}\n\t\ta.help.SetBindings(bindings)\n\n\t\toverlay := a.help.View()\n\t\trow := lipgloss.Height(appView) / 2\n\t\trow -= lipgloss.Height(overlay) / 2\n\t\tcol := lipgloss.Width(appView) / 2\n\t\tcol -= lipgloss.Width(overlay) / 2\n\t\tappView = layout.PlaceOverlay(\n\t\t\tcol,\n\t\t\trow,\n\t\t\toverlay,\n\t\t\tappView,\n\t\t\ttrue,\n\t\t)\n\t}\n\n\tif a.showQuit {\n\t\toverlay := a.quit.View()\n\t\trow := lipgloss.Height(appView) / 2\n\t\trow -= lipgloss.Height(overlay) / 2\n\t\tcol := lipgloss.Width(appView) / 2\n\t\tcol -= lipgloss.Width(overlay) / 2\n\t\tappView = layout.PlaceOverlay(\n\t\t\tcol,\n\t\t\trow,\n\t\t\toverlay,\n\t\t\tappView,\n\t\t\ttrue,\n\t\t)\n\t}\n\n\tif a.showSessionDialog {\n\t\toverlay := a.sessionDialog.View()\n\t\trow := lipgloss.Height(appView) / 2\n\t\trow -= lipgloss.Height(overlay) / 2\n\t\tcol := lipgloss.Width(appView) / 2\n\t\tcol -= lipgloss.Width(overlay) / 2\n\t\tappView = layout.PlaceOverlay(\n\t\t\tcol,\n\t\t\trow,\n\t\t\toverlay,\n\t\t\tappView,\n\t\t\ttrue,\n\t\t)\n\t}\n\n\tif a.showModelDialog {\n\t\toverlay := a.modelDialog.View()\n\t\trow := lipgloss.Height(appView) / 2\n\t\trow -= lipgloss.Height(overlay) / 2\n\t\tcol := lipgloss.Width(appView) / 2\n\t\tcol -= lipgloss.Width(overlay) / 2\n\t\tappView = layout.PlaceOverlay(\n\t\t\tcol,\n\t\t\trow,\n\t\t\toverlay,\n\t\t\tappView,\n\t\t\ttrue,\n\t\t)\n\t}\n\n\tif a.showCommandDialog {\n\t\toverlay := a.commandDialog.View()\n\t\trow := lipgloss.Height(appView) / 2\n\t\trow -= lipgloss.Height(overlay) / 2\n\t\tcol := lipgloss.Width(appView) / 2\n\t\tcol -= lipgloss.Width(overlay) / 2\n\t\tappView = layout.PlaceOverlay(\n\t\t\tcol,\n\t\t\trow,\n\t\t\toverlay,\n\t\t\tappView,\n\t\t\ttrue,\n\t\t)\n\t}\n\n\tif a.showInitDialog {\n\t\toverlay := a.initDialog.View()\n\t\tappView = layout.PlaceOverlay(\n\t\t\ta.width/2-lipgloss.Width(overlay)/2,\n\t\t\ta.height/2-lipgloss.Height(overlay)/2,\n\t\t\toverlay,\n\t\t\tappView,\n\t\t\ttrue,\n\t\t)\n\t}\n\n\tif a.showThemeDialog {\n\t\toverlay := a.themeDialog.View()\n\t\trow := lipgloss.Height(appView) / 2\n\t\trow -= lipgloss.Height(overlay) / 2\n\t\tcol := lipgloss.Width(appView) / 2\n\t\tcol -= lipgloss.Width(overlay) / 2\n\t\tappView = layout.PlaceOverlay(\n\t\t\tcol,\n\t\t\trow,\n\t\t\toverlay,\n\t\t\tappView,\n\t\t\ttrue,\n\t\t)\n\t}\n\n\tif a.showMultiArgumentsDialog {\n\t\toverlay := a.multiArgumentsDialog.View()\n\t\trow := lipgloss.Height(appView) / 2\n\t\trow -= lipgloss.Height(overlay) / 2\n\t\tcol := lipgloss.Width(appView) / 2\n\t\tcol -= lipgloss.Width(overlay) / 2\n\t\tappView = layout.PlaceOverlay(\n\t\t\tcol,\n\t\t\trow,\n\t\t\toverlay,\n\t\t\tappView,\n\t\t\ttrue,\n\t\t)\n\t}\n\n\treturn appView\n}\n\nfunc New(app *app.App) tea.Model {\n\tstartPage := page.ChatPage\n\tmodel := &appModel{\n\t\tcurrentPage: startPage,\n\t\tloadedPages: make(map[page.PageID]bool),\n\t\tstatus: core.NewStatusCmp(app.LSPClients),\n\t\thelp: dialog.NewHelpCmp(),\n\t\tquit: dialog.NewQuitCmp(),\n\t\tsessionDialog: dialog.NewSessionDialogCmp(),\n\t\tcommandDialog: dialog.NewCommandDialogCmp(),\n\t\tmodelDialog: dialog.NewModelDialogCmp(),\n\t\tpermissions: dialog.NewPermissionDialogCmp(),\n\t\tinitDialog: dialog.NewInitDialogCmp(),\n\t\tthemeDialog: dialog.NewThemeDialogCmp(),\n\t\tapp: app,\n\t\tcommands: []dialog.Command{},\n\t\tpages: map[page.PageID]tea.Model{\n\t\t\tpage.ChatPage: page.NewChatPage(app),\n\t\t\tpage.LogsPage: page.NewLogsPage(),\n\t\t},\n\t\tfilepicker: dialog.NewFilepickerCmp(app),\n\t}\n\n\tmodel.RegisterCommand(dialog.Command{\n\t\tID: \"init\",\n\t\tTitle: \"Initialize Project\",\n\t\tDescription: \"Create/Update the OpenCode.md memory file\",\n\t\tHandler: func(cmd dialog.Command) tea.Cmd {\n\t\t\tprompt := `Please analyze this codebase and create a OpenCode.md file containing:\n1. Build/lint/test commands - especially for running a single test\n2. Code style guidelines including imports, formatting, types, naming conventions, error handling, etc.\n\nThe file you create will be given to agentic coding agents (such as yourself) that operate in this repository. Make it about 20 lines long.\nIf there's already a opencode.md, improve it.\nIf there are Cursor rules (in .cursor/rules/ or .cursorrules) or Copilot rules (in .github/copilot-instructions.md), make sure to include them.`\n\t\t\treturn tea.Batch(\n\t\t\t\tutil.CmdHandler(chat.SendMsg{\n\t\t\t\t\tText: prompt,\n\t\t\t\t}),\n\t\t\t)\n\t\t},\n\t})\n\n\tmodel.RegisterCommand(dialog.Command{\n\t\tID: \"compact\",\n\t\tTitle: \"Compact Session\",\n\t\tDescription: \"Summarize the current session and create a new one with the summary\",\n\t\tHandler: func(cmd dialog.Command) tea.Cmd {\n\t\t\treturn func() tea.Msg {\n\t\t\t\treturn startCompactSessionMsg{}\n\t\t\t}\n\t\t},\n\t})\n\t// Load custom commands\n\tcustomCommands, err := dialog.LoadCustomCommands()\n\tif err != nil {\n\t\tlogging.Warn(\"Failed to load custom commands\", \"error\", err)\n\t} else {\n\t\tfor _, cmd := range customCommands {\n\t\t\tmodel.RegisterCommand(cmd)\n\t\t}\n\t}\n\n\treturn model\n}\n"], ["/opencode/internal/tui/components/core/status.go", "package core\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\t\"time\"\n\n\ttea \"github.com/charmbracelet/bubbletea\"\n\t\"github.com/charmbracelet/lipgloss\"\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/llm/models\"\n\t\"github.com/opencode-ai/opencode/internal/lsp\"\n\t\"github.com/opencode-ai/opencode/internal/lsp/protocol\"\n\t\"github.com/opencode-ai/opencode/internal/pubsub\"\n\t\"github.com/opencode-ai/opencode/internal/session\"\n\t\"github.com/opencode-ai/opencode/internal/tui/components/chat\"\n\t\"github.com/opencode-ai/opencode/internal/tui/styles\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n\t\"github.com/opencode-ai/opencode/internal/tui/util\"\n)\n\ntype StatusCmp interface {\n\ttea.Model\n}\n\ntype statusCmp struct {\n\tinfo util.InfoMsg\n\twidth int\n\tmessageTTL time.Duration\n\tlspClients map[string]*lsp.Client\n\tsession session.Session\n}\n\n// clearMessageCmd is a command that clears status messages after a timeout\nfunc (m statusCmp) clearMessageCmd(ttl time.Duration) tea.Cmd {\n\treturn tea.Tick(ttl, func(time.Time) tea.Msg {\n\t\treturn util.ClearStatusMsg{}\n\t})\n}\n\nfunc (m statusCmp) Init() tea.Cmd {\n\treturn nil\n}\n\nfunc (m statusCmp) Update(msg tea.Msg) (tea.Model, tea.Cmd) {\n\tswitch msg := msg.(type) {\n\tcase tea.WindowSizeMsg:\n\t\tm.width = msg.Width\n\t\treturn m, nil\n\tcase chat.SessionSelectedMsg:\n\t\tm.session = msg\n\tcase chat.SessionClearedMsg:\n\t\tm.session = session.Session{}\n\tcase pubsub.Event[session.Session]:\n\t\tif msg.Type == pubsub.UpdatedEvent {\n\t\t\tif m.session.ID == msg.Payload.ID {\n\t\t\t\tm.session = msg.Payload\n\t\t\t}\n\t\t}\n\tcase util.InfoMsg:\n\t\tm.info = msg\n\t\tttl := msg.TTL\n\t\tif ttl == 0 {\n\t\t\tttl = m.messageTTL\n\t\t}\n\t\treturn m, m.clearMessageCmd(ttl)\n\tcase util.ClearStatusMsg:\n\t\tm.info = util.InfoMsg{}\n\t}\n\treturn m, nil\n}\n\nvar helpWidget = \"\"\n\n// getHelpWidget returns the help widget with current theme colors\nfunc getHelpWidget() string {\n\tt := theme.CurrentTheme()\n\thelpText := \"ctrl+? help\"\n\n\treturn styles.Padded().\n\t\tBackground(t.TextMuted()).\n\t\tForeground(t.BackgroundDarker()).\n\t\tBold(true).\n\t\tRender(helpText)\n}\n\nfunc formatTokensAndCost(tokens, contextWindow int64, cost float64) string {\n\t// Format tokens in human-readable format (e.g., 110K, 1.2M)\n\tvar formattedTokens string\n\tswitch {\n\tcase tokens >= 1_000_000:\n\t\tformattedTokens = fmt.Sprintf(\"%.1fM\", float64(tokens)/1_000_000)\n\tcase tokens >= 1_000:\n\t\tformattedTokens = fmt.Sprintf(\"%.1fK\", float64(tokens)/1_000)\n\tdefault:\n\t\tformattedTokens = fmt.Sprintf(\"%d\", tokens)\n\t}\n\n\t// Remove .0 suffix if present\n\tif strings.HasSuffix(formattedTokens, \".0K\") {\n\t\tformattedTokens = strings.Replace(formattedTokens, \".0K\", \"K\", 1)\n\t}\n\tif strings.HasSuffix(formattedTokens, \".0M\") {\n\t\tformattedTokens = strings.Replace(formattedTokens, \".0M\", \"M\", 1)\n\t}\n\n\t// Format cost with $ symbol and 2 decimal places\n\tformattedCost := fmt.Sprintf(\"$%.2f\", cost)\n\n\tpercentage := (float64(tokens) / float64(contextWindow)) * 100\n\tif percentage > 80 {\n\t\t// add the warning icon and percentage\n\t\tformattedTokens = fmt.Sprintf(\"%s(%d%%)\", styles.WarningIcon, int(percentage))\n\t}\n\n\treturn fmt.Sprintf(\"Context: %s, Cost: %s\", formattedTokens, formattedCost)\n}\n\nfunc (m statusCmp) View() string {\n\tt := theme.CurrentTheme()\n\tmodelID := config.Get().Agents[config.AgentCoder].Model\n\tmodel := models.SupportedModels[modelID]\n\n\t// Initialize the help widget\n\tstatus := getHelpWidget()\n\n\ttokenInfoWidth := 0\n\tif m.session.ID != \"\" {\n\t\ttotalTokens := m.session.PromptTokens + m.session.CompletionTokens\n\t\ttokens := formatTokensAndCost(totalTokens, model.ContextWindow, m.session.Cost)\n\t\ttokensStyle := styles.Padded().\n\t\t\tBackground(t.Text()).\n\t\t\tForeground(t.BackgroundSecondary())\n\t\tpercentage := (float64(totalTokens) / float64(model.ContextWindow)) * 100\n\t\tif percentage > 80 {\n\t\t\ttokensStyle = tokensStyle.Background(t.Warning())\n\t\t}\n\t\ttokenInfoWidth = lipgloss.Width(tokens) + 2\n\t\tstatus += tokensStyle.Render(tokens)\n\t}\n\n\tdiagnostics := styles.Padded().\n\t\tBackground(t.BackgroundDarker()).\n\t\tRender(m.projectDiagnostics())\n\n\tavailableWidht := max(0, m.width-lipgloss.Width(helpWidget)-lipgloss.Width(m.model())-lipgloss.Width(diagnostics)-tokenInfoWidth)\n\n\tif m.info.Msg != \"\" {\n\t\tinfoStyle := styles.Padded().\n\t\t\tForeground(t.Background()).\n\t\t\tWidth(availableWidht)\n\n\t\tswitch m.info.Type {\n\t\tcase util.InfoTypeInfo:\n\t\t\tinfoStyle = infoStyle.Background(t.Info())\n\t\tcase util.InfoTypeWarn:\n\t\t\tinfoStyle = infoStyle.Background(t.Warning())\n\t\tcase util.InfoTypeError:\n\t\t\tinfoStyle = infoStyle.Background(t.Error())\n\t\t}\n\n\t\tinfoWidth := availableWidht - 10\n\t\t// Truncate message if it's longer than available width\n\t\tmsg := m.info.Msg\n\t\tif len(msg) > infoWidth && infoWidth > 0 {\n\t\t\tmsg = msg[:infoWidth] + \"...\"\n\t\t}\n\t\tstatus += infoStyle.Render(msg)\n\t} else {\n\t\tstatus += styles.Padded().\n\t\t\tForeground(t.Text()).\n\t\t\tBackground(t.BackgroundSecondary()).\n\t\t\tWidth(availableWidht).\n\t\t\tRender(\"\")\n\t}\n\n\tstatus += diagnostics\n\tstatus += m.model()\n\treturn status\n}\n\nfunc (m *statusCmp) projectDiagnostics() string {\n\tt := theme.CurrentTheme()\n\n\t// Check if any LSP server is still initializing\n\tinitializing := false\n\tfor _, client := range m.lspClients {\n\t\tif client.GetServerState() == lsp.StateStarting {\n\t\t\tinitializing = true\n\t\t\tbreak\n\t\t}\n\t}\n\n\t// If any server is initializing, show that status\n\tif initializing {\n\t\treturn lipgloss.NewStyle().\n\t\t\tBackground(t.BackgroundDarker()).\n\t\t\tForeground(t.Warning()).\n\t\t\tRender(fmt.Sprintf(\"%s Initializing LSP...\", styles.SpinnerIcon))\n\t}\n\n\terrorDiagnostics := []protocol.Diagnostic{}\n\twarnDiagnostics := []protocol.Diagnostic{}\n\thintDiagnostics := []protocol.Diagnostic{}\n\tinfoDiagnostics := []protocol.Diagnostic{}\n\tfor _, client := range m.lspClients {\n\t\tfor _, d := range client.GetDiagnostics() {\n\t\t\tfor _, diag := range d {\n\t\t\t\tswitch diag.Severity {\n\t\t\t\tcase protocol.SeverityError:\n\t\t\t\t\terrorDiagnostics = append(errorDiagnostics, diag)\n\t\t\t\tcase protocol.SeverityWarning:\n\t\t\t\t\twarnDiagnostics = append(warnDiagnostics, diag)\n\t\t\t\tcase protocol.SeverityHint:\n\t\t\t\t\thintDiagnostics = append(hintDiagnostics, diag)\n\t\t\t\tcase protocol.SeverityInformation:\n\t\t\t\t\tinfoDiagnostics = append(infoDiagnostics, diag)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif len(errorDiagnostics) == 0 && len(warnDiagnostics) == 0 && len(hintDiagnostics) == 0 && len(infoDiagnostics) == 0 {\n\t\treturn \"No diagnostics\"\n\t}\n\n\tdiagnostics := []string{}\n\n\tif len(errorDiagnostics) > 0 {\n\t\terrStr := lipgloss.NewStyle().\n\t\t\tBackground(t.BackgroundDarker()).\n\t\t\tForeground(t.Error()).\n\t\t\tRender(fmt.Sprintf(\"%s %d\", styles.ErrorIcon, len(errorDiagnostics)))\n\t\tdiagnostics = append(diagnostics, errStr)\n\t}\n\tif len(warnDiagnostics) > 0 {\n\t\twarnStr := lipgloss.NewStyle().\n\t\t\tBackground(t.BackgroundDarker()).\n\t\t\tForeground(t.Warning()).\n\t\t\tRender(fmt.Sprintf(\"%s %d\", styles.WarningIcon, len(warnDiagnostics)))\n\t\tdiagnostics = append(diagnostics, warnStr)\n\t}\n\tif len(hintDiagnostics) > 0 {\n\t\thintStr := lipgloss.NewStyle().\n\t\t\tBackground(t.BackgroundDarker()).\n\t\t\tForeground(t.Text()).\n\t\t\tRender(fmt.Sprintf(\"%s %d\", styles.HintIcon, len(hintDiagnostics)))\n\t\tdiagnostics = append(diagnostics, hintStr)\n\t}\n\tif len(infoDiagnostics) > 0 {\n\t\tinfoStr := lipgloss.NewStyle().\n\t\t\tBackground(t.BackgroundDarker()).\n\t\t\tForeground(t.Info()).\n\t\t\tRender(fmt.Sprintf(\"%s %d\", styles.InfoIcon, len(infoDiagnostics)))\n\t\tdiagnostics = append(diagnostics, infoStr)\n\t}\n\n\treturn strings.Join(diagnostics, \" \")\n}\n\nfunc (m statusCmp) availableFooterMsgWidth(diagnostics, tokenInfo string) int {\n\ttokensWidth := 0\n\tif m.session.ID != \"\" {\n\t\ttokensWidth = lipgloss.Width(tokenInfo) + 2\n\t}\n\treturn max(0, m.width-lipgloss.Width(helpWidget)-lipgloss.Width(m.model())-lipgloss.Width(diagnostics)-tokensWidth)\n}\n\nfunc (m statusCmp) model() string {\n\tt := theme.CurrentTheme()\n\n\tcfg := config.Get()\n\n\tcoder, ok := cfg.Agents[config.AgentCoder]\n\tif !ok {\n\t\treturn \"Unknown\"\n\t}\n\tmodel := models.SupportedModels[coder.Model]\n\n\treturn styles.Padded().\n\t\tBackground(t.Secondary()).\n\t\tForeground(t.Background()).\n\t\tRender(model.Name)\n}\n\nfunc NewStatusCmp(lspClients map[string]*lsp.Client) StatusCmp {\n\thelpWidget = getHelpWidget()\n\n\treturn &statusCmp{\n\t\tmessageTTL: 10 * time.Second,\n\t\tlspClients: lspClients,\n\t}\n}\n"], ["/opencode/internal/tui/components/dialog/filepicker.go", "package dialog\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"sort\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/charmbracelet/bubbles/key\"\n\t\"github.com/charmbracelet/bubbles/textinput\"\n\t\"github.com/charmbracelet/bubbles/viewport\"\n\ttea \"github.com/charmbracelet/bubbletea\"\n\t\"github.com/charmbracelet/lipgloss\"\n\t\"github.com/opencode-ai/opencode/internal/app\"\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n\t\"github.com/opencode-ai/opencode/internal/message\"\n\t\"github.com/opencode-ai/opencode/internal/tui/image\"\n\t\"github.com/opencode-ai/opencode/internal/tui/styles\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n\t\"github.com/opencode-ai/opencode/internal/tui/util\"\n)\n\nconst (\n\tmaxAttachmentSize = int64(5 * 1024 * 1024) // 5MB\n\tdownArrow = \"down\"\n\tupArrow = \"up\"\n)\n\ntype FilePrickerKeyMap struct {\n\tEnter key.Binding\n\tDown key.Binding\n\tUp key.Binding\n\tForward key.Binding\n\tBackward key.Binding\n\tOpenFilePicker key.Binding\n\tEsc key.Binding\n\tInsertCWD key.Binding\n}\n\nvar filePickerKeyMap = FilePrickerKeyMap{\n\tEnter: key.NewBinding(\n\t\tkey.WithKeys(\"enter\"),\n\t\tkey.WithHelp(\"enter\", \"select file/enter directory\"),\n\t),\n\tDown: key.NewBinding(\n\t\tkey.WithKeys(\"j\", downArrow),\n\t\tkey.WithHelp(\"↓/j\", \"down\"),\n\t),\n\tUp: key.NewBinding(\n\t\tkey.WithKeys(\"k\", upArrow),\n\t\tkey.WithHelp(\"↑/k\", \"up\"),\n\t),\n\tForward: key.NewBinding(\n\t\tkey.WithKeys(\"l\"),\n\t\tkey.WithHelp(\"l\", \"enter directory\"),\n\t),\n\tBackward: key.NewBinding(\n\t\tkey.WithKeys(\"h\", \"backspace\"),\n\t\tkey.WithHelp(\"h/backspace\", \"go back\"),\n\t),\n\tOpenFilePicker: key.NewBinding(\n\t\tkey.WithKeys(\"ctrl+f\"),\n\t\tkey.WithHelp(\"ctrl+f\", \"open file picker\"),\n\t),\n\tEsc: key.NewBinding(\n\t\tkey.WithKeys(\"esc\"),\n\t\tkey.WithHelp(\"esc\", \"close/exit\"),\n\t),\n\tInsertCWD: key.NewBinding(\n\t\tkey.WithKeys(\"i\"),\n\t\tkey.WithHelp(\"i\", \"manual path input\"),\n\t),\n}\n\ntype filepickerCmp struct {\n\tbasePath string\n\twidth int\n\theight int\n\tcursor int\n\terr error\n\tcursorChain stack\n\tviewport viewport.Model\n\tdirs []os.DirEntry\n\tcwdDetails *DirNode\n\tselectedFile string\n\tcwd textinput.Model\n\tShowFilePicker bool\n\tapp *app.App\n}\n\ntype DirNode struct {\n\tparent *DirNode\n\tchild *DirNode\n\tdirectory string\n}\ntype stack []int\n\nfunc (s stack) Push(v int) stack {\n\treturn append(s, v)\n}\n\nfunc (s stack) Pop() (stack, int) {\n\tl := len(s)\n\treturn s[:l-1], s[l-1]\n}\n\ntype AttachmentAddedMsg struct {\n\tAttachment message.Attachment\n}\n\nfunc (f *filepickerCmp) Init() tea.Cmd {\n\treturn nil\n}\n\nfunc (f *filepickerCmp) Update(msg tea.Msg) (tea.Model, tea.Cmd) {\n\tvar cmd tea.Cmd\n\tswitch msg := msg.(type) {\n\tcase tea.WindowSizeMsg:\n\t\tf.width = 60\n\t\tf.height = 20\n\t\tf.viewport.Width = 80\n\t\tf.viewport.Height = 22\n\t\tf.cursor = 0\n\t\tf.getCurrentFileBelowCursor()\n\tcase tea.KeyMsg:\n\t\tif f.cwd.Focused() {\n\t\t\tf.cwd, cmd = f.cwd.Update(msg)\n\t\t}\n\t\tswitch {\n\t\tcase key.Matches(msg, filePickerKeyMap.InsertCWD):\n\t\t\tf.cwd.Focus()\n\t\t\treturn f, cmd\n\t\tcase key.Matches(msg, filePickerKeyMap.Esc):\n\t\t\tif f.cwd.Focused() {\n\t\t\t\tf.cwd.Blur()\n\t\t\t}\n\t\tcase key.Matches(msg, filePickerKeyMap.Down):\n\t\t\tif !f.cwd.Focused() || msg.String() == downArrow {\n\t\t\t\tif f.cursor < len(f.dirs)-1 {\n\t\t\t\t\tf.cursor++\n\t\t\t\t\tf.getCurrentFileBelowCursor()\n\t\t\t\t}\n\t\t\t}\n\t\tcase key.Matches(msg, filePickerKeyMap.Up):\n\t\t\tif !f.cwd.Focused() || msg.String() == upArrow {\n\t\t\t\tif f.cursor > 0 {\n\t\t\t\t\tf.cursor--\n\t\t\t\t\tf.getCurrentFileBelowCursor()\n\t\t\t\t}\n\t\t\t}\n\t\tcase key.Matches(msg, filePickerKeyMap.Enter):\n\t\t\tvar path string\n\t\t\tvar isPathDir bool\n\t\t\tif f.cwd.Focused() {\n\t\t\t\tpath = f.cwd.Value()\n\t\t\t\tfileInfo, err := os.Stat(path)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlogging.ErrorPersist(\"Invalid path\")\n\t\t\t\t\treturn f, cmd\n\t\t\t\t}\n\t\t\t\tisPathDir = fileInfo.IsDir()\n\t\t\t} else {\n\t\t\t\tpath = filepath.Join(f.cwdDetails.directory, \"/\", f.dirs[f.cursor].Name())\n\t\t\t\tisPathDir = f.dirs[f.cursor].IsDir()\n\t\t\t}\n\t\t\tif isPathDir {\n\t\t\t\tnewWorkingDir := DirNode{parent: f.cwdDetails, directory: path}\n\t\t\t\tf.cwdDetails.child = &newWorkingDir\n\t\t\t\tf.cwdDetails = f.cwdDetails.child\n\t\t\t\tf.cursorChain = f.cursorChain.Push(f.cursor)\n\t\t\t\tf.dirs = readDir(f.cwdDetails.directory, false)\n\t\t\t\tf.cursor = 0\n\t\t\t\tf.cwd.SetValue(f.cwdDetails.directory)\n\t\t\t\tf.getCurrentFileBelowCursor()\n\t\t\t} else {\n\t\t\t\tf.selectedFile = path\n\t\t\t\treturn f.addAttachmentToMessage()\n\t\t\t}\n\t\tcase key.Matches(msg, filePickerKeyMap.Esc):\n\t\t\tif !f.cwd.Focused() {\n\t\t\t\tf.cursorChain = make(stack, 0)\n\t\t\t\tf.cursor = 0\n\t\t\t} else {\n\t\t\t\tf.cwd.Blur()\n\t\t\t}\n\t\tcase key.Matches(msg, filePickerKeyMap.Forward):\n\t\t\tif !f.cwd.Focused() {\n\t\t\t\tif f.dirs[f.cursor].IsDir() {\n\t\t\t\t\tpath := filepath.Join(f.cwdDetails.directory, \"/\", f.dirs[f.cursor].Name())\n\t\t\t\t\tnewWorkingDir := DirNode{parent: f.cwdDetails, directory: path}\n\t\t\t\t\tf.cwdDetails.child = &newWorkingDir\n\t\t\t\t\tf.cwdDetails = f.cwdDetails.child\n\t\t\t\t\tf.cursorChain = f.cursorChain.Push(f.cursor)\n\t\t\t\t\tf.dirs = readDir(f.cwdDetails.directory, false)\n\t\t\t\t\tf.cursor = 0\n\t\t\t\t\tf.cwd.SetValue(f.cwdDetails.directory)\n\t\t\t\t\tf.getCurrentFileBelowCursor()\n\t\t\t\t}\n\t\t\t}\n\t\tcase key.Matches(msg, filePickerKeyMap.Backward):\n\t\t\tif !f.cwd.Focused() {\n\t\t\t\tif len(f.cursorChain) != 0 && f.cwdDetails.parent != nil {\n\t\t\t\t\tf.cursorChain, f.cursor = f.cursorChain.Pop()\n\t\t\t\t\tf.cwdDetails = f.cwdDetails.parent\n\t\t\t\t\tf.cwdDetails.child = nil\n\t\t\t\t\tf.dirs = readDir(f.cwdDetails.directory, false)\n\t\t\t\t\tf.cwd.SetValue(f.cwdDetails.directory)\n\t\t\t\t\tf.getCurrentFileBelowCursor()\n\t\t\t\t}\n\t\t\t}\n\t\tcase key.Matches(msg, filePickerKeyMap.OpenFilePicker):\n\t\t\tf.dirs = readDir(f.cwdDetails.directory, false)\n\t\t\tf.cursor = 0\n\t\t\tf.getCurrentFileBelowCursor()\n\t\t}\n\t}\n\treturn f, cmd\n}\n\nfunc (f *filepickerCmp) addAttachmentToMessage() (tea.Model, tea.Cmd) {\n\tmodeInfo := GetSelectedModel(config.Get())\n\tif !modeInfo.SupportsAttachments {\n\t\tlogging.ErrorPersist(fmt.Sprintf(\"Model %s doesn't support attachments\", modeInfo.Name))\n\t\treturn f, nil\n\t}\n\n\tselectedFilePath := f.selectedFile\n\tif !isExtSupported(selectedFilePath) {\n\t\tlogging.ErrorPersist(\"Unsupported file\")\n\t\treturn f, nil\n\t}\n\n\tisFileLarge, err := image.ValidateFileSize(selectedFilePath, maxAttachmentSize)\n\tif err != nil {\n\t\tlogging.ErrorPersist(\"unable to read the image\")\n\t\treturn f, nil\n\t}\n\tif isFileLarge {\n\t\tlogging.ErrorPersist(\"file too large, max 5MB\")\n\t\treturn f, nil\n\t}\n\n\tcontent, err := os.ReadFile(selectedFilePath)\n\tif err != nil {\n\t\tlogging.ErrorPersist(\"Unable read selected file\")\n\t\treturn f, nil\n\t}\n\n\tmimeBufferSize := min(512, len(content))\n\tmimeType := http.DetectContentType(content[:mimeBufferSize])\n\tfileName := filepath.Base(selectedFilePath)\n\tattachment := message.Attachment{FilePath: selectedFilePath, FileName: fileName, MimeType: mimeType, Content: content}\n\tf.selectedFile = \"\"\n\treturn f, util.CmdHandler(AttachmentAddedMsg{attachment})\n}\n\nfunc (f *filepickerCmp) View() string {\n\tt := theme.CurrentTheme()\n\tconst maxVisibleDirs = 20\n\tconst maxWidth = 80\n\n\tadjustedWidth := maxWidth\n\tfor _, file := range f.dirs {\n\t\tif len(file.Name()) > adjustedWidth-4 { // Account for padding\n\t\t\tadjustedWidth = len(file.Name()) + 4\n\t\t}\n\t}\n\tadjustedWidth = max(30, min(adjustedWidth, f.width-15)) + 1\n\n\tfiles := make([]string, 0, maxVisibleDirs)\n\tstartIdx := 0\n\n\tif len(f.dirs) > maxVisibleDirs {\n\t\thalfVisible := maxVisibleDirs / 2\n\t\tif f.cursor >= halfVisible && f.cursor < len(f.dirs)-halfVisible {\n\t\t\tstartIdx = f.cursor - halfVisible\n\t\t} else if f.cursor >= len(f.dirs)-halfVisible {\n\t\t\tstartIdx = len(f.dirs) - maxVisibleDirs\n\t\t}\n\t}\n\n\tendIdx := min(startIdx+maxVisibleDirs, len(f.dirs))\n\n\tfor i := startIdx; i < endIdx; i++ {\n\t\tfile := f.dirs[i]\n\t\titemStyle := styles.BaseStyle().Width(adjustedWidth)\n\n\t\tif i == f.cursor {\n\t\t\titemStyle = itemStyle.\n\t\t\t\tBackground(t.Primary()).\n\t\t\t\tForeground(t.Background()).\n\t\t\t\tBold(true)\n\t\t}\n\t\tfilename := file.Name()\n\n\t\tif len(filename) > adjustedWidth-4 {\n\t\t\tfilename = filename[:adjustedWidth-7] + \"...\"\n\t\t}\n\t\tif file.IsDir() {\n\t\t\tfilename = filename + \"/\"\n\t\t}\n\t\t// No need to reassign filename if it's not changing\n\n\t\tfiles = append(files, itemStyle.Padding(0, 1).Render(filename))\n\t}\n\n\t// Pad to always show exactly 21 lines\n\tfor len(files) < maxVisibleDirs {\n\t\tfiles = append(files, styles.BaseStyle().Width(adjustedWidth).Render(\"\"))\n\t}\n\n\tcurrentPath := styles.BaseStyle().\n\t\tHeight(1).\n\t\tWidth(adjustedWidth).\n\t\tRender(f.cwd.View())\n\n\tviewportstyle := lipgloss.NewStyle().\n\t\tWidth(f.viewport.Width).\n\t\tBackground(t.Background()).\n\t\tBorder(lipgloss.RoundedBorder()).\n\t\tBorderForeground(t.TextMuted()).\n\t\tBorderBackground(t.Background()).\n\t\tPadding(2).\n\t\tRender(f.viewport.View())\n\tvar insertExitText string\n\tif f.IsCWDFocused() {\n\t\tinsertExitText = \"Press esc to exit typing path\"\n\t} else {\n\t\tinsertExitText = \"Press i to start typing path\"\n\t}\n\n\tcontent := lipgloss.JoinVertical(\n\t\tlipgloss.Left,\n\t\tcurrentPath,\n\t\tstyles.BaseStyle().Width(adjustedWidth).Render(\"\"),\n\t\tstyles.BaseStyle().Width(adjustedWidth).Render(lipgloss.JoinVertical(lipgloss.Left, files...)),\n\t\tstyles.BaseStyle().Width(adjustedWidth).Render(\"\"),\n\t\tstyles.BaseStyle().Foreground(t.TextMuted()).Width(adjustedWidth).Render(insertExitText),\n\t)\n\n\tf.cwd.SetValue(f.cwd.Value())\n\tcontentStyle := styles.BaseStyle().Padding(1, 2).\n\t\tBorder(lipgloss.RoundedBorder()).\n\t\tBorderBackground(t.Background()).\n\t\tBorderForeground(t.TextMuted()).\n\t\tWidth(lipgloss.Width(content) + 4)\n\n\treturn lipgloss.JoinHorizontal(lipgloss.Center, contentStyle.Render(content), viewportstyle)\n}\n\ntype FilepickerCmp interface {\n\ttea.Model\n\tToggleFilepicker(showFilepicker bool)\n\tIsCWDFocused() bool\n}\n\nfunc (f *filepickerCmp) ToggleFilepicker(showFilepicker bool) {\n\tf.ShowFilePicker = showFilepicker\n}\n\nfunc (f *filepickerCmp) IsCWDFocused() bool {\n\treturn f.cwd.Focused()\n}\n\nfunc NewFilepickerCmp(app *app.App) FilepickerCmp {\n\thomepath, err := os.UserHomeDir()\n\tif err != nil {\n\t\tlogging.Error(\"error loading user files\")\n\t\treturn nil\n\t}\n\tbaseDir := DirNode{parent: nil, directory: homepath}\n\tdirs := readDir(homepath, false)\n\tviewport := viewport.New(0, 0)\n\tcurrentDirectory := textinput.New()\n\tcurrentDirectory.CharLimit = 200\n\tcurrentDirectory.Width = 44\n\tcurrentDirectory.Cursor.Blink = true\n\tcurrentDirectory.SetValue(baseDir.directory)\n\treturn &filepickerCmp{cwdDetails: &baseDir, dirs: dirs, cursorChain: make(stack, 0), viewport: viewport, cwd: currentDirectory, app: app}\n}\n\nfunc (f *filepickerCmp) getCurrentFileBelowCursor() {\n\tif len(f.dirs) == 0 || f.cursor < 0 || f.cursor >= len(f.dirs) {\n\t\tlogging.Error(fmt.Sprintf(\"Invalid cursor position. Dirs length: %d, Cursor: %d\", len(f.dirs), f.cursor))\n\t\tf.viewport.SetContent(\"Preview unavailable\")\n\t\treturn\n\t}\n\n\tdir := f.dirs[f.cursor]\n\tfilename := dir.Name()\n\tif !dir.IsDir() && isExtSupported(filename) {\n\t\tfullPath := f.cwdDetails.directory + \"/\" + dir.Name()\n\n\t\tgo func() {\n\t\t\timageString, err := image.ImagePreview(f.viewport.Width-4, fullPath)\n\t\t\tif err != nil {\n\t\t\t\tlogging.Error(err.Error())\n\t\t\t\tf.viewport.SetContent(\"Preview unavailable\")\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tf.viewport.SetContent(imageString)\n\t\t}()\n\t} else {\n\t\tf.viewport.SetContent(\"Preview unavailable\")\n\t}\n}\n\nfunc readDir(path string, showHidden bool) []os.DirEntry {\n\tlogging.Info(fmt.Sprintf(\"Reading directory: %s\", path))\n\n\tentriesChan := make(chan []os.DirEntry, 1)\n\terrChan := make(chan error, 1)\n\n\tgo func() {\n\t\tdirEntries, err := os.ReadDir(path)\n\t\tif err != nil {\n\t\t\tlogging.ErrorPersist(err.Error())\n\t\t\terrChan <- err\n\t\t\treturn\n\t\t}\n\t\tentriesChan <- dirEntries\n\t}()\n\n\tselect {\n\tcase dirEntries := <-entriesChan:\n\t\tsort.Slice(dirEntries, func(i, j int) bool {\n\t\t\tif dirEntries[i].IsDir() == dirEntries[j].IsDir() {\n\t\t\t\treturn dirEntries[i].Name() < dirEntries[j].Name()\n\t\t\t}\n\t\t\treturn dirEntries[i].IsDir()\n\t\t})\n\n\t\tif showHidden {\n\t\t\treturn dirEntries\n\t\t}\n\n\t\tvar sanitizedDirEntries []os.DirEntry\n\t\tfor _, dirEntry := range dirEntries {\n\t\t\tisHidden, _ := IsHidden(dirEntry.Name())\n\t\t\tif !isHidden {\n\t\t\t\tif dirEntry.IsDir() || isExtSupported(dirEntry.Name()) {\n\t\t\t\t\tsanitizedDirEntries = append(sanitizedDirEntries, dirEntry)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn sanitizedDirEntries\n\n\tcase err := <-errChan:\n\t\tlogging.ErrorPersist(fmt.Sprintf(\"Error reading directory %s\", path), err)\n\t\treturn []os.DirEntry{}\n\n\tcase <-time.After(5 * time.Second):\n\t\tlogging.ErrorPersist(fmt.Sprintf(\"Timeout reading directory %s\", path), nil)\n\t\treturn []os.DirEntry{}\n\t}\n}\n\nfunc IsHidden(file string) (bool, error) {\n\treturn strings.HasPrefix(file, \".\"), nil\n}\n\nfunc isExtSupported(path string) bool {\n\text := strings.ToLower(filepath.Ext(path))\n\treturn (ext == \".jpg\" || ext == \".jpeg\" || ext == \".webp\" || ext == \".png\")\n}\n"], ["/opencode/internal/tui/components/dialog/session.go", "package dialog\n\nimport (\n\t\"github.com/charmbracelet/bubbles/key\"\n\ttea \"github.com/charmbracelet/bubbletea\"\n\t\"github.com/charmbracelet/lipgloss\"\n\t\"github.com/opencode-ai/opencode/internal/session\"\n\t\"github.com/opencode-ai/opencode/internal/tui/layout\"\n\t\"github.com/opencode-ai/opencode/internal/tui/styles\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n\t\"github.com/opencode-ai/opencode/internal/tui/util\"\n)\n\n// SessionSelectedMsg is sent when a session is selected\ntype SessionSelectedMsg struct {\n\tSession session.Session\n}\n\n// CloseSessionDialogMsg is sent when the session dialog is closed\ntype CloseSessionDialogMsg struct{}\n\n// SessionDialog interface for the session switching dialog\ntype SessionDialog interface {\n\ttea.Model\n\tlayout.Bindings\n\tSetSessions(sessions []session.Session)\n\tSetSelectedSession(sessionID string)\n}\n\ntype sessionDialogCmp struct {\n\tsessions []session.Session\n\tselectedIdx int\n\twidth int\n\theight int\n\tselectedSessionID string\n}\n\ntype sessionKeyMap struct {\n\tUp key.Binding\n\tDown key.Binding\n\tEnter key.Binding\n\tEscape key.Binding\n\tJ key.Binding\n\tK key.Binding\n}\n\nvar sessionKeys = sessionKeyMap{\n\tUp: key.NewBinding(\n\t\tkey.WithKeys(\"up\"),\n\t\tkey.WithHelp(\"↑\", \"previous session\"),\n\t),\n\tDown: key.NewBinding(\n\t\tkey.WithKeys(\"down\"),\n\t\tkey.WithHelp(\"↓\", \"next session\"),\n\t),\n\tEnter: key.NewBinding(\n\t\tkey.WithKeys(\"enter\"),\n\t\tkey.WithHelp(\"enter\", \"select session\"),\n\t),\n\tEscape: key.NewBinding(\n\t\tkey.WithKeys(\"esc\"),\n\t\tkey.WithHelp(\"esc\", \"close\"),\n\t),\n\tJ: key.NewBinding(\n\t\tkey.WithKeys(\"j\"),\n\t\tkey.WithHelp(\"j\", \"next session\"),\n\t),\n\tK: key.NewBinding(\n\t\tkey.WithKeys(\"k\"),\n\t\tkey.WithHelp(\"k\", \"previous session\"),\n\t),\n}\n\nfunc (s *sessionDialogCmp) Init() tea.Cmd {\n\treturn nil\n}\n\nfunc (s *sessionDialogCmp) Update(msg tea.Msg) (tea.Model, tea.Cmd) {\n\tswitch msg := msg.(type) {\n\tcase tea.KeyMsg:\n\t\tswitch {\n\t\tcase key.Matches(msg, sessionKeys.Up) || key.Matches(msg, sessionKeys.K):\n\t\t\tif s.selectedIdx > 0 {\n\t\t\t\ts.selectedIdx--\n\t\t\t}\n\t\t\treturn s, nil\n\t\tcase key.Matches(msg, sessionKeys.Down) || key.Matches(msg, sessionKeys.J):\n\t\t\tif s.selectedIdx < len(s.sessions)-1 {\n\t\t\t\ts.selectedIdx++\n\t\t\t}\n\t\t\treturn s, nil\n\t\tcase key.Matches(msg, sessionKeys.Enter):\n\t\t\tif len(s.sessions) > 0 {\n\t\t\t\treturn s, util.CmdHandler(SessionSelectedMsg{\n\t\t\t\t\tSession: s.sessions[s.selectedIdx],\n\t\t\t\t})\n\t\t\t}\n\t\tcase key.Matches(msg, sessionKeys.Escape):\n\t\t\treturn s, util.CmdHandler(CloseSessionDialogMsg{})\n\t\t}\n\tcase tea.WindowSizeMsg:\n\t\ts.width = msg.Width\n\t\ts.height = msg.Height\n\t}\n\treturn s, nil\n}\n\nfunc (s *sessionDialogCmp) View() string {\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\t\n\tif len(s.sessions) == 0 {\n\t\treturn baseStyle.Padding(1, 2).\n\t\t\tBorder(lipgloss.RoundedBorder()).\n\t\t\tBorderBackground(t.Background()).\n\t\t\tBorderForeground(t.TextMuted()).\n\t\t\tWidth(40).\n\t\t\tRender(\"No sessions available\")\n\t}\n\n\t// Calculate max width needed for session titles\n\tmaxWidth := 40 // Minimum width\n\tfor _, sess := range s.sessions {\n\t\tif len(sess.Title) > maxWidth-4 { // Account for padding\n\t\t\tmaxWidth = len(sess.Title) + 4\n\t\t}\n\t}\n\n\tmaxWidth = max(30, min(maxWidth, s.width-15)) // Limit width to avoid overflow\n\n\t// Limit height to avoid taking up too much screen space\n\tmaxVisibleSessions := min(10, len(s.sessions))\n\n\t// Build the session list\n\tsessionItems := make([]string, 0, maxVisibleSessions)\n\tstartIdx := 0\n\n\t// If we have more sessions than can be displayed, adjust the start index\n\tif len(s.sessions) > maxVisibleSessions {\n\t\t// Center the selected item when possible\n\t\thalfVisible := maxVisibleSessions / 2\n\t\tif s.selectedIdx >= halfVisible && s.selectedIdx < len(s.sessions)-halfVisible {\n\t\t\tstartIdx = s.selectedIdx - halfVisible\n\t\t} else if s.selectedIdx >= len(s.sessions)-halfVisible {\n\t\t\tstartIdx = len(s.sessions) - maxVisibleSessions\n\t\t}\n\t}\n\n\tendIdx := min(startIdx+maxVisibleSessions, len(s.sessions))\n\n\tfor i := startIdx; i < endIdx; i++ {\n\t\tsess := s.sessions[i]\n\t\titemStyle := baseStyle.Width(maxWidth)\n\n\t\tif i == s.selectedIdx {\n\t\t\titemStyle = itemStyle.\n\t\t\t\tBackground(t.Primary()).\n\t\t\t\tForeground(t.Background()).\n\t\t\t\tBold(true)\n\t\t}\n\n\t\tsessionItems = append(sessionItems, itemStyle.Padding(0, 1).Render(sess.Title))\n\t}\n\n\ttitle := baseStyle.\n\t\tForeground(t.Primary()).\n\t\tBold(true).\n\t\tWidth(maxWidth).\n\t\tPadding(0, 1).\n\t\tRender(\"Switch Session\")\n\n\tcontent := lipgloss.JoinVertical(\n\t\tlipgloss.Left,\n\t\ttitle,\n\t\tbaseStyle.Width(maxWidth).Render(\"\"),\n\t\tbaseStyle.Width(maxWidth).Render(lipgloss.JoinVertical(lipgloss.Left, sessionItems...)),\n\t\tbaseStyle.Width(maxWidth).Render(\"\"),\n\t)\n\n\treturn baseStyle.Padding(1, 2).\n\t\tBorder(lipgloss.RoundedBorder()).\n\t\tBorderBackground(t.Background()).\n\t\tBorderForeground(t.TextMuted()).\n\t\tWidth(lipgloss.Width(content) + 4).\n\t\tRender(content)\n}\n\nfunc (s *sessionDialogCmp) BindingKeys() []key.Binding {\n\treturn layout.KeyMapToSlice(sessionKeys)\n}\n\nfunc (s *sessionDialogCmp) SetSessions(sessions []session.Session) {\n\ts.sessions = sessions\n\n\t// If we have a selected session ID, find its index\n\tif s.selectedSessionID != \"\" {\n\t\tfor i, sess := range sessions {\n\t\t\tif sess.ID == s.selectedSessionID {\n\t\t\t\ts.selectedIdx = i\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\n\t// Default to first session if selected not found\n\ts.selectedIdx = 0\n}\n\nfunc (s *sessionDialogCmp) SetSelectedSession(sessionID string) {\n\ts.selectedSessionID = sessionID\n\n\t// Update the selected index if sessions are already loaded\n\tif len(s.sessions) > 0 {\n\t\tfor i, sess := range s.sessions {\n\t\t\tif sess.ID == sessionID {\n\t\t\t\ts.selectedIdx = i\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}\n\n// NewSessionDialogCmp creates a new session switching dialog\nfunc NewSessionDialogCmp() SessionDialog {\n\treturn &sessionDialogCmp{\n\t\tsessions: []session.Session{},\n\t\tselectedIdx: 0,\n\t\tselectedSessionID: \"\",\n\t}\n}\n"], ["/opencode/internal/tui/page/chat.go", "package page\n\nimport (\n\t\"context\"\n\t\"strings\"\n\n\t\"github.com/charmbracelet/bubbles/key\"\n\ttea \"github.com/charmbracelet/bubbletea\"\n\t\"github.com/charmbracelet/lipgloss\"\n\t\"github.com/opencode-ai/opencode/internal/app\"\n\t\"github.com/opencode-ai/opencode/internal/completions\"\n\t\"github.com/opencode-ai/opencode/internal/message\"\n\t\"github.com/opencode-ai/opencode/internal/session\"\n\t\"github.com/opencode-ai/opencode/internal/tui/components/chat\"\n\t\"github.com/opencode-ai/opencode/internal/tui/components/dialog\"\n\t\"github.com/opencode-ai/opencode/internal/tui/layout\"\n\t\"github.com/opencode-ai/opencode/internal/tui/util\"\n)\n\nvar ChatPage PageID = \"chat\"\n\ntype chatPage struct {\n\tapp *app.App\n\teditor layout.Container\n\tmessages layout.Container\n\tlayout layout.SplitPaneLayout\n\tsession session.Session\n\tcompletionDialog dialog.CompletionDialog\n\tshowCompletionDialog bool\n}\n\ntype ChatKeyMap struct {\n\tShowCompletionDialog key.Binding\n\tNewSession key.Binding\n\tCancel key.Binding\n}\n\nvar keyMap = ChatKeyMap{\n\tShowCompletionDialog: key.NewBinding(\n\t\tkey.WithKeys(\"@\"),\n\t\tkey.WithHelp(\"@\", \"Complete\"),\n\t),\n\tNewSession: key.NewBinding(\n\t\tkey.WithKeys(\"ctrl+n\"),\n\t\tkey.WithHelp(\"ctrl+n\", \"new session\"),\n\t),\n\tCancel: key.NewBinding(\n\t\tkey.WithKeys(\"esc\"),\n\t\tkey.WithHelp(\"esc\", \"cancel\"),\n\t),\n}\n\nfunc (p *chatPage) Init() tea.Cmd {\n\tcmds := []tea.Cmd{\n\t\tp.layout.Init(),\n\t\tp.completionDialog.Init(),\n\t}\n\treturn tea.Batch(cmds...)\n}\n\nfunc (p *chatPage) Update(msg tea.Msg) (tea.Model, tea.Cmd) {\n\tvar cmds []tea.Cmd\n\tswitch msg := msg.(type) {\n\tcase tea.WindowSizeMsg:\n\t\tcmd := p.layout.SetSize(msg.Width, msg.Height)\n\t\tcmds = append(cmds, cmd)\n\tcase dialog.CompletionDialogCloseMsg:\n\t\tp.showCompletionDialog = false\n\tcase chat.SendMsg:\n\t\tcmd := p.sendMessage(msg.Text, msg.Attachments)\n\t\tif cmd != nil {\n\t\t\treturn p, cmd\n\t\t}\n\tcase dialog.CommandRunCustomMsg:\n\t\t// Check if the agent is busy before executing custom commands\n\t\tif p.app.CoderAgent.IsBusy() {\n\t\t\treturn p, util.ReportWarn(\"Agent is busy, please wait before executing a command...\")\n\t\t}\n\t\t\n\t\t// Process the command content with arguments if any\n\t\tcontent := msg.Content\n\t\tif msg.Args != nil {\n\t\t\t// Replace all named arguments with their values\n\t\t\tfor name, value := range msg.Args {\n\t\t\t\tplaceholder := \"$\" + name\n\t\t\t\tcontent = strings.ReplaceAll(content, placeholder, value)\n\t\t\t}\n\t\t}\n\t\t\n\t\t// Handle custom command execution\n\t\tcmd := p.sendMessage(content, nil)\n\t\tif cmd != nil {\n\t\t\treturn p, cmd\n\t\t}\n\tcase chat.SessionSelectedMsg:\n\t\tif p.session.ID == \"\" {\n\t\t\tcmd := p.setSidebar()\n\t\t\tif cmd != nil {\n\t\t\t\tcmds = append(cmds, cmd)\n\t\t\t}\n\t\t}\n\t\tp.session = msg\n\tcase tea.KeyMsg:\n\t\tswitch {\n\t\tcase key.Matches(msg, keyMap.ShowCompletionDialog):\n\t\t\tp.showCompletionDialog = true\n\t\t\t// Continue sending keys to layout->chat\n\t\tcase key.Matches(msg, keyMap.NewSession):\n\t\t\tp.session = session.Session{}\n\t\t\treturn p, tea.Batch(\n\t\t\t\tp.clearSidebar(),\n\t\t\t\tutil.CmdHandler(chat.SessionClearedMsg{}),\n\t\t\t)\n\t\tcase key.Matches(msg, keyMap.Cancel):\n\t\t\tif p.session.ID != \"\" {\n\t\t\t\t// Cancel the current session's generation process\n\t\t\t\t// This allows users to interrupt long-running operations\n\t\t\t\tp.app.CoderAgent.Cancel(p.session.ID)\n\t\t\t\treturn p, nil\n\t\t\t}\n\t\t}\n\t}\n\tif p.showCompletionDialog {\n\t\tcontext, contextCmd := p.completionDialog.Update(msg)\n\t\tp.completionDialog = context.(dialog.CompletionDialog)\n\t\tcmds = append(cmds, contextCmd)\n\n\t\t// Doesn't forward event if enter key is pressed\n\t\tif keyMsg, ok := msg.(tea.KeyMsg); ok {\n\t\t\tif keyMsg.String() == \"enter\" {\n\t\t\t\treturn p, tea.Batch(cmds...)\n\t\t\t}\n\t\t}\n\t}\n\n\tu, cmd := p.layout.Update(msg)\n\tcmds = append(cmds, cmd)\n\tp.layout = u.(layout.SplitPaneLayout)\n\n\treturn p, tea.Batch(cmds...)\n}\n\nfunc (p *chatPage) setSidebar() tea.Cmd {\n\tsidebarContainer := layout.NewContainer(\n\t\tchat.NewSidebarCmp(p.session, p.app.History),\n\t\tlayout.WithPadding(1, 1, 1, 1),\n\t)\n\treturn tea.Batch(p.layout.SetRightPanel(sidebarContainer), sidebarContainer.Init())\n}\n\nfunc (p *chatPage) clearSidebar() tea.Cmd {\n\treturn p.layout.ClearRightPanel()\n}\n\nfunc (p *chatPage) sendMessage(text string, attachments []message.Attachment) tea.Cmd {\n\tvar cmds []tea.Cmd\n\tif p.session.ID == \"\" {\n\t\tsession, err := p.app.Sessions.Create(context.Background(), \"New Session\")\n\t\tif err != nil {\n\t\t\treturn util.ReportError(err)\n\t\t}\n\n\t\tp.session = session\n\t\tcmd := p.setSidebar()\n\t\tif cmd != nil {\n\t\t\tcmds = append(cmds, cmd)\n\t\t}\n\t\tcmds = append(cmds, util.CmdHandler(chat.SessionSelectedMsg(session)))\n\t}\n\n\t_, err := p.app.CoderAgent.Run(context.Background(), p.session.ID, text, attachments...)\n\tif err != nil {\n\t\treturn util.ReportError(err)\n\t}\n\treturn tea.Batch(cmds...)\n}\n\nfunc (p *chatPage) SetSize(width, height int) tea.Cmd {\n\treturn p.layout.SetSize(width, height)\n}\n\nfunc (p *chatPage) GetSize() (int, int) {\n\treturn p.layout.GetSize()\n}\n\nfunc (p *chatPage) View() string {\n\tlayoutView := p.layout.View()\n\n\tif p.showCompletionDialog {\n\t\t_, layoutHeight := p.layout.GetSize()\n\t\teditorWidth, editorHeight := p.editor.GetSize()\n\n\t\tp.completionDialog.SetWidth(editorWidth)\n\t\toverlay := p.completionDialog.View()\n\n\t\tlayoutView = layout.PlaceOverlay(\n\t\t\t0,\n\t\t\tlayoutHeight-editorHeight-lipgloss.Height(overlay),\n\t\t\toverlay,\n\t\t\tlayoutView,\n\t\t\tfalse,\n\t\t)\n\t}\n\n\treturn layoutView\n}\n\nfunc (p *chatPage) BindingKeys() []key.Binding {\n\tbindings := layout.KeyMapToSlice(keyMap)\n\tbindings = append(bindings, p.messages.BindingKeys()...)\n\tbindings = append(bindings, p.editor.BindingKeys()...)\n\treturn bindings\n}\n\nfunc NewChatPage(app *app.App) tea.Model {\n\tcg := completions.NewFileAndFolderContextGroup()\n\tcompletionDialog := dialog.NewCompletionDialogCmp(cg)\n\n\tmessagesContainer := layout.NewContainer(\n\t\tchat.NewMessagesCmp(app),\n\t\tlayout.WithPadding(1, 1, 0, 1),\n\t)\n\teditorContainer := layout.NewContainer(\n\t\tchat.NewEditorCmp(app),\n\t\tlayout.WithBorder(true, false, false, false),\n\t)\n\treturn &chatPage{\n\t\tapp: app,\n\t\teditor: editorContainer,\n\t\tmessages: messagesContainer,\n\t\tcompletionDialog: completionDialog,\n\t\tlayout: layout.NewSplitPane(\n\t\t\tlayout.WithLeftPanel(messagesContainer),\n\t\t\tlayout.WithBottomPanel(editorContainer),\n\t\t),\n\t}\n}\n"], ["/opencode/internal/tui/components/dialog/init.go", "package dialog\n\nimport (\n\t\"github.com/charmbracelet/bubbles/key\"\n\ttea \"github.com/charmbracelet/bubbletea\"\n\t\"github.com/charmbracelet/lipgloss\"\n\n\t\"github.com/opencode-ai/opencode/internal/tui/styles\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n\t\"github.com/opencode-ai/opencode/internal/tui/util\"\n)\n\n// InitDialogCmp is a component that asks the user if they want to initialize the project.\ntype InitDialogCmp struct {\n\twidth, height int\n\tselected int\n\tkeys initDialogKeyMap\n}\n\n// NewInitDialogCmp creates a new InitDialogCmp.\nfunc NewInitDialogCmp() InitDialogCmp {\n\treturn InitDialogCmp{\n\t\tselected: 0,\n\t\tkeys: initDialogKeyMap{},\n\t}\n}\n\ntype initDialogKeyMap struct {\n\tTab key.Binding\n\tLeft key.Binding\n\tRight key.Binding\n\tEnter key.Binding\n\tEscape key.Binding\n\tY key.Binding\n\tN key.Binding\n}\n\n// ShortHelp implements key.Map.\nfunc (k initDialogKeyMap) ShortHelp() []key.Binding {\n\treturn []key.Binding{\n\t\tkey.NewBinding(\n\t\t\tkey.WithKeys(\"tab\", \"left\", \"right\"),\n\t\t\tkey.WithHelp(\"tab/←/→\", \"toggle selection\"),\n\t\t),\n\t\tkey.NewBinding(\n\t\t\tkey.WithKeys(\"enter\"),\n\t\t\tkey.WithHelp(\"enter\", \"confirm\"),\n\t\t),\n\t\tkey.NewBinding(\n\t\t\tkey.WithKeys(\"esc\", \"q\"),\n\t\t\tkey.WithHelp(\"esc/q\", \"cancel\"),\n\t\t),\n\t\tkey.NewBinding(\n\t\t\tkey.WithKeys(\"y\", \"n\"),\n\t\t\tkey.WithHelp(\"y/n\", \"yes/no\"),\n\t\t),\n\t}\n}\n\n// FullHelp implements key.Map.\nfunc (k initDialogKeyMap) FullHelp() [][]key.Binding {\n\treturn [][]key.Binding{k.ShortHelp()}\n}\n\n// Init implements tea.Model.\nfunc (m InitDialogCmp) Init() tea.Cmd {\n\treturn nil\n}\n\n// Update implements tea.Model.\nfunc (m InitDialogCmp) Update(msg tea.Msg) (tea.Model, tea.Cmd) {\n\tswitch msg := msg.(type) {\n\tcase tea.KeyMsg:\n\t\tswitch {\n\t\tcase key.Matches(msg, key.NewBinding(key.WithKeys(\"esc\"))):\n\t\t\treturn m, util.CmdHandler(CloseInitDialogMsg{Initialize: false})\n\t\tcase key.Matches(msg, key.NewBinding(key.WithKeys(\"tab\", \"left\", \"right\", \"h\", \"l\"))):\n\t\t\tm.selected = (m.selected + 1) % 2\n\t\t\treturn m, nil\n\t\tcase key.Matches(msg, key.NewBinding(key.WithKeys(\"enter\"))):\n\t\t\treturn m, util.CmdHandler(CloseInitDialogMsg{Initialize: m.selected == 0})\n\t\tcase key.Matches(msg, key.NewBinding(key.WithKeys(\"y\"))):\n\t\t\treturn m, util.CmdHandler(CloseInitDialogMsg{Initialize: true})\n\t\tcase key.Matches(msg, key.NewBinding(key.WithKeys(\"n\"))):\n\t\t\treturn m, util.CmdHandler(CloseInitDialogMsg{Initialize: false})\n\t\t}\n\tcase tea.WindowSizeMsg:\n\t\tm.width = msg.Width\n\t\tm.height = msg.Height\n\t}\n\treturn m, nil\n}\n\n// View implements tea.Model.\nfunc (m InitDialogCmp) View() string {\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\t\n\t// Calculate width needed for content\n\tmaxWidth := 60 // Width for explanation text\n\n\ttitle := baseStyle.\n\t\tForeground(t.Primary()).\n\t\tBold(true).\n\t\tWidth(maxWidth).\n\t\tPadding(0, 1).\n\t\tRender(\"Initialize Project\")\n\n\texplanation := baseStyle.\n\t\tForeground(t.Text()).\n\t\tWidth(maxWidth).\n\t\tPadding(0, 1).\n\t\tRender(\"Initialization generates a new OpenCode.md file that contains information about your codebase, this file serves as memory for each project, you can freely add to it to help the agents be better at their job.\")\n\n\tquestion := baseStyle.\n\t\tForeground(t.Text()).\n\t\tWidth(maxWidth).\n\t\tPadding(1, 1).\n\t\tRender(\"Would you like to initialize this project?\")\n\n\tmaxWidth = min(maxWidth, m.width-10)\n\tyesStyle := baseStyle\n\tnoStyle := baseStyle\n\n\tif m.selected == 0 {\n\t\tyesStyle = yesStyle.\n\t\t\tBackground(t.Primary()).\n\t\t\tForeground(t.Background()).\n\t\t\tBold(true)\n\t\tnoStyle = noStyle.\n\t\t\tBackground(t.Background()).\n\t\t\tForeground(t.Primary())\n\t} else {\n\t\tnoStyle = noStyle.\n\t\t\tBackground(t.Primary()).\n\t\t\tForeground(t.Background()).\n\t\t\tBold(true)\n\t\tyesStyle = yesStyle.\n\t\t\tBackground(t.Background()).\n\t\t\tForeground(t.Primary())\n\t}\n\n\tyes := yesStyle.Padding(0, 3).Render(\"Yes\")\n\tno := noStyle.Padding(0, 3).Render(\"No\")\n\n\tbuttons := lipgloss.JoinHorizontal(lipgloss.Center, yes, baseStyle.Render(\" \"), no)\n\tbuttons = baseStyle.\n\t\tWidth(maxWidth).\n\t\tPadding(1, 0).\n\t\tRender(buttons)\n\n\tcontent := lipgloss.JoinVertical(\n\t\tlipgloss.Left,\n\t\ttitle,\n\t\tbaseStyle.Width(maxWidth).Render(\"\"),\n\t\texplanation,\n\t\tquestion,\n\t\tbuttons,\n\t\tbaseStyle.Width(maxWidth).Render(\"\"),\n\t)\n\n\treturn baseStyle.Padding(1, 2).\n\t\tBorder(lipgloss.RoundedBorder()).\n\t\tBorderBackground(t.Background()).\n\t\tBorderForeground(t.TextMuted()).\n\t\tWidth(lipgloss.Width(content) + 4).\n\t\tRender(content)\n}\n\n// SetSize sets the size of the component.\nfunc (m *InitDialogCmp) SetSize(width, height int) {\n\tm.width = width\n\tm.height = height\n}\n\n// Bindings implements layout.Bindings.\nfunc (m InitDialogCmp) Bindings() []key.Binding {\n\treturn m.keys.ShortHelp()\n}\n\n// CloseInitDialogMsg is a message that is sent when the init dialog is closed.\ntype CloseInitDialogMsg struct {\n\tInitialize bool\n}\n\n// ShowInitDialogMsg is a message that is sent to show the init dialog.\ntype ShowInitDialogMsg struct {\n\tShow bool\n}\n"], ["/opencode/internal/tui/components/dialog/theme.go", "package dialog\n\nimport (\n\t\"github.com/charmbracelet/bubbles/key\"\n\ttea \"github.com/charmbracelet/bubbletea\"\n\t\"github.com/charmbracelet/lipgloss\"\n\t\"github.com/opencode-ai/opencode/internal/tui/layout\"\n\t\"github.com/opencode-ai/opencode/internal/tui/styles\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n\t\"github.com/opencode-ai/opencode/internal/tui/util\"\n)\n\n// ThemeChangedMsg is sent when the theme is changed\ntype ThemeChangedMsg struct {\n\tThemeName string\n}\n\n// CloseThemeDialogMsg is sent when the theme dialog is closed\ntype CloseThemeDialogMsg struct{}\n\n// ThemeDialog interface for the theme switching dialog\ntype ThemeDialog interface {\n\ttea.Model\n\tlayout.Bindings\n}\n\ntype themeDialogCmp struct {\n\tthemes []string\n\tselectedIdx int\n\twidth int\n\theight int\n\tcurrentTheme string\n}\n\ntype themeKeyMap struct {\n\tUp key.Binding\n\tDown key.Binding\n\tEnter key.Binding\n\tEscape key.Binding\n\tJ key.Binding\n\tK key.Binding\n}\n\nvar themeKeys = themeKeyMap{\n\tUp: key.NewBinding(\n\t\tkey.WithKeys(\"up\"),\n\t\tkey.WithHelp(\"↑\", \"previous theme\"),\n\t),\n\tDown: key.NewBinding(\n\t\tkey.WithKeys(\"down\"),\n\t\tkey.WithHelp(\"↓\", \"next theme\"),\n\t),\n\tEnter: key.NewBinding(\n\t\tkey.WithKeys(\"enter\"),\n\t\tkey.WithHelp(\"enter\", \"select theme\"),\n\t),\n\tEscape: key.NewBinding(\n\t\tkey.WithKeys(\"esc\"),\n\t\tkey.WithHelp(\"esc\", \"close\"),\n\t),\n\tJ: key.NewBinding(\n\t\tkey.WithKeys(\"j\"),\n\t\tkey.WithHelp(\"j\", \"next theme\"),\n\t),\n\tK: key.NewBinding(\n\t\tkey.WithKeys(\"k\"),\n\t\tkey.WithHelp(\"k\", \"previous theme\"),\n\t),\n}\n\nfunc (t *themeDialogCmp) Init() tea.Cmd {\n\t// Load available themes and update selectedIdx based on current theme\n\tt.themes = theme.AvailableThemes()\n\tt.currentTheme = theme.CurrentThemeName()\n\n\t// Find the current theme in the list\n\tfor i, name := range t.themes {\n\t\tif name == t.currentTheme {\n\t\t\tt.selectedIdx = i\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc (t *themeDialogCmp) Update(msg tea.Msg) (tea.Model, tea.Cmd) {\n\tswitch msg := msg.(type) {\n\tcase tea.KeyMsg:\n\t\tswitch {\n\t\tcase key.Matches(msg, themeKeys.Up) || key.Matches(msg, themeKeys.K):\n\t\t\tif t.selectedIdx > 0 {\n\t\t\t\tt.selectedIdx--\n\t\t\t}\n\t\t\treturn t, nil\n\t\tcase key.Matches(msg, themeKeys.Down) || key.Matches(msg, themeKeys.J):\n\t\t\tif t.selectedIdx < len(t.themes)-1 {\n\t\t\t\tt.selectedIdx++\n\t\t\t}\n\t\t\treturn t, nil\n\t\tcase key.Matches(msg, themeKeys.Enter):\n\t\t\tif len(t.themes) > 0 {\n\t\t\t\tpreviousTheme := theme.CurrentThemeName()\n\t\t\t\tselectedTheme := t.themes[t.selectedIdx]\n\t\t\t\tif previousTheme == selectedTheme {\n\t\t\t\t\treturn t, util.CmdHandler(CloseThemeDialogMsg{})\n\t\t\t\t}\n\t\t\t\tif err := theme.SetTheme(selectedTheme); err != nil {\n\t\t\t\t\treturn t, util.ReportError(err)\n\t\t\t\t}\n\t\t\t\treturn t, util.CmdHandler(ThemeChangedMsg{\n\t\t\t\t\tThemeName: selectedTheme,\n\t\t\t\t})\n\t\t\t}\n\t\tcase key.Matches(msg, themeKeys.Escape):\n\t\t\treturn t, util.CmdHandler(CloseThemeDialogMsg{})\n\t\t}\n\tcase tea.WindowSizeMsg:\n\t\tt.width = msg.Width\n\t\tt.height = msg.Height\n\t}\n\treturn t, nil\n}\n\nfunc (t *themeDialogCmp) View() string {\n\tcurrentTheme := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\n\tif len(t.themes) == 0 {\n\t\treturn baseStyle.Padding(1, 2).\n\t\t\tBorder(lipgloss.RoundedBorder()).\n\t\t\tBorderBackground(currentTheme.Background()).\n\t\t\tBorderForeground(currentTheme.TextMuted()).\n\t\t\tWidth(40).\n\t\t\tRender(\"No themes available\")\n\t}\n\n\t// Calculate max width needed for theme names\n\tmaxWidth := 40 // Minimum width\n\tfor _, themeName := range t.themes {\n\t\tif len(themeName) > maxWidth-4 { // Account for padding\n\t\t\tmaxWidth = len(themeName) + 4\n\t\t}\n\t}\n\n\tmaxWidth = max(30, min(maxWidth, t.width-15)) // Limit width to avoid overflow\n\n\t// Build the theme list\n\tthemeItems := make([]string, 0, len(t.themes))\n\tfor i, themeName := range t.themes {\n\t\titemStyle := baseStyle.Width(maxWidth)\n\n\t\tif i == t.selectedIdx {\n\t\t\titemStyle = itemStyle.\n\t\t\t\tBackground(currentTheme.Primary()).\n\t\t\t\tForeground(currentTheme.Background()).\n\t\t\t\tBold(true)\n\t\t}\n\n\t\tthemeItems = append(themeItems, itemStyle.Padding(0, 1).Render(themeName))\n\t}\n\n\ttitle := baseStyle.\n\t\tForeground(currentTheme.Primary()).\n\t\tBold(true).\n\t\tWidth(maxWidth).\n\t\tPadding(0, 1).\n\t\tRender(\"Select Theme\")\n\n\tcontent := lipgloss.JoinVertical(\n\t\tlipgloss.Left,\n\t\ttitle,\n\t\tbaseStyle.Width(maxWidth).Render(\"\"),\n\t\tbaseStyle.Width(maxWidth).Render(lipgloss.JoinVertical(lipgloss.Left, themeItems...)),\n\t\tbaseStyle.Width(maxWidth).Render(\"\"),\n\t)\n\n\treturn baseStyle.Padding(1, 2).\n\t\tBorder(lipgloss.RoundedBorder()).\n\t\tBorderBackground(currentTheme.Background()).\n\t\tBorderForeground(currentTheme.TextMuted()).\n\t\tWidth(lipgloss.Width(content) + 4).\n\t\tRender(content)\n}\n\nfunc (t *themeDialogCmp) BindingKeys() []key.Binding {\n\treturn layout.KeyMapToSlice(themeKeys)\n}\n\n// NewThemeDialogCmp creates a new theme switching dialog\nfunc NewThemeDialogCmp() ThemeDialog {\n\treturn &themeDialogCmp{\n\t\tthemes: []string{},\n\t\tselectedIdx: 0,\n\t\tcurrentTheme: \"\",\n\t}\n}\n\n"], ["/opencode/internal/tui/components/logs/details.go", "package logs\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/charmbracelet/bubbles/key\"\n\t\"github.com/charmbracelet/bubbles/viewport\"\n\ttea \"github.com/charmbracelet/bubbletea\"\n\t\"github.com/charmbracelet/lipgloss\"\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n\t\"github.com/opencode-ai/opencode/internal/tui/layout\"\n\t\"github.com/opencode-ai/opencode/internal/tui/styles\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n)\n\ntype DetailComponent interface {\n\ttea.Model\n\tlayout.Sizeable\n\tlayout.Bindings\n}\n\ntype detailCmp struct {\n\twidth, height int\n\tcurrentLog logging.LogMessage\n\tviewport viewport.Model\n}\n\nfunc (i *detailCmp) Init() tea.Cmd {\n\tmessages := logging.List()\n\tif len(messages) == 0 {\n\t\treturn nil\n\t}\n\ti.currentLog = messages[0]\n\treturn nil\n}\n\nfunc (i *detailCmp) Update(msg tea.Msg) (tea.Model, tea.Cmd) {\n\tswitch msg := msg.(type) {\n\tcase selectedLogMsg:\n\t\tif msg.ID != i.currentLog.ID {\n\t\t\ti.currentLog = logging.LogMessage(msg)\n\t\t\ti.updateContent()\n\t\t}\n\t}\n\n\treturn i, nil\n}\n\nfunc (i *detailCmp) updateContent() {\n\tvar content strings.Builder\n\tt := theme.CurrentTheme()\n\n\t// Format the header with timestamp and level\n\ttimeStyle := lipgloss.NewStyle().Foreground(t.TextMuted())\n\tlevelStyle := getLevelStyle(i.currentLog.Level)\n\n\theader := lipgloss.JoinHorizontal(\n\t\tlipgloss.Center,\n\t\ttimeStyle.Render(i.currentLog.Time.Format(time.RFC3339)),\n\t\t\" \",\n\t\tlevelStyle.Render(i.currentLog.Level),\n\t)\n\n\tcontent.WriteString(lipgloss.NewStyle().Bold(true).Render(header))\n\tcontent.WriteString(\"\\n\\n\")\n\n\t// Message with styling\n\tmessageStyle := lipgloss.NewStyle().Bold(true).Foreground(t.Text())\n\tcontent.WriteString(messageStyle.Render(\"Message:\"))\n\tcontent.WriteString(\"\\n\")\n\tcontent.WriteString(lipgloss.NewStyle().Padding(0, 2).Render(i.currentLog.Message))\n\tcontent.WriteString(\"\\n\\n\")\n\n\t// Attributes section\n\tif len(i.currentLog.Attributes) > 0 {\n\t\tattrHeaderStyle := lipgloss.NewStyle().Bold(true).Foreground(t.Text())\n\t\tcontent.WriteString(attrHeaderStyle.Render(\"Attributes:\"))\n\t\tcontent.WriteString(\"\\n\")\n\n\t\t// Create a table-like display for attributes\n\t\tkeyStyle := lipgloss.NewStyle().Foreground(t.Primary()).Bold(true)\n\t\tvalueStyle := lipgloss.NewStyle().Foreground(t.Text())\n\n\t\tfor _, attr := range i.currentLog.Attributes {\n\t\t\tattrLine := fmt.Sprintf(\"%s: %s\",\n\t\t\t\tkeyStyle.Render(attr.Key),\n\t\t\t\tvalueStyle.Render(attr.Value),\n\t\t\t)\n\t\t\tcontent.WriteString(lipgloss.NewStyle().Padding(0, 2).Render(attrLine))\n\t\t\tcontent.WriteString(\"\\n\")\n\t\t}\n\t}\n\n\ti.viewport.SetContent(content.String())\n}\n\nfunc getLevelStyle(level string) lipgloss.Style {\n\tstyle := lipgloss.NewStyle().Bold(true)\n\tt := theme.CurrentTheme()\n\t\n\tswitch strings.ToLower(level) {\n\tcase \"info\":\n\t\treturn style.Foreground(t.Info())\n\tcase \"warn\", \"warning\":\n\t\treturn style.Foreground(t.Warning())\n\tcase \"error\", \"err\":\n\t\treturn style.Foreground(t.Error())\n\tcase \"debug\":\n\t\treturn style.Foreground(t.Success())\n\tdefault:\n\t\treturn style.Foreground(t.Text())\n\t}\n}\n\nfunc (i *detailCmp) View() string {\n\tt := theme.CurrentTheme()\n\treturn styles.ForceReplaceBackgroundWithLipgloss(i.viewport.View(), t.Background())\n}\n\nfunc (i *detailCmp) GetSize() (int, int) {\n\treturn i.width, i.height\n}\n\nfunc (i *detailCmp) SetSize(width int, height int) tea.Cmd {\n\ti.width = width\n\ti.height = height\n\ti.viewport.Width = i.width\n\ti.viewport.Height = i.height\n\ti.updateContent()\n\treturn nil\n}\n\nfunc (i *detailCmp) BindingKeys() []key.Binding {\n\treturn layout.KeyMapToSlice(i.viewport.KeyMap)\n}\n\nfunc NewLogsDetails() DetailComponent {\n\treturn &detailCmp{\n\t\tviewport: viewport.New(0, 0),\n\t}\n}\n"], ["/opencode/internal/llm/agent/agent.go", "package agent\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/llm/models\"\n\t\"github.com/opencode-ai/opencode/internal/llm/prompt\"\n\t\"github.com/opencode-ai/opencode/internal/llm/provider\"\n\t\"github.com/opencode-ai/opencode/internal/llm/tools\"\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n\t\"github.com/opencode-ai/opencode/internal/message\"\n\t\"github.com/opencode-ai/opencode/internal/permission\"\n\t\"github.com/opencode-ai/opencode/internal/pubsub\"\n\t\"github.com/opencode-ai/opencode/internal/session\"\n)\n\n// Common errors\nvar (\n\tErrRequestCancelled = errors.New(\"request cancelled by user\")\n\tErrSessionBusy = errors.New(\"session is currently processing another request\")\n)\n\ntype AgentEventType string\n\nconst (\n\tAgentEventTypeError AgentEventType = \"error\"\n\tAgentEventTypeResponse AgentEventType = \"response\"\n\tAgentEventTypeSummarize AgentEventType = \"summarize\"\n)\n\ntype AgentEvent struct {\n\tType AgentEventType\n\tMessage message.Message\n\tError error\n\n\t// When summarizing\n\tSessionID string\n\tProgress string\n\tDone bool\n}\n\ntype Service interface {\n\tpubsub.Suscriber[AgentEvent]\n\tModel() models.Model\n\tRun(ctx context.Context, sessionID string, content string, attachments ...message.Attachment) (<-chan AgentEvent, error)\n\tCancel(sessionID string)\n\tIsSessionBusy(sessionID string) bool\n\tIsBusy() bool\n\tUpdate(agentName config.AgentName, modelID models.ModelID) (models.Model, error)\n\tSummarize(ctx context.Context, sessionID string) error\n}\n\ntype agent struct {\n\t*pubsub.Broker[AgentEvent]\n\tsessions session.Service\n\tmessages message.Service\n\n\ttools []tools.BaseTool\n\tprovider provider.Provider\n\n\ttitleProvider provider.Provider\n\tsummarizeProvider provider.Provider\n\n\tactiveRequests sync.Map\n}\n\nfunc NewAgent(\n\tagentName config.AgentName,\n\tsessions session.Service,\n\tmessages message.Service,\n\tagentTools []tools.BaseTool,\n) (Service, error) {\n\tagentProvider, err := createAgentProvider(agentName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar titleProvider provider.Provider\n\t// Only generate titles for the coder agent\n\tif agentName == config.AgentCoder {\n\t\ttitleProvider, err = createAgentProvider(config.AgentTitle)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tvar summarizeProvider provider.Provider\n\tif agentName == config.AgentCoder {\n\t\tsummarizeProvider, err = createAgentProvider(config.AgentSummarizer)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tagent := &agent{\n\t\tBroker: pubsub.NewBroker[AgentEvent](),\n\t\tprovider: agentProvider,\n\t\tmessages: messages,\n\t\tsessions: sessions,\n\t\ttools: agentTools,\n\t\ttitleProvider: titleProvider,\n\t\tsummarizeProvider: summarizeProvider,\n\t\tactiveRequests: sync.Map{},\n\t}\n\n\treturn agent, nil\n}\n\nfunc (a *agent) Model() models.Model {\n\treturn a.provider.Model()\n}\n\nfunc (a *agent) Cancel(sessionID string) {\n\t// Cancel regular requests\n\tif cancelFunc, exists := a.activeRequests.LoadAndDelete(sessionID); exists {\n\t\tif cancel, ok := cancelFunc.(context.CancelFunc); ok {\n\t\t\tlogging.InfoPersist(fmt.Sprintf(\"Request cancellation initiated for session: %s\", sessionID))\n\t\t\tcancel()\n\t\t}\n\t}\n\n\t// Also check for summarize requests\n\tif cancelFunc, exists := a.activeRequests.LoadAndDelete(sessionID + \"-summarize\"); exists {\n\t\tif cancel, ok := cancelFunc.(context.CancelFunc); ok {\n\t\t\tlogging.InfoPersist(fmt.Sprintf(\"Summarize cancellation initiated for session: %s\", sessionID))\n\t\t\tcancel()\n\t\t}\n\t}\n}\n\nfunc (a *agent) IsBusy() bool {\n\tbusy := false\n\ta.activeRequests.Range(func(key, value interface{}) bool {\n\t\tif cancelFunc, ok := value.(context.CancelFunc); ok {\n\t\t\tif cancelFunc != nil {\n\t\t\t\tbusy = true\n\t\t\t\treturn false // Stop iterating\n\t\t\t}\n\t\t}\n\t\treturn true // Continue iterating\n\t})\n\treturn busy\n}\n\nfunc (a *agent) IsSessionBusy(sessionID string) bool {\n\t_, busy := a.activeRequests.Load(sessionID)\n\treturn busy\n}\n\nfunc (a *agent) generateTitle(ctx context.Context, sessionID string, content string) error {\n\tif content == \"\" {\n\t\treturn nil\n\t}\n\tif a.titleProvider == nil {\n\t\treturn nil\n\t}\n\tsession, err := a.sessions.Get(ctx, sessionID)\n\tif err != nil {\n\t\treturn err\n\t}\n\tctx = context.WithValue(ctx, tools.SessionIDContextKey, sessionID)\n\tparts := []message.ContentPart{message.TextContent{Text: content}}\n\tresponse, err := a.titleProvider.SendMessages(\n\t\tctx,\n\t\t[]message.Message{\n\t\t\t{\n\t\t\t\tRole: message.User,\n\t\t\t\tParts: parts,\n\t\t\t},\n\t\t},\n\t\tmake([]tools.BaseTool, 0),\n\t)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ttitle := strings.TrimSpace(strings.ReplaceAll(response.Content, \"\\n\", \" \"))\n\tif title == \"\" {\n\t\treturn nil\n\t}\n\n\tsession.Title = title\n\t_, err = a.sessions.Save(ctx, session)\n\treturn err\n}\n\nfunc (a *agent) err(err error) AgentEvent {\n\treturn AgentEvent{\n\t\tType: AgentEventTypeError,\n\t\tError: err,\n\t}\n}\n\nfunc (a *agent) Run(ctx context.Context, sessionID string, content string, attachments ...message.Attachment) (<-chan AgentEvent, error) {\n\tif !a.provider.Model().SupportsAttachments && attachments != nil {\n\t\tattachments = nil\n\t}\n\tevents := make(chan AgentEvent)\n\tif a.IsSessionBusy(sessionID) {\n\t\treturn nil, ErrSessionBusy\n\t}\n\n\tgenCtx, cancel := context.WithCancel(ctx)\n\n\ta.activeRequests.Store(sessionID, cancel)\n\tgo func() {\n\t\tlogging.Debug(\"Request started\", \"sessionID\", sessionID)\n\t\tdefer logging.RecoverPanic(\"agent.Run\", func() {\n\t\t\tevents <- a.err(fmt.Errorf(\"panic while running the agent\"))\n\t\t})\n\t\tvar attachmentParts []message.ContentPart\n\t\tfor _, attachment := range attachments {\n\t\t\tattachmentParts = append(attachmentParts, message.BinaryContent{Path: attachment.FilePath, MIMEType: attachment.MimeType, Data: attachment.Content})\n\t\t}\n\t\tresult := a.processGeneration(genCtx, sessionID, content, attachmentParts)\n\t\tif result.Error != nil && !errors.Is(result.Error, ErrRequestCancelled) && !errors.Is(result.Error, context.Canceled) {\n\t\t\tlogging.ErrorPersist(result.Error.Error())\n\t\t}\n\t\tlogging.Debug(\"Request completed\", \"sessionID\", sessionID)\n\t\ta.activeRequests.Delete(sessionID)\n\t\tcancel()\n\t\ta.Publish(pubsub.CreatedEvent, result)\n\t\tevents <- result\n\t\tclose(events)\n\t}()\n\treturn events, nil\n}\n\nfunc (a *agent) processGeneration(ctx context.Context, sessionID, content string, attachmentParts []message.ContentPart) AgentEvent {\n\tcfg := config.Get()\n\t// List existing messages; if none, start title generation asynchronously.\n\tmsgs, err := a.messages.List(ctx, sessionID)\n\tif err != nil {\n\t\treturn a.err(fmt.Errorf(\"failed to list messages: %w\", err))\n\t}\n\tif len(msgs) == 0 {\n\t\tgo func() {\n\t\t\tdefer logging.RecoverPanic(\"agent.Run\", func() {\n\t\t\t\tlogging.ErrorPersist(\"panic while generating title\")\n\t\t\t})\n\t\t\ttitleErr := a.generateTitle(context.Background(), sessionID, content)\n\t\t\tif titleErr != nil {\n\t\t\t\tlogging.ErrorPersist(fmt.Sprintf(\"failed to generate title: %v\", titleErr))\n\t\t\t}\n\t\t}()\n\t}\n\tsession, err := a.sessions.Get(ctx, sessionID)\n\tif err != nil {\n\t\treturn a.err(fmt.Errorf(\"failed to get session: %w\", err))\n\t}\n\tif session.SummaryMessageID != \"\" {\n\t\tsummaryMsgInex := -1\n\t\tfor i, msg := range msgs {\n\t\t\tif msg.ID == session.SummaryMessageID {\n\t\t\t\tsummaryMsgInex = i\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif summaryMsgInex != -1 {\n\t\t\tmsgs = msgs[summaryMsgInex:]\n\t\t\tmsgs[0].Role = message.User\n\t\t}\n\t}\n\n\tuserMsg, err := a.createUserMessage(ctx, sessionID, content, attachmentParts)\n\tif err != nil {\n\t\treturn a.err(fmt.Errorf(\"failed to create user message: %w\", err))\n\t}\n\t// Append the new user message to the conversation history.\n\tmsgHistory := append(msgs, userMsg)\n\n\tfor {\n\t\t// Check for cancellation before each iteration\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn a.err(ctx.Err())\n\t\tdefault:\n\t\t\t// Continue processing\n\t\t}\n\t\tagentMessage, toolResults, err := a.streamAndHandleEvents(ctx, sessionID, msgHistory)\n\t\tif err != nil {\n\t\t\tif errors.Is(err, context.Canceled) {\n\t\t\t\tagentMessage.AddFinish(message.FinishReasonCanceled)\n\t\t\t\ta.messages.Update(context.Background(), agentMessage)\n\t\t\t\treturn a.err(ErrRequestCancelled)\n\t\t\t}\n\t\t\treturn a.err(fmt.Errorf(\"failed to process events: %w\", err))\n\t\t}\n\t\tif cfg.Debug {\n\t\t\tseqId := (len(msgHistory) + 1) / 2\n\t\t\ttoolResultFilepath := logging.WriteToolResultsJson(sessionID, seqId, toolResults)\n\t\t\tlogging.Info(\"Result\", \"message\", agentMessage.FinishReason(), \"toolResults\", \"{}\", \"filepath\", toolResultFilepath)\n\t\t} else {\n\t\t\tlogging.Info(\"Result\", \"message\", agentMessage.FinishReason(), \"toolResults\", toolResults)\n\t\t}\n\t\tif (agentMessage.FinishReason() == message.FinishReasonToolUse) && toolResults != nil {\n\t\t\t// We are not done, we need to respond with the tool response\n\t\t\tmsgHistory = append(msgHistory, agentMessage, *toolResults)\n\t\t\tcontinue\n\t\t}\n\t\treturn AgentEvent{\n\t\t\tType: AgentEventTypeResponse,\n\t\t\tMessage: agentMessage,\n\t\t\tDone: true,\n\t\t}\n\t}\n}\n\nfunc (a *agent) createUserMessage(ctx context.Context, sessionID, content string, attachmentParts []message.ContentPart) (message.Message, error) {\n\tparts := []message.ContentPart{message.TextContent{Text: content}}\n\tparts = append(parts, attachmentParts...)\n\treturn a.messages.Create(ctx, sessionID, message.CreateMessageParams{\n\t\tRole: message.User,\n\t\tParts: parts,\n\t})\n}\n\nfunc (a *agent) streamAndHandleEvents(ctx context.Context, sessionID string, msgHistory []message.Message) (message.Message, *message.Message, error) {\n\tctx = context.WithValue(ctx, tools.SessionIDContextKey, sessionID)\n\teventChan := a.provider.StreamResponse(ctx, msgHistory, a.tools)\n\n\tassistantMsg, err := a.messages.Create(ctx, sessionID, message.CreateMessageParams{\n\t\tRole: message.Assistant,\n\t\tParts: []message.ContentPart{},\n\t\tModel: a.provider.Model().ID,\n\t})\n\tif err != nil {\n\t\treturn assistantMsg, nil, fmt.Errorf(\"failed to create assistant message: %w\", err)\n\t}\n\n\t// Add the session and message ID into the context if needed by tools.\n\tctx = context.WithValue(ctx, tools.MessageIDContextKey, assistantMsg.ID)\n\n\t// Process each event in the stream.\n\tfor event := range eventChan {\n\t\tif processErr := a.processEvent(ctx, sessionID, &assistantMsg, event); processErr != nil {\n\t\t\ta.finishMessage(ctx, &assistantMsg, message.FinishReasonCanceled)\n\t\t\treturn assistantMsg, nil, processErr\n\t\t}\n\t\tif ctx.Err() != nil {\n\t\t\ta.finishMessage(context.Background(), &assistantMsg, message.FinishReasonCanceled)\n\t\t\treturn assistantMsg, nil, ctx.Err()\n\t\t}\n\t}\n\n\ttoolResults := make([]message.ToolResult, len(assistantMsg.ToolCalls()))\n\ttoolCalls := assistantMsg.ToolCalls()\n\tfor i, toolCall := range toolCalls {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\ta.finishMessage(context.Background(), &assistantMsg, message.FinishReasonCanceled)\n\t\t\t// Make all future tool calls cancelled\n\t\t\tfor j := i; j < len(toolCalls); j++ {\n\t\t\t\ttoolResults[j] = message.ToolResult{\n\t\t\t\t\tToolCallID: toolCalls[j].ID,\n\t\t\t\t\tContent: \"Tool execution canceled by user\",\n\t\t\t\t\tIsError: true,\n\t\t\t\t}\n\t\t\t}\n\t\t\tgoto out\n\t\tdefault:\n\t\t\t// Continue processing\n\t\t\tvar tool tools.BaseTool\n\t\t\tfor _, availableTool := range a.tools {\n\t\t\t\tif availableTool.Info().Name == toolCall.Name {\n\t\t\t\t\ttool = availableTool\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\t// Monkey patch for Copilot Sonnet-4 tool repetition obfuscation\n\t\t\t\t// if strings.HasPrefix(toolCall.Name, availableTool.Info().Name) &&\n\t\t\t\t// \tstrings.HasPrefix(toolCall.Name, availableTool.Info().Name+availableTool.Info().Name) {\n\t\t\t\t// \ttool = availableTool\n\t\t\t\t// \tbreak\n\t\t\t\t// }\n\t\t\t}\n\n\t\t\t// Tool not found\n\t\t\tif tool == nil {\n\t\t\t\ttoolResults[i] = message.ToolResult{\n\t\t\t\t\tToolCallID: toolCall.ID,\n\t\t\t\t\tContent: fmt.Sprintf(\"Tool not found: %s\", toolCall.Name),\n\t\t\t\t\tIsError: true,\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\ttoolResult, toolErr := tool.Run(ctx, tools.ToolCall{\n\t\t\t\tID: toolCall.ID,\n\t\t\t\tName: toolCall.Name,\n\t\t\t\tInput: toolCall.Input,\n\t\t\t})\n\t\t\tif toolErr != nil {\n\t\t\t\tif errors.Is(toolErr, permission.ErrorPermissionDenied) {\n\t\t\t\t\ttoolResults[i] = message.ToolResult{\n\t\t\t\t\t\tToolCallID: toolCall.ID,\n\t\t\t\t\t\tContent: \"Permission denied\",\n\t\t\t\t\t\tIsError: true,\n\t\t\t\t\t}\n\t\t\t\t\tfor j := i + 1; j < len(toolCalls); j++ {\n\t\t\t\t\t\ttoolResults[j] = message.ToolResult{\n\t\t\t\t\t\t\tToolCallID: toolCalls[j].ID,\n\t\t\t\t\t\t\tContent: \"Tool execution canceled by user\",\n\t\t\t\t\t\t\tIsError: true,\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\ta.finishMessage(ctx, &assistantMsg, message.FinishReasonPermissionDenied)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\ttoolResults[i] = message.ToolResult{\n\t\t\t\tToolCallID: toolCall.ID,\n\t\t\t\tContent: toolResult.Content,\n\t\t\t\tMetadata: toolResult.Metadata,\n\t\t\t\tIsError: toolResult.IsError,\n\t\t\t}\n\t\t}\n\t}\nout:\n\tif len(toolResults) == 0 {\n\t\treturn assistantMsg, nil, nil\n\t}\n\tparts := make([]message.ContentPart, 0)\n\tfor _, tr := range toolResults {\n\t\tparts = append(parts, tr)\n\t}\n\tmsg, err := a.messages.Create(context.Background(), assistantMsg.SessionID, message.CreateMessageParams{\n\t\tRole: message.Tool,\n\t\tParts: parts,\n\t})\n\tif err != nil {\n\t\treturn assistantMsg, nil, fmt.Errorf(\"failed to create cancelled tool message: %w\", err)\n\t}\n\n\treturn assistantMsg, &msg, err\n}\n\nfunc (a *agent) finishMessage(ctx context.Context, msg *message.Message, finishReson message.FinishReason) {\n\tmsg.AddFinish(finishReson)\n\t_ = a.messages.Update(ctx, *msg)\n}\n\nfunc (a *agent) processEvent(ctx context.Context, sessionID string, assistantMsg *message.Message, event provider.ProviderEvent) error {\n\tselect {\n\tcase <-ctx.Done():\n\t\treturn ctx.Err()\n\tdefault:\n\t\t// Continue processing.\n\t}\n\n\tswitch event.Type {\n\tcase provider.EventThinkingDelta:\n\t\tassistantMsg.AppendReasoningContent(event.Content)\n\t\treturn a.messages.Update(ctx, *assistantMsg)\n\tcase provider.EventContentDelta:\n\t\tassistantMsg.AppendContent(event.Content)\n\t\treturn a.messages.Update(ctx, *assistantMsg)\n\tcase provider.EventToolUseStart:\n\t\tassistantMsg.AddToolCall(*event.ToolCall)\n\t\treturn a.messages.Update(ctx, *assistantMsg)\n\t// TODO: see how to handle this\n\t// case provider.EventToolUseDelta:\n\t// \ttm := time.Unix(assistantMsg.UpdatedAt, 0)\n\t// \tassistantMsg.AppendToolCallInput(event.ToolCall.ID, event.ToolCall.Input)\n\t// \tif time.Since(tm) > 1000*time.Millisecond {\n\t// \t\terr := a.messages.Update(ctx, *assistantMsg)\n\t// \t\tassistantMsg.UpdatedAt = time.Now().Unix()\n\t// \t\treturn err\n\t// \t}\n\tcase provider.EventToolUseStop:\n\t\tassistantMsg.FinishToolCall(event.ToolCall.ID)\n\t\treturn a.messages.Update(ctx, *assistantMsg)\n\tcase provider.EventError:\n\t\tif errors.Is(event.Error, context.Canceled) {\n\t\t\tlogging.InfoPersist(fmt.Sprintf(\"Event processing canceled for session: %s\", sessionID))\n\t\t\treturn context.Canceled\n\t\t}\n\t\tlogging.ErrorPersist(event.Error.Error())\n\t\treturn event.Error\n\tcase provider.EventComplete:\n\t\tassistantMsg.SetToolCalls(event.Response.ToolCalls)\n\t\tassistantMsg.AddFinish(event.Response.FinishReason)\n\t\tif err := a.messages.Update(ctx, *assistantMsg); err != nil {\n\t\t\treturn fmt.Errorf(\"failed to update message: %w\", err)\n\t\t}\n\t\treturn a.TrackUsage(ctx, sessionID, a.provider.Model(), event.Response.Usage)\n\t}\n\n\treturn nil\n}\n\nfunc (a *agent) TrackUsage(ctx context.Context, sessionID string, model models.Model, usage provider.TokenUsage) error {\n\tsess, err := a.sessions.Get(ctx, sessionID)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to get session: %w\", err)\n\t}\n\n\tcost := model.CostPer1MInCached/1e6*float64(usage.CacheCreationTokens) +\n\t\tmodel.CostPer1MOutCached/1e6*float64(usage.CacheReadTokens) +\n\t\tmodel.CostPer1MIn/1e6*float64(usage.InputTokens) +\n\t\tmodel.CostPer1MOut/1e6*float64(usage.OutputTokens)\n\n\tsess.Cost += cost\n\tsess.CompletionTokens = usage.OutputTokens + usage.CacheReadTokens\n\tsess.PromptTokens = usage.InputTokens + usage.CacheCreationTokens\n\n\t_, err = a.sessions.Save(ctx, sess)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to save session: %w\", err)\n\t}\n\treturn nil\n}\n\nfunc (a *agent) Update(agentName config.AgentName, modelID models.ModelID) (models.Model, error) {\n\tif a.IsBusy() {\n\t\treturn models.Model{}, fmt.Errorf(\"cannot change model while processing requests\")\n\t}\n\n\tif err := config.UpdateAgentModel(agentName, modelID); err != nil {\n\t\treturn models.Model{}, fmt.Errorf(\"failed to update config: %w\", err)\n\t}\n\n\tprovider, err := createAgentProvider(agentName)\n\tif err != nil {\n\t\treturn models.Model{}, fmt.Errorf(\"failed to create provider for model %s: %w\", modelID, err)\n\t}\n\n\ta.provider = provider\n\n\treturn a.provider.Model(), nil\n}\n\nfunc (a *agent) Summarize(ctx context.Context, sessionID string) error {\n\tif a.summarizeProvider == nil {\n\t\treturn fmt.Errorf(\"summarize provider not available\")\n\t}\n\n\t// Check if session is busy\n\tif a.IsSessionBusy(sessionID) {\n\t\treturn ErrSessionBusy\n\t}\n\n\t// Create a new context with cancellation\n\tsummarizeCtx, cancel := context.WithCancel(ctx)\n\n\t// Store the cancel function in activeRequests to allow cancellation\n\ta.activeRequests.Store(sessionID+\"-summarize\", cancel)\n\n\tgo func() {\n\t\tdefer a.activeRequests.Delete(sessionID + \"-summarize\")\n\t\tdefer cancel()\n\t\tevent := AgentEvent{\n\t\t\tType: AgentEventTypeSummarize,\n\t\t\tProgress: \"Starting summarization...\",\n\t\t}\n\n\t\ta.Publish(pubsub.CreatedEvent, event)\n\t\t// Get all messages from the session\n\t\tmsgs, err := a.messages.List(summarizeCtx, sessionID)\n\t\tif err != nil {\n\t\t\tevent = AgentEvent{\n\t\t\t\tType: AgentEventTypeError,\n\t\t\t\tError: fmt.Errorf(\"failed to list messages: %w\", err),\n\t\t\t\tDone: true,\n\t\t\t}\n\t\t\ta.Publish(pubsub.CreatedEvent, event)\n\t\t\treturn\n\t\t}\n\t\tsummarizeCtx = context.WithValue(summarizeCtx, tools.SessionIDContextKey, sessionID)\n\n\t\tif len(msgs) == 0 {\n\t\t\tevent = AgentEvent{\n\t\t\t\tType: AgentEventTypeError,\n\t\t\t\tError: fmt.Errorf(\"no messages to summarize\"),\n\t\t\t\tDone: true,\n\t\t\t}\n\t\t\ta.Publish(pubsub.CreatedEvent, event)\n\t\t\treturn\n\t\t}\n\n\t\tevent = AgentEvent{\n\t\t\tType: AgentEventTypeSummarize,\n\t\t\tProgress: \"Analyzing conversation...\",\n\t\t}\n\t\ta.Publish(pubsub.CreatedEvent, event)\n\n\t\t// Add a system message to guide the summarization\n\t\tsummarizePrompt := \"Provide a detailed but concise summary of our conversation above. Focus on information that would be helpful for continuing the conversation, including what we did, what we're doing, which files we're working on, and what we're going to do next.\"\n\n\t\t// Create a new message with the summarize prompt\n\t\tpromptMsg := message.Message{\n\t\t\tRole: message.User,\n\t\t\tParts: []message.ContentPart{message.TextContent{Text: summarizePrompt}},\n\t\t}\n\n\t\t// Append the prompt to the messages\n\t\tmsgsWithPrompt := append(msgs, promptMsg)\n\n\t\tevent = AgentEvent{\n\t\t\tType: AgentEventTypeSummarize,\n\t\t\tProgress: \"Generating summary...\",\n\t\t}\n\n\t\ta.Publish(pubsub.CreatedEvent, event)\n\n\t\t// Send the messages to the summarize provider\n\t\tresponse, err := a.summarizeProvider.SendMessages(\n\t\t\tsummarizeCtx,\n\t\t\tmsgsWithPrompt,\n\t\t\tmake([]tools.BaseTool, 0),\n\t\t)\n\t\tif err != nil {\n\t\t\tevent = AgentEvent{\n\t\t\t\tType: AgentEventTypeError,\n\t\t\t\tError: fmt.Errorf(\"failed to summarize: %w\", err),\n\t\t\t\tDone: true,\n\t\t\t}\n\t\t\ta.Publish(pubsub.CreatedEvent, event)\n\t\t\treturn\n\t\t}\n\n\t\tsummary := strings.TrimSpace(response.Content)\n\t\tif summary == \"\" {\n\t\t\tevent = AgentEvent{\n\t\t\t\tType: AgentEventTypeError,\n\t\t\t\tError: fmt.Errorf(\"empty summary returned\"),\n\t\t\t\tDone: true,\n\t\t\t}\n\t\t\ta.Publish(pubsub.CreatedEvent, event)\n\t\t\treturn\n\t\t}\n\t\tevent = AgentEvent{\n\t\t\tType: AgentEventTypeSummarize,\n\t\t\tProgress: \"Creating new session...\",\n\t\t}\n\n\t\ta.Publish(pubsub.CreatedEvent, event)\n\t\toldSession, err := a.sessions.Get(summarizeCtx, sessionID)\n\t\tif err != nil {\n\t\t\tevent = AgentEvent{\n\t\t\t\tType: AgentEventTypeError,\n\t\t\t\tError: fmt.Errorf(\"failed to get session: %w\", err),\n\t\t\t\tDone: true,\n\t\t\t}\n\n\t\t\ta.Publish(pubsub.CreatedEvent, event)\n\t\t\treturn\n\t\t}\n\t\t// Create a message in the new session with the summary\n\t\tmsg, err := a.messages.Create(summarizeCtx, oldSession.ID, message.CreateMessageParams{\n\t\t\tRole: message.Assistant,\n\t\t\tParts: []message.ContentPart{\n\t\t\t\tmessage.TextContent{Text: summary},\n\t\t\t\tmessage.Finish{\n\t\t\t\t\tReason: message.FinishReasonEndTurn,\n\t\t\t\t\tTime: time.Now().Unix(),\n\t\t\t\t},\n\t\t\t},\n\t\t\tModel: a.summarizeProvider.Model().ID,\n\t\t})\n\t\tif err != nil {\n\t\t\tevent = AgentEvent{\n\t\t\t\tType: AgentEventTypeError,\n\t\t\t\tError: fmt.Errorf(\"failed to create summary message: %w\", err),\n\t\t\t\tDone: true,\n\t\t\t}\n\n\t\t\ta.Publish(pubsub.CreatedEvent, event)\n\t\t\treturn\n\t\t}\n\t\toldSession.SummaryMessageID = msg.ID\n\t\toldSession.CompletionTokens = response.Usage.OutputTokens\n\t\toldSession.PromptTokens = 0\n\t\tmodel := a.summarizeProvider.Model()\n\t\tusage := response.Usage\n\t\tcost := model.CostPer1MInCached/1e6*float64(usage.CacheCreationTokens) +\n\t\t\tmodel.CostPer1MOutCached/1e6*float64(usage.CacheReadTokens) +\n\t\t\tmodel.CostPer1MIn/1e6*float64(usage.InputTokens) +\n\t\t\tmodel.CostPer1MOut/1e6*float64(usage.OutputTokens)\n\t\toldSession.Cost += cost\n\t\t_, err = a.sessions.Save(summarizeCtx, oldSession)\n\t\tif err != nil {\n\t\t\tevent = AgentEvent{\n\t\t\t\tType: AgentEventTypeError,\n\t\t\t\tError: fmt.Errorf(\"failed to save session: %w\", err),\n\t\t\t\tDone: true,\n\t\t\t}\n\t\t\ta.Publish(pubsub.CreatedEvent, event)\n\t\t}\n\n\t\tevent = AgentEvent{\n\t\t\tType: AgentEventTypeSummarize,\n\t\t\tSessionID: oldSession.ID,\n\t\t\tProgress: \"Summary complete\",\n\t\t\tDone: true,\n\t\t}\n\t\ta.Publish(pubsub.CreatedEvent, event)\n\t\t// Send final success event with the new session ID\n\t}()\n\n\treturn nil\n}\n\nfunc createAgentProvider(agentName config.AgentName) (provider.Provider, error) {\n\tcfg := config.Get()\n\tagentConfig, ok := cfg.Agents[agentName]\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"agent %s not found\", agentName)\n\t}\n\tmodel, ok := models.SupportedModels[agentConfig.Model]\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"model %s not supported\", agentConfig.Model)\n\t}\n\n\tproviderCfg, ok := cfg.Providers[model.Provider]\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"provider %s not supported\", model.Provider)\n\t}\n\tif providerCfg.Disabled {\n\t\treturn nil, fmt.Errorf(\"provider %s is not enabled\", model.Provider)\n\t}\n\tmaxTokens := model.DefaultMaxTokens\n\tif agentConfig.MaxTokens > 0 {\n\t\tmaxTokens = agentConfig.MaxTokens\n\t}\n\topts := []provider.ProviderClientOption{\n\t\tprovider.WithAPIKey(providerCfg.APIKey),\n\t\tprovider.WithModel(model),\n\t\tprovider.WithSystemMessage(prompt.GetAgentPrompt(agentName, model.Provider)),\n\t\tprovider.WithMaxTokens(maxTokens),\n\t}\n\tif model.Provider == models.ProviderOpenAI || model.Provider == models.ProviderLocal && model.CanReason {\n\t\topts = append(\n\t\t\topts,\n\t\t\tprovider.WithOpenAIOptions(\n\t\t\t\tprovider.WithReasoningEffort(agentConfig.ReasoningEffort),\n\t\t\t),\n\t\t)\n\t} else if model.Provider == models.ProviderAnthropic && model.CanReason && agentName == config.AgentCoder {\n\t\topts = append(\n\t\t\topts,\n\t\t\tprovider.WithAnthropicOptions(\n\t\t\t\tprovider.WithAnthropicShouldThinkFn(provider.DefaultShouldThinkFn),\n\t\t\t),\n\t\t)\n\t}\n\tagentProvider, err := provider.NewProvider(\n\t\tmodel.Provider,\n\t\topts...,\n\t)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"could not create provider: %v\", err)\n\t}\n\n\treturn agentProvider, nil\n}\n"], ["/opencode/internal/tui/components/dialog/commands.go", "package dialog\n\nimport (\n\t\"github.com/charmbracelet/bubbles/key\"\n\ttea \"github.com/charmbracelet/bubbletea\"\n\t\"github.com/charmbracelet/lipgloss\"\n\tutilComponents \"github.com/opencode-ai/opencode/internal/tui/components/util\"\n\t\"github.com/opencode-ai/opencode/internal/tui/layout\"\n\t\"github.com/opencode-ai/opencode/internal/tui/styles\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n\t\"github.com/opencode-ai/opencode/internal/tui/util\"\n)\n\n// Command represents a command that can be executed\ntype Command struct {\n\tID string\n\tTitle string\n\tDescription string\n\tHandler func(cmd Command) tea.Cmd\n}\n\nfunc (ci Command) Render(selected bool, width int) string {\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\n\tdescStyle := baseStyle.Width(width).Foreground(t.TextMuted())\n\titemStyle := baseStyle.Width(width).\n\t\tForeground(t.Text()).\n\t\tBackground(t.Background())\n\n\tif selected {\n\t\titemStyle = itemStyle.\n\t\t\tBackground(t.Primary()).\n\t\t\tForeground(t.Background()).\n\t\t\tBold(true)\n\t\tdescStyle = descStyle.\n\t\t\tBackground(t.Primary()).\n\t\t\tForeground(t.Background())\n\t}\n\n\ttitle := itemStyle.Padding(0, 1).Render(ci.Title)\n\tif ci.Description != \"\" {\n\t\tdescription := descStyle.Padding(0, 1).Render(ci.Description)\n\t\treturn lipgloss.JoinVertical(lipgloss.Left, title, description)\n\t}\n\treturn title\n}\n\n// CommandSelectedMsg is sent when a command is selected\ntype CommandSelectedMsg struct {\n\tCommand Command\n}\n\n// CloseCommandDialogMsg is sent when the command dialog is closed\ntype CloseCommandDialogMsg struct{}\n\n// CommandDialog interface for the command selection dialog\ntype CommandDialog interface {\n\ttea.Model\n\tlayout.Bindings\n\tSetCommands(commands []Command)\n}\n\ntype commandDialogCmp struct {\n\tlistView utilComponents.SimpleList[Command]\n\twidth int\n\theight int\n}\n\ntype commandKeyMap struct {\n\tEnter key.Binding\n\tEscape key.Binding\n}\n\nvar commandKeys = commandKeyMap{\n\tEnter: key.NewBinding(\n\t\tkey.WithKeys(\"enter\"),\n\t\tkey.WithHelp(\"enter\", \"select command\"),\n\t),\n\tEscape: key.NewBinding(\n\t\tkey.WithKeys(\"esc\"),\n\t\tkey.WithHelp(\"esc\", \"close\"),\n\t),\n}\n\nfunc (c *commandDialogCmp) Init() tea.Cmd {\n\treturn c.listView.Init()\n}\n\nfunc (c *commandDialogCmp) Update(msg tea.Msg) (tea.Model, tea.Cmd) {\n\tvar cmds []tea.Cmd\n\tswitch msg := msg.(type) {\n\tcase tea.KeyMsg:\n\t\tswitch {\n\t\tcase key.Matches(msg, commandKeys.Enter):\n\t\t\tselectedItem, idx := c.listView.GetSelectedItem()\n\t\t\tif idx != -1 {\n\t\t\t\treturn c, util.CmdHandler(CommandSelectedMsg{\n\t\t\t\t\tCommand: selectedItem,\n\t\t\t\t})\n\t\t\t}\n\t\tcase key.Matches(msg, commandKeys.Escape):\n\t\t\treturn c, util.CmdHandler(CloseCommandDialogMsg{})\n\t\t}\n\tcase tea.WindowSizeMsg:\n\t\tc.width = msg.Width\n\t\tc.height = msg.Height\n\t}\n\n\tu, cmd := c.listView.Update(msg)\n\tc.listView = u.(utilComponents.SimpleList[Command])\n\tcmds = append(cmds, cmd)\n\n\treturn c, tea.Batch(cmds...)\n}\n\nfunc (c *commandDialogCmp) View() string {\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\n\tmaxWidth := 40\n\n\tcommands := c.listView.GetItems()\n\n\tfor _, cmd := range commands {\n\t\tif len(cmd.Title) > maxWidth-4 {\n\t\t\tmaxWidth = len(cmd.Title) + 4\n\t\t}\n\t\tif cmd.Description != \"\" {\n\t\t\tif len(cmd.Description) > maxWidth-4 {\n\t\t\t\tmaxWidth = len(cmd.Description) + 4\n\t\t\t}\n\t\t}\n\t}\n\n\tc.listView.SetMaxWidth(maxWidth)\n\n\ttitle := baseStyle.\n\t\tForeground(t.Primary()).\n\t\tBold(true).\n\t\tWidth(maxWidth).\n\t\tPadding(0, 1).\n\t\tRender(\"Commands\")\n\n\tcontent := lipgloss.JoinVertical(\n\t\tlipgloss.Left,\n\t\ttitle,\n\t\tbaseStyle.Width(maxWidth).Render(\"\"),\n\t\tbaseStyle.Width(maxWidth).Render(c.listView.View()),\n\t\tbaseStyle.Width(maxWidth).Render(\"\"),\n\t)\n\n\treturn baseStyle.Padding(1, 2).\n\t\tBorder(lipgloss.RoundedBorder()).\n\t\tBorderBackground(t.Background()).\n\t\tBorderForeground(t.TextMuted()).\n\t\tWidth(lipgloss.Width(content) + 4).\n\t\tRender(content)\n}\n\nfunc (c *commandDialogCmp) BindingKeys() []key.Binding {\n\treturn layout.KeyMapToSlice(commandKeys)\n}\n\nfunc (c *commandDialogCmp) SetCommands(commands []Command) {\n\tc.listView.SetItems(commands)\n}\n\n// NewCommandDialogCmp creates a new command selection dialog\nfunc NewCommandDialogCmp() CommandDialog {\n\tlistView := utilComponents.NewSimpleList[Command](\n\t\t[]Command{},\n\t\t10,\n\t\t\"No commands available\",\n\t\ttrue,\n\t)\n\treturn &commandDialogCmp{\n\t\tlistView: listView,\n\t}\n}\n"], ["/opencode/internal/tui/components/dialog/complete.go", "package dialog\n\nimport (\n\t\"github.com/charmbracelet/bubbles/key\"\n\t\"github.com/charmbracelet/bubbles/textarea\"\n\ttea \"github.com/charmbracelet/bubbletea\"\n\t\"github.com/charmbracelet/lipgloss\"\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n\tutilComponents \"github.com/opencode-ai/opencode/internal/tui/components/util\"\n\t\"github.com/opencode-ai/opencode/internal/tui/layout\"\n\t\"github.com/opencode-ai/opencode/internal/tui/styles\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n\t\"github.com/opencode-ai/opencode/internal/tui/util\"\n)\n\ntype CompletionItem struct {\n\ttitle string\n\tTitle string\n\tValue string\n}\n\ntype CompletionItemI interface {\n\tutilComponents.SimpleListItem\n\tGetValue() string\n\tDisplayValue() string\n}\n\nfunc (ci *CompletionItem) Render(selected bool, width int) string {\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\n\titemStyle := baseStyle.\n\t\tWidth(width).\n\t\tPadding(0, 1)\n\n\tif selected {\n\t\titemStyle = itemStyle.\n\t\t\tBackground(t.Background()).\n\t\t\tForeground(t.Primary()).\n\t\t\tBold(true)\n\t}\n\n\ttitle := itemStyle.Render(\n\t\tci.GetValue(),\n\t)\n\n\treturn title\n}\n\nfunc (ci *CompletionItem) DisplayValue() string {\n\treturn ci.Title\n}\n\nfunc (ci *CompletionItem) GetValue() string {\n\treturn ci.Value\n}\n\nfunc NewCompletionItem(completionItem CompletionItem) CompletionItemI {\n\treturn &completionItem\n}\n\ntype CompletionProvider interface {\n\tGetId() string\n\tGetEntry() CompletionItemI\n\tGetChildEntries(query string) ([]CompletionItemI, error)\n}\n\ntype CompletionSelectedMsg struct {\n\tSearchString string\n\tCompletionValue string\n}\n\ntype CompletionDialogCompleteItemMsg struct {\n\tValue string\n}\n\ntype CompletionDialogCloseMsg struct{}\n\ntype CompletionDialog interface {\n\ttea.Model\n\tlayout.Bindings\n\tSetWidth(width int)\n}\n\ntype completionDialogCmp struct {\n\tquery string\n\tcompletionProvider CompletionProvider\n\twidth int\n\theight int\n\tpseudoSearchTextArea textarea.Model\n\tlistView utilComponents.SimpleList[CompletionItemI]\n}\n\ntype completionDialogKeyMap struct {\n\tComplete key.Binding\n\tCancel key.Binding\n}\n\nvar completionDialogKeys = completionDialogKeyMap{\n\tComplete: key.NewBinding(\n\t\tkey.WithKeys(\"tab\", \"enter\"),\n\t),\n\tCancel: key.NewBinding(\n\t\tkey.WithKeys(\" \", \"esc\", \"backspace\"),\n\t),\n}\n\nfunc (c *completionDialogCmp) Init() tea.Cmd {\n\treturn nil\n}\n\nfunc (c *completionDialogCmp) complete(item CompletionItemI) tea.Cmd {\n\tvalue := c.pseudoSearchTextArea.Value()\n\n\tif value == \"\" {\n\t\treturn nil\n\t}\n\n\treturn tea.Batch(\n\t\tutil.CmdHandler(CompletionSelectedMsg{\n\t\t\tSearchString: value,\n\t\t\tCompletionValue: item.GetValue(),\n\t\t}),\n\t\tc.close(),\n\t)\n}\n\nfunc (c *completionDialogCmp) close() tea.Cmd {\n\tc.listView.SetItems([]CompletionItemI{})\n\tc.pseudoSearchTextArea.Reset()\n\tc.pseudoSearchTextArea.Blur()\n\n\treturn util.CmdHandler(CompletionDialogCloseMsg{})\n}\n\nfunc (c *completionDialogCmp) Update(msg tea.Msg) (tea.Model, tea.Cmd) {\n\tvar cmds []tea.Cmd\n\tswitch msg := msg.(type) {\n\tcase tea.KeyMsg:\n\t\tif c.pseudoSearchTextArea.Focused() {\n\n\t\t\tif !key.Matches(msg, completionDialogKeys.Complete) {\n\n\t\t\t\tvar cmd tea.Cmd\n\t\t\t\tc.pseudoSearchTextArea, cmd = c.pseudoSearchTextArea.Update(msg)\n\t\t\t\tcmds = append(cmds, cmd)\n\n\t\t\t\tvar query string\n\t\t\t\tquery = c.pseudoSearchTextArea.Value()\n\t\t\t\tif query != \"\" {\n\t\t\t\t\tquery = query[1:]\n\t\t\t\t}\n\n\t\t\t\tif query != c.query {\n\t\t\t\t\tlogging.Info(\"Query\", query)\n\t\t\t\t\titems, err := c.completionProvider.GetChildEntries(query)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlogging.Error(\"Failed to get child entries\", err)\n\t\t\t\t\t}\n\n\t\t\t\t\tc.listView.SetItems(items)\n\t\t\t\t\tc.query = query\n\t\t\t\t}\n\n\t\t\t\tu, cmd := c.listView.Update(msg)\n\t\t\t\tc.listView = u.(utilComponents.SimpleList[CompletionItemI])\n\n\t\t\t\tcmds = append(cmds, cmd)\n\t\t\t}\n\n\t\t\tswitch {\n\t\t\tcase key.Matches(msg, completionDialogKeys.Complete):\n\t\t\t\titem, i := c.listView.GetSelectedItem()\n\t\t\t\tif i == -1 {\n\t\t\t\t\treturn c, nil\n\t\t\t\t}\n\n\t\t\t\tcmd := c.complete(item)\n\n\t\t\t\treturn c, cmd\n\t\t\tcase key.Matches(msg, completionDialogKeys.Cancel):\n\t\t\t\t// Only close on backspace when there are no characters left\n\t\t\t\tif msg.String() != \"backspace\" || len(c.pseudoSearchTextArea.Value()) <= 0 {\n\t\t\t\t\treturn c, c.close()\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn c, tea.Batch(cmds...)\n\t\t} else {\n\t\t\titems, err := c.completionProvider.GetChildEntries(\"\")\n\t\t\tif err != nil {\n\t\t\t\tlogging.Error(\"Failed to get child entries\", err)\n\t\t\t}\n\n\t\t\tc.listView.SetItems(items)\n\t\t\tc.pseudoSearchTextArea.SetValue(msg.String())\n\t\t\treturn c, c.pseudoSearchTextArea.Focus()\n\t\t}\n\tcase tea.WindowSizeMsg:\n\t\tc.width = msg.Width\n\t\tc.height = msg.Height\n\t}\n\n\treturn c, tea.Batch(cmds...)\n}\n\nfunc (c *completionDialogCmp) View() string {\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\n\tmaxWidth := 40\n\n\tcompletions := c.listView.GetItems()\n\n\tfor _, cmd := range completions {\n\t\ttitle := cmd.DisplayValue()\n\t\tif len(title) > maxWidth-4 {\n\t\t\tmaxWidth = len(title) + 4\n\t\t}\n\t}\n\n\tc.listView.SetMaxWidth(maxWidth)\n\n\treturn baseStyle.Padding(0, 0).\n\t\tBorder(lipgloss.NormalBorder()).\n\t\tBorderBottom(false).\n\t\tBorderRight(false).\n\t\tBorderLeft(false).\n\t\tBorderBackground(t.Background()).\n\t\tBorderForeground(t.TextMuted()).\n\t\tWidth(c.width).\n\t\tRender(c.listView.View())\n}\n\nfunc (c *completionDialogCmp) SetWidth(width int) {\n\tc.width = width\n}\n\nfunc (c *completionDialogCmp) BindingKeys() []key.Binding {\n\treturn layout.KeyMapToSlice(completionDialogKeys)\n}\n\nfunc NewCompletionDialogCmp(completionProvider CompletionProvider) CompletionDialog {\n\tti := textarea.New()\n\n\titems, err := completionProvider.GetChildEntries(\"\")\n\tif err != nil {\n\t\tlogging.Error(\"Failed to get child entries\", err)\n\t}\n\n\tli := utilComponents.NewSimpleList(\n\t\titems,\n\t\t7,\n\t\t\"No file matches found\",\n\t\tfalse,\n\t)\n\n\treturn &completionDialogCmp{\n\t\tquery: \"\",\n\t\tcompletionProvider: completionProvider,\n\t\tpseudoSearchTextArea: ti,\n\t\tlistView: li,\n\t}\n}\n"], ["/opencode/internal/llm/provider/anthropic.go", "package provider\n\nimport (\n\t\"context\"\n\t\"encoding/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/anthropics/anthropic-sdk-go\"\n\t\"github.com/anthropics/anthropic-sdk-go/bedrock\"\n\t\"github.com/anthropics/anthropic-sdk-go/option\"\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/llm/models\"\n\ttoolsPkg \"github.com/opencode-ai/opencode/internal/llm/tools\"\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n\t\"github.com/opencode-ai/opencode/internal/message\"\n)\n\ntype anthropicOptions struct {\n\tuseBedrock bool\n\tdisableCache bool\n\tshouldThink func(userMessage string) bool\n}\n\ntype AnthropicOption func(*anthropicOptions)\n\ntype anthropicClient struct {\n\tproviderOptions providerClientOptions\n\toptions anthropicOptions\n\tclient anthropic.Client\n}\n\ntype AnthropicClient ProviderClient\n\nfunc newAnthropicClient(opts providerClientOptions) AnthropicClient {\n\tanthropicOpts := anthropicOptions{}\n\tfor _, o := range opts.anthropicOptions {\n\t\to(&anthropicOpts)\n\t}\n\n\tanthropicClientOptions := []option.RequestOption{}\n\tif opts.apiKey != \"\" {\n\t\tanthropicClientOptions = append(anthropicClientOptions, option.WithAPIKey(opts.apiKey))\n\t}\n\tif anthropicOpts.useBedrock {\n\t\tanthropicClientOptions = append(anthropicClientOptions, bedrock.WithLoadDefaultConfig(context.Background()))\n\t}\n\n\tclient := anthropic.NewClient(anthropicClientOptions...)\n\treturn &anthropicClient{\n\t\tproviderOptions: opts,\n\t\toptions: anthropicOpts,\n\t\tclient: client,\n\t}\n}\n\nfunc (a *anthropicClient) convertMessages(messages []message.Message) (anthropicMessages []anthropic.MessageParam) {\n\tfor i, msg := range messages {\n\t\tcache := false\n\t\tif i > len(messages)-3 {\n\t\t\tcache = true\n\t\t}\n\t\tswitch msg.Role {\n\t\tcase message.User:\n\t\t\tcontent := anthropic.NewTextBlock(msg.Content().String())\n\t\t\tif cache && !a.options.disableCache {\n\t\t\t\tcontent.OfText.CacheControl = anthropic.CacheControlEphemeralParam{\n\t\t\t\t\tType: \"ephemeral\",\n\t\t\t\t}\n\t\t\t}\n\t\t\tvar contentBlocks []anthropic.ContentBlockParamUnion\n\t\t\tcontentBlocks = append(contentBlocks, content)\n\t\t\tfor _, binaryContent := range msg.BinaryContent() {\n\t\t\t\tbase64Image := binaryContent.String(models.ProviderAnthropic)\n\t\t\t\timageBlock := anthropic.NewImageBlockBase64(binaryContent.MIMEType, base64Image)\n\t\t\t\tcontentBlocks = append(contentBlocks, imageBlock)\n\t\t\t}\n\t\t\tanthropicMessages = append(anthropicMessages, anthropic.NewUserMessage(contentBlocks...))\n\n\t\tcase message.Assistant:\n\t\t\tblocks := []anthropic.ContentBlockParamUnion{}\n\t\t\tif msg.Content().String() != \"\" {\n\t\t\t\tcontent := anthropic.NewTextBlock(msg.Content().String())\n\t\t\t\tif cache && !a.options.disableCache {\n\t\t\t\t\tcontent.OfText.CacheControl = anthropic.CacheControlEphemeralParam{\n\t\t\t\t\t\tType: \"ephemeral\",\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tblocks = append(blocks, content)\n\t\t\t}\n\n\t\t\tfor _, toolCall := range msg.ToolCalls() {\n\t\t\t\tvar inputMap map[string]any\n\t\t\t\terr := json.Unmarshal([]byte(toolCall.Input), &inputMap)\n\t\t\t\tif err != nil {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tblocks = append(blocks, anthropic.NewToolUseBlock(toolCall.ID, inputMap, toolCall.Name))\n\t\t\t}\n\n\t\t\tif len(blocks) == 0 {\n\t\t\t\tlogging.Warn(\"There is a message without content, investigate, this should not happen\")\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tanthropicMessages = append(anthropicMessages, anthropic.NewAssistantMessage(blocks...))\n\n\t\tcase message.Tool:\n\t\t\tresults := make([]anthropic.ContentBlockParamUnion, len(msg.ToolResults()))\n\t\t\tfor i, toolResult := range msg.ToolResults() {\n\t\t\t\tresults[i] = anthropic.NewToolResultBlock(toolResult.ToolCallID, toolResult.Content, toolResult.IsError)\n\t\t\t}\n\t\t\tanthropicMessages = append(anthropicMessages, anthropic.NewUserMessage(results...))\n\t\t}\n\t}\n\treturn\n}\n\nfunc (a *anthropicClient) convertTools(tools []toolsPkg.BaseTool) []anthropic.ToolUnionParam {\n\tanthropicTools := make([]anthropic.ToolUnionParam, len(tools))\n\n\tfor i, tool := range tools {\n\t\tinfo := tool.Info()\n\t\ttoolParam := anthropic.ToolParam{\n\t\t\tName: info.Name,\n\t\t\tDescription: anthropic.String(info.Description),\n\t\t\tInputSchema: anthropic.ToolInputSchemaParam{\n\t\t\t\tProperties: info.Parameters,\n\t\t\t\t// TODO: figure out how we can tell claude the required fields?\n\t\t\t},\n\t\t}\n\n\t\tif i == len(tools)-1 && !a.options.disableCache {\n\t\t\ttoolParam.CacheControl = anthropic.CacheControlEphemeralParam{\n\t\t\t\tType: \"ephemeral\",\n\t\t\t}\n\t\t}\n\n\t\tanthropicTools[i] = anthropic.ToolUnionParam{OfTool: &toolParam}\n\t}\n\n\treturn anthropicTools\n}\n\nfunc (a *anthropicClient) finishReason(reason string) message.FinishReason {\n\tswitch reason {\n\tcase \"end_turn\":\n\t\treturn message.FinishReasonEndTurn\n\tcase \"max_tokens\":\n\t\treturn message.FinishReasonMaxTokens\n\tcase \"tool_use\":\n\t\treturn message.FinishReasonToolUse\n\tcase \"stop_sequence\":\n\t\treturn message.FinishReasonEndTurn\n\tdefault:\n\t\treturn message.FinishReasonUnknown\n\t}\n}\n\nfunc (a *anthropicClient) preparedMessages(messages []anthropic.MessageParam, tools []anthropic.ToolUnionParam) anthropic.MessageNewParams {\n\tvar thinkingParam anthropic.ThinkingConfigParamUnion\n\tlastMessage := messages[len(messages)-1]\n\tisUser := lastMessage.Role == anthropic.MessageParamRoleUser\n\tmessageContent := \"\"\n\ttemperature := anthropic.Float(0)\n\tif isUser {\n\t\tfor _, m := range lastMessage.Content {\n\t\t\tif m.OfText != nil && m.OfText.Text != \"\" {\n\t\t\t\tmessageContent = m.OfText.Text\n\t\t\t}\n\t\t}\n\t\tif messageContent != \"\" && a.options.shouldThink != nil && a.options.shouldThink(messageContent) {\n\t\t\tthinkingParam = anthropic.ThinkingConfigParamOfEnabled(int64(float64(a.providerOptions.maxTokens) * 0.8))\n\t\t\ttemperature = anthropic.Float(1)\n\t\t}\n\t}\n\n\treturn anthropic.MessageNewParams{\n\t\tModel: anthropic.Model(a.providerOptions.model.APIModel),\n\t\tMaxTokens: a.providerOptions.maxTokens,\n\t\tTemperature: temperature,\n\t\tMessages: messages,\n\t\tTools: tools,\n\t\tThinking: thinkingParam,\n\t\tSystem: []anthropic.TextBlockParam{\n\t\t\t{\n\t\t\t\tText: a.providerOptions.systemMessage,\n\t\t\t\tCacheControl: anthropic.CacheControlEphemeralParam{\n\t\t\t\t\tType: \"ephemeral\",\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n}\n\nfunc (a *anthropicClient) send(ctx context.Context, messages []message.Message, tools []toolsPkg.BaseTool) (resposne *ProviderResponse, err error) {\n\tpreparedMessages := a.preparedMessages(a.convertMessages(messages), a.convertTools(tools))\n\tcfg := config.Get()\n\tif cfg.Debug {\n\t\tjsonData, _ := json.Marshal(preparedMessages)\n\t\tlogging.Debug(\"Prepared messages\", \"messages\", string(jsonData))\n\t}\n\n\tattempts := 0\n\tfor {\n\t\tattempts++\n\t\tanthropicResponse, err := a.client.Messages.New(\n\t\t\tctx,\n\t\t\tpreparedMessages,\n\t\t)\n\t\t// If there is an error we are going to see if we can retry the call\n\t\tif err != nil {\n\t\t\tlogging.Error(\"Error in Anthropic API call\", \"error\", err)\n\t\t\tretry, after, retryErr := a.shouldRetry(attempts, err)\n\t\t\tif retryErr != nil {\n\t\t\t\treturn nil, retryErr\n\t\t\t}\n\t\t\tif retry {\n\t\t\t\tlogging.WarnPersist(fmt.Sprintf(\"Retrying due to rate limit... attempt %d of %d\", attempts, maxRetries), logging.PersistTimeArg, time.Millisecond*time.Duration(after+100))\n\t\t\t\tselect {\n\t\t\t\tcase <-ctx.Done():\n\t\t\t\t\treturn nil, ctx.Err()\n\t\t\t\tcase <-time.After(time.Duration(after) * time.Millisecond):\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn nil, retryErr\n\t\t}\n\n\t\tcontent := \"\"\n\t\tfor _, block := range anthropicResponse.Content {\n\t\t\tif text, ok := block.AsAny().(anthropic.TextBlock); ok {\n\t\t\t\tcontent += text.Text\n\t\t\t}\n\t\t}\n\n\t\treturn &ProviderResponse{\n\t\t\tContent: content,\n\t\t\tToolCalls: a.toolCalls(*anthropicResponse),\n\t\t\tUsage: a.usage(*anthropicResponse),\n\t\t}, nil\n\t}\n}\n\nfunc (a *anthropicClient) stream(ctx context.Context, messages []message.Message, tools []toolsPkg.BaseTool) <-chan ProviderEvent {\n\tpreparedMessages := a.preparedMessages(a.convertMessages(messages), a.convertTools(tools))\n\tcfg := config.Get()\n\n\tvar sessionId string\n\trequestSeqId := (len(messages) + 1) / 2\n\tif cfg.Debug {\n\t\tif sid, ok := ctx.Value(toolsPkg.SessionIDContextKey).(string); ok {\n\t\t\tsessionId = sid\n\t\t}\n\t\tjsonData, _ := json.Marshal(preparedMessages)\n\t\tif sessionId != \"\" {\n\t\t\tfilepath := logging.WriteRequestMessageJson(sessionId, requestSeqId, preparedMessages)\n\t\t\tlogging.Debug(\"Prepared messages\", \"filepath\", filepath)\n\t\t} else {\n\t\t\tlogging.Debug(\"Prepared messages\", \"messages\", string(jsonData))\n\t\t}\n\n\t}\n\tattempts := 0\n\teventChan := make(chan ProviderEvent)\n\tgo func() {\n\t\tfor {\n\t\t\tattempts++\n\t\t\tanthropicStream := a.client.Messages.NewStreaming(\n\t\t\t\tctx,\n\t\t\t\tpreparedMessages,\n\t\t\t)\n\t\t\taccumulatedMessage := anthropic.Message{}\n\n\t\t\tcurrentToolCallID := \"\"\n\t\t\tfor anthropicStream.Next() {\n\t\t\t\tevent := anthropicStream.Current()\n\t\t\t\terr := accumulatedMessage.Accumulate(event)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlogging.Warn(\"Error accumulating message\", \"error\", err)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tswitch event := event.AsAny().(type) {\n\t\t\t\tcase anthropic.ContentBlockStartEvent:\n\t\t\t\t\tif event.ContentBlock.Type == \"text\" {\n\t\t\t\t\t\teventChan <- ProviderEvent{Type: EventContentStart}\n\t\t\t\t\t} else if event.ContentBlock.Type == \"tool_use\" {\n\t\t\t\t\t\tcurrentToolCallID = event.ContentBlock.ID\n\t\t\t\t\t\teventChan <- ProviderEvent{\n\t\t\t\t\t\t\tType: EventToolUseStart,\n\t\t\t\t\t\t\tToolCall: &message.ToolCall{\n\t\t\t\t\t\t\t\tID: event.ContentBlock.ID,\n\t\t\t\t\t\t\t\tName: event.ContentBlock.Name,\n\t\t\t\t\t\t\t\tFinished: false,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\tcase anthropic.ContentBlockDeltaEvent:\n\t\t\t\t\tif event.Delta.Type == \"thinking_delta\" && event.Delta.Thinking != \"\" {\n\t\t\t\t\t\teventChan <- ProviderEvent{\n\t\t\t\t\t\t\tType: EventThinkingDelta,\n\t\t\t\t\t\t\tThinking: event.Delta.Thinking,\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if event.Delta.Type == \"text_delta\" && event.Delta.Text != \"\" {\n\t\t\t\t\t\teventChan <- ProviderEvent{\n\t\t\t\t\t\t\tType: EventContentDelta,\n\t\t\t\t\t\t\tContent: event.Delta.Text,\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if event.Delta.Type == \"input_json_delta\" {\n\t\t\t\t\t\tif currentToolCallID != \"\" {\n\t\t\t\t\t\t\teventChan <- ProviderEvent{\n\t\t\t\t\t\t\t\tType: EventToolUseDelta,\n\t\t\t\t\t\t\t\tToolCall: &message.ToolCall{\n\t\t\t\t\t\t\t\t\tID: currentToolCallID,\n\t\t\t\t\t\t\t\t\tFinished: false,\n\t\t\t\t\t\t\t\t\tInput: event.Delta.JSON.PartialJSON.Raw(),\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\tcase anthropic.ContentBlockStopEvent:\n\t\t\t\t\tif currentToolCallID != \"\" {\n\t\t\t\t\t\teventChan <- ProviderEvent{\n\t\t\t\t\t\t\tType: EventToolUseStop,\n\t\t\t\t\t\t\tToolCall: &message.ToolCall{\n\t\t\t\t\t\t\t\tID: currentToolCallID,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcurrentToolCallID = \"\"\n\t\t\t\t\t} else {\n\t\t\t\t\t\teventChan <- ProviderEvent{Type: EventContentStop}\n\t\t\t\t\t}\n\n\t\t\t\tcase anthropic.MessageStopEvent:\n\t\t\t\t\tcontent := \"\"\n\t\t\t\t\tfor _, block := range accumulatedMessage.Content {\n\t\t\t\t\t\tif text, ok := block.AsAny().(anthropic.TextBlock); ok {\n\t\t\t\t\t\t\tcontent += text.Text\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\teventChan <- ProviderEvent{\n\t\t\t\t\t\tType: EventComplete,\n\t\t\t\t\t\tResponse: &ProviderResponse{\n\t\t\t\t\t\t\tContent: content,\n\t\t\t\t\t\t\tToolCalls: a.toolCalls(accumulatedMessage),\n\t\t\t\t\t\t\tUsage: a.usage(accumulatedMessage),\n\t\t\t\t\t\t\tFinishReason: a.finishReason(string(accumulatedMessage.StopReason)),\n\t\t\t\t\t\t},\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\terr := anthropicStream.Err()\n\t\t\tif err == nil || errors.Is(err, io.EOF) {\n\t\t\t\tclose(eventChan)\n\t\t\t\treturn\n\t\t\t}\n\t\t\t// If there is an error we are going to see if we can retry the call\n\t\t\tretry, after, retryErr := a.shouldRetry(attempts, err)\n\t\t\tif retryErr != nil {\n\t\t\t\teventChan <- ProviderEvent{Type: EventError, Error: retryErr}\n\t\t\t\tclose(eventChan)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif retry {\n\t\t\t\tlogging.WarnPersist(fmt.Sprintf(\"Retrying due to rate limit... attempt %d of %d\", attempts, maxRetries), logging.PersistTimeArg, time.Millisecond*time.Duration(after+100))\n\t\t\t\tselect {\n\t\t\t\tcase <-ctx.Done():\n\t\t\t\t\t// context cancelled\n\t\t\t\t\tif ctx.Err() != nil {\n\t\t\t\t\t\teventChan <- ProviderEvent{Type: EventError, Error: ctx.Err()}\n\t\t\t\t\t}\n\t\t\t\t\tclose(eventChan)\n\t\t\t\t\treturn\n\t\t\t\tcase <-time.After(time.Duration(after) * time.Millisecond):\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t\tif ctx.Err() != nil {\n\t\t\t\teventChan <- ProviderEvent{Type: EventError, Error: ctx.Err()}\n\t\t\t}\n\n\t\t\tclose(eventChan)\n\t\t\treturn\n\t\t}\n\t}()\n\treturn eventChan\n}\n\nfunc (a *anthropicClient) shouldRetry(attempts int, err error) (bool, int64, error) {\n\tvar apierr *anthropic.Error\n\tif !errors.As(err, &apierr) {\n\t\treturn false, 0, err\n\t}\n\n\tif apierr.StatusCode != 429 && apierr.StatusCode != 529 {\n\t\treturn false, 0, err\n\t}\n\n\tif attempts > maxRetries {\n\t\treturn false, 0, fmt.Errorf(\"maximum retry attempts reached for rate limit: %d retries\", maxRetries)\n\t}\n\n\tretryMs := 0\n\tretryAfterValues := apierr.Response.Header.Values(\"Retry-After\")\n\n\tbackoffMs := 2000 * (1 << (attempts - 1))\n\tjitterMs := int(float64(backoffMs) * 0.2)\n\tretryMs = backoffMs + jitterMs\n\tif len(retryAfterValues) > 0 {\n\t\tif _, err := fmt.Sscanf(retryAfterValues[0], \"%d\", &retryMs); err == nil {\n\t\t\tretryMs = retryMs * 1000\n\t\t}\n\t}\n\treturn true, int64(retryMs), nil\n}\n\nfunc (a *anthropicClient) toolCalls(msg anthropic.Message) []message.ToolCall {\n\tvar toolCalls []message.ToolCall\n\n\tfor _, block := range msg.Content {\n\t\tswitch variant := block.AsAny().(type) {\n\t\tcase anthropic.ToolUseBlock:\n\t\t\ttoolCall := message.ToolCall{\n\t\t\t\tID: variant.ID,\n\t\t\t\tName: variant.Name,\n\t\t\t\tInput: string(variant.Input),\n\t\t\t\tType: string(variant.Type),\n\t\t\t\tFinished: true,\n\t\t\t}\n\t\t\ttoolCalls = append(toolCalls, toolCall)\n\t\t}\n\t}\n\n\treturn toolCalls\n}\n\nfunc (a *anthropicClient) usage(msg anthropic.Message) TokenUsage {\n\treturn TokenUsage{\n\t\tInputTokens: msg.Usage.InputTokens,\n\t\tOutputTokens: msg.Usage.OutputTokens,\n\t\tCacheCreationTokens: msg.Usage.CacheCreationInputTokens,\n\t\tCacheReadTokens: msg.Usage.CacheReadInputTokens,\n\t}\n}\n\nfunc WithAnthropicBedrock(useBedrock bool) AnthropicOption {\n\treturn func(options *anthropicOptions) {\n\t\toptions.useBedrock = useBedrock\n\t}\n}\n\nfunc WithAnthropicDisableCache() AnthropicOption {\n\treturn func(options *anthropicOptions) {\n\t\toptions.disableCache = true\n\t}\n}\n\nfunc DefaultShouldThinkFn(s string) bool {\n\treturn strings.Contains(strings.ToLower(s), \"think\")\n}\n\nfunc WithAnthropicShouldThinkFn(fn func(string) bool) AnthropicOption {\n\treturn func(options *anthropicOptions) {\n\t\toptions.shouldThink = fn\n\t}\n}\n"], ["/opencode/internal/tui/components/dialog/help.go", "package dialog\n\nimport (\n\t\"strings\"\n\n\t\"github.com/charmbracelet/bubbles/key\"\n\ttea \"github.com/charmbracelet/bubbletea\"\n\t\"github.com/charmbracelet/lipgloss\"\n\t\"github.com/opencode-ai/opencode/internal/tui/styles\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n)\n\ntype helpCmp struct {\n\twidth int\n\theight int\n\tkeys []key.Binding\n}\n\nfunc (h *helpCmp) Init() tea.Cmd {\n\treturn nil\n}\n\nfunc (h *helpCmp) SetBindings(k []key.Binding) {\n\th.keys = k\n}\n\nfunc (h *helpCmp) Update(msg tea.Msg) (tea.Model, tea.Cmd) {\n\tswitch msg := msg.(type) {\n\tcase tea.WindowSizeMsg:\n\t\th.width = 90\n\t\th.height = msg.Height\n\t}\n\treturn h, nil\n}\n\nfunc removeDuplicateBindings(bindings []key.Binding) []key.Binding {\n\tseen := make(map[string]struct{})\n\tresult := make([]key.Binding, 0, len(bindings))\n\n\t// Process bindings in reverse order\n\tfor i := len(bindings) - 1; i >= 0; i-- {\n\t\tb := bindings[i]\n\t\tk := strings.Join(b.Keys(), \" \")\n\t\tif _, ok := seen[k]; ok {\n\t\t\t// duplicate, skip\n\t\t\tcontinue\n\t\t}\n\t\tseen[k] = struct{}{}\n\t\t// Add to the beginning of result to maintain original order\n\t\tresult = append([]key.Binding{b}, result...)\n\t}\n\n\treturn result\n}\n\nfunc (h *helpCmp) render() string {\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\n\thelpKeyStyle := styles.Bold().\n\t\tBackground(t.Background()).\n\t\tForeground(t.Text()).\n\t\tPadding(0, 1, 0, 0)\n\n\thelpDescStyle := styles.Regular().\n\t\tBackground(t.Background()).\n\t\tForeground(t.TextMuted())\n\n\t// Compile list of bindings to render\n\tbindings := removeDuplicateBindings(h.keys)\n\n\t// Enumerate through each group of bindings, populating a series of\n\t// pairs of columns, one for keys, one for descriptions\n\tvar (\n\t\tpairs []string\n\t\twidth int\n\t\trows = 12 - 2\n\t)\n\n\tfor i := 0; i < len(bindings); i += rows {\n\t\tvar (\n\t\t\tkeys []string\n\t\t\tdescs []string\n\t\t)\n\t\tfor j := i; j < min(i+rows, len(bindings)); j++ {\n\t\t\tkeys = append(keys, helpKeyStyle.Render(bindings[j].Help().Key))\n\t\t\tdescs = append(descs, helpDescStyle.Render(bindings[j].Help().Desc))\n\t\t}\n\n\t\t// Render pair of columns; beyond the first pair, render a three space\n\t\t// left margin, in order to visually separate the pairs.\n\t\tvar cols []string\n\t\tif len(pairs) > 0 {\n\t\t\tcols = []string{baseStyle.Render(\" \")}\n\t\t}\n\n\t\tmaxDescWidth := 0\n\t\tfor _, desc := range descs {\n\t\t\tif maxDescWidth < lipgloss.Width(desc) {\n\t\t\t\tmaxDescWidth = lipgloss.Width(desc)\n\t\t\t}\n\t\t}\n\t\tfor i := range descs {\n\t\t\tremainingWidth := maxDescWidth - lipgloss.Width(descs[i])\n\t\t\tif remainingWidth > 0 {\n\t\t\t\tdescs[i] = descs[i] + baseStyle.Render(strings.Repeat(\" \", remainingWidth))\n\t\t\t}\n\t\t}\n\t\tmaxKeyWidth := 0\n\t\tfor _, key := range keys {\n\t\t\tif maxKeyWidth < lipgloss.Width(key) {\n\t\t\t\tmaxKeyWidth = lipgloss.Width(key)\n\t\t\t}\n\t\t}\n\t\tfor i := range keys {\n\t\t\tremainingWidth := maxKeyWidth - lipgloss.Width(keys[i])\n\t\t\tif remainingWidth > 0 {\n\t\t\t\tkeys[i] = keys[i] + baseStyle.Render(strings.Repeat(\" \", remainingWidth))\n\t\t\t}\n\t\t}\n\n\t\tcols = append(cols,\n\t\t\tstrings.Join(keys, \"\\n\"),\n\t\t\tstrings.Join(descs, \"\\n\"),\n\t\t)\n\n\t\tpair := baseStyle.Render(lipgloss.JoinHorizontal(lipgloss.Top, cols...))\n\t\t// check whether it exceeds the maximum width avail (the width of the\n\t\t// terminal, subtracting 2 for the borders).\n\t\twidth += lipgloss.Width(pair)\n\t\tif width > h.width-2 {\n\t\t\tbreak\n\t\t}\n\t\tpairs = append(pairs, pair)\n\t}\n\n\t// https://github.com/charmbracelet/lipgloss/issues/209\n\tif len(pairs) > 1 {\n\t\tprefix := pairs[:len(pairs)-1]\n\t\tlastPair := pairs[len(pairs)-1]\n\t\tprefix = append(prefix, lipgloss.Place(\n\t\t\tlipgloss.Width(lastPair), // width\n\t\t\tlipgloss.Height(prefix[0]), // height\n\t\t\tlipgloss.Left, // x\n\t\t\tlipgloss.Top, // y\n\t\t\tlastPair, // content\n\t\t\tlipgloss.WithWhitespaceBackground(t.Background()),\n\t\t))\n\t\tcontent := baseStyle.Width(h.width).Render(\n\t\t\tlipgloss.JoinHorizontal(\n\t\t\t\tlipgloss.Top,\n\t\t\t\tprefix...,\n\t\t\t),\n\t\t)\n\t\treturn content\n\t}\n\n\t// Join pairs of columns and enclose in a border\n\tcontent := baseStyle.Width(h.width).Render(\n\t\tlipgloss.JoinHorizontal(\n\t\t\tlipgloss.Top,\n\t\t\tpairs...,\n\t\t),\n\t)\n\treturn content\n}\n\nfunc (h *helpCmp) View() string {\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\n\tcontent := h.render()\n\theader := baseStyle.\n\t\tBold(true).\n\t\tWidth(lipgloss.Width(content)).\n\t\tForeground(t.Primary()).\n\t\tRender(\"Keyboard Shortcuts\")\n\n\treturn baseStyle.Padding(1).\n\t\tBorder(lipgloss.RoundedBorder()).\n\t\tBorderForeground(t.TextMuted()).\n\t\tWidth(h.width).\n\t\tBorderBackground(t.Background()).\n\t\tRender(\n\t\t\tlipgloss.JoinVertical(lipgloss.Center,\n\t\t\t\theader,\n\t\t\t\tbaseStyle.Render(strings.Repeat(\" \", lipgloss.Width(header))),\n\t\t\t\tcontent,\n\t\t\t),\n\t\t)\n}\n\ntype HelpCmp interface {\n\ttea.Model\n\tSetBindings([]key.Binding)\n}\n\nfunc NewHelpCmp() HelpCmp {\n\treturn &helpCmp{}\n}\n"], ["/opencode/internal/llm/provider/gemini.go", "package provider\n\nimport (\n\t\"context\"\n\t\"encoding/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/google/uuid\"\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/llm/tools\"\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n\t\"github.com/opencode-ai/opencode/internal/message\"\n\t\"google.golang.org/genai\"\n)\n\ntype geminiOptions struct {\n\tdisableCache bool\n}\n\ntype GeminiOption func(*geminiOptions)\n\ntype geminiClient struct {\n\tproviderOptions providerClientOptions\n\toptions geminiOptions\n\tclient *genai.Client\n}\n\ntype GeminiClient ProviderClient\n\nfunc newGeminiClient(opts providerClientOptions) GeminiClient {\n\tgeminiOpts := geminiOptions{}\n\tfor _, o := range opts.geminiOptions {\n\t\to(&geminiOpts)\n\t}\n\n\tclient, err := genai.NewClient(context.Background(), &genai.ClientConfig{APIKey: opts.apiKey, Backend: genai.BackendGeminiAPI})\n\tif err != nil {\n\t\tlogging.Error(\"Failed to create Gemini client\", \"error\", err)\n\t\treturn nil\n\t}\n\n\treturn &geminiClient{\n\t\tproviderOptions: opts,\n\t\toptions: geminiOpts,\n\t\tclient: client,\n\t}\n}\n\nfunc (g *geminiClient) convertMessages(messages []message.Message) []*genai.Content {\n\tvar history []*genai.Content\n\tfor _, msg := range messages {\n\t\tswitch msg.Role {\n\t\tcase message.User:\n\t\t\tvar parts []*genai.Part\n\t\t\tparts = append(parts, &genai.Part{Text: msg.Content().String()})\n\t\t\tfor _, binaryContent := range msg.BinaryContent() {\n\t\t\t\timageFormat := strings.Split(binaryContent.MIMEType, \"/\")\n\t\t\t\tparts = append(parts, &genai.Part{InlineData: &genai.Blob{\n\t\t\t\t\tMIMEType: imageFormat[1],\n\t\t\t\t\tData: binaryContent.Data,\n\t\t\t\t}})\n\t\t\t}\n\t\t\thistory = append(history, &genai.Content{\n\t\t\t\tParts: parts,\n\t\t\t\tRole: \"user\",\n\t\t\t})\n\t\tcase message.Assistant:\n\t\t\tvar assistantParts []*genai.Part\n\n\t\t\tif msg.Content().String() != \"\" {\n\t\t\t\tassistantParts = append(assistantParts, &genai.Part{Text: msg.Content().String()})\n\t\t\t}\n\n\t\t\tif len(msg.ToolCalls()) > 0 {\n\t\t\t\tfor _, call := range msg.ToolCalls() {\n\t\t\t\t\targs, _ := parseJsonToMap(call.Input)\n\t\t\t\t\tassistantParts = append(assistantParts, &genai.Part{\n\t\t\t\t\t\tFunctionCall: &genai.FunctionCall{\n\t\t\t\t\t\t\tName: call.Name,\n\t\t\t\t\t\t\tArgs: args,\n\t\t\t\t\t\t},\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif len(assistantParts) > 0 {\n\t\t\t\thistory = append(history, &genai.Content{\n\t\t\t\t\tRole: \"model\",\n\t\t\t\t\tParts: assistantParts,\n\t\t\t\t})\n\t\t\t}\n\n\t\tcase message.Tool:\n\t\t\tfor _, result := range msg.ToolResults() {\n\t\t\t\tresponse := map[string]interface{}{\"result\": result.Content}\n\t\t\t\tparsed, err := parseJsonToMap(result.Content)\n\t\t\t\tif err == nil {\n\t\t\t\t\tresponse = parsed\n\t\t\t\t}\n\n\t\t\t\tvar toolCall message.ToolCall\n\t\t\t\tfor _, m := range messages {\n\t\t\t\t\tif m.Role == message.Assistant {\n\t\t\t\t\t\tfor _, call := range m.ToolCalls() {\n\t\t\t\t\t\t\tif call.ID == result.ToolCallID {\n\t\t\t\t\t\t\t\ttoolCall = call\n\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\thistory = append(history, &genai.Content{\n\t\t\t\t\tParts: []*genai.Part{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tFunctionResponse: &genai.FunctionResponse{\n\t\t\t\t\t\t\t\tName: toolCall.Name,\n\t\t\t\t\t\t\t\tResponse: response,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\tRole: \"function\",\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\t}\n\n\treturn history\n}\n\nfunc (g *geminiClient) convertTools(tools []tools.BaseTool) []*genai.Tool {\n\tgeminiTool := &genai.Tool{}\n\tgeminiTool.FunctionDeclarations = make([]*genai.FunctionDeclaration, 0, len(tools))\n\n\tfor _, tool := range tools {\n\t\tinfo := tool.Info()\n\t\tdeclaration := &genai.FunctionDeclaration{\n\t\t\tName: info.Name,\n\t\t\tDescription: info.Description,\n\t\t\tParameters: &genai.Schema{\n\t\t\t\tType: genai.TypeObject,\n\t\t\t\tProperties: convertSchemaProperties(info.Parameters),\n\t\t\t\tRequired: info.Required,\n\t\t\t},\n\t\t}\n\n\t\tgeminiTool.FunctionDeclarations = append(geminiTool.FunctionDeclarations, declaration)\n\t}\n\n\treturn []*genai.Tool{geminiTool}\n}\n\nfunc (g *geminiClient) finishReason(reason genai.FinishReason) message.FinishReason {\n\tswitch {\n\tcase reason == genai.FinishReasonStop:\n\t\treturn message.FinishReasonEndTurn\n\tcase reason == genai.FinishReasonMaxTokens:\n\t\treturn message.FinishReasonMaxTokens\n\tdefault:\n\t\treturn message.FinishReasonUnknown\n\t}\n}\n\nfunc (g *geminiClient) send(ctx context.Context, messages []message.Message, tools []tools.BaseTool) (*ProviderResponse, error) {\n\t// Convert messages\n\tgeminiMessages := g.convertMessages(messages)\n\n\tcfg := config.Get()\n\tif cfg.Debug {\n\t\tjsonData, _ := json.Marshal(geminiMessages)\n\t\tlogging.Debug(\"Prepared messages\", \"messages\", string(jsonData))\n\t}\n\n\thistory := geminiMessages[:len(geminiMessages)-1] // All but last message\n\tlastMsg := geminiMessages[len(geminiMessages)-1]\n\tconfig := &genai.GenerateContentConfig{\n\t\tMaxOutputTokens: int32(g.providerOptions.maxTokens),\n\t\tSystemInstruction: &genai.Content{\n\t\t\tParts: []*genai.Part{{Text: g.providerOptions.systemMessage}},\n\t\t},\n\t}\n\tif len(tools) > 0 {\n\t\tconfig.Tools = g.convertTools(tools)\n\t}\n\tchat, _ := g.client.Chats.Create(ctx, g.providerOptions.model.APIModel, config, history)\n\n\tattempts := 0\n\tfor {\n\t\tattempts++\n\t\tvar toolCalls []message.ToolCall\n\n\t\tvar lastMsgParts []genai.Part\n\t\tfor _, part := range lastMsg.Parts {\n\t\t\tlastMsgParts = append(lastMsgParts, *part)\n\t\t}\n\t\tresp, err := chat.SendMessage(ctx, lastMsgParts...)\n\t\t// If there is an error we are going to see if we can retry the call\n\t\tif err != nil {\n\t\t\tretry, after, retryErr := g.shouldRetry(attempts, err)\n\t\t\tif retryErr != nil {\n\t\t\t\treturn nil, retryErr\n\t\t\t}\n\t\t\tif retry {\n\t\t\t\tlogging.WarnPersist(fmt.Sprintf(\"Retrying due to rate limit... attempt %d of %d\", attempts, maxRetries), logging.PersistTimeArg, time.Millisecond*time.Duration(after+100))\n\t\t\t\tselect {\n\t\t\t\tcase <-ctx.Done():\n\t\t\t\t\treturn nil, ctx.Err()\n\t\t\t\tcase <-time.After(time.Duration(after) * time.Millisecond):\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn nil, retryErr\n\t\t}\n\n\t\tcontent := \"\"\n\n\t\tif len(resp.Candidates) > 0 && resp.Candidates[0].Content != nil {\n\t\t\tfor _, part := range resp.Candidates[0].Content.Parts {\n\t\t\t\tswitch {\n\t\t\t\tcase part.Text != \"\":\n\t\t\t\t\tcontent = string(part.Text)\n\t\t\t\tcase part.FunctionCall != nil:\n\t\t\t\t\tid := \"call_\" + uuid.New().String()\n\t\t\t\t\targs, _ := json.Marshal(part.FunctionCall.Args)\n\t\t\t\t\ttoolCalls = append(toolCalls, message.ToolCall{\n\t\t\t\t\t\tID: id,\n\t\t\t\t\t\tName: part.FunctionCall.Name,\n\t\t\t\t\t\tInput: string(args),\n\t\t\t\t\t\tType: \"function\",\n\t\t\t\t\t\tFinished: true,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tfinishReason := message.FinishReasonEndTurn\n\t\tif len(resp.Candidates) > 0 {\n\t\t\tfinishReason = g.finishReason(resp.Candidates[0].FinishReason)\n\t\t}\n\t\tif len(toolCalls) > 0 {\n\t\t\tfinishReason = message.FinishReasonToolUse\n\t\t}\n\n\t\treturn &ProviderResponse{\n\t\t\tContent: content,\n\t\t\tToolCalls: toolCalls,\n\t\t\tUsage: g.usage(resp),\n\t\t\tFinishReason: finishReason,\n\t\t}, nil\n\t}\n}\n\nfunc (g *geminiClient) stream(ctx context.Context, messages []message.Message, tools []tools.BaseTool) <-chan ProviderEvent {\n\t// Convert messages\n\tgeminiMessages := g.convertMessages(messages)\n\n\tcfg := config.Get()\n\tif cfg.Debug {\n\t\tjsonData, _ := json.Marshal(geminiMessages)\n\t\tlogging.Debug(\"Prepared messages\", \"messages\", string(jsonData))\n\t}\n\n\thistory := geminiMessages[:len(geminiMessages)-1] // All but last message\n\tlastMsg := geminiMessages[len(geminiMessages)-1]\n\tconfig := &genai.GenerateContentConfig{\n\t\tMaxOutputTokens: int32(g.providerOptions.maxTokens),\n\t\tSystemInstruction: &genai.Content{\n\t\t\tParts: []*genai.Part{{Text: g.providerOptions.systemMessage}},\n\t\t},\n\t}\n\tif len(tools) > 0 {\n\t\tconfig.Tools = g.convertTools(tools)\n\t}\n\tchat, _ := g.client.Chats.Create(ctx, g.providerOptions.model.APIModel, config, history)\n\n\tattempts := 0\n\teventChan := make(chan ProviderEvent)\n\n\tgo func() {\n\t\tdefer close(eventChan)\n\n\t\tfor {\n\t\t\tattempts++\n\n\t\t\tcurrentContent := \"\"\n\t\t\ttoolCalls := []message.ToolCall{}\n\t\t\tvar finalResp *genai.GenerateContentResponse\n\n\t\t\teventChan <- ProviderEvent{Type: EventContentStart}\n\n\t\t\tvar lastMsgParts []genai.Part\n\n\t\t\tfor _, part := range lastMsg.Parts {\n\t\t\t\tlastMsgParts = append(lastMsgParts, *part)\n\t\t\t}\n\t\t\tfor resp, err := range chat.SendMessageStream(ctx, lastMsgParts...) {\n\t\t\t\tif err != nil {\n\t\t\t\t\tretry, after, retryErr := g.shouldRetry(attempts, err)\n\t\t\t\t\tif retryErr != nil {\n\t\t\t\t\t\teventChan <- ProviderEvent{Type: EventError, Error: retryErr}\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\tif retry {\n\t\t\t\t\t\tlogging.WarnPersist(fmt.Sprintf(\"Retrying due to rate limit... attempt %d of %d\", attempts, maxRetries), logging.PersistTimeArg, time.Millisecond*time.Duration(after+100))\n\t\t\t\t\t\tselect {\n\t\t\t\t\t\tcase <-ctx.Done():\n\t\t\t\t\t\t\tif ctx.Err() != nil {\n\t\t\t\t\t\t\t\teventChan <- ProviderEvent{Type: EventError, Error: ctx.Err()}\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\treturn\n\t\t\t\t\t\tcase <-time.After(time.Duration(after) * time.Millisecond):\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\teventChan <- ProviderEvent{Type: EventError, Error: err}\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tfinalResp = resp\n\n\t\t\t\tif len(resp.Candidates) > 0 && resp.Candidates[0].Content != nil {\n\t\t\t\t\tfor _, part := range resp.Candidates[0].Content.Parts {\n\t\t\t\t\t\tswitch {\n\t\t\t\t\t\tcase part.Text != \"\":\n\t\t\t\t\t\t\tdelta := string(part.Text)\n\t\t\t\t\t\t\tif delta != \"\" {\n\t\t\t\t\t\t\t\teventChan <- ProviderEvent{\n\t\t\t\t\t\t\t\t\tType: EventContentDelta,\n\t\t\t\t\t\t\t\t\tContent: delta,\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tcurrentContent += delta\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\tcase part.FunctionCall != nil:\n\t\t\t\t\t\t\tid := \"call_\" + uuid.New().String()\n\t\t\t\t\t\t\targs, _ := json.Marshal(part.FunctionCall.Args)\n\t\t\t\t\t\t\tnewCall := message.ToolCall{\n\t\t\t\t\t\t\t\tID: id,\n\t\t\t\t\t\t\t\tName: part.FunctionCall.Name,\n\t\t\t\t\t\t\t\tInput: string(args),\n\t\t\t\t\t\t\t\tType: \"function\",\n\t\t\t\t\t\t\t\tFinished: true,\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tisNew := true\n\t\t\t\t\t\t\tfor _, existing := range toolCalls {\n\t\t\t\t\t\t\t\tif existing.Name == newCall.Name && existing.Input == newCall.Input {\n\t\t\t\t\t\t\t\t\tisNew = false\n\t\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif isNew {\n\t\t\t\t\t\t\t\ttoolCalls = append(toolCalls, newCall)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\teventChan <- ProviderEvent{Type: EventContentStop}\n\n\t\t\tif finalResp != nil {\n\n\t\t\t\tfinishReason := message.FinishReasonEndTurn\n\t\t\t\tif len(finalResp.Candidates) > 0 {\n\t\t\t\t\tfinishReason = g.finishReason(finalResp.Candidates[0].FinishReason)\n\t\t\t\t}\n\t\t\t\tif len(toolCalls) > 0 {\n\t\t\t\t\tfinishReason = message.FinishReasonToolUse\n\t\t\t\t}\n\t\t\t\teventChan <- ProviderEvent{\n\t\t\t\t\tType: EventComplete,\n\t\t\t\t\tResponse: &ProviderResponse{\n\t\t\t\t\t\tContent: currentContent,\n\t\t\t\t\t\tToolCalls: toolCalls,\n\t\t\t\t\t\tUsage: g.usage(finalResp),\n\t\t\t\t\t\tFinishReason: finishReason,\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\n\t\t}\n\t}()\n\n\treturn eventChan\n}\n\nfunc (g *geminiClient) shouldRetry(attempts int, err error) (bool, int64, error) {\n\t// Check if error is a rate limit error\n\tif attempts > maxRetries {\n\t\treturn false, 0, fmt.Errorf(\"maximum retry attempts reached for rate limit: %d retries\", maxRetries)\n\t}\n\n\t// Gemini doesn't have a standard error type we can check against\n\t// So we'll check the error message for rate limit indicators\n\tif errors.Is(err, io.EOF) {\n\t\treturn false, 0, err\n\t}\n\n\terrMsg := err.Error()\n\tisRateLimit := false\n\n\t// Check for common rate limit error messages\n\tif contains(errMsg, \"rate limit\", \"quota exceeded\", \"too many requests\") {\n\t\tisRateLimit = true\n\t}\n\n\tif !isRateLimit {\n\t\treturn false, 0, err\n\t}\n\n\t// Calculate backoff with jitter\n\tbackoffMs := 2000 * (1 << (attempts - 1))\n\tjitterMs := int(float64(backoffMs) * 0.2)\n\tretryMs := backoffMs + jitterMs\n\n\treturn true, int64(retryMs), nil\n}\n\nfunc (g *geminiClient) toolCalls(resp *genai.GenerateContentResponse) []message.ToolCall {\n\tvar toolCalls []message.ToolCall\n\n\tif len(resp.Candidates) > 0 && resp.Candidates[0].Content != nil {\n\t\tfor _, part := range resp.Candidates[0].Content.Parts {\n\t\t\tif part.FunctionCall != nil {\n\t\t\t\tid := \"call_\" + uuid.New().String()\n\t\t\t\targs, _ := json.Marshal(part.FunctionCall.Args)\n\t\t\t\ttoolCalls = append(toolCalls, message.ToolCall{\n\t\t\t\t\tID: id,\n\t\t\t\t\tName: part.FunctionCall.Name,\n\t\t\t\t\tInput: string(args),\n\t\t\t\t\tType: \"function\",\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\t}\n\n\treturn toolCalls\n}\n\nfunc (g *geminiClient) usage(resp *genai.GenerateContentResponse) TokenUsage {\n\tif resp == nil || resp.UsageMetadata == nil {\n\t\treturn TokenUsage{}\n\t}\n\n\treturn TokenUsage{\n\t\tInputTokens: int64(resp.UsageMetadata.PromptTokenCount),\n\t\tOutputTokens: int64(resp.UsageMetadata.CandidatesTokenCount),\n\t\tCacheCreationTokens: 0, // Not directly provided by Gemini\n\t\tCacheReadTokens: int64(resp.UsageMetadata.CachedContentTokenCount),\n\t}\n}\n\nfunc WithGeminiDisableCache() GeminiOption {\n\treturn func(options *geminiOptions) {\n\t\toptions.disableCache = true\n\t}\n}\n\n// Helper functions\nfunc parseJsonToMap(jsonStr string) (map[string]interface{}, error) {\n\tvar result map[string]interface{}\n\terr := json.Unmarshal([]byte(jsonStr), &result)\n\treturn result, err\n}\n\nfunc convertSchemaProperties(parameters map[string]interface{}) map[string]*genai.Schema {\n\tproperties := make(map[string]*genai.Schema)\n\n\tfor name, param := range parameters {\n\t\tproperties[name] = convertToSchema(param)\n\t}\n\n\treturn properties\n}\n\nfunc convertToSchema(param interface{}) *genai.Schema {\n\tschema := &genai.Schema{Type: genai.TypeString}\n\n\tparamMap, ok := param.(map[string]interface{})\n\tif !ok {\n\t\treturn schema\n\t}\n\n\tif desc, ok := paramMap[\"description\"].(string); ok {\n\t\tschema.Description = desc\n\t}\n\n\ttypeVal, hasType := paramMap[\"type\"]\n\tif !hasType {\n\t\treturn schema\n\t}\n\n\ttypeStr, ok := typeVal.(string)\n\tif !ok {\n\t\treturn schema\n\t}\n\n\tschema.Type = mapJSONTypeToGenAI(typeStr)\n\n\tswitch typeStr {\n\tcase \"array\":\n\t\tschema.Items = processArrayItems(paramMap)\n\tcase \"object\":\n\t\tif props, ok := paramMap[\"properties\"].(map[string]interface{}); ok {\n\t\t\tschema.Properties = convertSchemaProperties(props)\n\t\t}\n\t}\n\n\treturn schema\n}\n\nfunc processArrayItems(paramMap map[string]interface{}) *genai.Schema {\n\titems, ok := paramMap[\"items\"].(map[string]interface{})\n\tif !ok {\n\t\treturn nil\n\t}\n\n\treturn convertToSchema(items)\n}\n\nfunc mapJSONTypeToGenAI(jsonType string) genai.Type {\n\tswitch jsonType {\n\tcase \"string\":\n\t\treturn genai.TypeString\n\tcase \"number\":\n\t\treturn genai.TypeNumber\n\tcase \"integer\":\n\t\treturn genai.TypeInteger\n\tcase \"boolean\":\n\t\treturn genai.TypeBoolean\n\tcase \"array\":\n\t\treturn genai.TypeArray\n\tcase \"object\":\n\t\treturn genai.TypeObject\n\tdefault:\n\t\treturn genai.TypeString // Default to string for unknown types\n\t}\n}\n\nfunc contains(s string, substrs ...string) bool {\n\tfor _, substr := range substrs {\n\t\tif strings.Contains(strings.ToLower(s), strings.ToLower(substr)) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n"], ["/opencode/internal/tui/components/util/simple-list.go", "package utilComponents\n\nimport (\n\t\"github.com/charmbracelet/bubbles/key\"\n\ttea \"github.com/charmbracelet/bubbletea\"\n\t\"github.com/charmbracelet/lipgloss\"\n\t\"github.com/opencode-ai/opencode/internal/tui/layout\"\n\t\"github.com/opencode-ai/opencode/internal/tui/styles\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n)\n\ntype SimpleListItem interface {\n\tRender(selected bool, width int) string\n}\n\ntype SimpleList[T SimpleListItem] interface {\n\ttea.Model\n\tlayout.Bindings\n\tSetMaxWidth(maxWidth int)\n\tGetSelectedItem() (item T, idx int)\n\tSetItems(items []T)\n\tGetItems() []T\n}\n\ntype simpleListCmp[T SimpleListItem] struct {\n\tfallbackMsg string\n\titems []T\n\tselectedIdx int\n\tmaxWidth int\n\tmaxVisibleItems int\n\tuseAlphaNumericKeys bool\n\twidth int\n\theight int\n}\n\ntype simpleListKeyMap struct {\n\tUp key.Binding\n\tDown key.Binding\n\tUpAlpha key.Binding\n\tDownAlpha key.Binding\n}\n\nvar simpleListKeys = simpleListKeyMap{\n\tUp: key.NewBinding(\n\t\tkey.WithKeys(\"up\"),\n\t\tkey.WithHelp(\"↑\", \"previous list item\"),\n\t),\n\tDown: key.NewBinding(\n\t\tkey.WithKeys(\"down\"),\n\t\tkey.WithHelp(\"↓\", \"next list item\"),\n\t),\n\tUpAlpha: key.NewBinding(\n\t\tkey.WithKeys(\"k\"),\n\t\tkey.WithHelp(\"k\", \"previous list item\"),\n\t),\n\tDownAlpha: key.NewBinding(\n\t\tkey.WithKeys(\"j\"),\n\t\tkey.WithHelp(\"j\", \"next list item\"),\n\t),\n}\n\nfunc (c *simpleListCmp[T]) Init() tea.Cmd {\n\treturn nil\n}\n\nfunc (c *simpleListCmp[T]) Update(msg tea.Msg) (tea.Model, tea.Cmd) {\n\tswitch msg := msg.(type) {\n\tcase tea.KeyMsg:\n\t\tswitch {\n\t\tcase key.Matches(msg, simpleListKeys.Up) || (c.useAlphaNumericKeys && key.Matches(msg, simpleListKeys.UpAlpha)):\n\t\t\tif c.selectedIdx > 0 {\n\t\t\t\tc.selectedIdx--\n\t\t\t}\n\t\t\treturn c, nil\n\t\tcase key.Matches(msg, simpleListKeys.Down) || (c.useAlphaNumericKeys && key.Matches(msg, simpleListKeys.DownAlpha)):\n\t\t\tif c.selectedIdx < len(c.items)-1 {\n\t\t\t\tc.selectedIdx++\n\t\t\t}\n\t\t\treturn c, nil\n\t\t}\n\t}\n\n\treturn c, nil\n}\n\nfunc (c *simpleListCmp[T]) BindingKeys() []key.Binding {\n\treturn layout.KeyMapToSlice(simpleListKeys)\n}\n\nfunc (c *simpleListCmp[T]) GetSelectedItem() (T, int) {\n\tif len(c.items) > 0 {\n\t\treturn c.items[c.selectedIdx], c.selectedIdx\n\t}\n\n\tvar zero T\n\treturn zero, -1\n}\n\nfunc (c *simpleListCmp[T]) SetItems(items []T) {\n\tc.selectedIdx = 0\n\tc.items = items\n}\n\nfunc (c *simpleListCmp[T]) GetItems() []T {\n\treturn c.items\n}\n\nfunc (c *simpleListCmp[T]) SetMaxWidth(width int) {\n\tc.maxWidth = width\n}\n\nfunc (c *simpleListCmp[T]) View() string {\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\n\titems := c.items\n\tmaxWidth := c.maxWidth\n\tmaxVisibleItems := min(c.maxVisibleItems, len(items))\n\tstartIdx := 0\n\n\tif len(items) <= 0 {\n\t\treturn baseStyle.\n\t\t\tBackground(t.Background()).\n\t\t\tPadding(0, 1).\n\t\t\tWidth(maxWidth).\n\t\t\tRender(c.fallbackMsg)\n\t}\n\n\tif len(items) > maxVisibleItems {\n\t\thalfVisible := maxVisibleItems / 2\n\t\tif c.selectedIdx >= halfVisible && c.selectedIdx < len(items)-halfVisible {\n\t\t\tstartIdx = c.selectedIdx - halfVisible\n\t\t} else if c.selectedIdx >= len(items)-halfVisible {\n\t\t\tstartIdx = len(items) - maxVisibleItems\n\t\t}\n\t}\n\n\tendIdx := min(startIdx+maxVisibleItems, len(items))\n\n\tlistItems := make([]string, 0, maxVisibleItems)\n\n\tfor i := startIdx; i < endIdx; i++ {\n\t\titem := items[i]\n\t\ttitle := item.Render(i == c.selectedIdx, maxWidth)\n\t\tlistItems = append(listItems, title)\n\t}\n\n\treturn lipgloss.JoinVertical(lipgloss.Left, listItems...)\n}\n\nfunc NewSimpleList[T SimpleListItem](items []T, maxVisibleItems int, fallbackMsg string, useAlphaNumericKeys bool) SimpleList[T] {\n\treturn &simpleListCmp[T]{\n\t\tfallbackMsg: fallbackMsg,\n\t\titems: items,\n\t\tmaxVisibleItems: maxVisibleItems,\n\t\tuseAlphaNumericKeys: useAlphaNumericKeys,\n\t\tselectedIdx: 0,\n\t}\n}\n"], ["/opencode/internal/llm/provider/copilot.go", "package provider\n\nimport (\n\t\"context\"\n\t\"encoding/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"net/http\"\n\t\"os\"\n\t\"time\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n\t\"github.com/openai/openai-go/shared\"\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/llm/models\"\n\ttoolsPkg \"github.com/opencode-ai/opencode/internal/llm/tools\"\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n\t\"github.com/opencode-ai/opencode/internal/message\"\n)\n\ntype copilotOptions struct {\n\treasoningEffort string\n\textraHeaders map[string]string\n\tbearerToken string\n}\n\ntype CopilotOption func(*copilotOptions)\n\ntype copilotClient struct {\n\tproviderOptions providerClientOptions\n\toptions copilotOptions\n\tclient openai.Client\n\thttpClient *http.Client\n}\n\ntype CopilotClient ProviderClient\n\n// CopilotTokenResponse represents the response from GitHub's token exchange endpoint\ntype CopilotTokenResponse struct {\n\tToken string `json:\"token\"`\n\tExpiresAt int64 `json:\"expires_at\"`\n}\n\nfunc (c *copilotClient) isAnthropicModel() bool {\n\tfor _, modelId := range models.CopilotAnthropicModels {\n\t\tif c.providerOptions.model.ID == modelId {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n// loadGitHubToken loads the GitHub OAuth token from the standard GitHub CLI/Copilot locations\n\n// exchangeGitHubToken exchanges a GitHub token for a Copilot bearer token\nfunc (c *copilotClient) exchangeGitHubToken(githubToken string) (string, error) {\n\treq, err := http.NewRequest(\"GET\", \"https://api.github.com/copilot_internal/v2/token\", nil)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed to create token exchange request: %w\", err)\n\t}\n\n\treq.Header.Set(\"Authorization\", \"Token \"+githubToken)\n\treq.Header.Set(\"User-Agent\", \"OpenCode/1.0\")\n\n\tresp, err := c.httpClient.Do(req)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed to exchange GitHub token: %w\", err)\n\t}\n\tdefer resp.Body.Close()\n\n\tif resp.StatusCode != http.StatusOK {\n\t\tbody, _ := io.ReadAll(resp.Body)\n\t\treturn \"\", fmt.Errorf(\"token exchange failed with status %d: %s\", resp.StatusCode, string(body))\n\t}\n\n\tvar tokenResp CopilotTokenResponse\n\tif err := json.NewDecoder(resp.Body).Decode(&tokenResp); err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed to decode token response: %w\", err)\n\t}\n\n\treturn tokenResp.Token, nil\n}\n\nfunc newCopilotClient(opts providerClientOptions) CopilotClient {\n\tcopilotOpts := copilotOptions{\n\t\treasoningEffort: \"medium\",\n\t}\n\t// Apply copilot-specific options\n\tfor _, o := range opts.copilotOptions {\n\t\to(&copilotOpts)\n\t}\n\n\t// Create HTTP client for token exchange\n\thttpClient := &http.Client{\n\t\tTimeout: 30 * time.Second,\n\t}\n\n\tvar bearerToken string\n\n\t// If bearer token is already provided, use it\n\tif copilotOpts.bearerToken != \"\" {\n\t\tbearerToken = copilotOpts.bearerToken\n\t} else {\n\t\t// Try to get GitHub token from multiple sources\n\t\tvar githubToken string\n\n\t\t// 1. Environment variable\n\t\tgithubToken = os.Getenv(\"GITHUB_TOKEN\")\n\n\t\t// 2. API key from options\n\t\tif githubToken == \"\" {\n\t\t\tgithubToken = opts.apiKey\n\t\t}\n\n\t\t// 3. Standard GitHub CLI/Copilot locations\n\t\tif githubToken == \"\" {\n\t\t\tvar err error\n\t\t\tgithubToken, err = config.LoadGitHubToken()\n\t\t\tif err != nil {\n\t\t\t\tlogging.Debug(\"Failed to load GitHub token from standard locations\", \"error\", err)\n\t\t\t}\n\t\t}\n\n\t\tif githubToken == \"\" {\n\t\t\tlogging.Error(\"GitHub token is required for Copilot provider. Set GITHUB_TOKEN environment variable, configure it in opencode.json, or ensure GitHub CLI/Copilot is properly authenticated.\")\n\t\t\treturn &copilotClient{\n\t\t\t\tproviderOptions: opts,\n\t\t\t\toptions: copilotOpts,\n\t\t\t\thttpClient: httpClient,\n\t\t\t}\n\t\t}\n\n\t\t// Create a temporary client for token exchange\n\t\ttempClient := &copilotClient{\n\t\t\tproviderOptions: opts,\n\t\t\toptions: copilotOpts,\n\t\t\thttpClient: httpClient,\n\t\t}\n\n\t\t// Exchange GitHub token for bearer token\n\t\tvar err error\n\t\tbearerToken, err = tempClient.exchangeGitHubToken(githubToken)\n\t\tif err != nil {\n\t\t\tlogging.Error(\"Failed to exchange GitHub token for Copilot bearer token\", \"error\", err)\n\t\t\treturn &copilotClient{\n\t\t\t\tproviderOptions: opts,\n\t\t\t\toptions: copilotOpts,\n\t\t\t\thttpClient: httpClient,\n\t\t\t}\n\t\t}\n\t}\n\n\tcopilotOpts.bearerToken = bearerToken\n\n\t// GitHub Copilot API base URL\n\tbaseURL := \"https://api.githubcopilot.com\"\n\n\topenaiClientOptions := []option.RequestOption{\n\t\toption.WithBaseURL(baseURL),\n\t\toption.WithAPIKey(bearerToken), // Use bearer token as API key\n\t}\n\n\t// Add GitHub Copilot specific headers\n\topenaiClientOptions = append(openaiClientOptions,\n\t\toption.WithHeader(\"Editor-Version\", \"OpenCode/1.0\"),\n\t\toption.WithHeader(\"Editor-Plugin-Version\", \"OpenCode/1.0\"),\n\t\toption.WithHeader(\"Copilot-Integration-Id\", \"vscode-chat\"),\n\t)\n\n\t// Add any extra headers\n\tif copilotOpts.extraHeaders != nil {\n\t\tfor key, value := range copilotOpts.extraHeaders {\n\t\t\topenaiClientOptions = append(openaiClientOptions, option.WithHeader(key, value))\n\t\t}\n\t}\n\n\tclient := openai.NewClient(openaiClientOptions...)\n\t// logging.Debug(\"Copilot client created\", \"opts\", opts, \"copilotOpts\", copilotOpts, \"model\", opts.model)\n\treturn &copilotClient{\n\t\tproviderOptions: opts,\n\t\toptions: copilotOpts,\n\t\tclient: client,\n\t\thttpClient: httpClient,\n\t}\n}\n\nfunc (c *copilotClient) convertMessages(messages []message.Message) (copilotMessages []openai.ChatCompletionMessageParamUnion) {\n\t// Add system message first\n\tcopilotMessages = append(copilotMessages, openai.SystemMessage(c.providerOptions.systemMessage))\n\n\tfor _, msg := range messages {\n\t\tswitch msg.Role {\n\t\tcase message.User:\n\t\t\tvar content []openai.ChatCompletionContentPartUnionParam\n\t\t\ttextBlock := openai.ChatCompletionContentPartTextParam{Text: msg.Content().String()}\n\t\t\tcontent = append(content, openai.ChatCompletionContentPartUnionParam{OfText: &textBlock})\n\n\t\t\tfor _, binaryContent := range msg.BinaryContent() {\n\t\t\t\timageURL := openai.ChatCompletionContentPartImageImageURLParam{URL: binaryContent.String(models.ProviderCopilot)}\n\t\t\t\timageBlock := openai.ChatCompletionContentPartImageParam{ImageURL: imageURL}\n\t\t\t\tcontent = append(content, openai.ChatCompletionContentPartUnionParam{OfImageURL: &imageBlock})\n\t\t\t}\n\n\t\t\tcopilotMessages = append(copilotMessages, openai.UserMessage(content))\n\n\t\tcase message.Assistant:\n\t\t\tassistantMsg := openai.ChatCompletionAssistantMessageParam{\n\t\t\t\tRole: \"assistant\",\n\t\t\t}\n\n\t\t\tif msg.Content().String() != \"\" {\n\t\t\t\tassistantMsg.Content = openai.ChatCompletionAssistantMessageParamContentUnion{\n\t\t\t\t\tOfString: openai.String(msg.Content().String()),\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif len(msg.ToolCalls()) > 0 {\n\t\t\t\tassistantMsg.ToolCalls = make([]openai.ChatCompletionMessageToolCallParam, len(msg.ToolCalls()))\n\t\t\t\tfor i, call := range msg.ToolCalls() {\n\t\t\t\t\tassistantMsg.ToolCalls[i] = openai.ChatCompletionMessageToolCallParam{\n\t\t\t\t\t\tID: call.ID,\n\t\t\t\t\t\tType: \"function\",\n\t\t\t\t\t\tFunction: openai.ChatCompletionMessageToolCallFunctionParam{\n\t\t\t\t\t\t\tName: call.Name,\n\t\t\t\t\t\t\tArguments: call.Input,\n\t\t\t\t\t\t},\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tcopilotMessages = append(copilotMessages, openai.ChatCompletionMessageParamUnion{\n\t\t\t\tOfAssistant: &assistantMsg,\n\t\t\t})\n\n\t\tcase message.Tool:\n\t\t\tfor _, result := range msg.ToolResults() {\n\t\t\t\tcopilotMessages = append(copilotMessages,\n\t\t\t\t\topenai.ToolMessage(result.Content, result.ToolCallID),\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn\n}\n\nfunc (c *copilotClient) convertTools(tools []toolsPkg.BaseTool) []openai.ChatCompletionToolParam {\n\tcopilotTools := make([]openai.ChatCompletionToolParam, len(tools))\n\n\tfor i, tool := range tools {\n\t\tinfo := tool.Info()\n\t\tcopilotTools[i] = openai.ChatCompletionToolParam{\n\t\t\tFunction: openai.FunctionDefinitionParam{\n\t\t\t\tName: info.Name,\n\t\t\t\tDescription: openai.String(info.Description),\n\t\t\t\tParameters: openai.FunctionParameters{\n\t\t\t\t\t\"type\": \"object\",\n\t\t\t\t\t\"properties\": info.Parameters,\n\t\t\t\t\t\"required\": info.Required,\n\t\t\t\t},\n\t\t\t},\n\t\t}\n\t}\n\n\treturn copilotTools\n}\n\nfunc (c *copilotClient) finishReason(reason string) message.FinishReason {\n\tswitch reason {\n\tcase \"stop\":\n\t\treturn message.FinishReasonEndTurn\n\tcase \"length\":\n\t\treturn message.FinishReasonMaxTokens\n\tcase \"tool_calls\":\n\t\treturn message.FinishReasonToolUse\n\tdefault:\n\t\treturn message.FinishReasonUnknown\n\t}\n}\n\nfunc (c *copilotClient) preparedParams(messages []openai.ChatCompletionMessageParamUnion, tools []openai.ChatCompletionToolParam) openai.ChatCompletionNewParams {\n\tparams := openai.ChatCompletionNewParams{\n\t\tModel: openai.ChatModel(c.providerOptions.model.APIModel),\n\t\tMessages: messages,\n\t\tTools: tools,\n\t}\n\n\tif c.providerOptions.model.CanReason == true {\n\t\tparams.MaxCompletionTokens = openai.Int(c.providerOptions.maxTokens)\n\t\tswitch c.options.reasoningEffort {\n\t\tcase \"low\":\n\t\t\tparams.ReasoningEffort = shared.ReasoningEffortLow\n\t\tcase \"medium\":\n\t\t\tparams.ReasoningEffort = shared.ReasoningEffortMedium\n\t\tcase \"high\":\n\t\t\tparams.ReasoningEffort = shared.ReasoningEffortHigh\n\t\tdefault:\n\t\t\tparams.ReasoningEffort = shared.ReasoningEffortMedium\n\t\t}\n\t} else {\n\t\tparams.MaxTokens = openai.Int(c.providerOptions.maxTokens)\n\t}\n\n\treturn params\n}\n\nfunc (c *copilotClient) send(ctx context.Context, messages []message.Message, tools []toolsPkg.BaseTool) (response *ProviderResponse, err error) {\n\tparams := c.preparedParams(c.convertMessages(messages), c.convertTools(tools))\n\tcfg := config.Get()\n\tvar sessionId string\n\trequestSeqId := (len(messages) + 1) / 2\n\tif cfg.Debug {\n\t\t// jsonData, _ := json.Marshal(params)\n\t\t// logging.Debug(\"Prepared messages\", \"messages\", string(jsonData))\n\t\tif sid, ok := ctx.Value(toolsPkg.SessionIDContextKey).(string); ok {\n\t\t\tsessionId = sid\n\t\t}\n\t\tjsonData, _ := json.Marshal(params)\n\t\tif sessionId != \"\" {\n\t\t\tfilepath := logging.WriteRequestMessageJson(sessionId, requestSeqId, params)\n\t\t\tlogging.Debug(\"Prepared messages\", \"filepath\", filepath)\n\t\t} else {\n\t\t\tlogging.Debug(\"Prepared messages\", \"messages\", string(jsonData))\n\t\t}\n\t}\n\n\tattempts := 0\n\tfor {\n\t\tattempts++\n\t\tcopilotResponse, err := c.client.Chat.Completions.New(\n\t\t\tctx,\n\t\t\tparams,\n\t\t)\n\n\t\t// If there is an error we are going to see if we can retry the call\n\t\tif err != nil {\n\t\t\tretry, after, retryErr := c.shouldRetry(attempts, err)\n\t\t\tif retryErr != nil {\n\t\t\t\treturn nil, retryErr\n\t\t\t}\n\t\t\tif retry {\n\t\t\t\tlogging.WarnPersist(fmt.Sprintf(\"Retrying due to rate limit... attempt %d of %d\", attempts, maxRetries), logging.PersistTimeArg, time.Millisecond*time.Duration(after+100))\n\t\t\t\tselect {\n\t\t\t\tcase <-ctx.Done():\n\t\t\t\t\treturn nil, ctx.Err()\n\t\t\t\tcase <-time.After(time.Duration(after) * time.Millisecond):\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn nil, retryErr\n\t\t}\n\n\t\tcontent := \"\"\n\t\tif copilotResponse.Choices[0].Message.Content != \"\" {\n\t\t\tcontent = copilotResponse.Choices[0].Message.Content\n\t\t}\n\n\t\ttoolCalls := c.toolCalls(*copilotResponse)\n\t\tfinishReason := c.finishReason(string(copilotResponse.Choices[0].FinishReason))\n\n\t\tif len(toolCalls) > 0 {\n\t\t\tfinishReason = message.FinishReasonToolUse\n\t\t}\n\n\t\treturn &ProviderResponse{\n\t\t\tContent: content,\n\t\t\tToolCalls: toolCalls,\n\t\t\tUsage: c.usage(*copilotResponse),\n\t\t\tFinishReason: finishReason,\n\t\t}, nil\n\t}\n}\n\nfunc (c *copilotClient) stream(ctx context.Context, messages []message.Message, tools []toolsPkg.BaseTool) <-chan ProviderEvent {\n\tparams := c.preparedParams(c.convertMessages(messages), c.convertTools(tools))\n\tparams.StreamOptions = openai.ChatCompletionStreamOptionsParam{\n\t\tIncludeUsage: openai.Bool(true),\n\t}\n\n\tcfg := config.Get()\n\tvar sessionId string\n\trequestSeqId := (len(messages) + 1) / 2\n\tif cfg.Debug {\n\t\tif sid, ok := ctx.Value(toolsPkg.SessionIDContextKey).(string); ok {\n\t\t\tsessionId = sid\n\t\t}\n\t\tjsonData, _ := json.Marshal(params)\n\t\tif sessionId != \"\" {\n\t\t\tfilepath := logging.WriteRequestMessageJson(sessionId, requestSeqId, params)\n\t\t\tlogging.Debug(\"Prepared messages\", \"filepath\", filepath)\n\t\t} else {\n\t\t\tlogging.Debug(\"Prepared messages\", \"messages\", string(jsonData))\n\t\t}\n\n\t}\n\n\tattempts := 0\n\teventChan := make(chan ProviderEvent)\n\n\tgo func() {\n\t\tfor {\n\t\t\tattempts++\n\t\t\tcopilotStream := c.client.Chat.Completions.NewStreaming(\n\t\t\t\tctx,\n\t\t\t\tparams,\n\t\t\t)\n\n\t\t\tacc := openai.ChatCompletionAccumulator{}\n\t\t\tcurrentContent := \"\"\n\t\t\ttoolCalls := make([]message.ToolCall, 0)\n\n\t\t\tvar currentToolCallId string\n\t\t\tvar currentToolCall openai.ChatCompletionMessageToolCall\n\t\t\tvar msgToolCalls []openai.ChatCompletionMessageToolCall\n\t\t\tfor copilotStream.Next() {\n\t\t\t\tchunk := copilotStream.Current()\n\t\t\t\tacc.AddChunk(chunk)\n\n\t\t\t\tif cfg.Debug {\n\t\t\t\t\tlogging.AppendToStreamSessionLogJson(sessionId, requestSeqId, chunk)\n\t\t\t\t}\n\n\t\t\t\tfor _, choice := range chunk.Choices {\n\t\t\t\t\tif choice.Delta.Content != \"\" {\n\t\t\t\t\t\teventChan <- ProviderEvent{\n\t\t\t\t\t\t\tType: EventContentDelta,\n\t\t\t\t\t\t\tContent: choice.Delta.Content,\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcurrentContent += choice.Delta.Content\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif c.isAnthropicModel() {\n\t\t\t\t\t// Monkeypatch adapter for Sonnet-4 multi-tool use\n\t\t\t\t\tfor _, choice := range chunk.Choices {\n\t\t\t\t\t\tif choice.Delta.ToolCalls != nil && len(choice.Delta.ToolCalls) > 0 {\n\t\t\t\t\t\t\ttoolCall := choice.Delta.ToolCalls[0]\n\t\t\t\t\t\t\t// Detect tool use start\n\t\t\t\t\t\t\tif currentToolCallId == \"\" {\n\t\t\t\t\t\t\t\tif toolCall.ID != \"\" {\n\t\t\t\t\t\t\t\t\tcurrentToolCallId = toolCall.ID\n\t\t\t\t\t\t\t\t\tcurrentToolCall = openai.ChatCompletionMessageToolCall{\n\t\t\t\t\t\t\t\t\t\tID: toolCall.ID,\n\t\t\t\t\t\t\t\t\t\tType: \"function\",\n\t\t\t\t\t\t\t\t\t\tFunction: openai.ChatCompletionMessageToolCallFunction{\n\t\t\t\t\t\t\t\t\t\t\tName: toolCall.Function.Name,\n\t\t\t\t\t\t\t\t\t\t\tArguments: toolCall.Function.Arguments,\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t// Delta tool use\n\t\t\t\t\t\t\t\tif toolCall.ID == \"\" {\n\t\t\t\t\t\t\t\t\tcurrentToolCall.Function.Arguments += toolCall.Function.Arguments\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t// Detect new tool use\n\t\t\t\t\t\t\t\t\tif toolCall.ID != currentToolCallId {\n\t\t\t\t\t\t\t\t\t\tmsgToolCalls = append(msgToolCalls, currentToolCall)\n\t\t\t\t\t\t\t\t\t\tcurrentToolCallId = toolCall.ID\n\t\t\t\t\t\t\t\t\t\tcurrentToolCall = openai.ChatCompletionMessageToolCall{\n\t\t\t\t\t\t\t\t\t\t\tID: toolCall.ID,\n\t\t\t\t\t\t\t\t\t\t\tType: \"function\",\n\t\t\t\t\t\t\t\t\t\t\tFunction: openai.ChatCompletionMessageToolCallFunction{\n\t\t\t\t\t\t\t\t\t\t\t\tName: toolCall.Function.Name,\n\t\t\t\t\t\t\t\t\t\t\t\tArguments: toolCall.Function.Arguments,\n\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif choice.FinishReason == \"tool_calls\" {\n\t\t\t\t\t\t\tmsgToolCalls = append(msgToolCalls, currentToolCall)\n\t\t\t\t\t\t\tacc.ChatCompletion.Choices[0].Message.ToolCalls = msgToolCalls\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\terr := copilotStream.Err()\n\t\t\tif err == nil || errors.Is(err, io.EOF) {\n\t\t\t\tif cfg.Debug {\n\t\t\t\t\trespFilepath := logging.WriteChatResponseJson(sessionId, requestSeqId, acc.ChatCompletion)\n\t\t\t\t\tlogging.Debug(\"Chat completion response\", \"filepath\", respFilepath)\n\t\t\t\t}\n\t\t\t\t// Stream completed successfully\n\t\t\t\tfinishReason := c.finishReason(string(acc.ChatCompletion.Choices[0].FinishReason))\n\t\t\t\tif len(acc.ChatCompletion.Choices[0].Message.ToolCalls) > 0 {\n\t\t\t\t\ttoolCalls = append(toolCalls, c.toolCalls(acc.ChatCompletion)...)\n\t\t\t\t}\n\t\t\t\tif len(toolCalls) > 0 {\n\t\t\t\t\tfinishReason = message.FinishReasonToolUse\n\t\t\t\t}\n\n\t\t\t\teventChan <- ProviderEvent{\n\t\t\t\t\tType: EventComplete,\n\t\t\t\t\tResponse: &ProviderResponse{\n\t\t\t\t\t\tContent: currentContent,\n\t\t\t\t\t\tToolCalls: toolCalls,\n\t\t\t\t\t\tUsage: c.usage(acc.ChatCompletion),\n\t\t\t\t\t\tFinishReason: finishReason,\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t\tclose(eventChan)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\t// If there is an error we are going to see if we can retry the call\n\t\t\tretry, after, retryErr := c.shouldRetry(attempts, err)\n\t\t\tif retryErr != nil {\n\t\t\t\teventChan <- ProviderEvent{Type: EventError, Error: retryErr}\n\t\t\t\tclose(eventChan)\n\t\t\t\treturn\n\t\t\t}\n\t\t\t// shouldRetry is not catching the max retries...\n\t\t\t// TODO: Figure out why\n\t\t\tif attempts > maxRetries {\n\t\t\t\tlogging.Warn(\"Maximum retry attempts reached for rate limit\", \"attempts\", attempts, \"max_retries\", maxRetries)\n\t\t\t\tretry = false\n\t\t\t}\n\t\t\tif retry {\n\t\t\t\tlogging.WarnPersist(fmt.Sprintf(\"Retrying due to rate limit... attempt %d of %d (paused for %d ms)\", attempts, maxRetries, after), logging.PersistTimeArg, time.Millisecond*time.Duration(after+100))\n\t\t\t\tselect {\n\t\t\t\tcase <-ctx.Done():\n\t\t\t\t\t// context cancelled\n\t\t\t\t\tif ctx.Err() == nil {\n\t\t\t\t\t\teventChan <- ProviderEvent{Type: EventError, Error: ctx.Err()}\n\t\t\t\t\t}\n\t\t\t\t\tclose(eventChan)\n\t\t\t\t\treturn\n\t\t\t\tcase <-time.After(time.Duration(after) * time.Millisecond):\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t\teventChan <- ProviderEvent{Type: EventError, Error: retryErr}\n\t\t\tclose(eventChan)\n\t\t\treturn\n\t\t}\n\t}()\n\n\treturn eventChan\n}\n\nfunc (c *copilotClient) shouldRetry(attempts int, err error) (bool, int64, error) {\n\tvar apierr *openai.Error\n\tif !errors.As(err, &apierr) {\n\t\treturn false, 0, err\n\t}\n\n\t// Check for token expiration (401 Unauthorized)\n\tif apierr.StatusCode == 401 {\n\t\t// Try to refresh the bearer token\n\t\tvar githubToken string\n\n\t\t// 1. Environment variable\n\t\tgithubToken = os.Getenv(\"GITHUB_TOKEN\")\n\n\t\t// 2. API key from options\n\t\tif githubToken == \"\" {\n\t\t\tgithubToken = c.providerOptions.apiKey\n\t\t}\n\n\t\t// 3. Standard GitHub CLI/Copilot locations\n\t\tif githubToken == \"\" {\n\t\t\tvar err error\n\t\t\tgithubToken, err = config.LoadGitHubToken()\n\t\t\tif err != nil {\n\t\t\t\tlogging.Debug(\"Failed to load GitHub token from standard locations during retry\", \"error\", err)\n\t\t\t}\n\t\t}\n\n\t\tif githubToken != \"\" {\n\t\t\tnewBearerToken, tokenErr := c.exchangeGitHubToken(githubToken)\n\t\t\tif tokenErr == nil {\n\t\t\t\tc.options.bearerToken = newBearerToken\n\t\t\t\t// Update the client with the new token\n\t\t\t\t// Note: This is a simplified approach. In a production system,\n\t\t\t\t// you might want to recreate the entire client with the new token\n\t\t\t\tlogging.Info(\"Refreshed Copilot bearer token\")\n\t\t\t\treturn true, 1000, nil // Retry immediately with new token\n\t\t\t}\n\t\t\tlogging.Error(\"Failed to refresh Copilot bearer token\", \"error\", tokenErr)\n\t\t}\n\t\treturn false, 0, fmt.Errorf(\"authentication failed: %w\", err)\n\t}\n\tlogging.Debug(\"Copilot API Error\", \"status\", apierr.StatusCode, \"headers\", apierr.Response.Header, \"body\", apierr.RawJSON())\n\n\tif apierr.StatusCode != 429 && apierr.StatusCode != 500 {\n\t\treturn false, 0, err\n\t}\n\n\tif apierr.StatusCode == 500 {\n\t\tlogging.Warn(\"Copilot API returned 500 error, retrying\", \"error\", err)\n\t}\n\n\tif attempts > maxRetries {\n\t\treturn false, 0, fmt.Errorf(\"maximum retry attempts reached for rate limit: %d retries\", maxRetries)\n\t}\n\n\tretryMs := 0\n\tretryAfterValues := apierr.Response.Header.Values(\"Retry-After\")\n\n\tbackoffMs := 2000 * (1 << (attempts - 1))\n\tjitterMs := int(float64(backoffMs) * 0.2)\n\tretryMs = backoffMs + jitterMs\n\tif len(retryAfterValues) > 0 {\n\t\tif _, err := fmt.Sscanf(retryAfterValues[0], \"%d\", &retryMs); err == nil {\n\t\t\tretryMs = retryMs * 1000\n\t\t}\n\t}\n\treturn true, int64(retryMs), nil\n}\n\nfunc (c *copilotClient) toolCalls(completion openai.ChatCompletion) []message.ToolCall {\n\tvar toolCalls []message.ToolCall\n\n\tif len(completion.Choices) > 0 && len(completion.Choices[0].Message.ToolCalls) > 0 {\n\t\tfor _, call := range completion.Choices[0].Message.ToolCalls {\n\t\t\ttoolCall := message.ToolCall{\n\t\t\t\tID: call.ID,\n\t\t\t\tName: call.Function.Name,\n\t\t\t\tInput: call.Function.Arguments,\n\t\t\t\tType: \"function\",\n\t\t\t\tFinished: true,\n\t\t\t}\n\t\t\ttoolCalls = append(toolCalls, toolCall)\n\t\t}\n\t}\n\n\treturn toolCalls\n}\n\nfunc (c *copilotClient) usage(completion openai.ChatCompletion) TokenUsage {\n\tcachedTokens := completion.Usage.PromptTokensDetails.CachedTokens\n\tinputTokens := completion.Usage.PromptTokens - cachedTokens\n\n\treturn TokenUsage{\n\t\tInputTokens: inputTokens,\n\t\tOutputTokens: completion.Usage.CompletionTokens,\n\t\tCacheCreationTokens: 0, // GitHub Copilot doesn't provide this directly\n\t\tCacheReadTokens: cachedTokens,\n\t}\n}\n\nfunc WithCopilotReasoningEffort(effort string) CopilotOption {\n\treturn func(options *copilotOptions) {\n\t\tdefaultReasoningEffort := \"medium\"\n\t\tswitch effort {\n\t\tcase \"low\", \"medium\", \"high\":\n\t\t\tdefaultReasoningEffort = effort\n\t\tdefault:\n\t\t\tlogging.Warn(\"Invalid reasoning effort, using default: medium\")\n\t\t}\n\t\toptions.reasoningEffort = defaultReasoningEffort\n\t}\n}\n\nfunc WithCopilotExtraHeaders(headers map[string]string) CopilotOption {\n\treturn func(options *copilotOptions) {\n\t\toptions.extraHeaders = headers\n\t}\n}\n\nfunc WithCopilotBearerToken(bearerToken string) CopilotOption {\n\treturn func(options *copilotOptions) {\n\t\toptions.bearerToken = bearerToken\n\t}\n}\n\n"], ["/opencode/internal/tui/components/dialog/quit.go", "package dialog\n\nimport (\n\t\"strings\"\n\n\t\"github.com/charmbracelet/bubbles/key\"\n\ttea \"github.com/charmbracelet/bubbletea\"\n\t\"github.com/charmbracelet/lipgloss\"\n\t\"github.com/opencode-ai/opencode/internal/tui/layout\"\n\t\"github.com/opencode-ai/opencode/internal/tui/styles\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n\t\"github.com/opencode-ai/opencode/internal/tui/util\"\n)\n\nconst question = \"Are you sure you want to quit?\"\n\ntype CloseQuitMsg struct{}\n\ntype QuitDialog interface {\n\ttea.Model\n\tlayout.Bindings\n}\n\ntype quitDialogCmp struct {\n\tselectedNo bool\n}\n\ntype helpMapping struct {\n\tLeftRight key.Binding\n\tEnterSpace key.Binding\n\tYes key.Binding\n\tNo key.Binding\n\tTab key.Binding\n}\n\nvar helpKeys = helpMapping{\n\tLeftRight: key.NewBinding(\n\t\tkey.WithKeys(\"left\", \"right\"),\n\t\tkey.WithHelp(\"←/→\", \"switch options\"),\n\t),\n\tEnterSpace: key.NewBinding(\n\t\tkey.WithKeys(\"enter\", \" \"),\n\t\tkey.WithHelp(\"enter/space\", \"confirm\"),\n\t),\n\tYes: key.NewBinding(\n\t\tkey.WithKeys(\"y\", \"Y\"),\n\t\tkey.WithHelp(\"y/Y\", \"yes\"),\n\t),\n\tNo: key.NewBinding(\n\t\tkey.WithKeys(\"n\", \"N\"),\n\t\tkey.WithHelp(\"n/N\", \"no\"),\n\t),\n\tTab: key.NewBinding(\n\t\tkey.WithKeys(\"tab\"),\n\t\tkey.WithHelp(\"tab\", \"switch options\"),\n\t),\n}\n\nfunc (q *quitDialogCmp) Init() tea.Cmd {\n\treturn nil\n}\n\nfunc (q *quitDialogCmp) Update(msg tea.Msg) (tea.Model, tea.Cmd) {\n\tswitch msg := msg.(type) {\n\tcase tea.KeyMsg:\n\t\tswitch {\n\t\tcase key.Matches(msg, helpKeys.LeftRight) || key.Matches(msg, helpKeys.Tab):\n\t\t\tq.selectedNo = !q.selectedNo\n\t\t\treturn q, nil\n\t\tcase key.Matches(msg, helpKeys.EnterSpace):\n\t\t\tif !q.selectedNo {\n\t\t\t\treturn q, tea.Quit\n\t\t\t}\n\t\t\treturn q, util.CmdHandler(CloseQuitMsg{})\n\t\tcase key.Matches(msg, helpKeys.Yes):\n\t\t\treturn q, tea.Quit\n\t\tcase key.Matches(msg, helpKeys.No):\n\t\t\treturn q, util.CmdHandler(CloseQuitMsg{})\n\t\t}\n\t}\n\treturn q, nil\n}\n\nfunc (q *quitDialogCmp) View() string {\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\t\n\tyesStyle := baseStyle\n\tnoStyle := baseStyle\n\tspacerStyle := baseStyle.Background(t.Background())\n\n\tif q.selectedNo {\n\t\tnoStyle = noStyle.Background(t.Primary()).Foreground(t.Background())\n\t\tyesStyle = yesStyle.Background(t.Background()).Foreground(t.Primary())\n\t} else {\n\t\tyesStyle = yesStyle.Background(t.Primary()).Foreground(t.Background())\n\t\tnoStyle = noStyle.Background(t.Background()).Foreground(t.Primary())\n\t}\n\n\tyesButton := yesStyle.Padding(0, 1).Render(\"Yes\")\n\tnoButton := noStyle.Padding(0, 1).Render(\"No\")\n\n\tbuttons := lipgloss.JoinHorizontal(lipgloss.Left, yesButton, spacerStyle.Render(\" \"), noButton)\n\n\twidth := lipgloss.Width(question)\n\tremainingWidth := width - lipgloss.Width(buttons)\n\tif remainingWidth > 0 {\n\t\tbuttons = spacerStyle.Render(strings.Repeat(\" \", remainingWidth)) + buttons\n\t}\n\n\tcontent := baseStyle.Render(\n\t\tlipgloss.JoinVertical(\n\t\t\tlipgloss.Center,\n\t\t\tquestion,\n\t\t\t\"\",\n\t\t\tbuttons,\n\t\t),\n\t)\n\n\treturn baseStyle.Padding(1, 2).\n\t\tBorder(lipgloss.RoundedBorder()).\n\t\tBorderBackground(t.Background()).\n\t\tBorderForeground(t.TextMuted()).\n\t\tWidth(lipgloss.Width(content) + 4).\n\t\tRender(content)\n}\n\nfunc (q *quitDialogCmp) BindingKeys() []key.Binding {\n\treturn layout.KeyMapToSlice(helpKeys)\n}\n\nfunc NewQuitCmp() QuitDialog {\n\treturn &quitDialogCmp{\n\t\tselectedNo: true,\n\t}\n}\n"], ["/opencode/internal/message/content.go", "package message\n\nimport (\n\t\"encoding/base64\"\n\t\"slices\"\n\t\"time\"\n\n\t\"github.com/opencode-ai/opencode/internal/llm/models\"\n)\n\ntype MessageRole string\n\nconst (\n\tAssistant MessageRole = \"assistant\"\n\tUser MessageRole = \"user\"\n\tSystem MessageRole = \"system\"\n\tTool MessageRole = \"tool\"\n)\n\ntype FinishReason string\n\nconst (\n\tFinishReasonEndTurn FinishReason = \"end_turn\"\n\tFinishReasonMaxTokens FinishReason = \"max_tokens\"\n\tFinishReasonToolUse FinishReason = \"tool_use\"\n\tFinishReasonCanceled FinishReason = \"canceled\"\n\tFinishReasonError FinishReason = \"error\"\n\tFinishReasonPermissionDenied FinishReason = \"permission_denied\"\n\n\t// Should never happen\n\tFinishReasonUnknown FinishReason = \"unknown\"\n)\n\ntype ContentPart interface {\n\tisPart()\n}\n\ntype ReasoningContent struct {\n\tThinking string `json:\"thinking\"`\n}\n\nfunc (tc ReasoningContent) String() string {\n\treturn tc.Thinking\n}\nfunc (ReasoningContent) isPart() {}\n\ntype TextContent struct {\n\tText string `json:\"text\"`\n}\n\nfunc (tc TextContent) String() string {\n\treturn tc.Text\n}\n\nfunc (TextContent) isPart() {}\n\ntype ImageURLContent struct {\n\tURL string `json:\"url\"`\n\tDetail string `json:\"detail,omitempty\"`\n}\n\nfunc (iuc ImageURLContent) String() string {\n\treturn iuc.URL\n}\n\nfunc (ImageURLContent) isPart() {}\n\ntype BinaryContent struct {\n\tPath string\n\tMIMEType string\n\tData []byte\n}\n\nfunc (bc BinaryContent) String(provider models.ModelProvider) string {\n\tbase64Encoded := base64.StdEncoding.EncodeToString(bc.Data)\n\tif provider == models.ProviderOpenAI {\n\t\treturn \"data:\" + bc.MIMEType + \";base64,\" + base64Encoded\n\t}\n\treturn base64Encoded\n}\n\nfunc (BinaryContent) isPart() {}\n\ntype ToolCall struct {\n\tID string `json:\"id\"`\n\tName string `json:\"name\"`\n\tInput string `json:\"input\"`\n\tType string `json:\"type\"`\n\tFinished bool `json:\"finished\"`\n}\n\nfunc (ToolCall) isPart() {}\n\ntype ToolResult struct {\n\tToolCallID string `json:\"tool_call_id\"`\n\tName string `json:\"name\"`\n\tContent string `json:\"content\"`\n\tMetadata string `json:\"metadata\"`\n\tIsError bool `json:\"is_error\"`\n}\n\nfunc (ToolResult) isPart() {}\n\ntype Finish struct {\n\tReason FinishReason `json:\"reason\"`\n\tTime int64 `json:\"time\"`\n}\n\nfunc (Finish) isPart() {}\n\ntype Message struct {\n\tID string\n\tRole MessageRole\n\tSessionID string\n\tParts []ContentPart\n\tModel models.ModelID\n\tCreatedAt int64\n\tUpdatedAt int64\n}\n\nfunc (m *Message) Content() TextContent {\n\tfor _, part := range m.Parts {\n\t\tif c, ok := part.(TextContent); ok {\n\t\t\treturn c\n\t\t}\n\t}\n\treturn TextContent{}\n}\n\nfunc (m *Message) ReasoningContent() ReasoningContent {\n\tfor _, part := range m.Parts {\n\t\tif c, ok := part.(ReasoningContent); ok {\n\t\t\treturn c\n\t\t}\n\t}\n\treturn ReasoningContent{}\n}\n\nfunc (m *Message) ImageURLContent() []ImageURLContent {\n\timageURLContents := make([]ImageURLContent, 0)\n\tfor _, part := range m.Parts {\n\t\tif c, ok := part.(ImageURLContent); ok {\n\t\t\timageURLContents = append(imageURLContents, c)\n\t\t}\n\t}\n\treturn imageURLContents\n}\n\nfunc (m *Message) BinaryContent() []BinaryContent {\n\tbinaryContents := make([]BinaryContent, 0)\n\tfor _, part := range m.Parts {\n\t\tif c, ok := part.(BinaryContent); ok {\n\t\t\tbinaryContents = append(binaryContents, c)\n\t\t}\n\t}\n\treturn binaryContents\n}\n\nfunc (m *Message) ToolCalls() []ToolCall {\n\ttoolCalls := make([]ToolCall, 0)\n\tfor _, part := range m.Parts {\n\t\tif c, ok := part.(ToolCall); ok {\n\t\t\ttoolCalls = append(toolCalls, c)\n\t\t}\n\t}\n\treturn toolCalls\n}\n\nfunc (m *Message) ToolResults() []ToolResult {\n\ttoolResults := make([]ToolResult, 0)\n\tfor _, part := range m.Parts {\n\t\tif c, ok := part.(ToolResult); ok {\n\t\t\ttoolResults = append(toolResults, c)\n\t\t}\n\t}\n\treturn toolResults\n}\n\nfunc (m *Message) IsFinished() bool {\n\tfor _, part := range m.Parts {\n\t\tif _, ok := part.(Finish); ok {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc (m *Message) FinishPart() *Finish {\n\tfor _, part := range m.Parts {\n\t\tif c, ok := part.(Finish); ok {\n\t\t\treturn &c\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (m *Message) FinishReason() FinishReason {\n\tfor _, part := range m.Parts {\n\t\tif c, ok := part.(Finish); ok {\n\t\t\treturn c.Reason\n\t\t}\n\t}\n\treturn \"\"\n}\n\nfunc (m *Message) IsThinking() bool {\n\tif m.ReasoningContent().Thinking != \"\" && m.Content().Text == \"\" && !m.IsFinished() {\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc (m *Message) AppendContent(delta string) {\n\tfound := false\n\tfor i, part := range m.Parts {\n\t\tif c, ok := part.(TextContent); ok {\n\t\t\tm.Parts[i] = TextContent{Text: c.Text + delta}\n\t\t\tfound = true\n\t\t}\n\t}\n\tif !found {\n\t\tm.Parts = append(m.Parts, TextContent{Text: delta})\n\t}\n}\n\nfunc (m *Message) AppendReasoningContent(delta string) {\n\tfound := false\n\tfor i, part := range m.Parts {\n\t\tif c, ok := part.(ReasoningContent); ok {\n\t\t\tm.Parts[i] = ReasoningContent{Thinking: c.Thinking + delta}\n\t\t\tfound = true\n\t\t}\n\t}\n\tif !found {\n\t\tm.Parts = append(m.Parts, ReasoningContent{Thinking: delta})\n\t}\n}\n\nfunc (m *Message) FinishToolCall(toolCallID string) {\n\tfor i, part := range m.Parts {\n\t\tif c, ok := part.(ToolCall); ok {\n\t\t\tif c.ID == toolCallID {\n\t\t\t\tm.Parts[i] = ToolCall{\n\t\t\t\t\tID: c.ID,\n\t\t\t\t\tName: c.Name,\n\t\t\t\t\tInput: c.Input,\n\t\t\t\t\tType: c.Type,\n\t\t\t\t\tFinished: true,\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc (m *Message) AppendToolCallInput(toolCallID string, inputDelta string) {\n\tfor i, part := range m.Parts {\n\t\tif c, ok := part.(ToolCall); ok {\n\t\t\tif c.ID == toolCallID {\n\t\t\t\tm.Parts[i] = ToolCall{\n\t\t\t\t\tID: c.ID,\n\t\t\t\t\tName: c.Name,\n\t\t\t\t\tInput: c.Input + inputDelta,\n\t\t\t\t\tType: c.Type,\n\t\t\t\t\tFinished: c.Finished,\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc (m *Message) AddToolCall(tc ToolCall) {\n\tfor i, part := range m.Parts {\n\t\tif c, ok := part.(ToolCall); ok {\n\t\t\tif c.ID == tc.ID {\n\t\t\t\tm.Parts[i] = tc\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\tm.Parts = append(m.Parts, tc)\n}\n\nfunc (m *Message) SetToolCalls(tc []ToolCall) {\n\t// remove any existing tool call part it could have multiple\n\tparts := make([]ContentPart, 0)\n\tfor _, part := range m.Parts {\n\t\tif _, ok := part.(ToolCall); ok {\n\t\t\tcontinue\n\t\t}\n\t\tparts = append(parts, part)\n\t}\n\tm.Parts = parts\n\tfor _, toolCall := range tc {\n\t\tm.Parts = append(m.Parts, toolCall)\n\t}\n}\n\nfunc (m *Message) AddToolResult(tr ToolResult) {\n\tm.Parts = append(m.Parts, tr)\n}\n\nfunc (m *Message) SetToolResults(tr []ToolResult) {\n\tfor _, toolResult := range tr {\n\t\tm.Parts = append(m.Parts, toolResult)\n\t}\n}\n\nfunc (m *Message) AddFinish(reason FinishReason) {\n\t// remove any existing finish part\n\tfor i, part := range m.Parts {\n\t\tif _, ok := part.(Finish); ok {\n\t\t\tm.Parts = slices.Delete(m.Parts, i, i+1)\n\t\t\tbreak\n\t\t}\n\t}\n\tm.Parts = append(m.Parts, Finish{Reason: reason, Time: time.Now().Unix()})\n}\n\nfunc (m *Message) AddImageURL(url, detail string) {\n\tm.Parts = append(m.Parts, ImageURLContent{URL: url, Detail: detail})\n}\n\nfunc (m *Message) AddBinary(mimeType string, data []byte) {\n\tm.Parts = append(m.Parts, BinaryContent{MIMEType: mimeType, Data: data})\n}\n"], ["/opencode/internal/llm/provider/openai.go", "package provider\n\nimport (\n\t\"context\"\n\t\"encoding/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"time\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n\t\"github.com/openai/openai-go/shared\"\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/llm/models\"\n\t\"github.com/opencode-ai/opencode/internal/llm/tools\"\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n\t\"github.com/opencode-ai/opencode/internal/message\"\n)\n\ntype openaiOptions struct {\n\tbaseURL string\n\tdisableCache bool\n\treasoningEffort string\n\textraHeaders map[string]string\n}\n\ntype OpenAIOption func(*openaiOptions)\n\ntype openaiClient struct {\n\tproviderOptions providerClientOptions\n\toptions openaiOptions\n\tclient openai.Client\n}\n\ntype OpenAIClient ProviderClient\n\nfunc newOpenAIClient(opts providerClientOptions) OpenAIClient {\n\topenaiOpts := openaiOptions{\n\t\treasoningEffort: \"medium\",\n\t}\n\tfor _, o := range opts.openaiOptions {\n\t\to(&openaiOpts)\n\t}\n\n\topenaiClientOptions := []option.RequestOption{}\n\tif opts.apiKey != \"\" {\n\t\topenaiClientOptions = append(openaiClientOptions, option.WithAPIKey(opts.apiKey))\n\t}\n\tif openaiOpts.baseURL != \"\" {\n\t\topenaiClientOptions = append(openaiClientOptions, option.WithBaseURL(openaiOpts.baseURL))\n\t}\n\n\tif openaiOpts.extraHeaders != nil {\n\t\tfor key, value := range openaiOpts.extraHeaders {\n\t\t\topenaiClientOptions = append(openaiClientOptions, option.WithHeader(key, value))\n\t\t}\n\t}\n\n\tclient := openai.NewClient(openaiClientOptions...)\n\treturn &openaiClient{\n\t\tproviderOptions: opts,\n\t\toptions: openaiOpts,\n\t\tclient: client,\n\t}\n}\n\nfunc (o *openaiClient) convertMessages(messages []message.Message) (openaiMessages []openai.ChatCompletionMessageParamUnion) {\n\t// Add system message first\n\topenaiMessages = append(openaiMessages, openai.SystemMessage(o.providerOptions.systemMessage))\n\n\tfor _, msg := range messages {\n\t\tswitch msg.Role {\n\t\tcase message.User:\n\t\t\tvar content []openai.ChatCompletionContentPartUnionParam\n\t\t\ttextBlock := openai.ChatCompletionContentPartTextParam{Text: msg.Content().String()}\n\t\t\tcontent = append(content, openai.ChatCompletionContentPartUnionParam{OfText: &textBlock})\n\t\t\tfor _, binaryContent := range msg.BinaryContent() {\n\t\t\t\timageURL := openai.ChatCompletionContentPartImageImageURLParam{URL: binaryContent.String(models.ProviderOpenAI)}\n\t\t\t\timageBlock := openai.ChatCompletionContentPartImageParam{ImageURL: imageURL}\n\n\t\t\t\tcontent = append(content, openai.ChatCompletionContentPartUnionParam{OfImageURL: &imageBlock})\n\t\t\t}\n\n\t\t\topenaiMessages = append(openaiMessages, openai.UserMessage(content))\n\n\t\tcase message.Assistant:\n\t\t\tassistantMsg := openai.ChatCompletionAssistantMessageParam{\n\t\t\t\tRole: \"assistant\",\n\t\t\t}\n\n\t\t\tif msg.Content().String() != \"\" {\n\t\t\t\tassistantMsg.Content = openai.ChatCompletionAssistantMessageParamContentUnion{\n\t\t\t\t\tOfString: openai.String(msg.Content().String()),\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif len(msg.ToolCalls()) > 0 {\n\t\t\t\tassistantMsg.ToolCalls = make([]openai.ChatCompletionMessageToolCallParam, len(msg.ToolCalls()))\n\t\t\t\tfor i, call := range msg.ToolCalls() {\n\t\t\t\t\tassistantMsg.ToolCalls[i] = openai.ChatCompletionMessageToolCallParam{\n\t\t\t\t\t\tID: call.ID,\n\t\t\t\t\t\tType: \"function\",\n\t\t\t\t\t\tFunction: openai.ChatCompletionMessageToolCallFunctionParam{\n\t\t\t\t\t\t\tName: call.Name,\n\t\t\t\t\t\t\tArguments: call.Input,\n\t\t\t\t\t\t},\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\topenaiMessages = append(openaiMessages, openai.ChatCompletionMessageParamUnion{\n\t\t\t\tOfAssistant: &assistantMsg,\n\t\t\t})\n\n\t\tcase message.Tool:\n\t\t\tfor _, result := range msg.ToolResults() {\n\t\t\t\topenaiMessages = append(openaiMessages,\n\t\t\t\t\topenai.ToolMessage(result.Content, result.ToolCallID),\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn\n}\n\nfunc (o *openaiClient) convertTools(tools []tools.BaseTool) []openai.ChatCompletionToolParam {\n\topenaiTools := make([]openai.ChatCompletionToolParam, len(tools))\n\n\tfor i, tool := range tools {\n\t\tinfo := tool.Info()\n\t\topenaiTools[i] = openai.ChatCompletionToolParam{\n\t\t\tFunction: openai.FunctionDefinitionParam{\n\t\t\t\tName: info.Name,\n\t\t\t\tDescription: openai.String(info.Description),\n\t\t\t\tParameters: openai.FunctionParameters{\n\t\t\t\t\t\"type\": \"object\",\n\t\t\t\t\t\"properties\": info.Parameters,\n\t\t\t\t\t\"required\": info.Required,\n\t\t\t\t},\n\t\t\t},\n\t\t}\n\t}\n\n\treturn openaiTools\n}\n\nfunc (o *openaiClient) finishReason(reason string) message.FinishReason {\n\tswitch reason {\n\tcase \"stop\":\n\t\treturn message.FinishReasonEndTurn\n\tcase \"length\":\n\t\treturn message.FinishReasonMaxTokens\n\tcase \"tool_calls\":\n\t\treturn message.FinishReasonToolUse\n\tdefault:\n\t\treturn message.FinishReasonUnknown\n\t}\n}\n\nfunc (o *openaiClient) preparedParams(messages []openai.ChatCompletionMessageParamUnion, tools []openai.ChatCompletionToolParam) openai.ChatCompletionNewParams {\n\tparams := openai.ChatCompletionNewParams{\n\t\tModel: openai.ChatModel(o.providerOptions.model.APIModel),\n\t\tMessages: messages,\n\t\tTools: tools,\n\t}\n\n\tif o.providerOptions.model.CanReason == true {\n\t\tparams.MaxCompletionTokens = openai.Int(o.providerOptions.maxTokens)\n\t\tswitch o.options.reasoningEffort {\n\t\tcase \"low\":\n\t\t\tparams.ReasoningEffort = shared.ReasoningEffortLow\n\t\tcase \"medium\":\n\t\t\tparams.ReasoningEffort = shared.ReasoningEffortMedium\n\t\tcase \"high\":\n\t\t\tparams.ReasoningEffort = shared.ReasoningEffortHigh\n\t\tdefault:\n\t\t\tparams.ReasoningEffort = shared.ReasoningEffortMedium\n\t\t}\n\t} else {\n\t\tparams.MaxTokens = openai.Int(o.providerOptions.maxTokens)\n\t}\n\n\treturn params\n}\n\nfunc (o *openaiClient) send(ctx context.Context, messages []message.Message, tools []tools.BaseTool) (response *ProviderResponse, err error) {\n\tparams := o.preparedParams(o.convertMessages(messages), o.convertTools(tools))\n\tcfg := config.Get()\n\tif cfg.Debug {\n\t\tjsonData, _ := json.Marshal(params)\n\t\tlogging.Debug(\"Prepared messages\", \"messages\", string(jsonData))\n\t}\n\tattempts := 0\n\tfor {\n\t\tattempts++\n\t\topenaiResponse, err := o.client.Chat.Completions.New(\n\t\t\tctx,\n\t\t\tparams,\n\t\t)\n\t\t// If there is an error we are going to see if we can retry the call\n\t\tif err != nil {\n\t\t\tretry, after, retryErr := o.shouldRetry(attempts, err)\n\t\t\tif retryErr != nil {\n\t\t\t\treturn nil, retryErr\n\t\t\t}\n\t\t\tif retry {\n\t\t\t\tlogging.WarnPersist(fmt.Sprintf(\"Retrying due to rate limit... attempt %d of %d\", attempts, maxRetries), logging.PersistTimeArg, time.Millisecond*time.Duration(after+100))\n\t\t\t\tselect {\n\t\t\t\tcase <-ctx.Done():\n\t\t\t\t\treturn nil, ctx.Err()\n\t\t\t\tcase <-time.After(time.Duration(after) * time.Millisecond):\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn nil, retryErr\n\t\t}\n\n\t\tcontent := \"\"\n\t\tif openaiResponse.Choices[0].Message.Content != \"\" {\n\t\t\tcontent = openaiResponse.Choices[0].Message.Content\n\t\t}\n\n\t\ttoolCalls := o.toolCalls(*openaiResponse)\n\t\tfinishReason := o.finishReason(string(openaiResponse.Choices[0].FinishReason))\n\n\t\tif len(toolCalls) > 0 {\n\t\t\tfinishReason = message.FinishReasonToolUse\n\t\t}\n\n\t\treturn &ProviderResponse{\n\t\t\tContent: content,\n\t\t\tToolCalls: toolCalls,\n\t\t\tUsage: o.usage(*openaiResponse),\n\t\t\tFinishReason: finishReason,\n\t\t}, nil\n\t}\n}\n\nfunc (o *openaiClient) stream(ctx context.Context, messages []message.Message, tools []tools.BaseTool) <-chan ProviderEvent {\n\tparams := o.preparedParams(o.convertMessages(messages), o.convertTools(tools))\n\tparams.StreamOptions = openai.ChatCompletionStreamOptionsParam{\n\t\tIncludeUsage: openai.Bool(true),\n\t}\n\n\tcfg := config.Get()\n\tif cfg.Debug {\n\t\tjsonData, _ := json.Marshal(params)\n\t\tlogging.Debug(\"Prepared messages\", \"messages\", string(jsonData))\n\t}\n\n\tattempts := 0\n\teventChan := make(chan ProviderEvent)\n\n\tgo func() {\n\t\tfor {\n\t\t\tattempts++\n\t\t\topenaiStream := o.client.Chat.Completions.NewStreaming(\n\t\t\t\tctx,\n\t\t\t\tparams,\n\t\t\t)\n\n\t\t\tacc := openai.ChatCompletionAccumulator{}\n\t\t\tcurrentContent := \"\"\n\t\t\ttoolCalls := make([]message.ToolCall, 0)\n\n\t\t\tfor openaiStream.Next() {\n\t\t\t\tchunk := openaiStream.Current()\n\t\t\t\tacc.AddChunk(chunk)\n\n\t\t\t\tfor _, choice := range chunk.Choices {\n\t\t\t\t\tif choice.Delta.Content != \"\" {\n\t\t\t\t\t\teventChan <- ProviderEvent{\n\t\t\t\t\t\t\tType: EventContentDelta,\n\t\t\t\t\t\t\tContent: choice.Delta.Content,\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcurrentContent += choice.Delta.Content\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\terr := openaiStream.Err()\n\t\t\tif err == nil || errors.Is(err, io.EOF) {\n\t\t\t\t// Stream completed successfully\n\t\t\t\tfinishReason := o.finishReason(string(acc.ChatCompletion.Choices[0].FinishReason))\n\t\t\t\tif len(acc.ChatCompletion.Choices[0].Message.ToolCalls) > 0 {\n\t\t\t\t\ttoolCalls = append(toolCalls, o.toolCalls(acc.ChatCompletion)...)\n\t\t\t\t}\n\t\t\t\tif len(toolCalls) > 0 {\n\t\t\t\t\tfinishReason = message.FinishReasonToolUse\n\t\t\t\t}\n\n\t\t\t\teventChan <- ProviderEvent{\n\t\t\t\t\tType: EventComplete,\n\t\t\t\t\tResponse: &ProviderResponse{\n\t\t\t\t\t\tContent: currentContent,\n\t\t\t\t\t\tToolCalls: toolCalls,\n\t\t\t\t\t\tUsage: o.usage(acc.ChatCompletion),\n\t\t\t\t\t\tFinishReason: finishReason,\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t\tclose(eventChan)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\t// If there is an error we are going to see if we can retry the call\n\t\t\tretry, after, retryErr := o.shouldRetry(attempts, err)\n\t\t\tif retryErr != nil {\n\t\t\t\teventChan <- ProviderEvent{Type: EventError, Error: retryErr}\n\t\t\t\tclose(eventChan)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif retry {\n\t\t\t\tlogging.WarnPersist(fmt.Sprintf(\"Retrying due to rate limit... attempt %d of %d\", attempts, maxRetries), logging.PersistTimeArg, time.Millisecond*time.Duration(after+100))\n\t\t\t\tselect {\n\t\t\t\tcase <-ctx.Done():\n\t\t\t\t\t// context cancelled\n\t\t\t\t\tif ctx.Err() == nil {\n\t\t\t\t\t\teventChan <- ProviderEvent{Type: EventError, Error: ctx.Err()}\n\t\t\t\t\t}\n\t\t\t\t\tclose(eventChan)\n\t\t\t\t\treturn\n\t\t\t\tcase <-time.After(time.Duration(after) * time.Millisecond):\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t\teventChan <- ProviderEvent{Type: EventError, Error: retryErr}\n\t\t\tclose(eventChan)\n\t\t\treturn\n\t\t}\n\t}()\n\n\treturn eventChan\n}\n\nfunc (o *openaiClient) shouldRetry(attempts int, err error) (bool, int64, error) {\n\tvar apierr *openai.Error\n\tif !errors.As(err, &apierr) {\n\t\treturn false, 0, err\n\t}\n\n\tif apierr.StatusCode != 429 && apierr.StatusCode != 500 {\n\t\treturn false, 0, err\n\t}\n\n\tif attempts > maxRetries {\n\t\treturn false, 0, fmt.Errorf(\"maximum retry attempts reached for rate limit: %d retries\", maxRetries)\n\t}\n\n\tretryMs := 0\n\tretryAfterValues := apierr.Response.Header.Values(\"Retry-After\")\n\n\tbackoffMs := 2000 * (1 << (attempts - 1))\n\tjitterMs := int(float64(backoffMs) * 0.2)\n\tretryMs = backoffMs + jitterMs\n\tif len(retryAfterValues) > 0 {\n\t\tif _, err := fmt.Sscanf(retryAfterValues[0], \"%d\", &retryMs); err == nil {\n\t\t\tretryMs = retryMs * 1000\n\t\t}\n\t}\n\treturn true, int64(retryMs), nil\n}\n\nfunc (o *openaiClient) toolCalls(completion openai.ChatCompletion) []message.ToolCall {\n\tvar toolCalls []message.ToolCall\n\n\tif len(completion.Choices) > 0 && len(completion.Choices[0].Message.ToolCalls) > 0 {\n\t\tfor _, call := range completion.Choices[0].Message.ToolCalls {\n\t\t\ttoolCall := message.ToolCall{\n\t\t\t\tID: call.ID,\n\t\t\t\tName: call.Function.Name,\n\t\t\t\tInput: call.Function.Arguments,\n\t\t\t\tType: \"function\",\n\t\t\t\tFinished: true,\n\t\t\t}\n\t\t\ttoolCalls = append(toolCalls, toolCall)\n\t\t}\n\t}\n\n\treturn toolCalls\n}\n\nfunc (o *openaiClient) usage(completion openai.ChatCompletion) TokenUsage {\n\tcachedTokens := completion.Usage.PromptTokensDetails.CachedTokens\n\tinputTokens := completion.Usage.PromptTokens - cachedTokens\n\n\treturn TokenUsage{\n\t\tInputTokens: inputTokens,\n\t\tOutputTokens: completion.Usage.CompletionTokens,\n\t\tCacheCreationTokens: 0, // OpenAI doesn't provide this directly\n\t\tCacheReadTokens: cachedTokens,\n\t}\n}\n\nfunc WithOpenAIBaseURL(baseURL string) OpenAIOption {\n\treturn func(options *openaiOptions) {\n\t\toptions.baseURL = baseURL\n\t}\n}\n\nfunc WithOpenAIExtraHeaders(headers map[string]string) OpenAIOption {\n\treturn func(options *openaiOptions) {\n\t\toptions.extraHeaders = headers\n\t}\n}\n\nfunc WithOpenAIDisableCache() OpenAIOption {\n\treturn func(options *openaiOptions) {\n\t\toptions.disableCache = true\n\t}\n}\n\nfunc WithReasoningEffort(effort string) OpenAIOption {\n\treturn func(options *openaiOptions) {\n\t\tdefaultReasoningEffort := \"medium\"\n\t\tswitch effort {\n\t\tcase \"low\", \"medium\", \"high\":\n\t\t\tdefaultReasoningEffort = effort\n\t\tdefault:\n\t\t\tlogging.Warn(\"Invalid reasoning effort, using default: medium\")\n\t\t}\n\t\toptions.reasoningEffort = defaultReasoningEffort\n\t}\n}\n"], ["/opencode/internal/diff/diff.go", "package diff\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\"\n\t\"regexp\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"github.com/alecthomas/chroma/v2\"\n\t\"github.com/alecthomas/chroma/v2/formatters\"\n\t\"github.com/alecthomas/chroma/v2/lexers\"\n\t\"github.com/alecthomas/chroma/v2/styles\"\n\t\"github.com/aymanbagabas/go-udiff\"\n\t\"github.com/charmbracelet/lipgloss\"\n\t\"github.com/charmbracelet/x/ansi\"\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n\t\"github.com/sergi/go-diff/diffmatchpatch\"\n)\n\n// -------------------------------------------------------------------------\n// Core Types\n// -------------------------------------------------------------------------\n\n// LineType represents the kind of line in a diff.\ntype LineType int\n\nconst (\n\tLineContext LineType = iota // Line exists in both files\n\tLineAdded // Line added in the new file\n\tLineRemoved // Line removed from the old file\n)\n\n// Segment represents a portion of a line for intra-line highlighting\ntype Segment struct {\n\tStart int\n\tEnd int\n\tType LineType\n\tText string\n}\n\n// DiffLine represents a single line in a diff\ntype DiffLine struct {\n\tOldLineNo int // Line number in old file (0 for added lines)\n\tNewLineNo int // Line number in new file (0 for removed lines)\n\tKind LineType // Type of line (added, removed, context)\n\tContent string // Content of the line\n\tSegments []Segment // Segments for intraline highlighting\n}\n\n// Hunk represents a section of changes in a diff\ntype Hunk struct {\n\tHeader string\n\tLines []DiffLine\n}\n\n// DiffResult contains the parsed result of a diff\ntype DiffResult struct {\n\tOldFile string\n\tNewFile string\n\tHunks []Hunk\n}\n\n// linePair represents a pair of lines for side-by-side display\ntype linePair struct {\n\tleft *DiffLine\n\tright *DiffLine\n}\n\n// -------------------------------------------------------------------------\n// Parse Configuration\n// -------------------------------------------------------------------------\n\n// ParseConfig configures the behavior of diff parsing\ntype ParseConfig struct {\n\tContextSize int // Number of context lines to include\n}\n\n// ParseOption modifies a ParseConfig\ntype ParseOption func(*ParseConfig)\n\n// WithContextSize sets the number of context lines to include\nfunc WithContextSize(size int) ParseOption {\n\treturn func(p *ParseConfig) {\n\t\tif size >= 0 {\n\t\t\tp.ContextSize = size\n\t\t}\n\t}\n}\n\n// -------------------------------------------------------------------------\n// Side-by-Side Configuration\n// -------------------------------------------------------------------------\n\n// SideBySideConfig configures the rendering of side-by-side diffs\ntype SideBySideConfig struct {\n\tTotalWidth int\n}\n\n// SideBySideOption modifies a SideBySideConfig\ntype SideBySideOption func(*SideBySideConfig)\n\n// NewSideBySideConfig creates a SideBySideConfig with default values\nfunc NewSideBySideConfig(opts ...SideBySideOption) SideBySideConfig {\n\tconfig := SideBySideConfig{\n\t\tTotalWidth: 160, // Default width for side-by-side view\n\t}\n\n\tfor _, opt := range opts {\n\t\topt(&config)\n\t}\n\n\treturn config\n}\n\n// WithTotalWidth sets the total width for side-by-side view\nfunc WithTotalWidth(width int) SideBySideOption {\n\treturn func(s *SideBySideConfig) {\n\t\tif width > 0 {\n\t\t\ts.TotalWidth = width\n\t\t}\n\t}\n}\n\n// -------------------------------------------------------------------------\n// Diff Parsing\n// -------------------------------------------------------------------------\n\n// ParseUnifiedDiff parses a unified diff format string into structured data\nfunc ParseUnifiedDiff(diff string) (DiffResult, error) {\n\tvar result DiffResult\n\tvar currentHunk *Hunk\n\n\thunkHeaderRe := regexp.MustCompile(`^@@ -(\\d+),?(\\d*) \\+(\\d+),?(\\d*) @@`)\n\tlines := strings.Split(diff, \"\\n\")\n\n\tvar oldLine, newLine int\n\tinFileHeader := true\n\n\tfor _, line := range lines {\n\t\t// Parse file headers\n\t\tif inFileHeader {\n\t\t\tif strings.HasPrefix(line, \"--- a/\") {\n\t\t\t\tresult.OldFile = strings.TrimPrefix(line, \"--- a/\")\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif strings.HasPrefix(line, \"+++ b/\") {\n\t\t\t\tresult.NewFile = strings.TrimPrefix(line, \"+++ b/\")\n\t\t\t\tinFileHeader = false\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\n\t\t// Parse hunk headers\n\t\tif matches := hunkHeaderRe.FindStringSubmatch(line); matches != nil {\n\t\t\tif currentHunk != nil {\n\t\t\t\tresult.Hunks = append(result.Hunks, *currentHunk)\n\t\t\t}\n\t\t\tcurrentHunk = &Hunk{\n\t\t\t\tHeader: line,\n\t\t\t\tLines: []DiffLine{},\n\t\t\t}\n\n\t\t\toldStart, _ := strconv.Atoi(matches[1])\n\t\t\tnewStart, _ := strconv.Atoi(matches[3])\n\t\t\toldLine = oldStart\n\t\t\tnewLine = newStart\n\t\t\tcontinue\n\t\t}\n\n\t\t// Ignore \"No newline at end of file\" markers\n\t\tif strings.HasPrefix(line, \"\\\\ No newline at end of file\") {\n\t\t\tcontinue\n\t\t}\n\n\t\tif currentHunk == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\t// Process the line based on its prefix\n\t\tif len(line) > 0 {\n\t\t\tswitch line[0] {\n\t\t\tcase '+':\n\t\t\t\tcurrentHunk.Lines = append(currentHunk.Lines, DiffLine{\n\t\t\t\t\tOldLineNo: 0,\n\t\t\t\t\tNewLineNo: newLine,\n\t\t\t\t\tKind: LineAdded,\n\t\t\t\t\tContent: line[1:],\n\t\t\t\t})\n\t\t\t\tnewLine++\n\t\t\tcase '-':\n\t\t\t\tcurrentHunk.Lines = append(currentHunk.Lines, DiffLine{\n\t\t\t\t\tOldLineNo: oldLine,\n\t\t\t\t\tNewLineNo: 0,\n\t\t\t\t\tKind: LineRemoved,\n\t\t\t\t\tContent: line[1:],\n\t\t\t\t})\n\t\t\t\toldLine++\n\t\t\tdefault:\n\t\t\t\tcurrentHunk.Lines = append(currentHunk.Lines, DiffLine{\n\t\t\t\t\tOldLineNo: oldLine,\n\t\t\t\t\tNewLineNo: newLine,\n\t\t\t\t\tKind: LineContext,\n\t\t\t\t\tContent: line,\n\t\t\t\t})\n\t\t\t\toldLine++\n\t\t\t\tnewLine++\n\t\t\t}\n\t\t} else {\n\t\t\t// Handle empty lines\n\t\t\tcurrentHunk.Lines = append(currentHunk.Lines, DiffLine{\n\t\t\t\tOldLineNo: oldLine,\n\t\t\t\tNewLineNo: newLine,\n\t\t\t\tKind: LineContext,\n\t\t\t\tContent: \"\",\n\t\t\t})\n\t\t\toldLine++\n\t\t\tnewLine++\n\t\t}\n\t}\n\n\t// Add the last hunk if there is one\n\tif currentHunk != nil {\n\t\tresult.Hunks = append(result.Hunks, *currentHunk)\n\t}\n\n\treturn result, nil\n}\n\n// HighlightIntralineChanges updates lines in a hunk to show character-level differences\nfunc HighlightIntralineChanges(h *Hunk) {\n\tvar updated []DiffLine\n\tdmp := diffmatchpatch.New()\n\n\tfor i := 0; i < len(h.Lines); i++ {\n\t\t// Look for removed line followed by added line\n\t\tif i+1 < len(h.Lines) &&\n\t\t\th.Lines[i].Kind == LineRemoved &&\n\t\t\th.Lines[i+1].Kind == LineAdded {\n\n\t\t\toldLine := h.Lines[i]\n\t\t\tnewLine := h.Lines[i+1]\n\n\t\t\t// Find character-level differences\n\t\t\tpatches := dmp.DiffMain(oldLine.Content, newLine.Content, false)\n\t\t\tpatches = dmp.DiffCleanupSemantic(patches)\n\t\t\tpatches = dmp.DiffCleanupMerge(patches)\n\t\t\tpatches = dmp.DiffCleanupEfficiency(patches)\n\n\t\t\tsegments := make([]Segment, 0)\n\n\t\t\tremoveStart := 0\n\t\t\taddStart := 0\n\t\t\tfor _, patch := range patches {\n\t\t\t\tswitch patch.Type {\n\t\t\t\tcase diffmatchpatch.DiffDelete:\n\t\t\t\t\tsegments = append(segments, Segment{\n\t\t\t\t\t\tStart: removeStart,\n\t\t\t\t\t\tEnd: removeStart + len(patch.Text),\n\t\t\t\t\t\tType: LineRemoved,\n\t\t\t\t\t\tText: patch.Text,\n\t\t\t\t\t})\n\t\t\t\t\tremoveStart += len(patch.Text)\n\t\t\t\tcase diffmatchpatch.DiffInsert:\n\t\t\t\t\tsegments = append(segments, Segment{\n\t\t\t\t\t\tStart: addStart,\n\t\t\t\t\t\tEnd: addStart + len(patch.Text),\n\t\t\t\t\t\tType: LineAdded,\n\t\t\t\t\t\tText: patch.Text,\n\t\t\t\t\t})\n\t\t\t\t\taddStart += len(patch.Text)\n\t\t\t\tdefault:\n\t\t\t\t\t// Context text, no highlighting needed\n\t\t\t\t\tremoveStart += len(patch.Text)\n\t\t\t\t\taddStart += len(patch.Text)\n\t\t\t\t}\n\t\t\t}\n\t\t\toldLine.Segments = segments\n\t\t\tnewLine.Segments = segments\n\n\t\t\tupdated = append(updated, oldLine, newLine)\n\t\t\ti++ // Skip the next line as we've already processed it\n\t\t} else {\n\t\t\tupdated = append(updated, h.Lines[i])\n\t\t}\n\t}\n\n\th.Lines = updated\n}\n\n// pairLines converts a flat list of diff lines to pairs for side-by-side display\nfunc pairLines(lines []DiffLine) []linePair {\n\tvar pairs []linePair\n\ti := 0\n\n\tfor i < len(lines) {\n\t\tswitch lines[i].Kind {\n\t\tcase LineRemoved:\n\t\t\t// Check if the next line is an addition, if so pair them\n\t\t\tif i+1 < len(lines) && lines[i+1].Kind == LineAdded {\n\t\t\t\tpairs = append(pairs, linePair{left: &lines[i], right: &lines[i+1]})\n\t\t\t\ti += 2\n\t\t\t} else {\n\t\t\t\tpairs = append(pairs, linePair{left: &lines[i], right: nil})\n\t\t\t\ti++\n\t\t\t}\n\t\tcase LineAdded:\n\t\t\tpairs = append(pairs, linePair{left: nil, right: &lines[i]})\n\t\t\ti++\n\t\tcase LineContext:\n\t\t\tpairs = append(pairs, linePair{left: &lines[i], right: &lines[i]})\n\t\t\ti++\n\t\t}\n\t}\n\n\treturn pairs\n}\n\n// -------------------------------------------------------------------------\n// Syntax Highlighting\n// -------------------------------------------------------------------------\n\n// SyntaxHighlight applies syntax highlighting to text based on file extension\nfunc SyntaxHighlight(w io.Writer, source, fileName, formatter string, bg lipgloss.TerminalColor) error {\n\tt := theme.CurrentTheme()\n\n\t// Determine the language lexer to use\n\tl := lexers.Match(fileName)\n\tif l == nil {\n\t\tl = lexers.Analyse(source)\n\t}\n\tif l == nil {\n\t\tl = lexers.Fallback\n\t}\n\tl = chroma.Coalesce(l)\n\n\t// Get the formatter\n\tf := formatters.Get(formatter)\n\tif f == nil {\n\t\tf = formatters.Fallback\n\t}\n\n\t// Dynamic theme based on current theme values\n\tsyntaxThemeXml := fmt.Sprintf(`\n\t\n`,\n\t\tgetColor(t.Background()), // Background\n\t\tgetColor(t.Text()), // Text\n\t\tgetColor(t.Text()), // Other\n\t\tgetColor(t.Error()), // Error\n\n\t\tgetColor(t.SyntaxKeyword()), // Keyword\n\t\tgetColor(t.SyntaxKeyword()), // KeywordConstant\n\t\tgetColor(t.SyntaxKeyword()), // KeywordDeclaration\n\t\tgetColor(t.SyntaxKeyword()), // KeywordNamespace\n\t\tgetColor(t.SyntaxKeyword()), // KeywordPseudo\n\t\tgetColor(t.SyntaxKeyword()), // KeywordReserved\n\t\tgetColor(t.SyntaxType()), // KeywordType\n\n\t\tgetColor(t.Text()), // Name\n\t\tgetColor(t.SyntaxVariable()), // NameAttribute\n\t\tgetColor(t.SyntaxType()), // NameBuiltin\n\t\tgetColor(t.SyntaxVariable()), // NameBuiltinPseudo\n\t\tgetColor(t.SyntaxType()), // NameClass\n\t\tgetColor(t.SyntaxVariable()), // NameConstant\n\t\tgetColor(t.SyntaxFunction()), // NameDecorator\n\t\tgetColor(t.SyntaxVariable()), // NameEntity\n\t\tgetColor(t.SyntaxType()), // NameException\n\t\tgetColor(t.SyntaxFunction()), // NameFunction\n\t\tgetColor(t.Text()), // NameLabel\n\t\tgetColor(t.SyntaxType()), // NameNamespace\n\t\tgetColor(t.SyntaxVariable()), // NameOther\n\t\tgetColor(t.SyntaxKeyword()), // NameTag\n\t\tgetColor(t.SyntaxVariable()), // NameVariable\n\t\tgetColor(t.SyntaxVariable()), // NameVariableClass\n\t\tgetColor(t.SyntaxVariable()), // NameVariableGlobal\n\t\tgetColor(t.SyntaxVariable()), // NameVariableInstance\n\n\t\tgetColor(t.SyntaxString()), // Literal\n\t\tgetColor(t.SyntaxString()), // LiteralDate\n\t\tgetColor(t.SyntaxString()), // LiteralString\n\t\tgetColor(t.SyntaxString()), // LiteralStringBacktick\n\t\tgetColor(t.SyntaxString()), // LiteralStringChar\n\t\tgetColor(t.SyntaxString()), // LiteralStringDoc\n\t\tgetColor(t.SyntaxString()), // LiteralStringDouble\n\t\tgetColor(t.SyntaxString()), // LiteralStringEscape\n\t\tgetColor(t.SyntaxString()), // LiteralStringHeredoc\n\t\tgetColor(t.SyntaxString()), // LiteralStringInterpol\n\t\tgetColor(t.SyntaxString()), // LiteralStringOther\n\t\tgetColor(t.SyntaxString()), // LiteralStringRegex\n\t\tgetColor(t.SyntaxString()), // LiteralStringSingle\n\t\tgetColor(t.SyntaxString()), // LiteralStringSymbol\n\n\t\tgetColor(t.SyntaxNumber()), // LiteralNumber\n\t\tgetColor(t.SyntaxNumber()), // LiteralNumberBin\n\t\tgetColor(t.SyntaxNumber()), // LiteralNumberFloat\n\t\tgetColor(t.SyntaxNumber()), // LiteralNumberHex\n\t\tgetColor(t.SyntaxNumber()), // LiteralNumberInteger\n\t\tgetColor(t.SyntaxNumber()), // LiteralNumberIntegerLong\n\t\tgetColor(t.SyntaxNumber()), // LiteralNumberOct\n\n\t\tgetColor(t.SyntaxOperator()), // Operator\n\t\tgetColor(t.SyntaxKeyword()), // OperatorWord\n\t\tgetColor(t.SyntaxPunctuation()), // Punctuation\n\n\t\tgetColor(t.SyntaxComment()), // Comment\n\t\tgetColor(t.SyntaxComment()), // CommentHashbang\n\t\tgetColor(t.SyntaxComment()), // CommentMultiline\n\t\tgetColor(t.SyntaxComment()), // CommentSingle\n\t\tgetColor(t.SyntaxComment()), // CommentSpecial\n\t\tgetColor(t.SyntaxKeyword()), // CommentPreproc\n\n\t\tgetColor(t.Text()), // Generic\n\t\tgetColor(t.Error()), // GenericDeleted\n\t\tgetColor(t.Text()), // GenericEmph\n\t\tgetColor(t.Error()), // GenericError\n\t\tgetColor(t.Text()), // GenericHeading\n\t\tgetColor(t.Success()), // GenericInserted\n\t\tgetColor(t.TextMuted()), // GenericOutput\n\t\tgetColor(t.Text()), // GenericPrompt\n\t\tgetColor(t.Text()), // GenericStrong\n\t\tgetColor(t.Text()), // GenericSubheading\n\t\tgetColor(t.Error()), // GenericTraceback\n\t\tgetColor(t.Text()), // TextWhitespace\n\t)\n\n\tr := strings.NewReader(syntaxThemeXml)\n\tstyle := chroma.MustNewXMLStyle(r)\n\n\t// Modify the style to use the provided background\n\ts, err := style.Builder().Transform(\n\t\tfunc(t chroma.StyleEntry) chroma.StyleEntry {\n\t\t\tr, g, b, _ := bg.RGBA()\n\t\t\tt.Background = chroma.NewColour(uint8(r>>8), uint8(g>>8), uint8(b>>8))\n\t\t\treturn t\n\t\t},\n\t).Build()\n\tif err != nil {\n\t\ts = styles.Fallback\n\t}\n\n\t// Tokenize and format\n\tit, err := l.Tokenise(nil, source)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn f.Format(w, s, it)\n}\n\n// getColor returns the appropriate hex color string based on terminal background\nfunc getColor(adaptiveColor lipgloss.AdaptiveColor) string {\n\tif lipgloss.HasDarkBackground() {\n\t\treturn adaptiveColor.Dark\n\t}\n\treturn adaptiveColor.Light\n}\n\n// highlightLine applies syntax highlighting to a single line\nfunc highlightLine(fileName string, line string, bg lipgloss.TerminalColor) string {\n\tvar buf bytes.Buffer\n\terr := SyntaxHighlight(&buf, line, fileName, \"terminal16m\", bg)\n\tif err != nil {\n\t\treturn line\n\t}\n\treturn buf.String()\n}\n\n// createStyles generates the lipgloss styles needed for rendering diffs\nfunc createStyles(t theme.Theme) (removedLineStyle, addedLineStyle, contextLineStyle, lineNumberStyle lipgloss.Style) {\n\tremovedLineStyle = lipgloss.NewStyle().Background(t.DiffRemovedBg())\n\taddedLineStyle = lipgloss.NewStyle().Background(t.DiffAddedBg())\n\tcontextLineStyle = lipgloss.NewStyle().Background(t.DiffContextBg())\n\tlineNumberStyle = lipgloss.NewStyle().Foreground(t.DiffLineNumber())\n\n\treturn\n}\n\n// -------------------------------------------------------------------------\n// Rendering Functions\n// -------------------------------------------------------------------------\n\nfunc lipglossToHex(color lipgloss.Color) string {\n\tr, g, b, a := color.RGBA()\n\n\t// Scale uint32 values (0-65535) to uint8 (0-255).\n\tr8 := uint8(r >> 8)\n\tg8 := uint8(g >> 8)\n\tb8 := uint8(b >> 8)\n\ta8 := uint8(a >> 8)\n\n\treturn fmt.Sprintf(\"#%02x%02x%02x%02x\", r8, g8, b8, a8)\n}\n\n// applyHighlighting applies intra-line highlighting to a piece of text\nfunc applyHighlighting(content string, segments []Segment, segmentType LineType, highlightBg lipgloss.AdaptiveColor) string {\n\t// Find all ANSI sequences in the content\n\tansiRegex := regexp.MustCompile(`\\x1b(?:[@-Z\\\\-_]|\\[[0-9?]*(?:;[0-9?]*)*[@-~])`)\n\tansiMatches := ansiRegex.FindAllStringIndex(content, -1)\n\n\t// Build a mapping of visible character positions to their actual indices\n\tvisibleIdx := 0\n\tansiSequences := make(map[int]string)\n\tlastAnsiSeq := \"\\x1b[0m\" // Default reset sequence\n\n\tfor i := 0; i < len(content); {\n\t\tisAnsi := false\n\t\tfor _, match := range ansiMatches {\n\t\t\tif match[0] == i {\n\t\t\t\tansiSequences[visibleIdx] = content[match[0]:match[1]]\n\t\t\t\tlastAnsiSeq = content[match[0]:match[1]]\n\t\t\t\ti = match[1]\n\t\t\t\tisAnsi = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif isAnsi {\n\t\t\tcontinue\n\t\t}\n\n\t\t// For non-ANSI positions, store the last ANSI sequence\n\t\tif _, exists := ansiSequences[visibleIdx]; !exists {\n\t\t\tansiSequences[visibleIdx] = lastAnsiSeq\n\t\t}\n\t\tvisibleIdx++\n\t\ti++\n\t}\n\n\t// Apply highlighting\n\tvar sb strings.Builder\n\tinSelection := false\n\tcurrentPos := 0\n\n\t// Get the appropriate color based on terminal background\n\tbgColor := lipgloss.Color(getColor(highlightBg))\n\tfgColor := lipgloss.Color(getColor(theme.CurrentTheme().Background()))\n\n\tfor i := 0; i < len(content); {\n\t\t// Check if we're at an ANSI sequence\n\t\tisAnsi := false\n\t\tfor _, match := range ansiMatches {\n\t\t\tif match[0] == i {\n\t\t\t\tsb.WriteString(content[match[0]:match[1]]) // Preserve ANSI sequence\n\t\t\t\ti = match[1]\n\t\t\t\tisAnsi = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif isAnsi {\n\t\t\tcontinue\n\t\t}\n\n\t\t// Check for segment boundaries\n\t\tfor _, seg := range segments {\n\t\t\tif seg.Type == segmentType {\n\t\t\t\tif currentPos == seg.Start {\n\t\t\t\t\tinSelection = true\n\t\t\t\t}\n\t\t\t\tif currentPos == seg.End {\n\t\t\t\t\tinSelection = false\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Get current character\n\t\tchar := string(content[i])\n\n\t\tif inSelection {\n\t\t\t// Get the current styling\n\t\t\tcurrentStyle := ansiSequences[currentPos]\n\n\t\t\t// Apply foreground and background highlight\n\t\t\tsb.WriteString(\"\\x1b[38;2;\")\n\t\t\tr, g, b, _ := fgColor.RGBA()\n\t\t\tsb.WriteString(fmt.Sprintf(\"%d;%d;%dm\", r>>8, g>>8, b>>8))\n\t\t\tsb.WriteString(\"\\x1b[48;2;\")\n\t\t\tr, g, b, _ = bgColor.RGBA()\n\t\t\tsb.WriteString(fmt.Sprintf(\"%d;%d;%dm\", r>>8, g>>8, b>>8))\n\t\t\tsb.WriteString(char)\n\t\t\t// Reset foreground and background\n\t\t\tsb.WriteString(\"\\x1b[39m\")\n\n\t\t\t// Reapply the original ANSI sequence\n\t\t\tsb.WriteString(currentStyle)\n\t\t} else {\n\t\t\t// Not in selection, just copy the character\n\t\t\tsb.WriteString(char)\n\t\t}\n\n\t\tcurrentPos++\n\t\ti++\n\t}\n\n\treturn sb.String()\n}\n\n// renderLeftColumn formats the left side of a side-by-side diff\nfunc renderLeftColumn(fileName string, dl *DiffLine, colWidth int) string {\n\tt := theme.CurrentTheme()\n\n\tif dl == nil {\n\t\tcontextLineStyle := lipgloss.NewStyle().Background(t.DiffContextBg())\n\t\treturn contextLineStyle.Width(colWidth).Render(\"\")\n\t}\n\n\tremovedLineStyle, _, contextLineStyle, lineNumberStyle := createStyles(t)\n\n\t// Determine line style based on line type\n\tvar marker string\n\tvar bgStyle lipgloss.Style\n\tswitch dl.Kind {\n\tcase LineRemoved:\n\t\tmarker = removedLineStyle.Foreground(t.DiffRemoved()).Render(\"-\")\n\t\tbgStyle = removedLineStyle\n\t\tlineNumberStyle = lineNumberStyle.Foreground(t.DiffRemoved()).Background(t.DiffRemovedLineNumberBg())\n\tcase LineAdded:\n\t\tmarker = \"?\"\n\t\tbgStyle = contextLineStyle\n\tcase LineContext:\n\t\tmarker = contextLineStyle.Render(\" \")\n\t\tbgStyle = contextLineStyle\n\t}\n\n\t// Format line number\n\tlineNum := \"\"\n\tif dl.OldLineNo > 0 {\n\t\tlineNum = fmt.Sprintf(\"%6d\", dl.OldLineNo)\n\t}\n\n\t// Create the line prefix\n\tprefix := lineNumberStyle.Render(lineNum + \" \" + marker)\n\n\t// Apply syntax highlighting\n\tcontent := highlightLine(fileName, dl.Content, bgStyle.GetBackground())\n\n\t// Apply intra-line highlighting for removed lines\n\tif dl.Kind == LineRemoved && len(dl.Segments) > 0 {\n\t\tcontent = applyHighlighting(content, dl.Segments, LineRemoved, t.DiffHighlightRemoved())\n\t}\n\n\t// Add a padding space for removed lines\n\tif dl.Kind == LineRemoved {\n\t\tcontent = bgStyle.Render(\" \") + content\n\t}\n\n\t// Create the final line and truncate if needed\n\tlineText := prefix + content\n\treturn bgStyle.MaxHeight(1).Width(colWidth).Render(\n\t\tansi.Truncate(\n\t\t\tlineText,\n\t\t\tcolWidth,\n\t\t\tlipgloss.NewStyle().Background(bgStyle.GetBackground()).Foreground(t.TextMuted()).Render(\"...\"),\n\t\t),\n\t)\n}\n\n// renderRightColumn formats the right side of a side-by-side diff\nfunc renderRightColumn(fileName string, dl *DiffLine, colWidth int) string {\n\tt := theme.CurrentTheme()\n\n\tif dl == nil {\n\t\tcontextLineStyle := lipgloss.NewStyle().Background(t.DiffContextBg())\n\t\treturn contextLineStyle.Width(colWidth).Render(\"\")\n\t}\n\n\t_, addedLineStyle, contextLineStyle, lineNumberStyle := createStyles(t)\n\n\t// Determine line style based on line type\n\tvar marker string\n\tvar bgStyle lipgloss.Style\n\tswitch dl.Kind {\n\tcase LineAdded:\n\t\tmarker = addedLineStyle.Foreground(t.DiffAdded()).Render(\"+\")\n\t\tbgStyle = addedLineStyle\n\t\tlineNumberStyle = lineNumberStyle.Foreground(t.DiffAdded()).Background(t.DiffAddedLineNumberBg())\n\tcase LineRemoved:\n\t\tmarker = \"?\"\n\t\tbgStyle = contextLineStyle\n\tcase LineContext:\n\t\tmarker = contextLineStyle.Render(\" \")\n\t\tbgStyle = contextLineStyle\n\t}\n\n\t// Format line number\n\tlineNum := \"\"\n\tif dl.NewLineNo > 0 {\n\t\tlineNum = fmt.Sprintf(\"%6d\", dl.NewLineNo)\n\t}\n\n\t// Create the line prefix\n\tprefix := lineNumberStyle.Render(lineNum + \" \" + marker)\n\n\t// Apply syntax highlighting\n\tcontent := highlightLine(fileName, dl.Content, bgStyle.GetBackground())\n\n\t// Apply intra-line highlighting for added lines\n\tif dl.Kind == LineAdded && len(dl.Segments) > 0 {\n\t\tcontent = applyHighlighting(content, dl.Segments, LineAdded, t.DiffHighlightAdded())\n\t}\n\n\t// Add a padding space for added lines\n\tif dl.Kind == LineAdded {\n\t\tcontent = bgStyle.Render(\" \") + content\n\t}\n\n\t// Create the final line and truncate if needed\n\tlineText := prefix + content\n\treturn bgStyle.MaxHeight(1).Width(colWidth).Render(\n\t\tansi.Truncate(\n\t\t\tlineText,\n\t\t\tcolWidth,\n\t\t\tlipgloss.NewStyle().Background(bgStyle.GetBackground()).Foreground(t.TextMuted()).Render(\"...\"),\n\t\t),\n\t)\n}\n\n// -------------------------------------------------------------------------\n// Public API\n// -------------------------------------------------------------------------\n\n// RenderSideBySideHunk formats a hunk for side-by-side display\nfunc RenderSideBySideHunk(fileName string, h Hunk, opts ...SideBySideOption) string {\n\t// Apply options to create the configuration\n\tconfig := NewSideBySideConfig(opts...)\n\n\t// Make a copy of the hunk so we don't modify the original\n\thunkCopy := Hunk{Lines: make([]DiffLine, len(h.Lines))}\n\tcopy(hunkCopy.Lines, h.Lines)\n\n\t// Highlight changes within lines\n\tHighlightIntralineChanges(&hunkCopy)\n\n\t// Pair lines for side-by-side display\n\tpairs := pairLines(hunkCopy.Lines)\n\n\t// Calculate column width\n\tcolWidth := config.TotalWidth / 2\n\n\tleftWidth := colWidth\n\trightWidth := config.TotalWidth - colWidth\n\tvar sb strings.Builder\n\tfor _, p := range pairs {\n\t\tleftStr := renderLeftColumn(fileName, p.left, leftWidth)\n\t\trightStr := renderRightColumn(fileName, p.right, rightWidth)\n\t\tsb.WriteString(leftStr + rightStr + \"\\n\")\n\t}\n\n\treturn sb.String()\n}\n\n// FormatDiff creates a side-by-side formatted view of a diff\nfunc FormatDiff(diffText string, opts ...SideBySideOption) (string, error) {\n\tdiffResult, err := ParseUnifiedDiff(diffText)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tvar sb strings.Builder\n\tfor _, h := range diffResult.Hunks {\n\t\tsb.WriteString(RenderSideBySideHunk(diffResult.OldFile, h, opts...))\n\t}\n\n\treturn sb.String(), nil\n}\n\n// GenerateDiff creates a unified diff from two file contents\nfunc GenerateDiff(beforeContent, afterContent, fileName string) (string, int, int) {\n\t// remove the cwd prefix and ensure consistent path format\n\t// this prevents issues with absolute paths in different environments\n\tcwd := config.WorkingDirectory()\n\tfileName = strings.TrimPrefix(fileName, cwd)\n\tfileName = strings.TrimPrefix(fileName, \"/\")\n\n\tvar (\n\t\tunified = udiff.Unified(\"a/\"+fileName, \"b/\"+fileName, beforeContent, afterContent)\n\t\tadditions = 0\n\t\tremovals = 0\n\t)\n\n\tlines := strings.SplitSeq(unified, \"\\n\")\n\tfor line := range lines {\n\t\tif strings.HasPrefix(line, \"+\") && !strings.HasPrefix(line, \"+++\") {\n\t\t\tadditions++\n\t\t} else if strings.HasPrefix(line, \"-\") && !strings.HasPrefix(line, \"---\") {\n\t\t\tremovals++\n\t\t}\n\t}\n\n\treturn unified, additions, removals\n}\n"], ["/opencode/internal/llm/agent/mcp-tools.go", "package agent\n\nimport (\n\t\"context\"\n\t\"encoding/json\"\n\t\"fmt\"\n\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/llm/tools\"\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n\t\"github.com/opencode-ai/opencode/internal/permission\"\n\t\"github.com/opencode-ai/opencode/internal/version\"\n\n\t\"github.com/mark3labs/mcp-go/client\"\n\t\"github.com/mark3labs/mcp-go/mcp\"\n)\n\ntype mcpTool struct {\n\tmcpName string\n\ttool mcp.Tool\n\tmcpConfig config.MCPServer\n\tpermissions permission.Service\n}\n\ntype MCPClient interface {\n\tInitialize(\n\t\tctx context.Context,\n\t\trequest mcp.InitializeRequest,\n\t) (*mcp.InitializeResult, error)\n\tListTools(ctx context.Context, request mcp.ListToolsRequest) (*mcp.ListToolsResult, error)\n\tCallTool(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error)\n\tClose() error\n}\n\nfunc (b *mcpTool) Info() tools.ToolInfo {\n\trequired := b.tool.InputSchema.Required\n\tif required == nil {\n\t\trequired = make([]string, 0)\n\t}\n\treturn tools.ToolInfo{\n\t\tName: fmt.Sprintf(\"%s_%s\", b.mcpName, b.tool.Name),\n\t\tDescription: b.tool.Description,\n\t\tParameters: b.tool.InputSchema.Properties,\n\t\tRequired: required,\n\t}\n}\n\nfunc runTool(ctx context.Context, c MCPClient, toolName string, input string) (tools.ToolResponse, error) {\n\tdefer c.Close()\n\tinitRequest := mcp.InitializeRequest{}\n\tinitRequest.Params.ProtocolVersion = mcp.LATEST_PROTOCOL_VERSION\n\tinitRequest.Params.ClientInfo = mcp.Implementation{\n\t\tName: \"OpenCode\",\n\t\tVersion: version.Version,\n\t}\n\n\t_, err := c.Initialize(ctx, initRequest)\n\tif err != nil {\n\t\treturn tools.NewTextErrorResponse(err.Error()), nil\n\t}\n\n\ttoolRequest := mcp.CallToolRequest{}\n\ttoolRequest.Params.Name = toolName\n\tvar args map[string]any\n\tif err = json.Unmarshal([]byte(input), &args); err != nil {\n\t\treturn tools.NewTextErrorResponse(fmt.Sprintf(\"error parsing parameters: %s\", err)), nil\n\t}\n\ttoolRequest.Params.Arguments = args\n\tresult, err := c.CallTool(ctx, toolRequest)\n\tif err != nil {\n\t\treturn tools.NewTextErrorResponse(err.Error()), nil\n\t}\n\n\toutput := \"\"\n\tfor _, v := range result.Content {\n\t\tif v, ok := v.(mcp.TextContent); ok {\n\t\t\toutput = v.Text\n\t\t} else {\n\t\t\toutput = fmt.Sprintf(\"%v\", v)\n\t\t}\n\t}\n\n\treturn tools.NewTextResponse(output), nil\n}\n\nfunc (b *mcpTool) Run(ctx context.Context, params tools.ToolCall) (tools.ToolResponse, error) {\n\tsessionID, messageID := tools.GetContextValues(ctx)\n\tif sessionID == \"\" || messageID == \"\" {\n\t\treturn tools.ToolResponse{}, fmt.Errorf(\"session ID and message ID are required for creating a new file\")\n\t}\n\tpermissionDescription := fmt.Sprintf(\"execute %s with the following parameters: %s\", b.Info().Name, params.Input)\n\tp := b.permissions.Request(\n\t\tpermission.CreatePermissionRequest{\n\t\t\tSessionID: sessionID,\n\t\t\tPath: config.WorkingDirectory(),\n\t\t\tToolName: b.Info().Name,\n\t\t\tAction: \"execute\",\n\t\t\tDescription: permissionDescription,\n\t\t\tParams: params.Input,\n\t\t},\n\t)\n\tif !p {\n\t\treturn tools.NewTextErrorResponse(\"permission denied\"), nil\n\t}\n\n\tswitch b.mcpConfig.Type {\n\tcase config.MCPStdio:\n\t\tc, err := client.NewStdioMCPClient(\n\t\t\tb.mcpConfig.Command,\n\t\t\tb.mcpConfig.Env,\n\t\t\tb.mcpConfig.Args...,\n\t\t)\n\t\tif err != nil {\n\t\t\treturn tools.NewTextErrorResponse(err.Error()), nil\n\t\t}\n\t\treturn runTool(ctx, c, b.tool.Name, params.Input)\n\tcase config.MCPSse:\n\t\tc, err := client.NewSSEMCPClient(\n\t\t\tb.mcpConfig.URL,\n\t\t\tclient.WithHeaders(b.mcpConfig.Headers),\n\t\t)\n\t\tif err != nil {\n\t\t\treturn tools.NewTextErrorResponse(err.Error()), nil\n\t\t}\n\t\treturn runTool(ctx, c, b.tool.Name, params.Input)\n\t}\n\n\treturn tools.NewTextErrorResponse(\"invalid mcp type\"), nil\n}\n\nfunc NewMcpTool(name string, tool mcp.Tool, permissions permission.Service, mcpConfig config.MCPServer) tools.BaseTool {\n\treturn &mcpTool{\n\t\tmcpName: name,\n\t\ttool: tool,\n\t\tmcpConfig: mcpConfig,\n\t\tpermissions: permissions,\n\t}\n}\n\nvar mcpTools []tools.BaseTool\n\nfunc getTools(ctx context.Context, name string, m config.MCPServer, permissions permission.Service, c MCPClient) []tools.BaseTool {\n\tvar stdioTools []tools.BaseTool\n\tinitRequest := mcp.InitializeRequest{}\n\tinitRequest.Params.ProtocolVersion = mcp.LATEST_PROTOCOL_VERSION\n\tinitRequest.Params.ClientInfo = mcp.Implementation{\n\t\tName: \"OpenCode\",\n\t\tVersion: version.Version,\n\t}\n\n\t_, err := c.Initialize(ctx, initRequest)\n\tif err != nil {\n\t\tlogging.Error(\"error initializing mcp client\", \"error\", err)\n\t\treturn stdioTools\n\t}\n\ttoolsRequest := mcp.ListToolsRequest{}\n\ttools, err := c.ListTools(ctx, toolsRequest)\n\tif err != nil {\n\t\tlogging.Error(\"error listing tools\", \"error\", err)\n\t\treturn stdioTools\n\t}\n\tfor _, t := range tools.Tools {\n\t\tstdioTools = append(stdioTools, NewMcpTool(name, t, permissions, m))\n\t}\n\tdefer c.Close()\n\treturn stdioTools\n}\n\nfunc GetMcpTools(ctx context.Context, permissions permission.Service) []tools.BaseTool {\n\tif len(mcpTools) > 0 {\n\t\treturn mcpTools\n\t}\n\tfor name, m := range config.Get().MCPServers {\n\t\tswitch m.Type {\n\t\tcase config.MCPStdio:\n\t\t\tc, err := client.NewStdioMCPClient(\n\t\t\t\tm.Command,\n\t\t\t\tm.Env,\n\t\t\t\tm.Args...,\n\t\t\t)\n\t\t\tif err != nil {\n\t\t\t\tlogging.Error(\"error creating mcp client\", \"error\", err)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tmcpTools = append(mcpTools, getTools(ctx, name, m, permissions, c)...)\n\t\tcase config.MCPSse:\n\t\t\tc, err := client.NewSSEMCPClient(\n\t\t\t\tm.URL,\n\t\t\t\tclient.WithHeaders(m.Headers),\n\t\t\t)\n\t\t\tif err != nil {\n\t\t\t\tlogging.Error(\"error creating mcp client\", \"error\", err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tmcpTools = append(mcpTools, getTools(ctx, name, m, permissions, c)...)\n\t\t}\n\t}\n\n\treturn mcpTools\n}\n"], ["/opencode/internal/tui/components/logs/table.go", "package logs\n\nimport (\n\t\"encoding/json\"\n\t\"slices\"\n\n\t\"github.com/charmbracelet/bubbles/key\"\n\t\"github.com/charmbracelet/bubbles/table\"\n\ttea \"github.com/charmbracelet/bubbletea\"\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n\t\"github.com/opencode-ai/opencode/internal/pubsub\"\n\t\"github.com/opencode-ai/opencode/internal/tui/layout\"\n\t\"github.com/opencode-ai/opencode/internal/tui/styles\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n\t\"github.com/opencode-ai/opencode/internal/tui/util\"\n)\n\ntype TableComponent interface {\n\ttea.Model\n\tlayout.Sizeable\n\tlayout.Bindings\n}\n\ntype tableCmp struct {\n\ttable table.Model\n}\n\ntype selectedLogMsg logging.LogMessage\n\nfunc (i *tableCmp) Init() tea.Cmd {\n\ti.setRows()\n\treturn nil\n}\n\nfunc (i *tableCmp) Update(msg tea.Msg) (tea.Model, tea.Cmd) {\n\tvar cmds []tea.Cmd\n\tswitch msg.(type) {\n\tcase pubsub.Event[logging.LogMessage]:\n\t\ti.setRows()\n\t\treturn i, nil\n\t}\n\tprevSelectedRow := i.table.SelectedRow()\n\tt, cmd := i.table.Update(msg)\n\tcmds = append(cmds, cmd)\n\ti.table = t\n\tselectedRow := i.table.SelectedRow()\n\tif selectedRow != nil {\n\t\tif prevSelectedRow == nil || selectedRow[0] == prevSelectedRow[0] {\n\t\t\tvar log logging.LogMessage\n\t\t\tfor _, row := range logging.List() {\n\t\t\t\tif row.ID == selectedRow[0] {\n\t\t\t\t\tlog = row\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\tif log.ID != \"\" {\n\t\t\t\tcmds = append(cmds, util.CmdHandler(selectedLogMsg(log)))\n\t\t\t}\n\t\t}\n\t}\n\treturn i, tea.Batch(cmds...)\n}\n\nfunc (i *tableCmp) View() string {\n\tt := theme.CurrentTheme()\n\tdefaultStyles := table.DefaultStyles()\n\tdefaultStyles.Selected = defaultStyles.Selected.Foreground(t.Primary())\n\ti.table.SetStyles(defaultStyles)\n\treturn styles.ForceReplaceBackgroundWithLipgloss(i.table.View(), t.Background())\n}\n\nfunc (i *tableCmp) GetSize() (int, int) {\n\treturn i.table.Width(), i.table.Height()\n}\n\nfunc (i *tableCmp) SetSize(width int, height int) tea.Cmd {\n\ti.table.SetWidth(width)\n\ti.table.SetHeight(height)\n\tcloumns := i.table.Columns()\n\tfor i, col := range cloumns {\n\t\tcol.Width = (width / len(cloumns)) - 2\n\t\tcloumns[i] = col\n\t}\n\ti.table.SetColumns(cloumns)\n\treturn nil\n}\n\nfunc (i *tableCmp) BindingKeys() []key.Binding {\n\treturn layout.KeyMapToSlice(i.table.KeyMap)\n}\n\nfunc (i *tableCmp) setRows() {\n\trows := []table.Row{}\n\n\tlogs := logging.List()\n\tslices.SortFunc(logs, func(a, b logging.LogMessage) int {\n\t\tif a.Time.Before(b.Time) {\n\t\t\treturn 1\n\t\t}\n\t\tif a.Time.After(b.Time) {\n\t\t\treturn -1\n\t\t}\n\t\treturn 0\n\t})\n\n\tfor _, log := range logs {\n\t\tbm, _ := json.Marshal(log.Attributes)\n\n\t\trow := table.Row{\n\t\t\tlog.ID,\n\t\t\tlog.Time.Format(\"15:04:05\"),\n\t\t\tlog.Level,\n\t\t\tlog.Message,\n\t\t\tstring(bm),\n\t\t}\n\t\trows = append(rows, row)\n\t}\n\ti.table.SetRows(rows)\n}\n\nfunc NewLogsTable() TableComponent {\n\tcolumns := []table.Column{\n\t\t{Title: \"ID\", Width: 4},\n\t\t{Title: \"Time\", Width: 4},\n\t\t{Title: \"Level\", Width: 10},\n\t\t{Title: \"Message\", Width: 10},\n\t\t{Title: \"Attributes\", Width: 10},\n\t}\n\n\ttableModel := table.New(\n\t\ttable.WithColumns(columns),\n\t)\n\ttableModel.Focus()\n\treturn &tableCmp{\n\t\ttable: tableModel,\n\t}\n}\n"], ["/opencode/internal/tui/components/chat/chat.go", "package chat\n\nimport (\n\t\"fmt\"\n\t\"sort\"\n\n\t\"github.com/charmbracelet/lipgloss\"\n\t\"github.com/charmbracelet/x/ansi\"\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/message\"\n\t\"github.com/opencode-ai/opencode/internal/session\"\n\t\"github.com/opencode-ai/opencode/internal/tui/styles\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n\t\"github.com/opencode-ai/opencode/internal/version\"\n)\n\ntype SendMsg struct {\n\tText string\n\tAttachments []message.Attachment\n}\n\ntype SessionSelectedMsg = session.Session\n\ntype SessionClearedMsg struct{}\n\ntype EditorFocusMsg bool\n\nfunc header(width int) string {\n\treturn lipgloss.JoinVertical(\n\t\tlipgloss.Top,\n\t\tlogo(width),\n\t\trepo(width),\n\t\t\"\",\n\t\tcwd(width),\n\t)\n}\n\nfunc lspsConfigured(width int) string {\n\tcfg := config.Get()\n\ttitle := \"LSP Configuration\"\n\ttitle = ansi.Truncate(title, width, \"…\")\n\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\n\tlsps := baseStyle.\n\t\tWidth(width).\n\t\tForeground(t.Primary()).\n\t\tBold(true).\n\t\tRender(title)\n\n\t// Get LSP names and sort them for consistent ordering\n\tvar lspNames []string\n\tfor name := range cfg.LSP {\n\t\tlspNames = append(lspNames, name)\n\t}\n\tsort.Strings(lspNames)\n\n\tvar lspViews []string\n\tfor _, name := range lspNames {\n\t\tlsp := cfg.LSP[name]\n\t\tlspName := baseStyle.\n\t\t\tForeground(t.Text()).\n\t\t\tRender(fmt.Sprintf(\"• %s\", name))\n\n\t\tcmd := lsp.Command\n\t\tcmd = ansi.Truncate(cmd, width-lipgloss.Width(lspName)-3, \"…\")\n\n\t\tlspPath := baseStyle.\n\t\t\tForeground(t.TextMuted()).\n\t\t\tRender(fmt.Sprintf(\" (%s)\", cmd))\n\n\t\tlspViews = append(lspViews,\n\t\t\tbaseStyle.\n\t\t\t\tWidth(width).\n\t\t\t\tRender(\n\t\t\t\t\tlipgloss.JoinHorizontal(\n\t\t\t\t\t\tlipgloss.Left,\n\t\t\t\t\t\tlspName,\n\t\t\t\t\t\tlspPath,\n\t\t\t\t\t),\n\t\t\t\t),\n\t\t)\n\t}\n\n\treturn baseStyle.\n\t\tWidth(width).\n\t\tRender(\n\t\t\tlipgloss.JoinVertical(\n\t\t\t\tlipgloss.Left,\n\t\t\t\tlsps,\n\t\t\t\tlipgloss.JoinVertical(\n\t\t\t\t\tlipgloss.Left,\n\t\t\t\t\tlspViews...,\n\t\t\t\t),\n\t\t\t),\n\t\t)\n}\n\nfunc logo(width int) string {\n\tlogo := fmt.Sprintf(\"%s %s\", styles.OpenCodeIcon, \"OpenCode\")\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\n\tversionText := baseStyle.\n\t\tForeground(t.TextMuted()).\n\t\tRender(version.Version)\n\n\treturn baseStyle.\n\t\tBold(true).\n\t\tWidth(width).\n\t\tRender(\n\t\t\tlipgloss.JoinHorizontal(\n\t\t\t\tlipgloss.Left,\n\t\t\t\tlogo,\n\t\t\t\t\" \",\n\t\t\t\tversionText,\n\t\t\t),\n\t\t)\n}\n\nfunc repo(width int) string {\n\trepo := \"https://github.com/opencode-ai/opencode\"\n\tt := theme.CurrentTheme()\n\n\treturn styles.BaseStyle().\n\t\tForeground(t.TextMuted()).\n\t\tWidth(width).\n\t\tRender(repo)\n}\n\nfunc cwd(width int) string {\n\tcwd := fmt.Sprintf(\"cwd: %s\", config.WorkingDirectory())\n\tt := theme.CurrentTheme()\n\n\treturn styles.BaseStyle().\n\t\tForeground(t.TextMuted()).\n\t\tWidth(width).\n\t\tRender(cwd)\n}\n\n"], ["/opencode/internal/message/message.go", "package message\n\nimport (\n\t\"context\"\n\t\"database/sql\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com/google/uuid\"\n\t\"github.com/opencode-ai/opencode/internal/db\"\n\t\"github.com/opencode-ai/opencode/internal/llm/models\"\n\t\"github.com/opencode-ai/opencode/internal/pubsub\"\n)\n\ntype CreateMessageParams struct {\n\tRole MessageRole\n\tParts []ContentPart\n\tModel models.ModelID\n}\n\ntype Service interface {\n\tpubsub.Suscriber[Message]\n\tCreate(ctx context.Context, sessionID string, params CreateMessageParams) (Message, error)\n\tUpdate(ctx context.Context, message Message) error\n\tGet(ctx context.Context, id string) (Message, error)\n\tList(ctx context.Context, sessionID string) ([]Message, error)\n\tDelete(ctx context.Context, id string) error\n\tDeleteSessionMessages(ctx context.Context, sessionID string) error\n}\n\ntype service struct {\n\t*pubsub.Broker[Message]\n\tq db.Querier\n}\n\nfunc NewService(q db.Querier) Service {\n\treturn &service{\n\t\tBroker: pubsub.NewBroker[Message](),\n\t\tq: q,\n\t}\n}\n\nfunc (s *service) Delete(ctx context.Context, id string) error {\n\tmessage, err := s.Get(ctx, id)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = s.q.DeleteMessage(ctx, message.ID)\n\tif err != nil {\n\t\treturn err\n\t}\n\ts.Publish(pubsub.DeletedEvent, message)\n\treturn nil\n}\n\nfunc (s *service) Create(ctx context.Context, sessionID string, params CreateMessageParams) (Message, error) {\n\tif params.Role != Assistant {\n\t\tparams.Parts = append(params.Parts, Finish{\n\t\t\tReason: \"stop\",\n\t\t})\n\t}\n\tpartsJSON, err := marshallParts(params.Parts)\n\tif err != nil {\n\t\treturn Message{}, err\n\t}\n\tdbMessage, err := s.q.CreateMessage(ctx, db.CreateMessageParams{\n\t\tID: uuid.New().String(),\n\t\tSessionID: sessionID,\n\t\tRole: string(params.Role),\n\t\tParts: string(partsJSON),\n\t\tModel: sql.NullString{String: string(params.Model), Valid: true},\n\t})\n\tif err != nil {\n\t\treturn Message{}, err\n\t}\n\tmessage, err := s.fromDBItem(dbMessage)\n\tif err != nil {\n\t\treturn Message{}, err\n\t}\n\ts.Publish(pubsub.CreatedEvent, message)\n\treturn message, nil\n}\n\nfunc (s *service) DeleteSessionMessages(ctx context.Context, sessionID string) error {\n\tmessages, err := s.List(ctx, sessionID)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor _, message := range messages {\n\t\tif message.SessionID == sessionID {\n\t\t\terr = s.Delete(ctx, message.ID)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (s *service) Update(ctx context.Context, message Message) error {\n\tparts, err := marshallParts(message.Parts)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfinishedAt := sql.NullInt64{}\n\tif f := message.FinishPart(); f != nil {\n\t\tfinishedAt.Int64 = f.Time\n\t\tfinishedAt.Valid = true\n\t}\n\terr = s.q.UpdateMessage(ctx, db.UpdateMessageParams{\n\t\tID: message.ID,\n\t\tParts: string(parts),\n\t\tFinishedAt: finishedAt,\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\tmessage.UpdatedAt = time.Now().Unix()\n\ts.Publish(pubsub.UpdatedEvent, message)\n\treturn nil\n}\n\nfunc (s *service) Get(ctx context.Context, id string) (Message, error) {\n\tdbMessage, err := s.q.GetMessage(ctx, id)\n\tif err != nil {\n\t\treturn Message{}, err\n\t}\n\treturn s.fromDBItem(dbMessage)\n}\n\nfunc (s *service) List(ctx context.Context, sessionID string) ([]Message, error) {\n\tdbMessages, err := s.q.ListMessagesBySession(ctx, sessionID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tmessages := make([]Message, len(dbMessages))\n\tfor i, dbMessage := range dbMessages {\n\t\tmessages[i], err = s.fromDBItem(dbMessage)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn messages, nil\n}\n\nfunc (s *service) fromDBItem(item db.Message) (Message, error) {\n\tparts, err := unmarshallParts([]byte(item.Parts))\n\tif err != nil {\n\t\treturn Message{}, err\n\t}\n\treturn Message{\n\t\tID: item.ID,\n\t\tSessionID: item.SessionID,\n\t\tRole: MessageRole(item.Role),\n\t\tParts: parts,\n\t\tModel: models.ModelID(item.Model.String),\n\t\tCreatedAt: item.CreatedAt,\n\t\tUpdatedAt: item.UpdatedAt,\n\t}, nil\n}\n\ntype partType string\n\nconst (\n\treasoningType partType = \"reasoning\"\n\ttextType partType = \"text\"\n\timageURLType partType = \"image_url\"\n\tbinaryType partType = \"binary\"\n\ttoolCallType partType = \"tool_call\"\n\ttoolResultType partType = \"tool_result\"\n\tfinishType partType = \"finish\"\n)\n\ntype partWrapper struct {\n\tType partType `json:\"type\"`\n\tData ContentPart `json:\"data\"`\n}\n\nfunc marshallParts(parts []ContentPart) ([]byte, error) {\n\twrappedParts := make([]partWrapper, len(parts))\n\n\tfor i, part := range parts {\n\t\tvar typ partType\n\n\t\tswitch part.(type) {\n\t\tcase ReasoningContent:\n\t\t\ttyp = reasoningType\n\t\tcase TextContent:\n\t\t\ttyp = textType\n\t\tcase ImageURLContent:\n\t\t\ttyp = imageURLType\n\t\tcase BinaryContent:\n\t\t\ttyp = binaryType\n\t\tcase ToolCall:\n\t\t\ttyp = toolCallType\n\t\tcase ToolResult:\n\t\t\ttyp = toolResultType\n\t\tcase Finish:\n\t\t\ttyp = finishType\n\t\tdefault:\n\t\t\treturn nil, fmt.Errorf(\"unknown part type: %T\", part)\n\t\t}\n\n\t\twrappedParts[i] = partWrapper{\n\t\t\tType: typ,\n\t\t\tData: part,\n\t\t}\n\t}\n\treturn json.Marshal(wrappedParts)\n}\n\nfunc unmarshallParts(data []byte) ([]ContentPart, error) {\n\ttemp := []json.RawMessage{}\n\n\tif err := json.Unmarshal(data, &temp); err != nil {\n\t\treturn nil, err\n\t}\n\n\tparts := make([]ContentPart, 0)\n\n\tfor _, rawPart := range temp {\n\t\tvar wrapper struct {\n\t\t\tType partType `json:\"type\"`\n\t\t\tData json.RawMessage `json:\"data\"`\n\t\t}\n\n\t\tif err := json.Unmarshal(rawPart, &wrapper); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tswitch wrapper.Type {\n\t\tcase reasoningType:\n\t\t\tpart := ReasoningContent{}\n\t\t\tif err := json.Unmarshal(wrapper.Data, &part); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tparts = append(parts, part)\n\t\tcase textType:\n\t\t\tpart := TextContent{}\n\t\t\tif err := json.Unmarshal(wrapper.Data, &part); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tparts = append(parts, part)\n\t\tcase imageURLType:\n\t\t\tpart := ImageURLContent{}\n\t\t\tif err := json.Unmarshal(wrapper.Data, &part); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\tcase binaryType:\n\t\t\tpart := BinaryContent{}\n\t\t\tif err := json.Unmarshal(wrapper.Data, &part); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tparts = append(parts, part)\n\t\tcase toolCallType:\n\t\t\tpart := ToolCall{}\n\t\t\tif err := json.Unmarshal(wrapper.Data, &part); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tparts = append(parts, part)\n\t\tcase toolResultType:\n\t\t\tpart := ToolResult{}\n\t\t\tif err := json.Unmarshal(wrapper.Data, &part); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tparts = append(parts, part)\n\t\tcase finishType:\n\t\t\tpart := Finish{}\n\t\t\tif err := json.Unmarshal(wrapper.Data, &part); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tparts = append(parts, part)\n\t\tdefault:\n\t\t\treturn nil, fmt.Errorf(\"unknown part type: %s\", wrapper.Type)\n\t\t}\n\n\t}\n\n\treturn parts, nil\n}\n"], ["/opencode/internal/tui/layout/split.go", "package layout\n\nimport (\n\t\"github.com/charmbracelet/bubbles/key\"\n\ttea \"github.com/charmbracelet/bubbletea\"\n\t\"github.com/charmbracelet/lipgloss\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n)\n\ntype SplitPaneLayout interface {\n\ttea.Model\n\tSizeable\n\tBindings\n\tSetLeftPanel(panel Container) tea.Cmd\n\tSetRightPanel(panel Container) tea.Cmd\n\tSetBottomPanel(panel Container) tea.Cmd\n\n\tClearLeftPanel() tea.Cmd\n\tClearRightPanel() tea.Cmd\n\tClearBottomPanel() tea.Cmd\n}\n\ntype splitPaneLayout struct {\n\twidth int\n\theight int\n\tratio float64\n\tverticalRatio float64\n\n\trightPanel Container\n\tleftPanel Container\n\tbottomPanel Container\n}\n\ntype SplitPaneOption func(*splitPaneLayout)\n\nfunc (s *splitPaneLayout) Init() tea.Cmd {\n\tvar cmds []tea.Cmd\n\n\tif s.leftPanel != nil {\n\t\tcmds = append(cmds, s.leftPanel.Init())\n\t}\n\n\tif s.rightPanel != nil {\n\t\tcmds = append(cmds, s.rightPanel.Init())\n\t}\n\n\tif s.bottomPanel != nil {\n\t\tcmds = append(cmds, s.bottomPanel.Init())\n\t}\n\n\treturn tea.Batch(cmds...)\n}\n\nfunc (s *splitPaneLayout) Update(msg tea.Msg) (tea.Model, tea.Cmd) {\n\tvar cmds []tea.Cmd\n\tswitch msg := msg.(type) {\n\tcase tea.WindowSizeMsg:\n\t\treturn s, s.SetSize(msg.Width, msg.Height)\n\t}\n\n\tif s.rightPanel != nil {\n\t\tu, cmd := s.rightPanel.Update(msg)\n\t\ts.rightPanel = u.(Container)\n\t\tif cmd != nil {\n\t\t\tcmds = append(cmds, cmd)\n\t\t}\n\t}\n\n\tif s.leftPanel != nil {\n\t\tu, cmd := s.leftPanel.Update(msg)\n\t\ts.leftPanel = u.(Container)\n\t\tif cmd != nil {\n\t\t\tcmds = append(cmds, cmd)\n\t\t}\n\t}\n\n\tif s.bottomPanel != nil {\n\t\tu, cmd := s.bottomPanel.Update(msg)\n\t\ts.bottomPanel = u.(Container)\n\t\tif cmd != nil {\n\t\t\tcmds = append(cmds, cmd)\n\t\t}\n\t}\n\n\treturn s, tea.Batch(cmds...)\n}\n\nfunc (s *splitPaneLayout) View() string {\n\tvar topSection string\n\n\tif s.leftPanel != nil && s.rightPanel != nil {\n\t\tleftView := s.leftPanel.View()\n\t\trightView := s.rightPanel.View()\n\t\ttopSection = lipgloss.JoinHorizontal(lipgloss.Top, leftView, rightView)\n\t} else if s.leftPanel != nil {\n\t\ttopSection = s.leftPanel.View()\n\t} else if s.rightPanel != nil {\n\t\ttopSection = s.rightPanel.View()\n\t} else {\n\t\ttopSection = \"\"\n\t}\n\n\tvar finalView string\n\n\tif s.bottomPanel != nil && topSection != \"\" {\n\t\tbottomView := s.bottomPanel.View()\n\t\tfinalView = lipgloss.JoinVertical(lipgloss.Left, topSection, bottomView)\n\t} else if s.bottomPanel != nil {\n\t\tfinalView = s.bottomPanel.View()\n\t} else {\n\t\tfinalView = topSection\n\t}\n\n\tif finalView != \"\" {\n\t\tt := theme.CurrentTheme()\n\n\t\tstyle := lipgloss.NewStyle().\n\t\t\tWidth(s.width).\n\t\t\tHeight(s.height).\n\t\t\tBackground(t.Background())\n\n\t\treturn style.Render(finalView)\n\t}\n\n\treturn finalView\n}\n\nfunc (s *splitPaneLayout) SetSize(width, height int) tea.Cmd {\n\ts.width = width\n\ts.height = height\n\n\tvar topHeight, bottomHeight int\n\tif s.bottomPanel != nil {\n\t\ttopHeight = int(float64(height) * s.verticalRatio)\n\t\tbottomHeight = height - topHeight\n\t} else {\n\t\ttopHeight = height\n\t\tbottomHeight = 0\n\t}\n\n\tvar leftWidth, rightWidth int\n\tif s.leftPanel != nil && s.rightPanel != nil {\n\t\tleftWidth = int(float64(width) * s.ratio)\n\t\trightWidth = width - leftWidth\n\t} else if s.leftPanel != nil {\n\t\tleftWidth = width\n\t\trightWidth = 0\n\t} else if s.rightPanel != nil {\n\t\tleftWidth = 0\n\t\trightWidth = width\n\t}\n\n\tvar cmds []tea.Cmd\n\tif s.leftPanel != nil {\n\t\tcmd := s.leftPanel.SetSize(leftWidth, topHeight)\n\t\tcmds = append(cmds, cmd)\n\t}\n\n\tif s.rightPanel != nil {\n\t\tcmd := s.rightPanel.SetSize(rightWidth, topHeight)\n\t\tcmds = append(cmds, cmd)\n\t}\n\n\tif s.bottomPanel != nil {\n\t\tcmd := s.bottomPanel.SetSize(width, bottomHeight)\n\t\tcmds = append(cmds, cmd)\n\t}\n\treturn tea.Batch(cmds...)\n}\n\nfunc (s *splitPaneLayout) GetSize() (int, int) {\n\treturn s.width, s.height\n}\n\nfunc (s *splitPaneLayout) SetLeftPanel(panel Container) tea.Cmd {\n\ts.leftPanel = panel\n\tif s.width > 0 && s.height > 0 {\n\t\treturn s.SetSize(s.width, s.height)\n\t}\n\treturn nil\n}\n\nfunc (s *splitPaneLayout) SetRightPanel(panel Container) tea.Cmd {\n\ts.rightPanel = panel\n\tif s.width > 0 && s.height > 0 {\n\t\treturn s.SetSize(s.width, s.height)\n\t}\n\treturn nil\n}\n\nfunc (s *splitPaneLayout) SetBottomPanel(panel Container) tea.Cmd {\n\ts.bottomPanel = panel\n\tif s.width > 0 && s.height > 0 {\n\t\treturn s.SetSize(s.width, s.height)\n\t}\n\treturn nil\n}\n\nfunc (s *splitPaneLayout) ClearLeftPanel() tea.Cmd {\n\ts.leftPanel = nil\n\tif s.width > 0 && s.height > 0 {\n\t\treturn s.SetSize(s.width, s.height)\n\t}\n\treturn nil\n}\n\nfunc (s *splitPaneLayout) ClearRightPanel() tea.Cmd {\n\ts.rightPanel = nil\n\tif s.width > 0 && s.height > 0 {\n\t\treturn s.SetSize(s.width, s.height)\n\t}\n\treturn nil\n}\n\nfunc (s *splitPaneLayout) ClearBottomPanel() tea.Cmd {\n\ts.bottomPanel = nil\n\tif s.width > 0 && s.height > 0 {\n\t\treturn s.SetSize(s.width, s.height)\n\t}\n\treturn nil\n}\n\nfunc (s *splitPaneLayout) BindingKeys() []key.Binding {\n\tkeys := []key.Binding{}\n\tif s.leftPanel != nil {\n\t\tif b, ok := s.leftPanel.(Bindings); ok {\n\t\t\tkeys = append(keys, b.BindingKeys()...)\n\t\t}\n\t}\n\tif s.rightPanel != nil {\n\t\tif b, ok := s.rightPanel.(Bindings); ok {\n\t\t\tkeys = append(keys, b.BindingKeys()...)\n\t\t}\n\t}\n\tif s.bottomPanel != nil {\n\t\tif b, ok := s.bottomPanel.(Bindings); ok {\n\t\t\tkeys = append(keys, b.BindingKeys()...)\n\t\t}\n\t}\n\treturn keys\n}\n\nfunc NewSplitPane(options ...SplitPaneOption) SplitPaneLayout {\n\n\tlayout := &splitPaneLayout{\n\t\tratio: 0.7,\n\t\tverticalRatio: 0.9, // Default 90% for top section, 10% for bottom\n\t}\n\tfor _, option := range options {\n\t\toption(layout)\n\t}\n\treturn layout\n}\n\nfunc WithLeftPanel(panel Container) SplitPaneOption {\n\treturn func(s *splitPaneLayout) {\n\t\ts.leftPanel = panel\n\t}\n}\n\nfunc WithRightPanel(panel Container) SplitPaneOption {\n\treturn func(s *splitPaneLayout) {\n\t\ts.rightPanel = panel\n\t}\n}\n\nfunc WithRatio(ratio float64) SplitPaneOption {\n\treturn func(s *splitPaneLayout) {\n\t\ts.ratio = ratio\n\t}\n}\n\nfunc WithBottomPanel(panel Container) SplitPaneOption {\n\treturn func(s *splitPaneLayout) {\n\t\ts.bottomPanel = panel\n\t}\n}\n\nfunc WithVerticalRatio(ratio float64) SplitPaneOption {\n\treturn func(s *splitPaneLayout) {\n\t\ts.verticalRatio = ratio\n\t}\n}\n"], ["/opencode/internal/tui/page/logs.go", "package page\n\nimport (\n\t\"github.com/charmbracelet/bubbles/key\"\n\ttea \"github.com/charmbracelet/bubbletea\"\n\t\"github.com/charmbracelet/lipgloss\"\n\t\"github.com/opencode-ai/opencode/internal/tui/components/logs\"\n\t\"github.com/opencode-ai/opencode/internal/tui/layout\"\n\t\"github.com/opencode-ai/opencode/internal/tui/styles\"\n)\n\nvar LogsPage PageID = \"logs\"\n\ntype LogPage interface {\n\ttea.Model\n\tlayout.Sizeable\n\tlayout.Bindings\n}\ntype logsPage struct {\n\twidth, height int\n\ttable layout.Container\n\tdetails layout.Container\n}\n\nfunc (p *logsPage) Update(msg tea.Msg) (tea.Model, tea.Cmd) {\n\tvar cmds []tea.Cmd\n\tswitch msg := msg.(type) {\n\tcase tea.WindowSizeMsg:\n\t\tp.width = msg.Width\n\t\tp.height = msg.Height\n\t\treturn p, p.SetSize(msg.Width, msg.Height)\n\t}\n\n\ttable, cmd := p.table.Update(msg)\n\tcmds = append(cmds, cmd)\n\tp.table = table.(layout.Container)\n\tdetails, cmd := p.details.Update(msg)\n\tcmds = append(cmds, cmd)\n\tp.details = details.(layout.Container)\n\n\treturn p, tea.Batch(cmds...)\n}\n\nfunc (p *logsPage) View() string {\n\tstyle := styles.BaseStyle().Width(p.width).Height(p.height)\n\treturn style.Render(lipgloss.JoinVertical(lipgloss.Top,\n\t\tp.table.View(),\n\t\tp.details.View(),\n\t))\n}\n\nfunc (p *logsPage) BindingKeys() []key.Binding {\n\treturn p.table.BindingKeys()\n}\n\n// GetSize implements LogPage.\nfunc (p *logsPage) GetSize() (int, int) {\n\treturn p.width, p.height\n}\n\n// SetSize implements LogPage.\nfunc (p *logsPage) SetSize(width int, height int) tea.Cmd {\n\tp.width = width\n\tp.height = height\n\treturn tea.Batch(\n\t\tp.table.SetSize(width, height/2),\n\t\tp.details.SetSize(width, height/2),\n\t)\n}\n\nfunc (p *logsPage) Init() tea.Cmd {\n\treturn tea.Batch(\n\t\tp.table.Init(),\n\t\tp.details.Init(),\n\t)\n}\n\nfunc NewLogsPage() LogPage {\n\treturn &logsPage{\n\t\ttable: layout.NewContainer(logs.NewLogsTable(), layout.WithBorderAll()),\n\t\tdetails: layout.NewContainer(logs.NewLogsDetails(), layout.WithBorderAll()),\n\t}\n}\n"], ["/opencode/internal/format/spinner.go", "package format\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"os\"\n\n\t\"github.com/charmbracelet/bubbles/spinner\"\n\ttea \"github.com/charmbracelet/bubbletea\"\n)\n\n// Spinner wraps the bubbles spinner for non-interactive mode\ntype Spinner struct {\n\tmodel spinner.Model\n\tdone chan struct{}\n\tprog *tea.Program\n\tctx context.Context\n\tcancel context.CancelFunc\n}\n\n// spinnerModel is the tea.Model for the spinner\ntype spinnerModel struct {\n\tspinner spinner.Model\n\tmessage string\n\tquitting bool\n}\n\nfunc (m spinnerModel) Init() tea.Cmd {\n\treturn m.spinner.Tick\n}\n\nfunc (m spinnerModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {\n\tswitch msg := msg.(type) {\n\tcase tea.KeyMsg:\n\t\tm.quitting = true\n\t\treturn m, tea.Quit\n\tcase spinner.TickMsg:\n\t\tvar cmd tea.Cmd\n\t\tm.spinner, cmd = m.spinner.Update(msg)\n\t\treturn m, cmd\n\tcase quitMsg:\n\t\tm.quitting = true\n\t\treturn m, tea.Quit\n\tdefault:\n\t\treturn m, nil\n\t}\n}\n\nfunc (m spinnerModel) View() string {\n\tif m.quitting {\n\t\treturn \"\"\n\t}\n\treturn fmt.Sprintf(\"%s %s\", m.spinner.View(), m.message)\n}\n\n// quitMsg is sent when we want to quit the spinner\ntype quitMsg struct{}\n\n// NewSpinner creates a new spinner with the given message\nfunc NewSpinner(message string) *Spinner {\n\ts := spinner.New()\n\ts.Spinner = spinner.Dot\n\ts.Style = s.Style.Foreground(s.Style.GetForeground())\n\n\tctx, cancel := context.WithCancel(context.Background())\n\n\tmodel := spinnerModel{\n\t\tspinner: s,\n\t\tmessage: message,\n\t}\n\n\tprog := tea.NewProgram(model, tea.WithOutput(os.Stderr), tea.WithoutCatchPanics())\n\n\treturn &Spinner{\n\t\tmodel: s,\n\t\tdone: make(chan struct{}),\n\t\tprog: prog,\n\t\tctx: ctx,\n\t\tcancel: cancel,\n\t}\n}\n\n// Start begins the spinner animation\nfunc (s *Spinner) Start() {\n\tgo func() {\n\t\tdefer close(s.done)\n\t\tgo func() {\n\t\t\t<-s.ctx.Done()\n\t\t\ts.prog.Send(quitMsg{})\n\t\t}()\n\t\t_, err := s.prog.Run()\n\t\tif err != nil {\n\t\t\tfmt.Fprintf(os.Stderr, \"Error running spinner: %v\\n\", err)\n\t\t}\n\t}()\n}\n\n// Stop ends the spinner animation\nfunc (s *Spinner) Stop() {\n\ts.cancel()\n\t<-s.done\n}\n"], ["/opencode/internal/tui/layout/overlay.go", "package layout\n\nimport (\n\t\"strings\"\n\n\t\"github.com/charmbracelet/lipgloss\"\n\tchAnsi \"github.com/charmbracelet/x/ansi\"\n\t\"github.com/muesli/ansi\"\n\t\"github.com/muesli/reflow/truncate\"\n\t\"github.com/muesli/termenv\"\n\t\"github.com/opencode-ai/opencode/internal/tui/styles\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n\t\"github.com/opencode-ai/opencode/internal/tui/util\"\n)\n\n// Most of this code is borrowed from\n// https://github.com/charmbracelet/lipgloss/pull/102\n// as well as the lipgloss library, with some modification for what I needed.\n\n// Split a string into lines, additionally returning the size of the widest\n// line.\nfunc getLines(s string) (lines []string, widest int) {\n\tlines = strings.Split(s, \"\\n\")\n\n\tfor _, l := range lines {\n\t\tw := ansi.PrintableRuneWidth(l)\n\t\tif widest < w {\n\t\t\twidest = w\n\t\t}\n\t}\n\n\treturn lines, widest\n}\n\n// PlaceOverlay places fg on top of bg.\nfunc PlaceOverlay(\n\tx, y int,\n\tfg, bg string,\n\tshadow bool, opts ...WhitespaceOption,\n) string {\n\tfgLines, fgWidth := getLines(fg)\n\tbgLines, bgWidth := getLines(bg)\n\tbgHeight := len(bgLines)\n\tfgHeight := len(fgLines)\n\n\tif shadow {\n\t\tt := theme.CurrentTheme()\n\t\tbaseStyle := styles.BaseStyle()\n\n\t\tvar shadowbg string = \"\"\n\t\tshadowchar := lipgloss.NewStyle().\n\t\t\tBackground(t.BackgroundDarker()).\n\t\t\tForeground(t.Background()).\n\t\t\tRender(\"░\")\n\t\tbgchar := baseStyle.Render(\" \")\n\t\tfor i := 0; i <= fgHeight; i++ {\n\t\t\tif i == 0 {\n\t\t\t\tshadowbg += bgchar + strings.Repeat(bgchar, fgWidth) + \"\\n\"\n\t\t\t} else {\n\t\t\t\tshadowbg += bgchar + strings.Repeat(shadowchar, fgWidth) + \"\\n\"\n\t\t\t}\n\t\t}\n\n\t\tfg = PlaceOverlay(0, 0, fg, shadowbg, false, opts...)\n\t\tfgLines, fgWidth = getLines(fg)\n\t\tfgHeight = len(fgLines)\n\t}\n\n\tif fgWidth >= bgWidth && fgHeight >= bgHeight {\n\t\t// FIXME: return fg or bg?\n\t\treturn fg\n\t}\n\t// TODO: allow placement outside of the bg box?\n\tx = util.Clamp(x, 0, bgWidth-fgWidth)\n\ty = util.Clamp(y, 0, bgHeight-fgHeight)\n\n\tws := &whitespace{}\n\tfor _, opt := range opts {\n\t\topt(ws)\n\t}\n\n\tvar b strings.Builder\n\tfor i, bgLine := range bgLines {\n\t\tif i > 0 {\n\t\t\tb.WriteByte('\\n')\n\t\t}\n\t\tif i < y || i >= y+fgHeight {\n\t\t\tb.WriteString(bgLine)\n\t\t\tcontinue\n\t\t}\n\n\t\tpos := 0\n\t\tif x > 0 {\n\t\t\tleft := truncate.String(bgLine, uint(x))\n\t\t\tpos = ansi.PrintableRuneWidth(left)\n\t\t\tb.WriteString(left)\n\t\t\tif pos < x {\n\t\t\t\tb.WriteString(ws.render(x - pos))\n\t\t\t\tpos = x\n\t\t\t}\n\t\t}\n\n\t\tfgLine := fgLines[i-y]\n\t\tb.WriteString(fgLine)\n\t\tpos += ansi.PrintableRuneWidth(fgLine)\n\n\t\tright := cutLeft(bgLine, pos)\n\t\tbgWidth := ansi.PrintableRuneWidth(bgLine)\n\t\trightWidth := ansi.PrintableRuneWidth(right)\n\t\tif rightWidth <= bgWidth-pos {\n\t\t\tb.WriteString(ws.render(bgWidth - rightWidth - pos))\n\t\t}\n\n\t\tb.WriteString(right)\n\t}\n\n\treturn b.String()\n}\n\n// cutLeft cuts printable characters from the left.\n// This function is heavily based on muesli's ansi and truncate packages.\nfunc cutLeft(s string, cutWidth int) string {\n\treturn chAnsi.Cut(s, cutWidth, lipgloss.Width(s))\n}\n\nfunc max(a, b int) int {\n\tif a > b {\n\t\treturn a\n\t}\n\treturn b\n}\n\ntype whitespace struct {\n\tstyle termenv.Style\n\tchars string\n}\n\n// Render whitespaces.\nfunc (w whitespace) render(width int) string {\n\tif w.chars == \"\" {\n\t\tw.chars = \" \"\n\t}\n\n\tr := []rune(w.chars)\n\tj := 0\n\tb := strings.Builder{}\n\n\t// Cycle through runes and print them into the whitespace.\n\tfor i := 0; i < width; {\n\t\tb.WriteRune(r[j])\n\t\tj++\n\t\tif j >= len(r) {\n\t\t\tj = 0\n\t\t}\n\t\ti += ansi.PrintableRuneWidth(string(r[j]))\n\t}\n\n\t// Fill any extra gaps white spaces. This might be necessary if any runes\n\t// are more than one cell wide, which could leave a one-rune gap.\n\tshort := width - ansi.PrintableRuneWidth(b.String())\n\tif short > 0 {\n\t\tb.WriteString(strings.Repeat(\" \", short))\n\t}\n\n\treturn w.style.Styled(b.String())\n}\n\n// WhitespaceOption sets a styling rule for rendering whitespace.\ntype WhitespaceOption func(*whitespace)\n"], ["/opencode/cmd/root.go", "package cmd\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"os\"\n\t\"sync\"\n\t\"time\"\n\n\ttea \"github.com/charmbracelet/bubbletea\"\n\tzone \"github.com/lrstanley/bubblezone\"\n\t\"github.com/opencode-ai/opencode/internal/app\"\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/db\"\n\t\"github.com/opencode-ai/opencode/internal/format\"\n\t\"github.com/opencode-ai/opencode/internal/llm/agent\"\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n\t\"github.com/opencode-ai/opencode/internal/pubsub\"\n\t\"github.com/opencode-ai/opencode/internal/tui\"\n\t\"github.com/opencode-ai/opencode/internal/version\"\n\t\"github.com/spf13/cobra\"\n)\n\nvar rootCmd = &cobra.Command{\n\tUse: \"opencode\",\n\tShort: \"Terminal-based AI assistant for software development\",\n\tLong: `OpenCode is a powerful terminal-based AI assistant that helps with software development tasks.\nIt provides an interactive chat interface with AI capabilities, code analysis, and LSP integration\nto assist developers in writing, debugging, and understanding code directly from the terminal.`,\n\tExample: `\n # Run in interactive mode\n opencode\n\n # Run with debug logging\n opencode -d\n\n # Run with debug logging in a specific directory\n opencode -d -c /path/to/project\n\n # Print version\n opencode -v\n\n # Run a single non-interactive prompt\n opencode -p \"Explain the use of context in Go\"\n\n # Run a single non-interactive prompt with JSON output format\n opencode -p \"Explain the use of context in Go\" -f json\n `,\n\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t// If the help flag is set, show the help message\n\t\tif cmd.Flag(\"help\").Changed {\n\t\t\tcmd.Help()\n\t\t\treturn nil\n\t\t}\n\t\tif cmd.Flag(\"version\").Changed {\n\t\t\tfmt.Println(version.Version)\n\t\t\treturn nil\n\t\t}\n\n\t\t// Load the config\n\t\tdebug, _ := cmd.Flags().GetBool(\"debug\")\n\t\tcwd, _ := cmd.Flags().GetString(\"cwd\")\n\t\tprompt, _ := cmd.Flags().GetString(\"prompt\")\n\t\toutputFormat, _ := cmd.Flags().GetString(\"output-format\")\n\t\tquiet, _ := cmd.Flags().GetBool(\"quiet\")\n\n\t\t// Validate format option\n\t\tif !format.IsValid(outputFormat) {\n\t\t\treturn fmt.Errorf(\"invalid format option: %s\\n%s\", outputFormat, format.GetHelpText())\n\t\t}\n\n\t\tif cwd != \"\" {\n\t\t\terr := os.Chdir(cwd)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"failed to change directory: %v\", err)\n\t\t\t}\n\t\t}\n\t\tif cwd == \"\" {\n\t\t\tc, err := os.Getwd()\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"failed to get current working directory: %v\", err)\n\t\t\t}\n\t\t\tcwd = c\n\t\t}\n\t\t_, err := config.Load(cwd, debug)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Connect DB, this will also run migrations\n\t\tconn, err := db.Connect()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Create main context for the application\n\t\tctx, cancel := context.WithCancel(context.Background())\n\t\tdefer cancel()\n\n\t\tapp, err := app.New(ctx, conn)\n\t\tif err != nil {\n\t\t\tlogging.Error(\"Failed to create app: %v\", err)\n\t\t\treturn err\n\t\t}\n\t\t// Defer shutdown here so it runs for both interactive and non-interactive modes\n\t\tdefer app.Shutdown()\n\n\t\t// Initialize MCP tools early for both modes\n\t\tinitMCPTools(ctx, app)\n\n\t\t// Non-interactive mode\n\t\tif prompt != \"\" {\n\t\t\t// Run non-interactive flow using the App method\n\t\t\treturn app.RunNonInteractive(ctx, prompt, outputFormat, quiet)\n\t\t}\n\n\t\t// Interactive mode\n\t\t// Set up the TUI\n\t\tzone.NewGlobal()\n\t\tprogram := tea.NewProgram(\n\t\t\ttui.New(app),\n\t\t\ttea.WithAltScreen(),\n\t\t)\n\n\t\t// Setup the subscriptions, this will send services events to the TUI\n\t\tch, cancelSubs := setupSubscriptions(app, ctx)\n\n\t\t// Create a context for the TUI message handler\n\t\ttuiCtx, tuiCancel := context.WithCancel(ctx)\n\t\tvar tuiWg sync.WaitGroup\n\t\ttuiWg.Add(1)\n\n\t\t// Set up message handling for the TUI\n\t\tgo func() {\n\t\t\tdefer tuiWg.Done()\n\t\t\tdefer logging.RecoverPanic(\"TUI-message-handler\", func() {\n\t\t\t\tattemptTUIRecovery(program)\n\t\t\t})\n\n\t\t\tfor {\n\t\t\t\tselect {\n\t\t\t\tcase <-tuiCtx.Done():\n\t\t\t\t\tlogging.Info(\"TUI message handler shutting down\")\n\t\t\t\t\treturn\n\t\t\t\tcase msg, ok := <-ch:\n\t\t\t\t\tif !ok {\n\t\t\t\t\t\tlogging.Info(\"TUI message channel closed\")\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\tprogram.Send(msg)\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\n\t\t// Cleanup function for when the program exits\n\t\tcleanup := func() {\n\t\t\t// Shutdown the app\n\t\t\tapp.Shutdown()\n\n\t\t\t// Cancel subscriptions first\n\t\t\tcancelSubs()\n\n\t\t\t// Then cancel TUI message handler\n\t\t\ttuiCancel()\n\n\t\t\t// Wait for TUI message handler to finish\n\t\t\ttuiWg.Wait()\n\n\t\t\tlogging.Info(\"All goroutines cleaned up\")\n\t\t}\n\n\t\t// Run the TUI\n\t\tresult, err := program.Run()\n\t\tcleanup()\n\n\t\tif err != nil {\n\t\t\tlogging.Error(\"TUI error: %v\", err)\n\t\t\treturn fmt.Errorf(\"TUI error: %v\", err)\n\t\t}\n\n\t\tlogging.Info(\"TUI exited with result: %v\", result)\n\t\treturn nil\n\t},\n}\n\n// attemptTUIRecovery tries to recover the TUI after a panic\nfunc attemptTUIRecovery(program *tea.Program) {\n\tlogging.Info(\"Attempting to recover TUI after panic\")\n\n\t// We could try to restart the TUI or gracefully exit\n\t// For now, we'll just quit the program to avoid further issues\n\tprogram.Quit()\n}\n\nfunc initMCPTools(ctx context.Context, app *app.App) {\n\tgo func() {\n\t\tdefer logging.RecoverPanic(\"MCP-goroutine\", nil)\n\n\t\t// Create a context with timeout for the initial MCP tools fetch\n\t\tctxWithTimeout, cancel := context.WithTimeout(ctx, 30*time.Second)\n\t\tdefer cancel()\n\n\t\t// Set this up once with proper error handling\n\t\tagent.GetMcpTools(ctxWithTimeout, app.Permissions)\n\t\tlogging.Info(\"MCP message handling goroutine exiting\")\n\t}()\n}\n\nfunc setupSubscriber[T any](\n\tctx context.Context,\n\twg *sync.WaitGroup,\n\tname string,\n\tsubscriber func(context.Context) <-chan pubsub.Event[T],\n\toutputCh chan<- tea.Msg,\n) {\n\twg.Add(1)\n\tgo func() {\n\t\tdefer wg.Done()\n\t\tdefer logging.RecoverPanic(fmt.Sprintf(\"subscription-%s\", name), nil)\n\n\t\tsubCh := subscriber(ctx)\n\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase event, ok := <-subCh:\n\t\t\t\tif !ok {\n\t\t\t\t\tlogging.Info(\"subscription channel closed\", \"name\", name)\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tvar msg tea.Msg = event\n\n\t\t\t\tselect {\n\t\t\t\tcase outputCh <- msg:\n\t\t\t\tcase <-time.After(2 * time.Second):\n\t\t\t\t\tlogging.Warn(\"message dropped due to slow consumer\", \"name\", name)\n\t\t\t\tcase <-ctx.Done():\n\t\t\t\t\tlogging.Info(\"subscription cancelled\", \"name\", name)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\tcase <-ctx.Done():\n\t\t\t\tlogging.Info(\"subscription cancelled\", \"name\", name)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}()\n}\n\nfunc setupSubscriptions(app *app.App, parentCtx context.Context) (chan tea.Msg, func()) {\n\tch := make(chan tea.Msg, 100)\n\n\twg := sync.WaitGroup{}\n\tctx, cancel := context.WithCancel(parentCtx) // Inherit from parent context\n\n\tsetupSubscriber(ctx, &wg, \"logging\", logging.Subscribe, ch)\n\tsetupSubscriber(ctx, &wg, \"sessions\", app.Sessions.Subscribe, ch)\n\tsetupSubscriber(ctx, &wg, \"messages\", app.Messages.Subscribe, ch)\n\tsetupSubscriber(ctx, &wg, \"permissions\", app.Permissions.Subscribe, ch)\n\tsetupSubscriber(ctx, &wg, \"coderAgent\", app.CoderAgent.Subscribe, ch)\n\n\tcleanupFunc := func() {\n\t\tlogging.Info(\"Cancelling all subscriptions\")\n\t\tcancel() // Signal all goroutines to stop\n\n\t\twaitCh := make(chan struct{})\n\t\tgo func() {\n\t\t\tdefer logging.RecoverPanic(\"subscription-cleanup\", nil)\n\t\t\twg.Wait()\n\t\t\tclose(waitCh)\n\t\t}()\n\n\t\tselect {\n\t\tcase <-waitCh:\n\t\t\tlogging.Info(\"All subscription goroutines completed successfully\")\n\t\t\tclose(ch) // Only close after all writers are confirmed done\n\t\tcase <-time.After(5 * time.Second):\n\t\t\tlogging.Warn(\"Timed out waiting for some subscription goroutines to complete\")\n\t\t\tclose(ch)\n\t\t}\n\t}\n\treturn ch, cleanupFunc\n}\n\nfunc Execute() {\n\terr := rootCmd.Execute()\n\tif err != nil {\n\t\tos.Exit(1)\n\t}\n}\n\nfunc init() {\n\trootCmd.Flags().BoolP(\"help\", \"h\", false, \"Help\")\n\trootCmd.Flags().BoolP(\"version\", \"v\", false, \"Version\")\n\trootCmd.Flags().BoolP(\"debug\", \"d\", false, \"Debug\")\n\trootCmd.Flags().StringP(\"cwd\", \"c\", \"\", \"Current working directory\")\n\trootCmd.Flags().StringP(\"prompt\", \"p\", \"\", \"Prompt to run in non-interactive mode\")\n\n\t// Add format flag with validation logic\n\trootCmd.Flags().StringP(\"output-format\", \"f\", format.Text.String(),\n\t\t\"Output format for non-interactive mode (text, json)\")\n\n\t// Add quiet flag to hide spinner in non-interactive mode\n\trootCmd.Flags().BoolP(\"quiet\", \"q\", false, \"Hide spinner in non-interactive mode\")\n\n\t// Register custom validation for the format flag\n\trootCmd.RegisterFlagCompletionFunc(\"output-format\", func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {\n\t\treturn format.SupportedFormats, cobra.ShellCompDirectiveNoFileComp\n\t})\n}\n"], ["/opencode/internal/logging/writer.go", "package logging\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"fmt\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com/go-logfmt/logfmt\"\n\t\"github.com/opencode-ai/opencode/internal/pubsub\"\n)\n\nconst (\n\tpersistKeyArg = \"$_persist\"\n\tPersistTimeArg = \"$_persist_time\"\n)\n\ntype LogData struct {\n\tmessages []LogMessage\n\t*pubsub.Broker[LogMessage]\n\tlock sync.Mutex\n}\n\nfunc (l *LogData) Add(msg LogMessage) {\n\tl.lock.Lock()\n\tdefer l.lock.Unlock()\n\tl.messages = append(l.messages, msg)\n\tl.Publish(pubsub.CreatedEvent, msg)\n}\n\nfunc (l *LogData) List() []LogMessage {\n\tl.lock.Lock()\n\tdefer l.lock.Unlock()\n\treturn l.messages\n}\n\nvar defaultLogData = &LogData{\n\tmessages: make([]LogMessage, 0),\n\tBroker: pubsub.NewBroker[LogMessage](),\n}\n\ntype writer struct{}\n\nfunc (w *writer) Write(p []byte) (int, error) {\n\td := logfmt.NewDecoder(bytes.NewReader(p))\n\n\tfor d.ScanRecord() {\n\t\tmsg := LogMessage{\n\t\t\tID: fmt.Sprintf(\"%d\", time.Now().UnixNano()),\n\t\t\tTime: time.Now(),\n\t\t}\n\t\tfor d.ScanKeyval() {\n\t\t\tswitch string(d.Key()) {\n\t\t\tcase \"time\":\n\t\t\t\tparsed, err := time.Parse(time.RFC3339, string(d.Value()))\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn 0, fmt.Errorf(\"parsing time: %w\", err)\n\t\t\t\t}\n\t\t\t\tmsg.Time = parsed\n\t\t\tcase \"level\":\n\t\t\t\tmsg.Level = strings.ToLower(string(d.Value()))\n\t\t\tcase \"msg\":\n\t\t\t\tmsg.Message = string(d.Value())\n\t\t\tdefault:\n\t\t\t\tif string(d.Key()) == persistKeyArg {\n\t\t\t\t\tmsg.Persist = true\n\t\t\t\t} else if string(d.Key()) == PersistTimeArg {\n\t\t\t\t\tparsed, err := time.ParseDuration(string(d.Value()))\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tmsg.PersistTime = parsed\n\t\t\t\t} else {\n\t\t\t\t\tmsg.Attributes = append(msg.Attributes, Attr{\n\t\t\t\t\t\tKey: string(d.Key()),\n\t\t\t\t\t\tValue: string(d.Value()),\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tdefaultLogData.Add(msg)\n\t}\n\tif d.Err() != nil {\n\t\treturn 0, d.Err()\n\t}\n\treturn len(p), nil\n}\n\nfunc NewWriter() *writer {\n\tw := &writer{}\n\treturn w\n}\n\nfunc Subscribe(ctx context.Context) <-chan pubsub.Event[LogMessage] {\n\treturn defaultLogData.Subscribe(ctx)\n}\n\nfunc List() []LogMessage {\n\treturn defaultLogData.List()\n}\n"], ["/opencode/internal/config/config.go", "// Package config manages application configuration from various sources.\npackage config\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"log/slog\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"runtime\"\n\t\"strings\"\n\n\t\"github.com/opencode-ai/opencode/internal/llm/models\"\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n\t\"github.com/spf13/viper\"\n)\n\n// MCPType defines the type of MCP (Model Control Protocol) server.\ntype MCPType string\n\n// Supported MCP types\nconst (\n\tMCPStdio MCPType = \"stdio\"\n\tMCPSse MCPType = \"sse\"\n)\n\n// MCPServer defines the configuration for a Model Control Protocol server.\ntype MCPServer struct {\n\tCommand string `json:\"command\"`\n\tEnv []string `json:\"env\"`\n\tArgs []string `json:\"args\"`\n\tType MCPType `json:\"type\"`\n\tURL string `json:\"url\"`\n\tHeaders map[string]string `json:\"headers\"`\n}\n\ntype AgentName string\n\nconst (\n\tAgentCoder AgentName = \"coder\"\n\tAgentSummarizer AgentName = \"summarizer\"\n\tAgentTask AgentName = \"task\"\n\tAgentTitle AgentName = \"title\"\n)\n\n// Agent defines configuration for different LLM models and their token limits.\ntype Agent struct {\n\tModel models.ModelID `json:\"model\"`\n\tMaxTokens int64 `json:\"maxTokens\"`\n\tReasoningEffort string `json:\"reasoningEffort\"` // For openai models low,medium,heigh\n}\n\n// Provider defines configuration for an LLM provider.\ntype Provider struct {\n\tAPIKey string `json:\"apiKey\"`\n\tDisabled bool `json:\"disabled\"`\n}\n\n// Data defines storage configuration.\ntype Data struct {\n\tDirectory string `json:\"directory,omitempty\"`\n}\n\n// LSPConfig defines configuration for Language Server Protocol integration.\ntype LSPConfig struct {\n\tDisabled bool `json:\"enabled\"`\n\tCommand string `json:\"command\"`\n\tArgs []string `json:\"args\"`\n\tOptions any `json:\"options\"`\n}\n\n// TUIConfig defines the configuration for the Terminal User Interface.\ntype TUIConfig struct {\n\tTheme string `json:\"theme,omitempty\"`\n}\n\n// ShellConfig defines the configuration for the shell used by the bash tool.\ntype ShellConfig struct {\n\tPath string `json:\"path,omitempty\"`\n\tArgs []string `json:\"args,omitempty\"`\n}\n\n// Config is the main configuration structure for the application.\ntype Config struct {\n\tData Data `json:\"data\"`\n\tWorkingDir string `json:\"wd,omitempty\"`\n\tMCPServers map[string]MCPServer `json:\"mcpServers,omitempty\"`\n\tProviders map[models.ModelProvider]Provider `json:\"providers,omitempty\"`\n\tLSP map[string]LSPConfig `json:\"lsp,omitempty\"`\n\tAgents map[AgentName]Agent `json:\"agents,omitempty\"`\n\tDebug bool `json:\"debug,omitempty\"`\n\tDebugLSP bool `json:\"debugLSP,omitempty\"`\n\tContextPaths []string `json:\"contextPaths,omitempty\"`\n\tTUI TUIConfig `json:\"tui\"`\n\tShell ShellConfig `json:\"shell,omitempty\"`\n\tAutoCompact bool `json:\"autoCompact,omitempty\"`\n}\n\n// Application constants\nconst (\n\tdefaultDataDirectory = \".opencode\"\n\tdefaultLogLevel = \"info\"\n\tappName = \"opencode\"\n\n\tMaxTokensFallbackDefault = 4096\n)\n\nvar defaultContextPaths = []string{\n\t\".github/copilot-instructions.md\",\n\t\".cursorrules\",\n\t\".cursor/rules/\",\n\t\"CLAUDE.md\",\n\t\"CLAUDE.local.md\",\n\t\"opencode.md\",\n\t\"opencode.local.md\",\n\t\"OpenCode.md\",\n\t\"OpenCode.local.md\",\n\t\"OPENCODE.md\",\n\t\"OPENCODE.local.md\",\n}\n\n// Global configuration instance\nvar cfg *Config\n\n// Load initializes the configuration from environment variables and config files.\n// If debug is true, debug mode is enabled and log level is set to debug.\n// It returns an error if configuration loading fails.\nfunc Load(workingDir string, debug bool) (*Config, error) {\n\tif cfg != nil {\n\t\treturn cfg, nil\n\t}\n\n\tcfg = &Config{\n\t\tWorkingDir: workingDir,\n\t\tMCPServers: make(map[string]MCPServer),\n\t\tProviders: make(map[models.ModelProvider]Provider),\n\t\tLSP: make(map[string]LSPConfig),\n\t}\n\n\tconfigureViper()\n\tsetDefaults(debug)\n\n\t// Read global config\n\tif err := readConfig(viper.ReadInConfig()); err != nil {\n\t\treturn cfg, err\n\t}\n\n\t// Load and merge local config\n\tmergeLocalConfig(workingDir)\n\n\tsetProviderDefaults()\n\n\t// Apply configuration to the struct\n\tif err := viper.Unmarshal(cfg); err != nil {\n\t\treturn cfg, fmt.Errorf(\"failed to unmarshal config: %w\", err)\n\t}\n\n\tapplyDefaultValues()\n\tdefaultLevel := slog.LevelInfo\n\tif cfg.Debug {\n\t\tdefaultLevel = slog.LevelDebug\n\t}\n\tif os.Getenv(\"OPENCODE_DEV_DEBUG\") == \"true\" {\n\t\tloggingFile := fmt.Sprintf(\"%s/%s\", cfg.Data.Directory, \"debug.log\")\n\t\tmessagesPath := fmt.Sprintf(\"%s/%s\", cfg.Data.Directory, \"messages\")\n\n\t\t// if file does not exist create it\n\t\tif _, err := os.Stat(loggingFile); os.IsNotExist(err) {\n\t\t\tif err := os.MkdirAll(cfg.Data.Directory, 0o755); err != nil {\n\t\t\t\treturn cfg, fmt.Errorf(\"failed to create directory: %w\", err)\n\t\t\t}\n\t\t\tif _, err := os.Create(loggingFile); err != nil {\n\t\t\t\treturn cfg, fmt.Errorf(\"failed to create log file: %w\", err)\n\t\t\t}\n\t\t}\n\n\t\tif _, err := os.Stat(messagesPath); os.IsNotExist(err) {\n\t\t\tif err := os.MkdirAll(messagesPath, 0o756); err != nil {\n\t\t\t\treturn cfg, fmt.Errorf(\"failed to create directory: %w\", err)\n\t\t\t}\n\t\t}\n\t\tlogging.MessageDir = messagesPath\n\n\t\tsloggingFileWriter, err := os.OpenFile(loggingFile, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o666)\n\t\tif err != nil {\n\t\t\treturn cfg, fmt.Errorf(\"failed to open log file: %w\", err)\n\t\t}\n\t\t// Configure logger\n\t\tlogger := slog.New(slog.NewTextHandler(sloggingFileWriter, &slog.HandlerOptions{\n\t\t\tLevel: defaultLevel,\n\t\t}))\n\t\tslog.SetDefault(logger)\n\t} else {\n\t\t// Configure logger\n\t\tlogger := slog.New(slog.NewTextHandler(logging.NewWriter(), &slog.HandlerOptions{\n\t\t\tLevel: defaultLevel,\n\t\t}))\n\t\tslog.SetDefault(logger)\n\t}\n\n\t// Validate configuration\n\tif err := Validate(); err != nil {\n\t\treturn cfg, fmt.Errorf(\"config validation failed: %w\", err)\n\t}\n\n\tif cfg.Agents == nil {\n\t\tcfg.Agents = make(map[AgentName]Agent)\n\t}\n\n\t// Override the max tokens for title agent\n\tcfg.Agents[AgentTitle] = Agent{\n\t\tModel: cfg.Agents[AgentTitle].Model,\n\t\tMaxTokens: 80,\n\t}\n\treturn cfg, nil\n}\n\n// configureViper sets up viper's configuration paths and environment variables.\nfunc configureViper() {\n\tviper.SetConfigName(fmt.Sprintf(\".%s\", appName))\n\tviper.SetConfigType(\"json\")\n\tviper.AddConfigPath(\"$HOME\")\n\tviper.AddConfigPath(fmt.Sprintf(\"$XDG_CONFIG_HOME/%s\", appName))\n\tviper.AddConfigPath(fmt.Sprintf(\"$HOME/.config/%s\", appName))\n\tviper.SetEnvPrefix(strings.ToUpper(appName))\n\tviper.AutomaticEnv()\n}\n\n// setDefaults configures default values for configuration options.\nfunc setDefaults(debug bool) {\n\tviper.SetDefault(\"data.directory\", defaultDataDirectory)\n\tviper.SetDefault(\"contextPaths\", defaultContextPaths)\n\tviper.SetDefault(\"tui.theme\", \"opencode\")\n\tviper.SetDefault(\"autoCompact\", true)\n\n\t// Set default shell from environment or fallback to /bin/bash\n\tshellPath := os.Getenv(\"SHELL\")\n\tif shellPath == \"\" {\n\t\tshellPath = \"/bin/bash\"\n\t}\n\tviper.SetDefault(\"shell.path\", shellPath)\n\tviper.SetDefault(\"shell.args\", []string{\"-l\"})\n\n\tif debug {\n\t\tviper.SetDefault(\"debug\", true)\n\t\tviper.Set(\"log.level\", \"debug\")\n\t} else {\n\t\tviper.SetDefault(\"debug\", false)\n\t\tviper.SetDefault(\"log.level\", defaultLogLevel)\n\t}\n}\n\n// setProviderDefaults configures LLM provider defaults based on provider provided by\n// environment variables and configuration file.\nfunc setProviderDefaults() {\n\t// Set all API keys we can find in the environment\n\t// Note: Viper does not default if the json apiKey is \"\"\n\tif apiKey := os.Getenv(\"ANTHROPIC_API_KEY\"); apiKey != \"\" {\n\t\tviper.SetDefault(\"providers.anthropic.apiKey\", apiKey)\n\t}\n\tif apiKey := os.Getenv(\"OPENAI_API_KEY\"); apiKey != \"\" {\n\t\tviper.SetDefault(\"providers.openai.apiKey\", apiKey)\n\t}\n\tif apiKey := os.Getenv(\"GEMINI_API_KEY\"); apiKey != \"\" {\n\t\tviper.SetDefault(\"providers.gemini.apiKey\", apiKey)\n\t}\n\tif apiKey := os.Getenv(\"GROQ_API_KEY\"); apiKey != \"\" {\n\t\tviper.SetDefault(\"providers.groq.apiKey\", apiKey)\n\t}\n\tif apiKey := os.Getenv(\"OPENROUTER_API_KEY\"); apiKey != \"\" {\n\t\tviper.SetDefault(\"providers.openrouter.apiKey\", apiKey)\n\t}\n\tif apiKey := os.Getenv(\"XAI_API_KEY\"); apiKey != \"\" {\n\t\tviper.SetDefault(\"providers.xai.apiKey\", apiKey)\n\t}\n\tif apiKey := os.Getenv(\"AZURE_OPENAI_ENDPOINT\"); apiKey != \"\" {\n\t\t// api-key may be empty when using Entra ID credentials – that's okay\n\t\tviper.SetDefault(\"providers.azure.apiKey\", os.Getenv(\"AZURE_OPENAI_API_KEY\"))\n\t}\n\tif apiKey, err := LoadGitHubToken(); err == nil && apiKey != \"\" {\n\t\tviper.SetDefault(\"providers.copilot.apiKey\", apiKey)\n\t\tif viper.GetString(\"providers.copilot.apiKey\") == \"\" {\n\t\t\tviper.Set(\"providers.copilot.apiKey\", apiKey)\n\t\t}\n\t}\n\n\t// Use this order to set the default models\n\t// 1. Copilot\n\t// 2. Anthropic\n\t// 3. OpenAI\n\t// 4. Google Gemini\n\t// 5. Groq\n\t// 6. OpenRouter\n\t// 7. AWS Bedrock\n\t// 8. Azure\n\t// 9. Google Cloud VertexAI\n\n\t// copilot configuration\n\tif key := viper.GetString(\"providers.copilot.apiKey\"); strings.TrimSpace(key) != \"\" {\n\t\tviper.SetDefault(\"agents.coder.model\", models.CopilotGPT4o)\n\t\tviper.SetDefault(\"agents.summarizer.model\", models.CopilotGPT4o)\n\t\tviper.SetDefault(\"agents.task.model\", models.CopilotGPT4o)\n\t\tviper.SetDefault(\"agents.title.model\", models.CopilotGPT4o)\n\t\treturn\n\t}\n\n\t// Anthropic configuration\n\tif key := viper.GetString(\"providers.anthropic.apiKey\"); strings.TrimSpace(key) != \"\" {\n\t\tviper.SetDefault(\"agents.coder.model\", models.Claude4Sonnet)\n\t\tviper.SetDefault(\"agents.summarizer.model\", models.Claude4Sonnet)\n\t\tviper.SetDefault(\"agents.task.model\", models.Claude4Sonnet)\n\t\tviper.SetDefault(\"agents.title.model\", models.Claude4Sonnet)\n\t\treturn\n\t}\n\n\t// OpenAI configuration\n\tif key := viper.GetString(\"providers.openai.apiKey\"); strings.TrimSpace(key) != \"\" {\n\t\tviper.SetDefault(\"agents.coder.model\", models.GPT41)\n\t\tviper.SetDefault(\"agents.summarizer.model\", models.GPT41)\n\t\tviper.SetDefault(\"agents.task.model\", models.GPT41Mini)\n\t\tviper.SetDefault(\"agents.title.model\", models.GPT41Mini)\n\t\treturn\n\t}\n\n\t// Google Gemini configuration\n\tif key := viper.GetString(\"providers.gemini.apiKey\"); strings.TrimSpace(key) != \"\" {\n\t\tviper.SetDefault(\"agents.coder.model\", models.Gemini25)\n\t\tviper.SetDefault(\"agents.summarizer.model\", models.Gemini25)\n\t\tviper.SetDefault(\"agents.task.model\", models.Gemini25Flash)\n\t\tviper.SetDefault(\"agents.title.model\", models.Gemini25Flash)\n\t\treturn\n\t}\n\n\t// Groq configuration\n\tif key := viper.GetString(\"providers.groq.apiKey\"); strings.TrimSpace(key) != \"\" {\n\t\tviper.SetDefault(\"agents.coder.model\", models.QWENQwq)\n\t\tviper.SetDefault(\"agents.summarizer.model\", models.QWENQwq)\n\t\tviper.SetDefault(\"agents.task.model\", models.QWENQwq)\n\t\tviper.SetDefault(\"agents.title.model\", models.QWENQwq)\n\t\treturn\n\t}\n\n\t// OpenRouter configuration\n\tif key := viper.GetString(\"providers.openrouter.apiKey\"); strings.TrimSpace(key) != \"\" {\n\t\tviper.SetDefault(\"agents.coder.model\", models.OpenRouterClaude37Sonnet)\n\t\tviper.SetDefault(\"agents.summarizer.model\", models.OpenRouterClaude37Sonnet)\n\t\tviper.SetDefault(\"agents.task.model\", models.OpenRouterClaude37Sonnet)\n\t\tviper.SetDefault(\"agents.title.model\", models.OpenRouterClaude35Haiku)\n\t\treturn\n\t}\n\n\t// XAI configuration\n\tif key := viper.GetString(\"providers.xai.apiKey\"); strings.TrimSpace(key) != \"\" {\n\t\tviper.SetDefault(\"agents.coder.model\", models.XAIGrok3Beta)\n\t\tviper.SetDefault(\"agents.summarizer.model\", models.XAIGrok3Beta)\n\t\tviper.SetDefault(\"agents.task.model\", models.XAIGrok3Beta)\n\t\tviper.SetDefault(\"agents.title.model\", models.XAiGrok3MiniFastBeta)\n\t\treturn\n\t}\n\n\t// AWS Bedrock configuration\n\tif hasAWSCredentials() {\n\t\tviper.SetDefault(\"agents.coder.model\", models.BedrockClaude37Sonnet)\n\t\tviper.SetDefault(\"agents.summarizer.model\", models.BedrockClaude37Sonnet)\n\t\tviper.SetDefault(\"agents.task.model\", models.BedrockClaude37Sonnet)\n\t\tviper.SetDefault(\"agents.title.model\", models.BedrockClaude37Sonnet)\n\t\treturn\n\t}\n\n\t// Azure OpenAI configuration\n\tif os.Getenv(\"AZURE_OPENAI_ENDPOINT\") != \"\" {\n\t\tviper.SetDefault(\"agents.coder.model\", models.AzureGPT41)\n\t\tviper.SetDefault(\"agents.summarizer.model\", models.AzureGPT41)\n\t\tviper.SetDefault(\"agents.task.model\", models.AzureGPT41Mini)\n\t\tviper.SetDefault(\"agents.title.model\", models.AzureGPT41Mini)\n\t\treturn\n\t}\n\n\t// Google Cloud VertexAI configuration\n\tif hasVertexAICredentials() {\n\t\tviper.SetDefault(\"agents.coder.model\", models.VertexAIGemini25)\n\t\tviper.SetDefault(\"agents.summarizer.model\", models.VertexAIGemini25)\n\t\tviper.SetDefault(\"agents.task.model\", models.VertexAIGemini25Flash)\n\t\tviper.SetDefault(\"agents.title.model\", models.VertexAIGemini25Flash)\n\t\treturn\n\t}\n}\n\n// hasAWSCredentials checks if AWS credentials are available in the environment.\nfunc hasAWSCredentials() bool {\n\t// Check for explicit AWS credentials\n\tif os.Getenv(\"AWS_ACCESS_KEY_ID\") != \"\" && os.Getenv(\"AWS_SECRET_ACCESS_KEY\") != \"\" {\n\t\treturn true\n\t}\n\n\t// Check for AWS profile\n\tif os.Getenv(\"AWS_PROFILE\") != \"\" || os.Getenv(\"AWS_DEFAULT_PROFILE\") != \"\" {\n\t\treturn true\n\t}\n\n\t// Check for AWS region\n\tif os.Getenv(\"AWS_REGION\") != \"\" || os.Getenv(\"AWS_DEFAULT_REGION\") != \"\" {\n\t\treturn true\n\t}\n\n\t// Check if running on EC2 with instance profile\n\tif os.Getenv(\"AWS_CONTAINER_CREDENTIALS_RELATIVE_URI\") != \"\" ||\n\t\tos.Getenv(\"AWS_CONTAINER_CREDENTIALS_FULL_URI\") != \"\" {\n\t\treturn true\n\t}\n\n\treturn false\n}\n\n// hasVertexAICredentials checks if VertexAI credentials are available in the environment.\nfunc hasVertexAICredentials() bool {\n\t// Check for explicit VertexAI parameters\n\tif os.Getenv(\"VERTEXAI_PROJECT\") != \"\" && os.Getenv(\"VERTEXAI_LOCATION\") != \"\" {\n\t\treturn true\n\t}\n\t// Check for Google Cloud project and location\n\tif os.Getenv(\"GOOGLE_CLOUD_PROJECT\") != \"\" && (os.Getenv(\"GOOGLE_CLOUD_REGION\") != \"\" || os.Getenv(\"GOOGLE_CLOUD_LOCATION\") != \"\") {\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc hasCopilotCredentials() bool {\n\t// Check for explicit Copilot parameters\n\tif token, _ := LoadGitHubToken(); token != \"\" {\n\t\treturn true\n\t}\n\treturn false\n}\n\n// readConfig handles the result of reading a configuration file.\nfunc readConfig(err error) error {\n\tif err == nil {\n\t\treturn nil\n\t}\n\n\t// It's okay if the config file doesn't exist\n\tif _, ok := err.(viper.ConfigFileNotFoundError); ok {\n\t\treturn nil\n\t}\n\n\treturn fmt.Errorf(\"failed to read config: %w\", err)\n}\n\n// mergeLocalConfig loads and merges configuration from the local directory.\nfunc mergeLocalConfig(workingDir string) {\n\tlocal := viper.New()\n\tlocal.SetConfigName(fmt.Sprintf(\".%s\", appName))\n\tlocal.SetConfigType(\"json\")\n\tlocal.AddConfigPath(workingDir)\n\n\t// Merge local config if it exists\n\tif err := local.ReadInConfig(); err == nil {\n\t\tviper.MergeConfigMap(local.AllSettings())\n\t}\n}\n\n// applyDefaultValues sets default values for configuration fields that need processing.\nfunc applyDefaultValues() {\n\t// Set default MCP type if not specified\n\tfor k, v := range cfg.MCPServers {\n\t\tif v.Type == \"\" {\n\t\t\tv.Type = MCPStdio\n\t\t\tcfg.MCPServers[k] = v\n\t\t}\n\t}\n}\n\n// It validates model IDs and providers, ensuring they are supported.\nfunc validateAgent(cfg *Config, name AgentName, agent Agent) error {\n\t// Check if model exists\n\t// TODO:\tIf a copilot model is specified, but model is not found,\n\t// \t\t \tit might be new model. The https://api.githubcopilot.com/models\n\t// \t\t \tendpoint should be queried to validate if the model is supported.\n\tmodel, modelExists := models.SupportedModels[agent.Model]\n\tif !modelExists {\n\t\tlogging.Warn(\"unsupported model configured, reverting to default\",\n\t\t\t\"agent\", name,\n\t\t\t\"configured_model\", agent.Model)\n\n\t\t// Set default model based on available providers\n\t\tif setDefaultModelForAgent(name) {\n\t\t\tlogging.Info(\"set default model for agent\", \"agent\", name, \"model\", cfg.Agents[name].Model)\n\t\t} else {\n\t\t\treturn fmt.Errorf(\"no valid provider available for agent %s\", name)\n\t\t}\n\t\treturn nil\n\t}\n\n\t// Check if provider for the model is configured\n\tprovider := model.Provider\n\tproviderCfg, providerExists := cfg.Providers[provider]\n\n\tif !providerExists {\n\t\t// Provider not configured, check if we have environment variables\n\t\tapiKey := getProviderAPIKey(provider)\n\t\tif apiKey == \"\" {\n\t\t\tlogging.Warn(\"provider not configured for model, reverting to default\",\n\t\t\t\t\"agent\", name,\n\t\t\t\t\"model\", agent.Model,\n\t\t\t\t\"provider\", provider)\n\n\t\t\t// Set default model based on available providers\n\t\t\tif setDefaultModelForAgent(name) {\n\t\t\t\tlogging.Info(\"set default model for agent\", \"agent\", name, \"model\", cfg.Agents[name].Model)\n\t\t\t} else {\n\t\t\t\treturn fmt.Errorf(\"no valid provider available for agent %s\", name)\n\t\t\t}\n\t\t} else {\n\t\t\t// Add provider with API key from environment\n\t\t\tcfg.Providers[provider] = Provider{\n\t\t\t\tAPIKey: apiKey,\n\t\t\t}\n\t\t\tlogging.Info(\"added provider from environment\", \"provider\", provider)\n\t\t}\n\t} else if providerCfg.Disabled || providerCfg.APIKey == \"\" {\n\t\t// Provider is disabled or has no API key\n\t\tlogging.Warn(\"provider is disabled or has no API key, reverting to default\",\n\t\t\t\"agent\", name,\n\t\t\t\"model\", agent.Model,\n\t\t\t\"provider\", provider)\n\n\t\t// Set default model based on available providers\n\t\tif setDefaultModelForAgent(name) {\n\t\t\tlogging.Info(\"set default model for agent\", \"agent\", name, \"model\", cfg.Agents[name].Model)\n\t\t} else {\n\t\t\treturn fmt.Errorf(\"no valid provider available for agent %s\", name)\n\t\t}\n\t}\n\n\t// Validate max tokens\n\tif agent.MaxTokens <= 0 {\n\t\tlogging.Warn(\"invalid max tokens, setting to default\",\n\t\t\t\"agent\", name,\n\t\t\t\"model\", agent.Model,\n\t\t\t\"max_tokens\", agent.MaxTokens)\n\n\t\t// Update the agent with default max tokens\n\t\tupdatedAgent := cfg.Agents[name]\n\t\tif model.DefaultMaxTokens > 0 {\n\t\t\tupdatedAgent.MaxTokens = model.DefaultMaxTokens\n\t\t} else {\n\t\t\tupdatedAgent.MaxTokens = MaxTokensFallbackDefault\n\t\t}\n\t\tcfg.Agents[name] = updatedAgent\n\t} else if model.ContextWindow > 0 && agent.MaxTokens > model.ContextWindow/2 {\n\t\t// Ensure max tokens doesn't exceed half the context window (reasonable limit)\n\t\tlogging.Warn(\"max tokens exceeds half the context window, adjusting\",\n\t\t\t\"agent\", name,\n\t\t\t\"model\", agent.Model,\n\t\t\t\"max_tokens\", agent.MaxTokens,\n\t\t\t\"context_window\", model.ContextWindow)\n\n\t\t// Update the agent with adjusted max tokens\n\t\tupdatedAgent := cfg.Agents[name]\n\t\tupdatedAgent.MaxTokens = model.ContextWindow / 2\n\t\tcfg.Agents[name] = updatedAgent\n\t}\n\n\t// Validate reasoning effort for models that support reasoning\n\tif model.CanReason && provider == models.ProviderOpenAI || provider == models.ProviderLocal {\n\t\tif agent.ReasoningEffort == \"\" {\n\t\t\t// Set default reasoning effort for models that support it\n\t\t\tlogging.Info(\"setting default reasoning effort for model that supports reasoning\",\n\t\t\t\t\"agent\", name,\n\t\t\t\t\"model\", agent.Model)\n\n\t\t\t// Update the agent with default reasoning effort\n\t\t\tupdatedAgent := cfg.Agents[name]\n\t\t\tupdatedAgent.ReasoningEffort = \"medium\"\n\t\t\tcfg.Agents[name] = updatedAgent\n\t\t} else {\n\t\t\t// Check if reasoning effort is valid (low, medium, high)\n\t\t\teffort := strings.ToLower(agent.ReasoningEffort)\n\t\t\tif effort != \"low\" && effort != \"medium\" && effort != \"high\" {\n\t\t\t\tlogging.Warn(\"invalid reasoning effort, setting to medium\",\n\t\t\t\t\t\"agent\", name,\n\t\t\t\t\t\"model\", agent.Model,\n\t\t\t\t\t\"reasoning_effort\", agent.ReasoningEffort)\n\n\t\t\t\t// Update the agent with valid reasoning effort\n\t\t\t\tupdatedAgent := cfg.Agents[name]\n\t\t\t\tupdatedAgent.ReasoningEffort = \"medium\"\n\t\t\t\tcfg.Agents[name] = updatedAgent\n\t\t\t}\n\t\t}\n\t} else if !model.CanReason && agent.ReasoningEffort != \"\" {\n\t\t// Model doesn't support reasoning but reasoning effort is set\n\t\tlogging.Warn(\"model doesn't support reasoning but reasoning effort is set, ignoring\",\n\t\t\t\"agent\", name,\n\t\t\t\"model\", agent.Model,\n\t\t\t\"reasoning_effort\", agent.ReasoningEffort)\n\n\t\t// Update the agent to remove reasoning effort\n\t\tupdatedAgent := cfg.Agents[name]\n\t\tupdatedAgent.ReasoningEffort = \"\"\n\t\tcfg.Agents[name] = updatedAgent\n\t}\n\n\treturn nil\n}\n\n// Validate checks if the configuration is valid and applies defaults where needed.\nfunc Validate() error {\n\tif cfg == nil {\n\t\treturn fmt.Errorf(\"config not loaded\")\n\t}\n\n\t// Validate agent models\n\tfor name, agent := range cfg.Agents {\n\t\tif err := validateAgent(cfg, name, agent); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// Validate providers\n\tfor provider, providerCfg := range cfg.Providers {\n\t\tif providerCfg.APIKey == \"\" && !providerCfg.Disabled {\n\t\t\tfmt.Printf(\"provider has no API key, marking as disabled %s\", provider)\n\t\t\tlogging.Warn(\"provider has no API key, marking as disabled\", \"provider\", provider)\n\t\t\tproviderCfg.Disabled = true\n\t\t\tcfg.Providers[provider] = providerCfg\n\t\t}\n\t}\n\n\t// Validate LSP configurations\n\tfor language, lspConfig := range cfg.LSP {\n\t\tif lspConfig.Command == \"\" && !lspConfig.Disabled {\n\t\t\tlogging.Warn(\"LSP configuration has no command, marking as disabled\", \"language\", language)\n\t\t\tlspConfig.Disabled = true\n\t\t\tcfg.LSP[language] = lspConfig\n\t\t}\n\t}\n\n\treturn nil\n}\n\n// getProviderAPIKey gets the API key for a provider from environment variables\nfunc getProviderAPIKey(provider models.ModelProvider) string {\n\tswitch provider {\n\tcase models.ProviderAnthropic:\n\t\treturn os.Getenv(\"ANTHROPIC_API_KEY\")\n\tcase models.ProviderOpenAI:\n\t\treturn os.Getenv(\"OPENAI_API_KEY\")\n\tcase models.ProviderGemini:\n\t\treturn os.Getenv(\"GEMINI_API_KEY\")\n\tcase models.ProviderGROQ:\n\t\treturn os.Getenv(\"GROQ_API_KEY\")\n\tcase models.ProviderAzure:\n\t\treturn os.Getenv(\"AZURE_OPENAI_API_KEY\")\n\tcase models.ProviderOpenRouter:\n\t\treturn os.Getenv(\"OPENROUTER_API_KEY\")\n\tcase models.ProviderBedrock:\n\t\tif hasAWSCredentials() {\n\t\t\treturn \"aws-credentials-available\"\n\t\t}\n\tcase models.ProviderVertexAI:\n\t\tif hasVertexAICredentials() {\n\t\t\treturn \"vertex-ai-credentials-available\"\n\t\t}\n\t}\n\treturn \"\"\n}\n\n// setDefaultModelForAgent sets a default model for an agent based on available providers\nfunc setDefaultModelForAgent(agent AgentName) bool {\n\tif hasCopilotCredentials() {\n\t\tmaxTokens := int64(5000)\n\t\tif agent == AgentTitle {\n\t\t\tmaxTokens = 80\n\t\t}\n\n\t\tcfg.Agents[agent] = Agent{\n\t\t\tModel: models.CopilotGPT4o,\n\t\t\tMaxTokens: maxTokens,\n\t\t}\n\t\treturn true\n\t}\n\t// Check providers in order of preference\n\tif apiKey := os.Getenv(\"ANTHROPIC_API_KEY\"); apiKey != \"\" {\n\t\tmaxTokens := int64(5000)\n\t\tif agent == AgentTitle {\n\t\t\tmaxTokens = 80\n\t\t}\n\t\tcfg.Agents[agent] = Agent{\n\t\t\tModel: models.Claude37Sonnet,\n\t\t\tMaxTokens: maxTokens,\n\t\t}\n\t\treturn true\n\t}\n\n\tif apiKey := os.Getenv(\"OPENAI_API_KEY\"); apiKey != \"\" {\n\t\tvar model models.ModelID\n\t\tmaxTokens := int64(5000)\n\t\treasoningEffort := \"\"\n\n\t\tswitch agent {\n\t\tcase AgentTitle:\n\t\t\tmodel = models.GPT41Mini\n\t\t\tmaxTokens = 80\n\t\tcase AgentTask:\n\t\t\tmodel = models.GPT41Mini\n\t\tdefault:\n\t\t\tmodel = models.GPT41\n\t\t}\n\n\t\t// Check if model supports reasoning\n\t\tif modelInfo, ok := models.SupportedModels[model]; ok && modelInfo.CanReason {\n\t\t\treasoningEffort = \"medium\"\n\t\t}\n\n\t\tcfg.Agents[agent] = Agent{\n\t\t\tModel: model,\n\t\t\tMaxTokens: maxTokens,\n\t\t\tReasoningEffort: reasoningEffort,\n\t\t}\n\t\treturn true\n\t}\n\n\tif apiKey := os.Getenv(\"OPENROUTER_API_KEY\"); apiKey != \"\" {\n\t\tvar model models.ModelID\n\t\tmaxTokens := int64(5000)\n\t\treasoningEffort := \"\"\n\n\t\tswitch agent {\n\t\tcase AgentTitle:\n\t\t\tmodel = models.OpenRouterClaude35Haiku\n\t\t\tmaxTokens = 80\n\t\tcase AgentTask:\n\t\t\tmodel = models.OpenRouterClaude37Sonnet\n\t\tdefault:\n\t\t\tmodel = models.OpenRouterClaude37Sonnet\n\t\t}\n\n\t\t// Check if model supports reasoning\n\t\tif modelInfo, ok := models.SupportedModels[model]; ok && modelInfo.CanReason {\n\t\t\treasoningEffort = \"medium\"\n\t\t}\n\n\t\tcfg.Agents[agent] = Agent{\n\t\t\tModel: model,\n\t\t\tMaxTokens: maxTokens,\n\t\t\tReasoningEffort: reasoningEffort,\n\t\t}\n\t\treturn true\n\t}\n\n\tif apiKey := os.Getenv(\"GEMINI_API_KEY\"); apiKey != \"\" {\n\t\tvar model models.ModelID\n\t\tmaxTokens := int64(5000)\n\n\t\tif agent == AgentTitle {\n\t\t\tmodel = models.Gemini25Flash\n\t\t\tmaxTokens = 80\n\t\t} else {\n\t\t\tmodel = models.Gemini25\n\t\t}\n\n\t\tcfg.Agents[agent] = Agent{\n\t\t\tModel: model,\n\t\t\tMaxTokens: maxTokens,\n\t\t}\n\t\treturn true\n\t}\n\n\tif apiKey := os.Getenv(\"GROQ_API_KEY\"); apiKey != \"\" {\n\t\tmaxTokens := int64(5000)\n\t\tif agent == AgentTitle {\n\t\t\tmaxTokens = 80\n\t\t}\n\n\t\tcfg.Agents[agent] = Agent{\n\t\t\tModel: models.QWENQwq,\n\t\t\tMaxTokens: maxTokens,\n\t\t}\n\t\treturn true\n\t}\n\n\tif hasAWSCredentials() {\n\t\tmaxTokens := int64(5000)\n\t\tif agent == AgentTitle {\n\t\t\tmaxTokens = 80\n\t\t}\n\n\t\tcfg.Agents[agent] = Agent{\n\t\t\tModel: models.BedrockClaude37Sonnet,\n\t\t\tMaxTokens: maxTokens,\n\t\t\tReasoningEffort: \"medium\", // Claude models support reasoning\n\t\t}\n\t\treturn true\n\t}\n\n\tif hasVertexAICredentials() {\n\t\tvar model models.ModelID\n\t\tmaxTokens := int64(5000)\n\n\t\tif agent == AgentTitle {\n\t\t\tmodel = models.VertexAIGemini25Flash\n\t\t\tmaxTokens = 80\n\t\t} else {\n\t\t\tmodel = models.VertexAIGemini25\n\t\t}\n\n\t\tcfg.Agents[agent] = Agent{\n\t\t\tModel: model,\n\t\t\tMaxTokens: maxTokens,\n\t\t}\n\t\treturn true\n\t}\n\n\treturn false\n}\n\nfunc updateCfgFile(updateCfg func(config *Config)) error {\n\tif cfg == nil {\n\t\treturn fmt.Errorf(\"config not loaded\")\n\t}\n\n\t// Get the config file path\n\tconfigFile := viper.ConfigFileUsed()\n\tvar configData []byte\n\tif configFile == \"\" {\n\t\thomeDir, err := os.UserHomeDir()\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to get home directory: %w\", err)\n\t\t}\n\t\tconfigFile = filepath.Join(homeDir, fmt.Sprintf(\".%s.json\", appName))\n\t\tlogging.Info(\"config file not found, creating new one\", \"path\", configFile)\n\t\tconfigData = []byte(`{}`)\n\t} else {\n\t\t// Read the existing config file\n\t\tdata, err := os.ReadFile(configFile)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to read config file: %w\", err)\n\t\t}\n\t\tconfigData = data\n\t}\n\n\t// Parse the JSON\n\tvar userCfg *Config\n\tif err := json.Unmarshal(configData, &userCfg); err != nil {\n\t\treturn fmt.Errorf(\"failed to parse config file: %w\", err)\n\t}\n\n\tupdateCfg(userCfg)\n\n\t// Write the updated config back to file\n\tupdatedData, err := json.MarshalIndent(userCfg, \"\", \" \")\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to marshal config: %w\", err)\n\t}\n\n\tif err := os.WriteFile(configFile, updatedData, 0o644); err != nil {\n\t\treturn fmt.Errorf(\"failed to write config file: %w\", err)\n\t}\n\n\treturn nil\n}\n\n// Get returns the current configuration.\n// It's safe to call this function multiple times.\nfunc Get() *Config {\n\treturn cfg\n}\n\n// WorkingDirectory returns the current working directory from the configuration.\nfunc WorkingDirectory() string {\n\tif cfg == nil {\n\t\tpanic(\"config not loaded\")\n\t}\n\treturn cfg.WorkingDir\n}\n\nfunc UpdateAgentModel(agentName AgentName, modelID models.ModelID) error {\n\tif cfg == nil {\n\t\tpanic(\"config not loaded\")\n\t}\n\n\texistingAgentCfg := cfg.Agents[agentName]\n\n\tmodel, ok := models.SupportedModels[modelID]\n\tif !ok {\n\t\treturn fmt.Errorf(\"model %s not supported\", modelID)\n\t}\n\n\tmaxTokens := existingAgentCfg.MaxTokens\n\tif model.DefaultMaxTokens > 0 {\n\t\tmaxTokens = model.DefaultMaxTokens\n\t}\n\n\tnewAgentCfg := Agent{\n\t\tModel: modelID,\n\t\tMaxTokens: maxTokens,\n\t\tReasoningEffort: existingAgentCfg.ReasoningEffort,\n\t}\n\tcfg.Agents[agentName] = newAgentCfg\n\n\tif err := validateAgent(cfg, agentName, newAgentCfg); err != nil {\n\t\t// revert config update on failure\n\t\tcfg.Agents[agentName] = existingAgentCfg\n\t\treturn fmt.Errorf(\"failed to update agent model: %w\", err)\n\t}\n\n\treturn updateCfgFile(func(config *Config) {\n\t\tif config.Agents == nil {\n\t\t\tconfig.Agents = make(map[AgentName]Agent)\n\t\t}\n\t\tconfig.Agents[agentName] = newAgentCfg\n\t})\n}\n\n// UpdateTheme updates the theme in the configuration and writes it to the config file.\nfunc UpdateTheme(themeName string) error {\n\tif cfg == nil {\n\t\treturn fmt.Errorf(\"config not loaded\")\n\t}\n\n\t// Update the in-memory config\n\tcfg.TUI.Theme = themeName\n\n\t// Update the file config\n\treturn updateCfgFile(func(config *Config) {\n\t\tconfig.TUI.Theme = themeName\n\t})\n}\n\n// Tries to load Github token from all possible locations\nfunc LoadGitHubToken() (string, error) {\n\t// First check environment variable\n\tif token := os.Getenv(\"GITHUB_TOKEN\"); token != \"\" {\n\t\treturn token, nil\n\t}\n\n\t// Get config directory\n\tvar configDir string\n\tif xdgConfig := os.Getenv(\"XDG_CONFIG_HOME\"); xdgConfig != \"\" {\n\t\tconfigDir = xdgConfig\n\t} else if runtime.GOOS == \"windows\" {\n\t\tif localAppData := os.Getenv(\"LOCALAPPDATA\"); localAppData != \"\" {\n\t\t\tconfigDir = localAppData\n\t\t} else {\n\t\t\tconfigDir = filepath.Join(os.Getenv(\"HOME\"), \"AppData\", \"Local\")\n\t\t}\n\t} else {\n\t\tconfigDir = filepath.Join(os.Getenv(\"HOME\"), \".config\")\n\t}\n\n\t// Try both hosts.json and apps.json files\n\tfilePaths := []string{\n\t\tfilepath.Join(configDir, \"github-copilot\", \"hosts.json\"),\n\t\tfilepath.Join(configDir, \"github-copilot\", \"apps.json\"),\n\t}\n\n\tfor _, filePath := range filePaths {\n\t\tdata, err := os.ReadFile(filePath)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tvar config map[string]map[string]interface{}\n\t\tif err := json.Unmarshal(data, &config); err != nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tfor key, value := range config {\n\t\t\tif strings.Contains(key, \"github.com\") {\n\t\t\t\tif oauthToken, ok := value[\"oauth_token\"].(string); ok {\n\t\t\t\t\treturn oauthToken, nil\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn \"\", fmt.Errorf(\"GitHub token not found in standard locations\")\n}\n"], ["/opencode/internal/lsp/watcher/watcher.go", "package watcher\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com/bmatcuk/doublestar/v4\"\n\t\"github.com/fsnotify/fsnotify\"\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n\t\"github.com/opencode-ai/opencode/internal/lsp\"\n\t\"github.com/opencode-ai/opencode/internal/lsp/protocol\"\n)\n\n// WorkspaceWatcher manages LSP file watching\ntype WorkspaceWatcher struct {\n\tclient *lsp.Client\n\tworkspacePath string\n\n\tdebounceTime time.Duration\n\tdebounceMap map[string]*time.Timer\n\tdebounceMu sync.Mutex\n\n\t// File watchers registered by the server\n\tregistrations []protocol.FileSystemWatcher\n\tregistrationMu sync.RWMutex\n}\n\n// NewWorkspaceWatcher creates a new workspace watcher\nfunc NewWorkspaceWatcher(client *lsp.Client) *WorkspaceWatcher {\n\treturn &WorkspaceWatcher{\n\t\tclient: client,\n\t\tdebounceTime: 300 * time.Millisecond,\n\t\tdebounceMap: make(map[string]*time.Timer),\n\t\tregistrations: []protocol.FileSystemWatcher{},\n\t}\n}\n\n// AddRegistrations adds file watchers to track\nfunc (w *WorkspaceWatcher) AddRegistrations(ctx context.Context, id string, watchers []protocol.FileSystemWatcher) {\n\tcnf := config.Get()\n\n\tlogging.Debug(\"Adding file watcher registrations\")\n\tw.registrationMu.Lock()\n\tdefer w.registrationMu.Unlock()\n\n\t// Add new watchers\n\tw.registrations = append(w.registrations, watchers...)\n\n\t// Print detailed registration information for debugging\n\tif cnf.DebugLSP {\n\t\tlogging.Debug(\"Adding file watcher registrations\",\n\t\t\t\"id\", id,\n\t\t\t\"watchers\", len(watchers),\n\t\t\t\"total\", len(w.registrations),\n\t\t)\n\n\t\tfor i, watcher := range watchers {\n\t\t\tlogging.Debug(\"Registration\", \"index\", i+1)\n\n\t\t\t// Log the GlobPattern\n\t\t\tswitch v := watcher.GlobPattern.Value.(type) {\n\t\t\tcase string:\n\t\t\t\tlogging.Debug(\"GlobPattern\", \"pattern\", v)\n\t\t\tcase protocol.RelativePattern:\n\t\t\t\tlogging.Debug(\"GlobPattern\", \"pattern\", v.Pattern)\n\n\t\t\t\t// Log BaseURI details\n\t\t\t\tswitch u := v.BaseURI.Value.(type) {\n\t\t\t\tcase string:\n\t\t\t\t\tlogging.Debug(\"BaseURI\", \"baseURI\", u)\n\t\t\t\tcase protocol.DocumentUri:\n\t\t\t\t\tlogging.Debug(\"BaseURI\", \"baseURI\", u)\n\t\t\t\tdefault:\n\t\t\t\t\tlogging.Debug(\"BaseURI\", \"baseURI\", u)\n\t\t\t\t}\n\t\t\tdefault:\n\t\t\t\tlogging.Debug(\"GlobPattern\", \"unknown type\", fmt.Sprintf(\"%T\", v))\n\t\t\t}\n\n\t\t\t// Log WatchKind\n\t\t\twatchKind := protocol.WatchKind(protocol.WatchChange | protocol.WatchCreate | protocol.WatchDelete)\n\t\t\tif watcher.Kind != nil {\n\t\t\t\twatchKind = *watcher.Kind\n\t\t\t}\n\n\t\t\tlogging.Debug(\"WatchKind\", \"kind\", watchKind)\n\t\t}\n\t}\n\n\t// Determine server type for specialized handling\n\tserverName := getServerNameFromContext(ctx)\n\tlogging.Debug(\"Server type detected\", \"serverName\", serverName)\n\n\t// Check if this server has sent file watchers\n\thasFileWatchers := len(watchers) > 0\n\n\t// For servers that need file preloading, we'll use a smart approach\n\tif shouldPreloadFiles(serverName) || !hasFileWatchers {\n\t\tgo func() {\n\t\t\tstartTime := time.Now()\n\t\t\tfilesOpened := 0\n\n\t\t\t// Determine max files to open based on server type\n\t\t\tmaxFilesToOpen := 50 // Default conservative limit\n\n\t\t\tswitch serverName {\n\t\t\tcase \"typescript\", \"typescript-language-server\", \"tsserver\", \"vtsls\":\n\t\t\t\t// TypeScript servers benefit from seeing more files\n\t\t\t\tmaxFilesToOpen = 100\n\t\t\tcase \"java\", \"jdtls\":\n\t\t\t\t// Java servers need to see many files for project model\n\t\t\t\tmaxFilesToOpen = 200\n\t\t\t}\n\n\t\t\t// First, open high-priority files\n\t\t\thighPriorityFilesOpened := w.openHighPriorityFiles(ctx, serverName)\n\t\t\tfilesOpened += highPriorityFilesOpened\n\n\t\t\tif cnf.DebugLSP {\n\t\t\t\tlogging.Debug(\"Opened high-priority files\",\n\t\t\t\t\t\"count\", highPriorityFilesOpened,\n\t\t\t\t\t\"serverName\", serverName)\n\t\t\t}\n\n\t\t\t// If we've already opened enough high-priority files, we might not need more\n\t\t\tif filesOpened >= maxFilesToOpen {\n\t\t\t\tif cnf.DebugLSP {\n\t\t\t\t\tlogging.Debug(\"Reached file limit with high-priority files\",\n\t\t\t\t\t\t\"filesOpened\", filesOpened,\n\t\t\t\t\t\t\"maxFiles\", maxFilesToOpen)\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\t// For the remaining slots, walk the directory and open matching files\n\n\t\t\terr := filepath.WalkDir(w.workspacePath, func(path string, d os.DirEntry, err error) error {\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\n\t\t\t\t// Skip directories that should be excluded\n\t\t\t\tif d.IsDir() {\n\t\t\t\t\tif path != w.workspacePath && shouldExcludeDir(path) {\n\t\t\t\t\t\tif cnf.DebugLSP {\n\t\t\t\t\t\t\tlogging.Debug(\"Skipping excluded directory\", \"path\", path)\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn filepath.SkipDir\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\t// Process files, but limit the total number\n\t\t\t\t\tif filesOpened < maxFilesToOpen {\n\t\t\t\t\t\t// Only process if it's not already open (high-priority files were opened earlier)\n\t\t\t\t\t\tif !w.client.IsFileOpen(path) {\n\t\t\t\t\t\t\tw.openMatchingFile(ctx, path)\n\t\t\t\t\t\t\tfilesOpened++\n\n\t\t\t\t\t\t\t// Add a small delay after every 10 files to prevent overwhelming the server\n\t\t\t\t\t\t\tif filesOpened%10 == 0 {\n\t\t\t\t\t\t\t\ttime.Sleep(50 * time.Millisecond)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// We've reached our limit, stop walking\n\t\t\t\t\t\treturn filepath.SkipAll\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\treturn nil\n\t\t\t})\n\n\t\t\telapsedTime := time.Since(startTime)\n\t\t\tif cnf.DebugLSP {\n\t\t\t\tlogging.Debug(\"Limited workspace scan complete\",\n\t\t\t\t\t\"filesOpened\", filesOpened,\n\t\t\t\t\t\"maxFiles\", maxFilesToOpen,\n\t\t\t\t\t\"elapsedTime\", elapsedTime.Seconds(),\n\t\t\t\t\t\"workspacePath\", w.workspacePath,\n\t\t\t\t)\n\t\t\t}\n\n\t\t\tif err != nil && cnf.DebugLSP {\n\t\t\t\tlogging.Debug(\"Error scanning workspace for files to open\", \"error\", err)\n\t\t\t}\n\t\t}()\n\t} else if cnf.DebugLSP {\n\t\tlogging.Debug(\"Using on-demand file loading for server\", \"server\", serverName)\n\t}\n}\n\n// openHighPriorityFiles opens important files for the server type\n// Returns the number of files opened\nfunc (w *WorkspaceWatcher) openHighPriorityFiles(ctx context.Context, serverName string) int {\n\tcnf := config.Get()\n\tfilesOpened := 0\n\n\t// Define patterns for high-priority files based on server type\n\tvar patterns []string\n\n\tswitch serverName {\n\tcase \"typescript\", \"typescript-language-server\", \"tsserver\", \"vtsls\":\n\t\tpatterns = []string{\n\t\t\t\"**/tsconfig.json\",\n\t\t\t\"**/package.json\",\n\t\t\t\"**/jsconfig.json\",\n\t\t\t\"**/index.ts\",\n\t\t\t\"**/index.js\",\n\t\t\t\"**/main.ts\",\n\t\t\t\"**/main.js\",\n\t\t}\n\tcase \"gopls\":\n\t\tpatterns = []string{\n\t\t\t\"**/go.mod\",\n\t\t\t\"**/go.sum\",\n\t\t\t\"**/main.go\",\n\t\t}\n\tcase \"rust-analyzer\":\n\t\tpatterns = []string{\n\t\t\t\"**/Cargo.toml\",\n\t\t\t\"**/Cargo.lock\",\n\t\t\t\"**/src/lib.rs\",\n\t\t\t\"**/src/main.rs\",\n\t\t}\n\tcase \"python\", \"pyright\", \"pylsp\":\n\t\tpatterns = []string{\n\t\t\t\"**/pyproject.toml\",\n\t\t\t\"**/setup.py\",\n\t\t\t\"**/requirements.txt\",\n\t\t\t\"**/__init__.py\",\n\t\t\t\"**/__main__.py\",\n\t\t}\n\tcase \"clangd\":\n\t\tpatterns = []string{\n\t\t\t\"**/CMakeLists.txt\",\n\t\t\t\"**/Makefile\",\n\t\t\t\"**/compile_commands.json\",\n\t\t}\n\tcase \"java\", \"jdtls\":\n\t\tpatterns = []string{\n\t\t\t\"**/pom.xml\",\n\t\t\t\"**/build.gradle\",\n\t\t\t\"**/src/main/java/**/*.java\",\n\t\t}\n\tdefault:\n\t\t// For unknown servers, use common configuration files\n\t\tpatterns = []string{\n\t\t\t\"**/package.json\",\n\t\t\t\"**/Makefile\",\n\t\t\t\"**/CMakeLists.txt\",\n\t\t\t\"**/.editorconfig\",\n\t\t}\n\t}\n\n\t// For each pattern, find and open matching files\n\tfor _, pattern := range patterns {\n\t\t// Use doublestar.Glob to find files matching the pattern (supports ** patterns)\n\t\tmatches, err := doublestar.Glob(os.DirFS(w.workspacePath), pattern)\n\t\tif err != nil {\n\t\t\tif cnf.DebugLSP {\n\t\t\t\tlogging.Debug(\"Error finding high-priority files\", \"pattern\", pattern, \"error\", err)\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\tfor _, match := range matches {\n\t\t\t// Convert relative path to absolute\n\t\t\tfullPath := filepath.Join(w.workspacePath, match)\n\n\t\t\t// Skip directories and excluded files\n\t\t\tinfo, err := os.Stat(fullPath)\n\t\t\tif err != nil || info.IsDir() || shouldExcludeFile(fullPath) {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// Open the file\n\t\t\tif err := w.client.OpenFile(ctx, fullPath); err != nil {\n\t\t\t\tif cnf.DebugLSP {\n\t\t\t\t\tlogging.Debug(\"Error opening high-priority file\", \"path\", fullPath, \"error\", err)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tfilesOpened++\n\t\t\t\tif cnf.DebugLSP {\n\t\t\t\t\tlogging.Debug(\"Opened high-priority file\", \"path\", fullPath)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Add a small delay to prevent overwhelming the server\n\t\t\ttime.Sleep(20 * time.Millisecond)\n\n\t\t\t// Limit the number of files opened per pattern\n\t\t\tif filesOpened >= 5 && (serverName != \"java\" && serverName != \"jdtls\") {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\treturn filesOpened\n}\n\n// WatchWorkspace sets up file watching for a workspace\nfunc (w *WorkspaceWatcher) WatchWorkspace(ctx context.Context, workspacePath string) {\n\tcnf := config.Get()\n\tw.workspacePath = workspacePath\n\n\t// Store the watcher in the context for later use\n\tctx = context.WithValue(ctx, \"workspaceWatcher\", w)\n\n\t// If the server name isn't already in the context, try to detect it\n\tif _, ok := ctx.Value(\"serverName\").(string); !ok {\n\t\tserverName := getServerNameFromContext(ctx)\n\t\tctx = context.WithValue(ctx, \"serverName\", serverName)\n\t}\n\n\tserverName := getServerNameFromContext(ctx)\n\tlogging.Debug(\"Starting workspace watcher\", \"workspacePath\", workspacePath, \"serverName\", serverName)\n\n\t// Register handler for file watcher registrations from the server\n\tlsp.RegisterFileWatchHandler(func(id string, watchers []protocol.FileSystemWatcher) {\n\t\tw.AddRegistrations(ctx, id, watchers)\n\t})\n\n\twatcher, err := fsnotify.NewWatcher()\n\tif err != nil {\n\t\tlogging.Error(\"Error creating watcher\", \"error\", err)\n\t}\n\tdefer watcher.Close()\n\n\t// Watch the workspace recursively\n\terr = filepath.WalkDir(workspacePath, func(path string, d os.DirEntry, err error) error {\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Skip excluded directories (except workspace root)\n\t\tif d.IsDir() && path != workspacePath {\n\t\t\tif shouldExcludeDir(path) {\n\t\t\t\tif cnf.DebugLSP {\n\t\t\t\t\tlogging.Debug(\"Skipping excluded directory\", \"path\", path)\n\t\t\t\t}\n\t\t\t\treturn filepath.SkipDir\n\t\t\t}\n\t\t}\n\n\t\t// Add directories to watcher\n\t\tif d.IsDir() {\n\t\t\terr = watcher.Add(path)\n\t\t\tif err != nil {\n\t\t\t\tlogging.Error(\"Error watching path\", \"path\", path, \"error\", err)\n\t\t\t}\n\t\t}\n\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\tlogging.Error(\"Error walking workspace\", \"error\", err)\n\t}\n\n\t// Event loop\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn\n\t\tcase event, ok := <-watcher.Events:\n\t\t\tif !ok {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\turi := fmt.Sprintf(\"file://%s\", event.Name)\n\n\t\t\t// Add new directories to the watcher\n\t\t\tif event.Op&fsnotify.Create != 0 {\n\t\t\t\tif info, err := os.Stat(event.Name); err == nil {\n\t\t\t\t\tif info.IsDir() {\n\t\t\t\t\t\t// Skip excluded directories\n\t\t\t\t\t\tif !shouldExcludeDir(event.Name) {\n\t\t\t\t\t\t\tif err := watcher.Add(event.Name); err != nil {\n\t\t\t\t\t\t\t\tlogging.Error(\"Error adding directory to watcher\", \"path\", event.Name, \"error\", err)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// For newly created files\n\t\t\t\t\t\tif !shouldExcludeFile(event.Name) {\n\t\t\t\t\t\t\tw.openMatchingFile(ctx, event.Name)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Debug logging\n\t\t\tif cnf.DebugLSP {\n\t\t\t\tmatched, kind := w.isPathWatched(event.Name)\n\t\t\t\tlogging.Debug(\"File event\",\n\t\t\t\t\t\"path\", event.Name,\n\t\t\t\t\t\"operation\", event.Op.String(),\n\t\t\t\t\t\"watched\", matched,\n\t\t\t\t\t\"kind\", kind,\n\t\t\t\t)\n\n\t\t\t}\n\n\t\t\t// Check if this path should be watched according to server registrations\n\t\t\tif watched, watchKind := w.isPathWatched(event.Name); watched {\n\t\t\t\tswitch {\n\t\t\t\tcase event.Op&fsnotify.Write != 0:\n\t\t\t\t\tif watchKind&protocol.WatchChange != 0 {\n\t\t\t\t\t\tw.debounceHandleFileEvent(ctx, uri, protocol.FileChangeType(protocol.Changed))\n\t\t\t\t\t}\n\t\t\t\tcase event.Op&fsnotify.Create != 0:\n\t\t\t\t\t// Already handled earlier in the event loop\n\t\t\t\t\t// Just send the notification if needed\n\t\t\t\t\tinfo, err := os.Stat(event.Name)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlogging.Error(\"Error getting file info\", \"path\", event.Name, \"error\", err)\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\tif !info.IsDir() && watchKind&protocol.WatchCreate != 0 {\n\t\t\t\t\t\tw.debounceHandleFileEvent(ctx, uri, protocol.FileChangeType(protocol.Created))\n\t\t\t\t\t}\n\t\t\t\tcase event.Op&fsnotify.Remove != 0:\n\t\t\t\t\tif watchKind&protocol.WatchDelete != 0 {\n\t\t\t\t\t\tw.handleFileEvent(ctx, uri, protocol.FileChangeType(protocol.Deleted))\n\t\t\t\t\t}\n\t\t\t\tcase event.Op&fsnotify.Rename != 0:\n\t\t\t\t\t// For renames, first delete\n\t\t\t\t\tif watchKind&protocol.WatchDelete != 0 {\n\t\t\t\t\t\tw.handleFileEvent(ctx, uri, protocol.FileChangeType(protocol.Deleted))\n\t\t\t\t\t}\n\n\t\t\t\t\t// Then check if the new file exists and create an event\n\t\t\t\t\tif info, err := os.Stat(event.Name); err == nil && !info.IsDir() {\n\t\t\t\t\t\tif watchKind&protocol.WatchCreate != 0 {\n\t\t\t\t\t\t\tw.debounceHandleFileEvent(ctx, uri, protocol.FileChangeType(protocol.Created))\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\tcase err, ok := <-watcher.Errors:\n\t\t\tif !ok {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tlogging.Error(\"Error watching file\", \"error\", err)\n\t\t}\n\t}\n}\n\n// isPathWatched checks if a path should be watched based on server registrations\nfunc (w *WorkspaceWatcher) isPathWatched(path string) (bool, protocol.WatchKind) {\n\tw.registrationMu.RLock()\n\tdefer w.registrationMu.RUnlock()\n\n\t// If no explicit registrations, watch everything\n\tif len(w.registrations) == 0 {\n\t\treturn true, protocol.WatchKind(protocol.WatchChange | protocol.WatchCreate | protocol.WatchDelete)\n\t}\n\n\t// Check each registration\n\tfor _, reg := range w.registrations {\n\t\tisMatch := w.matchesPattern(path, reg.GlobPattern)\n\t\tif isMatch {\n\t\t\tkind := protocol.WatchKind(protocol.WatchChange | protocol.WatchCreate | protocol.WatchDelete)\n\t\t\tif reg.Kind != nil {\n\t\t\t\tkind = *reg.Kind\n\t\t\t}\n\t\t\treturn true, kind\n\t\t}\n\t}\n\n\treturn false, 0\n}\n\n// matchesGlob handles advanced glob patterns including ** and alternatives\nfunc matchesGlob(pattern, path string) bool {\n\t// Handle file extension patterns with braces like *.{go,mod,sum}\n\tif strings.Contains(pattern, \"{\") && strings.Contains(pattern, \"}\") {\n\t\t// Extract extensions from pattern like \"*.{go,mod,sum}\"\n\t\tparts := strings.SplitN(pattern, \"{\", 2)\n\t\tif len(parts) == 2 {\n\t\t\tprefix := parts[0]\n\t\t\textPart := strings.SplitN(parts[1], \"}\", 2)\n\t\t\tif len(extPart) == 2 {\n\t\t\t\textensions := strings.Split(extPart[0], \",\")\n\t\t\t\tsuffix := extPart[1]\n\n\t\t\t\t// Check if the path matches any of the extensions\n\t\t\t\tfor _, ext := range extensions {\n\t\t\t\t\textPattern := prefix + ext + suffix\n\t\t\t\t\tisMatch := matchesSimpleGlob(extPattern, path)\n\t\t\t\t\tif isMatch {\n\t\t\t\t\t\treturn true\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t}\n\n\treturn matchesSimpleGlob(pattern, path)\n}\n\n// matchesSimpleGlob handles glob patterns with ** wildcards\nfunc matchesSimpleGlob(pattern, path string) bool {\n\t// Handle special case for **/*.ext pattern (common in LSP)\n\tif strings.HasPrefix(pattern, \"**/\") {\n\t\trest := strings.TrimPrefix(pattern, \"**/\")\n\n\t\t// If the rest is a simple file extension pattern like *.go\n\t\tif strings.HasPrefix(rest, \"*.\") {\n\t\t\text := strings.TrimPrefix(rest, \"*\")\n\t\t\tisMatch := strings.HasSuffix(path, ext)\n\t\t\treturn isMatch\n\t\t}\n\n\t\t// Otherwise, try to check if the path ends with the rest part\n\t\tisMatch := strings.HasSuffix(path, rest)\n\n\t\t// If it matches directly, great!\n\t\tif isMatch {\n\t\t\treturn true\n\t\t}\n\n\t\t// Otherwise, check if any path component matches\n\t\tpathComponents := strings.Split(path, \"/\")\n\t\tfor i := range pathComponents {\n\t\t\tsubPath := strings.Join(pathComponents[i:], \"/\")\n\t\t\tif strings.HasSuffix(subPath, rest) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\n\t\treturn false\n\t}\n\n\t// Handle other ** wildcard pattern cases\n\tif strings.Contains(pattern, \"**\") {\n\t\tparts := strings.Split(pattern, \"**\")\n\n\t\t// Validate the path starts with the first part\n\t\tif !strings.HasPrefix(path, parts[0]) && parts[0] != \"\" {\n\t\t\treturn false\n\t\t}\n\n\t\t// For patterns like \"**/*.go\", just check the suffix\n\t\tif len(parts) == 2 && parts[0] == \"\" {\n\t\t\tisMatch := strings.HasSuffix(path, parts[1])\n\t\t\treturn isMatch\n\t\t}\n\n\t\t// For other patterns, handle middle part\n\t\tremaining := strings.TrimPrefix(path, parts[0])\n\t\tif len(parts) == 2 {\n\t\t\tisMatch := strings.HasSuffix(remaining, parts[1])\n\t\t\treturn isMatch\n\t\t}\n\t}\n\n\t// Handle simple * wildcard for file extension patterns (*.go, *.sum, etc)\n\tif strings.HasPrefix(pattern, \"*.\") {\n\t\text := strings.TrimPrefix(pattern, \"*\")\n\t\tisMatch := strings.HasSuffix(path, ext)\n\t\treturn isMatch\n\t}\n\n\t// Fall back to simple matching for simpler patterns\n\tmatched, err := filepath.Match(pattern, path)\n\tif err != nil {\n\t\tlogging.Error(\"Error matching pattern\", \"pattern\", pattern, \"path\", path, \"error\", err)\n\t\treturn false\n\t}\n\n\treturn matched\n}\n\n// matchesPattern checks if a path matches the glob pattern\nfunc (w *WorkspaceWatcher) matchesPattern(path string, pattern protocol.GlobPattern) bool {\n\tpatternInfo, err := pattern.AsPattern()\n\tif err != nil {\n\t\tlogging.Error(\"Error parsing pattern\", \"pattern\", pattern, \"error\", err)\n\t\treturn false\n\t}\n\n\tbasePath := patternInfo.GetBasePath()\n\tpatternText := patternInfo.GetPattern()\n\n\tpath = filepath.ToSlash(path)\n\n\t// For simple patterns without base path\n\tif basePath == \"\" {\n\t\t// Check if the pattern matches the full path or just the file extension\n\t\tfullPathMatch := matchesGlob(patternText, path)\n\t\tbaseNameMatch := matchesGlob(patternText, filepath.Base(path))\n\n\t\treturn fullPathMatch || baseNameMatch\n\t}\n\n\t// For relative patterns\n\tbasePath = strings.TrimPrefix(basePath, \"file://\")\n\tbasePath = filepath.ToSlash(basePath)\n\n\t// Make path relative to basePath for matching\n\trelPath, err := filepath.Rel(basePath, path)\n\tif err != nil {\n\t\tlogging.Error(\"Error getting relative path\", \"path\", path, \"basePath\", basePath, \"error\", err)\n\t\treturn false\n\t}\n\trelPath = filepath.ToSlash(relPath)\n\n\tisMatch := matchesGlob(patternText, relPath)\n\n\treturn isMatch\n}\n\n// debounceHandleFileEvent handles file events with debouncing to reduce notifications\nfunc (w *WorkspaceWatcher) debounceHandleFileEvent(ctx context.Context, uri string, changeType protocol.FileChangeType) {\n\tw.debounceMu.Lock()\n\tdefer w.debounceMu.Unlock()\n\n\t// Create a unique key based on URI and change type\n\tkey := fmt.Sprintf(\"%s:%d\", uri, changeType)\n\n\t// Cancel existing timer if any\n\tif timer, exists := w.debounceMap[key]; exists {\n\t\ttimer.Stop()\n\t}\n\n\t// Create new timer\n\tw.debounceMap[key] = time.AfterFunc(w.debounceTime, func() {\n\t\tw.handleFileEvent(ctx, uri, changeType)\n\n\t\t// Cleanup timer after execution\n\t\tw.debounceMu.Lock()\n\t\tdelete(w.debounceMap, key)\n\t\tw.debounceMu.Unlock()\n\t})\n}\n\n// handleFileEvent sends file change notifications\nfunc (w *WorkspaceWatcher) handleFileEvent(ctx context.Context, uri string, changeType protocol.FileChangeType) {\n\t// If the file is open and it's a change event, use didChange notification\n\tfilePath := uri[7:] // Remove \"file://\" prefix\n\tif changeType == protocol.FileChangeType(protocol.Deleted) {\n\t\tw.client.ClearDiagnosticsForURI(protocol.DocumentUri(uri))\n\t} else if changeType == protocol.FileChangeType(protocol.Changed) && w.client.IsFileOpen(filePath) {\n\t\terr := w.client.NotifyChange(ctx, filePath)\n\t\tif err != nil {\n\t\t\tlogging.Error(\"Error notifying change\", \"error\", err)\n\t\t}\n\t\treturn\n\t}\n\n\t// Notify LSP server about the file event using didChangeWatchedFiles\n\tif err := w.notifyFileEvent(ctx, uri, changeType); err != nil {\n\t\tlogging.Error(\"Error notifying LSP server about file event\", \"error\", err)\n\t}\n}\n\n// notifyFileEvent sends a didChangeWatchedFiles notification for a file event\nfunc (w *WorkspaceWatcher) notifyFileEvent(ctx context.Context, uri string, changeType protocol.FileChangeType) error {\n\tcnf := config.Get()\n\tif cnf.DebugLSP {\n\t\tlogging.Debug(\"Notifying file event\",\n\t\t\t\"uri\", uri,\n\t\t\t\"changeType\", changeType,\n\t\t)\n\t}\n\n\tparams := protocol.DidChangeWatchedFilesParams{\n\t\tChanges: []protocol.FileEvent{\n\t\t\t{\n\t\t\t\tURI: protocol.DocumentUri(uri),\n\t\t\t\tType: changeType,\n\t\t\t},\n\t\t},\n\t}\n\n\treturn w.client.DidChangeWatchedFiles(ctx, params)\n}\n\n// getServerNameFromContext extracts the server name from the context\n// This is a best-effort function that tries to identify which LSP server we're dealing with\nfunc getServerNameFromContext(ctx context.Context) string {\n\t// First check if the server name is directly stored in the context\n\tif serverName, ok := ctx.Value(\"serverName\").(string); ok && serverName != \"\" {\n\t\treturn strings.ToLower(serverName)\n\t}\n\n\t// Otherwise, try to extract server name from the client command path\n\tif w, ok := ctx.Value(\"workspaceWatcher\").(*WorkspaceWatcher); ok && w != nil && w.client != nil && w.client.Cmd != nil {\n\t\tpath := strings.ToLower(w.client.Cmd.Path)\n\n\t\t// Extract server name from path\n\t\tif strings.Contains(path, \"typescript\") || strings.Contains(path, \"tsserver\") || strings.Contains(path, \"vtsls\") {\n\t\t\treturn \"typescript\"\n\t\t} else if strings.Contains(path, \"gopls\") {\n\t\t\treturn \"gopls\"\n\t\t} else if strings.Contains(path, \"rust-analyzer\") {\n\t\t\treturn \"rust-analyzer\"\n\t\t} else if strings.Contains(path, \"pyright\") || strings.Contains(path, \"pylsp\") || strings.Contains(path, \"python\") {\n\t\t\treturn \"python\"\n\t\t} else if strings.Contains(path, \"clangd\") {\n\t\t\treturn \"clangd\"\n\t\t} else if strings.Contains(path, \"jdtls\") || strings.Contains(path, \"java\") {\n\t\t\treturn \"java\"\n\t\t}\n\n\t\t// Return the base name as fallback\n\t\treturn filepath.Base(path)\n\t}\n\n\treturn \"unknown\"\n}\n\n// shouldPreloadFiles determines if we should preload files for a specific language server\n// Some servers work better with preloaded files, others don't need it\nfunc shouldPreloadFiles(serverName string) bool {\n\t// TypeScript/JavaScript servers typically need some files preloaded\n\t// to properly resolve imports and provide intellisense\n\tswitch serverName {\n\tcase \"typescript\", \"typescript-language-server\", \"tsserver\", \"vtsls\":\n\t\treturn true\n\tcase \"java\", \"jdtls\":\n\t\t// Java servers often need to see source files to build the project model\n\t\treturn true\n\tdefault:\n\t\t// For most servers, we'll use lazy loading by default\n\t\treturn false\n\t}\n}\n\n// Common patterns for directories and files to exclude\n// TODO: make configurable\nvar (\n\texcludedDirNames = map[string]bool{\n\t\t\".git\": true,\n\t\t\"node_modules\": true,\n\t\t\"dist\": true,\n\t\t\"build\": true,\n\t\t\"out\": true,\n\t\t\"bin\": true,\n\t\t\".idea\": true,\n\t\t\".vscode\": true,\n\t\t\".cache\": true,\n\t\t\"coverage\": true,\n\t\t\"target\": true, // Rust build output\n\t\t\"vendor\": true, // Go vendor directory\n\t}\n\n\texcludedFileExtensions = map[string]bool{\n\t\t\".swp\": true,\n\t\t\".swo\": true,\n\t\t\".tmp\": true,\n\t\t\".temp\": true,\n\t\t\".bak\": true,\n\t\t\".log\": true,\n\t\t\".o\": true, // Object files\n\t\t\".so\": true, // Shared libraries\n\t\t\".dylib\": true, // macOS shared libraries\n\t\t\".dll\": true, // Windows shared libraries\n\t\t\".a\": true, // Static libraries\n\t\t\".exe\": true, // Windows executables\n\t\t\".lock\": true, // Lock files\n\t}\n\n\t// Large binary files that shouldn't be opened\n\tlargeBinaryExtensions = map[string]bool{\n\t\t\".png\": true,\n\t\t\".jpg\": true,\n\t\t\".jpeg\": true,\n\t\t\".gif\": true,\n\t\t\".bmp\": true,\n\t\t\".ico\": true,\n\t\t\".zip\": true,\n\t\t\".tar\": true,\n\t\t\".gz\": true,\n\t\t\".rar\": true,\n\t\t\".7z\": true,\n\t\t\".pdf\": true,\n\t\t\".mp3\": true,\n\t\t\".mp4\": true,\n\t\t\".mov\": true,\n\t\t\".wav\": true,\n\t\t\".wasm\": true,\n\t}\n\n\t// Maximum file size to open (5MB)\n\tmaxFileSize int64 = 5 * 1024 * 1024\n)\n\n// shouldExcludeDir returns true if the directory should be excluded from watching/opening\nfunc shouldExcludeDir(dirPath string) bool {\n\tdirName := filepath.Base(dirPath)\n\n\t// Skip dot directories\n\tif strings.HasPrefix(dirName, \".\") {\n\t\treturn true\n\t}\n\n\t// Skip common excluded directories\n\tif excludedDirNames[dirName] {\n\t\treturn true\n\t}\n\n\treturn false\n}\n\n// shouldExcludeFile returns true if the file should be excluded from opening\nfunc shouldExcludeFile(filePath string) bool {\n\tfileName := filepath.Base(filePath)\n\tcnf := config.Get()\n\t// Skip dot files\n\tif strings.HasPrefix(fileName, \".\") {\n\t\treturn true\n\t}\n\n\t// Check file extension\n\text := strings.ToLower(filepath.Ext(filePath))\n\tif excludedFileExtensions[ext] || largeBinaryExtensions[ext] {\n\t\treturn true\n\t}\n\n\t// Skip temporary files\n\tif strings.HasSuffix(filePath, \"~\") {\n\t\treturn true\n\t}\n\n\t// Check file size\n\tinfo, err := os.Stat(filePath)\n\tif err != nil {\n\t\t// If we can't stat the file, skip it\n\t\treturn true\n\t}\n\n\t// Skip large files\n\tif info.Size() > maxFileSize {\n\t\tif cnf.DebugLSP {\n\t\t\tlogging.Debug(\"Skipping large file\",\n\t\t\t\t\"path\", filePath,\n\t\t\t\t\"size\", info.Size(),\n\t\t\t\t\"maxSize\", maxFileSize,\n\t\t\t\t\"debug\", cnf.Debug,\n\t\t\t\t\"sizeMB\", float64(info.Size())/(1024*1024),\n\t\t\t\t\"maxSizeMB\", float64(maxFileSize)/(1024*1024),\n\t\t\t)\n\t\t}\n\t\treturn true\n\t}\n\n\treturn false\n}\n\n// openMatchingFile opens a file if it matches any of the registered patterns\nfunc (w *WorkspaceWatcher) openMatchingFile(ctx context.Context, path string) {\n\tcnf := config.Get()\n\t// Skip directories\n\tinfo, err := os.Stat(path)\n\tif err != nil || info.IsDir() {\n\t\treturn\n\t}\n\n\t// Skip excluded files\n\tif shouldExcludeFile(path) {\n\t\treturn\n\t}\n\n\t// Check if this path should be watched according to server registrations\n\tif watched, _ := w.isPathWatched(path); watched {\n\t\t// Get server name for specialized handling\n\t\tserverName := getServerNameFromContext(ctx)\n\n\t\t// Check if the file is a high-priority file that should be opened immediately\n\t\t// This helps with project initialization for certain language servers\n\t\tif isHighPriorityFile(path, serverName) {\n\t\t\tif cnf.DebugLSP {\n\t\t\t\tlogging.Debug(\"Opening high-priority file\", \"path\", path, \"serverName\", serverName)\n\t\t\t}\n\t\t\tif err := w.client.OpenFile(ctx, path); err != nil && cnf.DebugLSP {\n\t\t\t\tlogging.Error(\"Error opening high-priority file\", \"path\", path, \"error\", err)\n\t\t\t}\n\t\t\treturn\n\t\t}\n\n\t\t// For non-high-priority files, we'll use different strategies based on server type\n\t\tif shouldPreloadFiles(serverName) {\n\t\t\t// For servers that benefit from preloading, open files but with limits\n\n\t\t\t// Check file size - for preloading we're more conservative\n\t\t\tif info.Size() > (1 * 1024 * 1024) { // 1MB limit for preloaded files\n\t\t\t\tif cnf.DebugLSP {\n\t\t\t\t\tlogging.Debug(\"Skipping large file for preloading\", \"path\", path, \"size\", info.Size())\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\t// Check file extension for common source files\n\t\t\text := strings.ToLower(filepath.Ext(path))\n\n\t\t\t// Only preload source files for the specific language\n\t\t\tshouldOpen := false\n\n\t\t\tswitch serverName {\n\t\t\tcase \"typescript\", \"typescript-language-server\", \"tsserver\", \"vtsls\":\n\t\t\t\tshouldOpen = ext == \".ts\" || ext == \".js\" || ext == \".tsx\" || ext == \".jsx\"\n\t\t\tcase \"gopls\":\n\t\t\t\tshouldOpen = ext == \".go\"\n\t\t\tcase \"rust-analyzer\":\n\t\t\t\tshouldOpen = ext == \".rs\"\n\t\t\tcase \"python\", \"pyright\", \"pylsp\":\n\t\t\t\tshouldOpen = ext == \".py\"\n\t\t\tcase \"clangd\":\n\t\t\t\tshouldOpen = ext == \".c\" || ext == \".cpp\" || ext == \".h\" || ext == \".hpp\"\n\t\t\tcase \"java\", \"jdtls\":\n\t\t\t\tshouldOpen = ext == \".java\"\n\t\t\tdefault:\n\t\t\t\t// For unknown servers, be conservative\n\t\t\t\tshouldOpen = false\n\t\t\t}\n\n\t\t\tif shouldOpen {\n\t\t\t\t// Don't need to check if it's already open - the client.OpenFile handles that\n\t\t\t\tif err := w.client.OpenFile(ctx, path); err != nil && cnf.DebugLSP {\n\t\t\t\t\tlogging.Error(\"Error opening file\", \"path\", path, \"error\", err)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\n// isHighPriorityFile determines if a file should be opened immediately\n// regardless of the preloading strategy\nfunc isHighPriorityFile(path string, serverName string) bool {\n\tfileName := filepath.Base(path)\n\text := filepath.Ext(path)\n\n\tswitch serverName {\n\tcase \"typescript\", \"typescript-language-server\", \"tsserver\", \"vtsls\":\n\t\t// For TypeScript, we want to open configuration files immediately\n\t\treturn fileName == \"tsconfig.json\" ||\n\t\t\tfileName == \"package.json\" ||\n\t\t\tfileName == \"jsconfig.json\" ||\n\t\t\t// Also open main entry points\n\t\t\tfileName == \"index.ts\" ||\n\t\t\tfileName == \"index.js\" ||\n\t\t\tfileName == \"main.ts\" ||\n\t\t\tfileName == \"main.js\"\n\tcase \"gopls\":\n\t\t// For Go, we want to open go.mod files immediately\n\t\treturn fileName == \"go.mod\" ||\n\t\t\tfileName == \"go.sum\" ||\n\t\t\t// Also open main.go files\n\t\t\tfileName == \"main.go\"\n\tcase \"rust-analyzer\":\n\t\t// For Rust, we want to open Cargo.toml files immediately\n\t\treturn fileName == \"Cargo.toml\" ||\n\t\t\tfileName == \"Cargo.lock\" ||\n\t\t\t// Also open lib.rs and main.rs\n\t\t\tfileName == \"lib.rs\" ||\n\t\t\tfileName == \"main.rs\"\n\tcase \"python\", \"pyright\", \"pylsp\":\n\t\t// For Python, open key project files\n\t\treturn fileName == \"pyproject.toml\" ||\n\t\t\tfileName == \"setup.py\" ||\n\t\t\tfileName == \"requirements.txt\" ||\n\t\t\tfileName == \"__init__.py\" ||\n\t\t\tfileName == \"__main__.py\"\n\tcase \"clangd\":\n\t\t// For C/C++, open key project files\n\t\treturn fileName == \"CMakeLists.txt\" ||\n\t\t\tfileName == \"Makefile\" ||\n\t\t\tfileName == \"compile_commands.json\"\n\tcase \"java\", \"jdtls\":\n\t\t// For Java, open key project files\n\t\treturn fileName == \"pom.xml\" ||\n\t\t\tfileName == \"build.gradle\" ||\n\t\t\text == \".java\" // Java servers often need to see source files\n\t}\n\n\t// For unknown servers, prioritize common configuration files\n\treturn fileName == \"package.json\" ||\n\t\tfileName == \"Makefile\" ||\n\t\tfileName == \"CMakeLists.txt\" ||\n\t\tfileName == \".editorconfig\"\n}\n"], ["/opencode/internal/tui/layout/container.go", "package layout\n\nimport (\n\t\"github.com/charmbracelet/bubbles/key\"\n\ttea \"github.com/charmbracelet/bubbletea\"\n\t\"github.com/charmbracelet/lipgloss\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n)\n\ntype Container interface {\n\ttea.Model\n\tSizeable\n\tBindings\n}\ntype container struct {\n\twidth int\n\theight int\n\n\tcontent tea.Model\n\n\t// Style options\n\tpaddingTop int\n\tpaddingRight int\n\tpaddingBottom int\n\tpaddingLeft int\n\n\tborderTop bool\n\tborderRight bool\n\tborderBottom bool\n\tborderLeft bool\n\tborderStyle lipgloss.Border\n}\n\nfunc (c *container) Init() tea.Cmd {\n\treturn c.content.Init()\n}\n\nfunc (c *container) Update(msg tea.Msg) (tea.Model, tea.Cmd) {\n\tu, cmd := c.content.Update(msg)\n\tc.content = u\n\treturn c, cmd\n}\n\nfunc (c *container) View() string {\n\tt := theme.CurrentTheme()\n\tstyle := lipgloss.NewStyle()\n\twidth := c.width\n\theight := c.height\n\n\tstyle = style.Background(t.Background())\n\n\t// Apply border if any side is enabled\n\tif c.borderTop || c.borderRight || c.borderBottom || c.borderLeft {\n\t\t// Adjust width and height for borders\n\t\tif c.borderTop {\n\t\t\theight--\n\t\t}\n\t\tif c.borderBottom {\n\t\t\theight--\n\t\t}\n\t\tif c.borderLeft {\n\t\t\twidth--\n\t\t}\n\t\tif c.borderRight {\n\t\t\twidth--\n\t\t}\n\t\tstyle = style.Border(c.borderStyle, c.borderTop, c.borderRight, c.borderBottom, c.borderLeft)\n\t\tstyle = style.BorderBackground(t.Background()).BorderForeground(t.BorderNormal())\n\t}\n\tstyle = style.\n\t\tWidth(width).\n\t\tHeight(height).\n\t\tPaddingTop(c.paddingTop).\n\t\tPaddingRight(c.paddingRight).\n\t\tPaddingBottom(c.paddingBottom).\n\t\tPaddingLeft(c.paddingLeft)\n\n\treturn style.Render(c.content.View())\n}\n\nfunc (c *container) SetSize(width, height int) tea.Cmd {\n\tc.width = width\n\tc.height = height\n\n\t// If the content implements Sizeable, adjust its size to account for padding and borders\n\tif sizeable, ok := c.content.(Sizeable); ok {\n\t\t// Calculate horizontal space taken by padding and borders\n\t\thorizontalSpace := c.paddingLeft + c.paddingRight\n\t\tif c.borderLeft {\n\t\t\thorizontalSpace++\n\t\t}\n\t\tif c.borderRight {\n\t\t\thorizontalSpace++\n\t\t}\n\n\t\t// Calculate vertical space taken by padding and borders\n\t\tverticalSpace := c.paddingTop + c.paddingBottom\n\t\tif c.borderTop {\n\t\t\tverticalSpace++\n\t\t}\n\t\tif c.borderBottom {\n\t\t\tverticalSpace++\n\t\t}\n\n\t\t// Set content size with adjusted dimensions\n\t\tcontentWidth := max(0, width-horizontalSpace)\n\t\tcontentHeight := max(0, height-verticalSpace)\n\t\treturn sizeable.SetSize(contentWidth, contentHeight)\n\t}\n\treturn nil\n}\n\nfunc (c *container) GetSize() (int, int) {\n\treturn c.width, c.height\n}\n\nfunc (c *container) BindingKeys() []key.Binding {\n\tif b, ok := c.content.(Bindings); ok {\n\t\treturn b.BindingKeys()\n\t}\n\treturn []key.Binding{}\n}\n\ntype ContainerOption func(*container)\n\nfunc NewContainer(content tea.Model, options ...ContainerOption) Container {\n\n\tc := &container{\n\t\tcontent: content,\n\t\tborderStyle: lipgloss.NormalBorder(),\n\t}\n\n\tfor _, option := range options {\n\t\toption(c)\n\t}\n\n\treturn c\n}\n\n// Padding options\nfunc WithPadding(top, right, bottom, left int) ContainerOption {\n\treturn func(c *container) {\n\t\tc.paddingTop = top\n\t\tc.paddingRight = right\n\t\tc.paddingBottom = bottom\n\t\tc.paddingLeft = left\n\t}\n}\n\nfunc WithPaddingAll(padding int) ContainerOption {\n\treturn WithPadding(padding, padding, padding, padding)\n}\n\nfunc WithPaddingHorizontal(padding int) ContainerOption {\n\treturn func(c *container) {\n\t\tc.paddingLeft = padding\n\t\tc.paddingRight = padding\n\t}\n}\n\nfunc WithPaddingVertical(padding int) ContainerOption {\n\treturn func(c *container) {\n\t\tc.paddingTop = padding\n\t\tc.paddingBottom = padding\n\t}\n}\n\nfunc WithBorder(top, right, bottom, left bool) ContainerOption {\n\treturn func(c *container) {\n\t\tc.borderTop = top\n\t\tc.borderRight = right\n\t\tc.borderBottom = bottom\n\t\tc.borderLeft = left\n\t}\n}\n\nfunc WithBorderAll() ContainerOption {\n\treturn WithBorder(true, true, true, true)\n}\n\nfunc WithBorderHorizontal() ContainerOption {\n\treturn WithBorder(true, false, true, false)\n}\n\nfunc WithBorderVertical() ContainerOption {\n\treturn WithBorder(false, true, false, true)\n}\n\nfunc WithBorderStyle(style lipgloss.Border) ContainerOption {\n\treturn func(c *container) {\n\t\tc.borderStyle = style\n\t}\n}\n\nfunc WithRoundedBorder() ContainerOption {\n\treturn WithBorderStyle(lipgloss.RoundedBorder())\n}\n\nfunc WithThickBorder() ContainerOption {\n\treturn WithBorderStyle(lipgloss.ThickBorder())\n}\n\nfunc WithDoubleBorder() ContainerOption {\n\treturn WithBorderStyle(lipgloss.DoubleBorder())\n}\n"], ["/opencode/internal/llm/models/local.go", "package models\n\nimport (\n\t\"cmp\"\n\t\"encoding/json\"\n\t\"net/http\"\n\t\"net/url\"\n\t\"os\"\n\t\"regexp\"\n\t\"strings\"\n\t\"unicode\"\n\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n\t\"github.com/spf13/viper\"\n)\n\nconst (\n\tProviderLocal ModelProvider = \"local\"\n\n\tlocalModelsPath = \"v1/models\"\n\tlmStudioBetaModelsPath = \"api/v0/models\"\n)\n\nfunc init() {\n\tif endpoint := os.Getenv(\"LOCAL_ENDPOINT\"); endpoint != \"\" {\n\t\tlocalEndpoint, err := url.Parse(endpoint)\n\t\tif err != nil {\n\t\t\tlogging.Debug(\"Failed to parse local endpoint\",\n\t\t\t\t\"error\", err,\n\t\t\t\t\"endpoint\", endpoint,\n\t\t\t)\n\t\t\treturn\n\t\t}\n\n\t\tload := func(url *url.URL, path string) []localModel {\n\t\t\turl.Path = path\n\t\t\treturn listLocalModels(url.String())\n\t\t}\n\n\t\tmodels := load(localEndpoint, lmStudioBetaModelsPath)\n\n\t\tif len(models) == 0 {\n\t\t\tmodels = load(localEndpoint, localModelsPath)\n\t\t}\n\n\t\tif len(models) == 0 {\n\t\t\tlogging.Debug(\"No local models found\",\n\t\t\t\t\"endpoint\", endpoint,\n\t\t\t)\n\t\t\treturn\n\t\t}\n\n\t\tloadLocalModels(models)\n\n\t\tviper.SetDefault(\"providers.local.apiKey\", \"dummy\")\n\t\tProviderPopularity[ProviderLocal] = 0\n\t}\n}\n\ntype localModelList struct {\n\tData []localModel `json:\"data\"`\n}\n\ntype localModel struct {\n\tID string `json:\"id\"`\n\tObject string `json:\"object\"`\n\tType string `json:\"type\"`\n\tPublisher string `json:\"publisher\"`\n\tArch string `json:\"arch\"`\n\tCompatibilityType string `json:\"compatibility_type\"`\n\tQuantization string `json:\"quantization\"`\n\tState string `json:\"state\"`\n\tMaxContextLength int64 `json:\"max_context_length\"`\n\tLoadedContextLength int64 `json:\"loaded_context_length\"`\n}\n\nfunc listLocalModels(modelsEndpoint string) []localModel {\n\tres, err := http.Get(modelsEndpoint)\n\tif err != nil {\n\t\tlogging.Debug(\"Failed to list local models\",\n\t\t\t\"error\", err,\n\t\t\t\"endpoint\", modelsEndpoint,\n\t\t)\n\t\treturn []localModel{}\n\t}\n\tdefer res.Body.Close()\n\n\tif res.StatusCode != http.StatusOK {\n\t\tlogging.Debug(\"Failed to list local models\",\n\t\t\t\"status\", res.StatusCode,\n\t\t\t\"endpoint\", modelsEndpoint,\n\t\t)\n\t\treturn []localModel{}\n\t}\n\n\tvar modelList localModelList\n\tif err = json.NewDecoder(res.Body).Decode(&modelList); err != nil {\n\t\tlogging.Debug(\"Failed to list local models\",\n\t\t\t\"error\", err,\n\t\t\t\"endpoint\", modelsEndpoint,\n\t\t)\n\t\treturn []localModel{}\n\t}\n\n\tvar supportedModels []localModel\n\tfor _, model := range modelList.Data {\n\t\tif strings.HasSuffix(modelsEndpoint, lmStudioBetaModelsPath) {\n\t\t\tif model.Object != \"model\" || model.Type != \"llm\" {\n\t\t\t\tlogging.Debug(\"Skipping unsupported LMStudio model\",\n\t\t\t\t\t\"endpoint\", modelsEndpoint,\n\t\t\t\t\t\"id\", model.ID,\n\t\t\t\t\t\"object\", model.Object,\n\t\t\t\t\t\"type\", model.Type,\n\t\t\t\t)\n\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\n\t\tsupportedModels = append(supportedModels, model)\n\t}\n\n\treturn supportedModels\n}\n\nfunc loadLocalModels(models []localModel) {\n\tfor i, m := range models {\n\t\tmodel := convertLocalModel(m)\n\t\tSupportedModels[model.ID] = model\n\n\t\tif i == 0 || m.State == \"loaded\" {\n\t\t\tviper.SetDefault(\"agents.coder.model\", model.ID)\n\t\t\tviper.SetDefault(\"agents.summarizer.model\", model.ID)\n\t\t\tviper.SetDefault(\"agents.task.model\", model.ID)\n\t\t\tviper.SetDefault(\"agents.title.model\", model.ID)\n\t\t}\n\t}\n}\n\nfunc convertLocalModel(model localModel) Model {\n\treturn Model{\n\t\tID: ModelID(\"local.\" + model.ID),\n\t\tName: friendlyModelName(model.ID),\n\t\tProvider: ProviderLocal,\n\t\tAPIModel: model.ID,\n\t\tContextWindow: cmp.Or(model.LoadedContextLength, 4096),\n\t\tDefaultMaxTokens: cmp.Or(model.LoadedContextLength, 4096),\n\t\tCanReason: true,\n\t\tSupportsAttachments: true,\n\t}\n}\n\nvar modelInfoRegex = regexp.MustCompile(`(?i)^([a-z0-9]+)(?:[-_]?([rv]?\\d[\\.\\d]*))?(?:[-_]?([a-z]+))?.*`)\n\nfunc friendlyModelName(modelID string) string {\n\tmainID := modelID\n\ttag := \"\"\n\n\tif slash := strings.LastIndex(mainID, \"/\"); slash != -1 {\n\t\tmainID = mainID[slash+1:]\n\t}\n\n\tif at := strings.Index(modelID, \"@\"); at != -1 {\n\t\tmainID = modelID[:at]\n\t\ttag = modelID[at+1:]\n\t}\n\n\tmatch := modelInfoRegex.FindStringSubmatch(mainID)\n\tif match == nil {\n\t\treturn modelID\n\t}\n\n\tcapitalize := func(s string) string {\n\t\tif s == \"\" {\n\t\t\treturn \"\"\n\t\t}\n\t\trunes := []rune(s)\n\t\trunes[0] = unicode.ToUpper(runes[0])\n\t\treturn string(runes)\n\t}\n\n\tfamily := capitalize(match[1])\n\tversion := \"\"\n\tlabel := \"\"\n\n\tif len(match) > 2 && match[2] != \"\" {\n\t\tversion = strings.ToUpper(match[2])\n\t}\n\n\tif len(match) > 3 && match[3] != \"\" {\n\t\tlabel = capitalize(match[3])\n\t}\n\n\tvar parts []string\n\tif family != \"\" {\n\t\tparts = append(parts, family)\n\t}\n\tif version != \"\" {\n\t\tparts = append(parts, version)\n\t}\n\tif label != \"\" {\n\t\tparts = append(parts, label)\n\t}\n\tif tag != \"\" {\n\t\tparts = append(parts, tag)\n\t}\n\n\treturn strings.Join(parts, \" \")\n}\n"], ["/opencode/internal/llm/provider/provider.go", "package provider\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"os\"\n\n\t\"github.com/opencode-ai/opencode/internal/llm/models\"\n\t\"github.com/opencode-ai/opencode/internal/llm/tools\"\n\t\"github.com/opencode-ai/opencode/internal/message\"\n)\n\ntype EventType string\n\nconst maxRetries = 8\n\nconst (\n\tEventContentStart EventType = \"content_start\"\n\tEventToolUseStart EventType = \"tool_use_start\"\n\tEventToolUseDelta EventType = \"tool_use_delta\"\n\tEventToolUseStop EventType = \"tool_use_stop\"\n\tEventContentDelta EventType = \"content_delta\"\n\tEventThinkingDelta EventType = \"thinking_delta\"\n\tEventContentStop EventType = \"content_stop\"\n\tEventComplete EventType = \"complete\"\n\tEventError EventType = \"error\"\n\tEventWarning EventType = \"warning\"\n)\n\ntype TokenUsage struct {\n\tInputTokens int64\n\tOutputTokens int64\n\tCacheCreationTokens int64\n\tCacheReadTokens int64\n}\n\ntype ProviderResponse struct {\n\tContent string\n\tToolCalls []message.ToolCall\n\tUsage TokenUsage\n\tFinishReason message.FinishReason\n}\n\ntype ProviderEvent struct {\n\tType EventType\n\n\tContent string\n\tThinking string\n\tResponse *ProviderResponse\n\tToolCall *message.ToolCall\n\tError error\n}\ntype Provider interface {\n\tSendMessages(ctx context.Context, messages []message.Message, tools []tools.BaseTool) (*ProviderResponse, error)\n\n\tStreamResponse(ctx context.Context, messages []message.Message, tools []tools.BaseTool) <-chan ProviderEvent\n\n\tModel() models.Model\n}\n\ntype providerClientOptions struct {\n\tapiKey string\n\tmodel models.Model\n\tmaxTokens int64\n\tsystemMessage string\n\n\tanthropicOptions []AnthropicOption\n\topenaiOptions []OpenAIOption\n\tgeminiOptions []GeminiOption\n\tbedrockOptions []BedrockOption\n\tcopilotOptions []CopilotOption\n}\n\ntype ProviderClientOption func(*providerClientOptions)\n\ntype ProviderClient interface {\n\tsend(ctx context.Context, messages []message.Message, tools []tools.BaseTool) (*ProviderResponse, error)\n\tstream(ctx context.Context, messages []message.Message, tools []tools.BaseTool) <-chan ProviderEvent\n}\n\ntype baseProvider[C ProviderClient] struct {\n\toptions providerClientOptions\n\tclient C\n}\n\nfunc NewProvider(providerName models.ModelProvider, opts ...ProviderClientOption) (Provider, error) {\n\tclientOptions := providerClientOptions{}\n\tfor _, o := range opts {\n\t\to(&clientOptions)\n\t}\n\tswitch providerName {\n\tcase models.ProviderCopilot:\n\t\treturn &baseProvider[CopilotClient]{\n\t\t\toptions: clientOptions,\n\t\t\tclient: newCopilotClient(clientOptions),\n\t\t}, nil\n\tcase models.ProviderAnthropic:\n\t\treturn &baseProvider[AnthropicClient]{\n\t\t\toptions: clientOptions,\n\t\t\tclient: newAnthropicClient(clientOptions),\n\t\t}, nil\n\tcase models.ProviderOpenAI:\n\t\treturn &baseProvider[OpenAIClient]{\n\t\t\toptions: clientOptions,\n\t\t\tclient: newOpenAIClient(clientOptions),\n\t\t}, nil\n\tcase models.ProviderGemini:\n\t\treturn &baseProvider[GeminiClient]{\n\t\t\toptions: clientOptions,\n\t\t\tclient: newGeminiClient(clientOptions),\n\t\t}, nil\n\tcase models.ProviderBedrock:\n\t\treturn &baseProvider[BedrockClient]{\n\t\t\toptions: clientOptions,\n\t\t\tclient: newBedrockClient(clientOptions),\n\t\t}, nil\n\tcase models.ProviderGROQ:\n\t\tclientOptions.openaiOptions = append(clientOptions.openaiOptions,\n\t\t\tWithOpenAIBaseURL(\"https://api.groq.com/openai/v1\"),\n\t\t)\n\t\treturn &baseProvider[OpenAIClient]{\n\t\t\toptions: clientOptions,\n\t\t\tclient: newOpenAIClient(clientOptions),\n\t\t}, nil\n\tcase models.ProviderAzure:\n\t\treturn &baseProvider[AzureClient]{\n\t\t\toptions: clientOptions,\n\t\t\tclient: newAzureClient(clientOptions),\n\t\t}, nil\n\tcase models.ProviderVertexAI:\n\t\treturn &baseProvider[VertexAIClient]{\n\t\t\toptions: clientOptions,\n\t\t\tclient: newVertexAIClient(clientOptions),\n\t\t}, nil\n\tcase models.ProviderOpenRouter:\n\t\tclientOptions.openaiOptions = append(clientOptions.openaiOptions,\n\t\t\tWithOpenAIBaseURL(\"https://openrouter.ai/api/v1\"),\n\t\t\tWithOpenAIExtraHeaders(map[string]string{\n\t\t\t\t\"HTTP-Referer\": \"opencode.ai\",\n\t\t\t\t\"X-Title\": \"OpenCode\",\n\t\t\t}),\n\t\t)\n\t\treturn &baseProvider[OpenAIClient]{\n\t\t\toptions: clientOptions,\n\t\t\tclient: newOpenAIClient(clientOptions),\n\t\t}, nil\n\tcase models.ProviderXAI:\n\t\tclientOptions.openaiOptions = append(clientOptions.openaiOptions,\n\t\t\tWithOpenAIBaseURL(\"https://api.x.ai/v1\"),\n\t\t)\n\t\treturn &baseProvider[OpenAIClient]{\n\t\t\toptions: clientOptions,\n\t\t\tclient: newOpenAIClient(clientOptions),\n\t\t}, nil\n\tcase models.ProviderLocal:\n\t\tclientOptions.openaiOptions = append(clientOptions.openaiOptions,\n\t\t\tWithOpenAIBaseURL(os.Getenv(\"LOCAL_ENDPOINT\")),\n\t\t)\n\t\treturn &baseProvider[OpenAIClient]{\n\t\t\toptions: clientOptions,\n\t\t\tclient: newOpenAIClient(clientOptions),\n\t\t}, nil\n\tcase models.ProviderMock:\n\t\t// TODO: implement mock client for test\n\t\tpanic(\"not implemented\")\n\t}\n\treturn nil, fmt.Errorf(\"provider not supported: %s\", providerName)\n}\n\nfunc (p *baseProvider[C]) cleanMessages(messages []message.Message) (cleaned []message.Message) {\n\tfor _, msg := range messages {\n\t\t// The message has no content\n\t\tif len(msg.Parts) == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tcleaned = append(cleaned, msg)\n\t}\n\treturn\n}\n\nfunc (p *baseProvider[C]) SendMessages(ctx context.Context, messages []message.Message, tools []tools.BaseTool) (*ProviderResponse, error) {\n\tmessages = p.cleanMessages(messages)\n\treturn p.client.send(ctx, messages, tools)\n}\n\nfunc (p *baseProvider[C]) Model() models.Model {\n\treturn p.options.model\n}\n\nfunc (p *baseProvider[C]) StreamResponse(ctx context.Context, messages []message.Message, tools []tools.BaseTool) <-chan ProviderEvent {\n\tmessages = p.cleanMessages(messages)\n\treturn p.client.stream(ctx, messages, tools)\n}\n\nfunc WithAPIKey(apiKey string) ProviderClientOption {\n\treturn func(options *providerClientOptions) {\n\t\toptions.apiKey = apiKey\n\t}\n}\n\nfunc WithModel(model models.Model) ProviderClientOption {\n\treturn func(options *providerClientOptions) {\n\t\toptions.model = model\n\t}\n}\n\nfunc WithMaxTokens(maxTokens int64) ProviderClientOption {\n\treturn func(options *providerClientOptions) {\n\t\toptions.maxTokens = maxTokens\n\t}\n}\n\nfunc WithSystemMessage(systemMessage string) ProviderClientOption {\n\treturn func(options *providerClientOptions) {\n\t\toptions.systemMessage = systemMessage\n\t}\n}\n\nfunc WithAnthropicOptions(anthropicOptions ...AnthropicOption) ProviderClientOption {\n\treturn func(options *providerClientOptions) {\n\t\toptions.anthropicOptions = anthropicOptions\n\t}\n}\n\nfunc WithOpenAIOptions(openaiOptions ...OpenAIOption) ProviderClientOption {\n\treturn func(options *providerClientOptions) {\n\t\toptions.openaiOptions = openaiOptions\n\t}\n}\n\nfunc WithGeminiOptions(geminiOptions ...GeminiOption) ProviderClientOption {\n\treturn func(options *providerClientOptions) {\n\t\toptions.geminiOptions = geminiOptions\n\t}\n}\n\nfunc WithBedrockOptions(bedrockOptions ...BedrockOption) ProviderClientOption {\n\treturn func(options *providerClientOptions) {\n\t\toptions.bedrockOptions = bedrockOptions\n\t}\n}\n\nfunc WithCopilotOptions(copilotOptions ...CopilotOption) ProviderClientOption {\n\treturn func(options *providerClientOptions) {\n\t\toptions.copilotOptions = copilotOptions\n\t}\n}\n"], ["/opencode/internal/tui/styles/background.go", "package styles\n\nimport (\n\t\"fmt\"\n\t\"regexp\"\n\t\"strings\"\n\n\t\"github.com/charmbracelet/lipgloss\"\n)\n\nvar ansiEscape = regexp.MustCompile(\"\\x1b\\\\[[0-9;]*m\")\n\nfunc getColorRGB(c lipgloss.TerminalColor) (uint8, uint8, uint8) {\n\tr, g, b, a := c.RGBA()\n\n\t// Un-premultiply alpha if needed\n\tif a > 0 && a < 0xffff {\n\t\tr = (r * 0xffff) / a\n\t\tg = (g * 0xffff) / a\n\t\tb = (b * 0xffff) / a\n\t}\n\n\t// Convert from 16-bit to 8-bit color\n\treturn uint8(r >> 8), uint8(g >> 8), uint8(b >> 8)\n}\n\n// ForceReplaceBackgroundWithLipgloss replaces any ANSI background color codes\n// in `input` with a single 24‑bit background (48;2;R;G;B).\nfunc ForceReplaceBackgroundWithLipgloss(input string, newBgColor lipgloss.TerminalColor) string {\n\t// Precompute our new-bg sequence once\n\tr, g, b := getColorRGB(newBgColor)\n\tnewBg := fmt.Sprintf(\"48;2;%d;%d;%d\", r, g, b)\n\n\treturn ansiEscape.ReplaceAllStringFunc(input, func(seq string) string {\n\t\tconst (\n\t\t\tescPrefixLen = 2 // \"\\x1b[\"\n\t\t\tescSuffixLen = 1 // \"m\"\n\t\t)\n\n\t\traw := seq\n\t\tstart := escPrefixLen\n\t\tend := len(raw) - escSuffixLen\n\n\t\tvar sb strings.Builder\n\t\t// reserve enough space: original content minus bg codes + our newBg\n\t\tsb.Grow((end - start) + len(newBg) + 2)\n\n\t\t// scan from start..end, token by token\n\t\tfor i := start; i < end; {\n\t\t\t// find the next ';' or end\n\t\t\tj := i\n\t\t\tfor j < end && raw[j] != ';' {\n\t\t\t\tj++\n\t\t\t}\n\t\t\ttoken := raw[i:j]\n\n\t\t\t// fast‑path: skip \"48;5;N\" or \"48;2;R;G;B\"\n\t\t\tif len(token) == 2 && token[0] == '4' && token[1] == '8' {\n\t\t\t\tk := j + 1\n\t\t\t\tif k < end {\n\t\t\t\t\t// find next token\n\t\t\t\t\tl := k\n\t\t\t\t\tfor l < end && raw[l] != ';' {\n\t\t\t\t\t\tl++\n\t\t\t\t\t}\n\t\t\t\t\tnext := raw[k:l]\n\t\t\t\t\tif next == \"5\" {\n\t\t\t\t\t\t// skip \"48;5;N\"\n\t\t\t\t\t\tm := l + 1\n\t\t\t\t\t\tfor m < end && raw[m] != ';' {\n\t\t\t\t\t\t\tm++\n\t\t\t\t\t\t}\n\t\t\t\t\t\ti = m + 1\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t} else if next == \"2\" {\n\t\t\t\t\t\t// skip \"48;2;R;G;B\"\n\t\t\t\t\t\tm := l + 1\n\t\t\t\t\t\tfor count := 0; count < 3 && m < end; count++ {\n\t\t\t\t\t\t\tfor m < end && raw[m] != ';' {\n\t\t\t\t\t\t\t\tm++\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tm++\n\t\t\t\t\t\t}\n\t\t\t\t\t\ti = m\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// decide whether to keep this token\n\t\t\t// manually parse ASCII digits to int\n\t\t\tisNum := true\n\t\t\tval := 0\n\t\t\tfor p := i; p < j; p++ {\n\t\t\t\tc := raw[p]\n\t\t\t\tif c < '0' || c > '9' {\n\t\t\t\t\tisNum = false\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tval = val*10 + int(c-'0')\n\t\t\t}\n\t\t\tkeep := !isNum ||\n\t\t\t\t((val < 40 || val > 47) && (val < 100 || val > 107) && val != 49)\n\n\t\t\tif keep {\n\t\t\t\tif sb.Len() > 0 {\n\t\t\t\t\tsb.WriteByte(';')\n\t\t\t\t}\n\t\t\t\tsb.WriteString(token)\n\t\t\t}\n\t\t\t// advance past this token (and the semicolon)\n\t\t\ti = j + 1\n\t\t}\n\n\t\t// append our new background\n\t\tif sb.Len() > 0 {\n\t\t\tsb.WriteByte(';')\n\t\t}\n\t\tsb.WriteString(newBg)\n\n\t\treturn \"\\x1b[\" + sb.String() + \"m\"\n\t})\n}\n"], ["/opencode/internal/lsp/client.go", "package lsp\n\nimport (\n\t\"bufio\"\n\t\"context\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"os/exec\"\n\t\"path/filepath\"\n\t\"strings\"\n\t\"sync\"\n\t\"sync/atomic\"\n\t\"time\"\n\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n\t\"github.com/opencode-ai/opencode/internal/lsp/protocol\"\n)\n\ntype Client struct {\n\tCmd *exec.Cmd\n\tstdin io.WriteCloser\n\tstdout *bufio.Reader\n\tstderr io.ReadCloser\n\n\t// Request ID counter\n\tnextID atomic.Int32\n\n\t// Response handlers\n\thandlers map[int32]chan *Message\n\thandlersMu sync.RWMutex\n\n\t// Server request handlers\n\tserverRequestHandlers map[string]ServerRequestHandler\n\tserverHandlersMu sync.RWMutex\n\n\t// Notification handlers\n\tnotificationHandlers map[string]NotificationHandler\n\tnotificationMu sync.RWMutex\n\n\t// Diagnostic cache\n\tdiagnostics map[protocol.DocumentUri][]protocol.Diagnostic\n\tdiagnosticsMu sync.RWMutex\n\n\t// Files are currently opened by the LSP\n\topenFiles map[string]*OpenFileInfo\n\topenFilesMu sync.RWMutex\n\n\t// Server state\n\tserverState atomic.Value\n}\n\nfunc NewClient(ctx context.Context, command string, args ...string) (*Client, error) {\n\tcmd := exec.CommandContext(ctx, command, args...)\n\t// Copy env\n\tcmd.Env = os.Environ()\n\n\tstdin, err := cmd.StdinPipe()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to create stdin pipe: %w\", err)\n\t}\n\n\tstdout, err := cmd.StdoutPipe()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to create stdout pipe: %w\", err)\n\t}\n\n\tstderr, err := cmd.StderrPipe()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to create stderr pipe: %w\", err)\n\t}\n\n\tclient := &Client{\n\t\tCmd: cmd,\n\t\tstdin: stdin,\n\t\tstdout: bufio.NewReader(stdout),\n\t\tstderr: stderr,\n\t\thandlers: make(map[int32]chan *Message),\n\t\tnotificationHandlers: make(map[string]NotificationHandler),\n\t\tserverRequestHandlers: make(map[string]ServerRequestHandler),\n\t\tdiagnostics: make(map[protocol.DocumentUri][]protocol.Diagnostic),\n\t\topenFiles: make(map[string]*OpenFileInfo),\n\t}\n\n\t// Initialize server state\n\tclient.serverState.Store(StateStarting)\n\n\t// Start the LSP server process\n\tif err := cmd.Start(); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to start LSP server: %w\", err)\n\t}\n\n\t// Handle stderr in a separate goroutine\n\tgo func() {\n\t\tscanner := bufio.NewScanner(stderr)\n\t\tfor scanner.Scan() {\n\t\t\tfmt.Fprintf(os.Stderr, \"LSP Server: %s\\n\", scanner.Text())\n\t\t}\n\t\tif err := scanner.Err(); err != nil {\n\t\t\tfmt.Fprintf(os.Stderr, \"Error reading stderr: %v\\n\", err)\n\t\t}\n\t}()\n\n\t// Start message handling loop\n\tgo func() {\n\t\tdefer logging.RecoverPanic(\"LSP-message-handler\", func() {\n\t\t\tlogging.ErrorPersist(\"LSP message handler crashed, LSP functionality may be impaired\")\n\t\t})\n\t\tclient.handleMessages()\n\t}()\n\n\treturn client, nil\n}\n\nfunc (c *Client) RegisterNotificationHandler(method string, handler NotificationHandler) {\n\tc.notificationMu.Lock()\n\tdefer c.notificationMu.Unlock()\n\tc.notificationHandlers[method] = handler\n}\n\nfunc (c *Client) RegisterServerRequestHandler(method string, handler ServerRequestHandler) {\n\tc.serverHandlersMu.Lock()\n\tdefer c.serverHandlersMu.Unlock()\n\tc.serverRequestHandlers[method] = handler\n}\n\nfunc (c *Client) InitializeLSPClient(ctx context.Context, workspaceDir string) (*protocol.InitializeResult, error) {\n\tinitParams := &protocol.InitializeParams{\n\t\tWorkspaceFoldersInitializeParams: protocol.WorkspaceFoldersInitializeParams{\n\t\t\tWorkspaceFolders: []protocol.WorkspaceFolder{\n\t\t\t\t{\n\t\t\t\t\tURI: protocol.URI(\"file://\" + workspaceDir),\n\t\t\t\t\tName: workspaceDir,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\n\t\tXInitializeParams: protocol.XInitializeParams{\n\t\t\tProcessID: int32(os.Getpid()),\n\t\t\tClientInfo: &protocol.ClientInfo{\n\t\t\t\tName: \"mcp-language-server\",\n\t\t\t\tVersion: \"0.1.0\",\n\t\t\t},\n\t\t\tRootPath: workspaceDir,\n\t\t\tRootURI: protocol.DocumentUri(\"file://\" + workspaceDir),\n\t\t\tCapabilities: protocol.ClientCapabilities{\n\t\t\t\tWorkspace: protocol.WorkspaceClientCapabilities{\n\t\t\t\t\tConfiguration: true,\n\t\t\t\t\tDidChangeConfiguration: protocol.DidChangeConfigurationClientCapabilities{\n\t\t\t\t\t\tDynamicRegistration: true,\n\t\t\t\t\t},\n\t\t\t\t\tDidChangeWatchedFiles: protocol.DidChangeWatchedFilesClientCapabilities{\n\t\t\t\t\t\tDynamicRegistration: true,\n\t\t\t\t\t\tRelativePatternSupport: true,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tTextDocument: protocol.TextDocumentClientCapabilities{\n\t\t\t\t\tSynchronization: &protocol.TextDocumentSyncClientCapabilities{\n\t\t\t\t\t\tDynamicRegistration: true,\n\t\t\t\t\t\tDidSave: true,\n\t\t\t\t\t},\n\t\t\t\t\tCompletion: protocol.CompletionClientCapabilities{\n\t\t\t\t\t\tCompletionItem: protocol.ClientCompletionItemOptions{},\n\t\t\t\t\t},\n\t\t\t\t\tCodeLens: &protocol.CodeLensClientCapabilities{\n\t\t\t\t\t\tDynamicRegistration: true,\n\t\t\t\t\t},\n\t\t\t\t\tDocumentSymbol: protocol.DocumentSymbolClientCapabilities{},\n\t\t\t\t\tCodeAction: protocol.CodeActionClientCapabilities{\n\t\t\t\t\t\tCodeActionLiteralSupport: protocol.ClientCodeActionLiteralOptions{\n\t\t\t\t\t\t\tCodeActionKind: protocol.ClientCodeActionKindOptions{\n\t\t\t\t\t\t\t\tValueSet: []protocol.CodeActionKind{},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\tPublishDiagnostics: protocol.PublishDiagnosticsClientCapabilities{\n\t\t\t\t\t\tVersionSupport: true,\n\t\t\t\t\t},\n\t\t\t\t\tSemanticTokens: protocol.SemanticTokensClientCapabilities{\n\t\t\t\t\t\tRequests: protocol.ClientSemanticTokensRequestOptions{\n\t\t\t\t\t\t\tRange: &protocol.Or_ClientSemanticTokensRequestOptions_range{},\n\t\t\t\t\t\t\tFull: &protocol.Or_ClientSemanticTokensRequestOptions_full{},\n\t\t\t\t\t\t},\n\t\t\t\t\t\tTokenTypes: []string{},\n\t\t\t\t\t\tTokenModifiers: []string{},\n\t\t\t\t\t\tFormats: []protocol.TokenFormat{},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tWindow: protocol.WindowClientCapabilities{},\n\t\t\t},\n\t\t\tInitializationOptions: map[string]any{\n\t\t\t\t\"codelenses\": map[string]bool{\n\t\t\t\t\t\"generate\": true,\n\t\t\t\t\t\"regenerate_cgo\": true,\n\t\t\t\t\t\"test\": true,\n\t\t\t\t\t\"tidy\": true,\n\t\t\t\t\t\"upgrade_dependency\": true,\n\t\t\t\t\t\"vendor\": true,\n\t\t\t\t\t\"vulncheck\": false,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\tvar result protocol.InitializeResult\n\tif err := c.Call(ctx, \"initialize\", initParams, &result); err != nil {\n\t\treturn nil, fmt.Errorf(\"initialize failed: %w\", err)\n\t}\n\n\tif err := c.Notify(ctx, \"initialized\", struct{}{}); err != nil {\n\t\treturn nil, fmt.Errorf(\"initialized notification failed: %w\", err)\n\t}\n\n\t// Register handlers\n\tc.RegisterServerRequestHandler(\"workspace/applyEdit\", HandleApplyEdit)\n\tc.RegisterServerRequestHandler(\"workspace/configuration\", HandleWorkspaceConfiguration)\n\tc.RegisterServerRequestHandler(\"client/registerCapability\", HandleRegisterCapability)\n\tc.RegisterNotificationHandler(\"window/showMessage\", HandleServerMessage)\n\tc.RegisterNotificationHandler(\"textDocument/publishDiagnostics\",\n\t\tfunc(params json.RawMessage) { HandleDiagnostics(c, params) })\n\n\t// Notify the LSP server\n\terr := c.Initialized(ctx, protocol.InitializedParams{})\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"initialization failed: %w\", err)\n\t}\n\n\treturn &result, nil\n}\n\nfunc (c *Client) Close() error {\n\t// Try to close all open files first\n\tctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)\n\tdefer cancel()\n\n\t// Attempt to close files but continue shutdown regardless\n\tc.CloseAllFiles(ctx)\n\n\t// Close stdin to signal the server\n\tif err := c.stdin.Close(); err != nil {\n\t\treturn fmt.Errorf(\"failed to close stdin: %w\", err)\n\t}\n\n\t// Use a channel to handle the Wait with timeout\n\tdone := make(chan error, 1)\n\tgo func() {\n\t\tdone <- c.Cmd.Wait()\n\t}()\n\n\t// Wait for process to exit with timeout\n\tselect {\n\tcase err := <-done:\n\t\treturn err\n\tcase <-time.After(2 * time.Second):\n\t\t// If we timeout, try to kill the process\n\t\tif err := c.Cmd.Process.Kill(); err != nil {\n\t\t\treturn fmt.Errorf(\"failed to kill process: %w\", err)\n\t\t}\n\t\treturn fmt.Errorf(\"process killed after timeout\")\n\t}\n}\n\ntype ServerState int\n\nconst (\n\tStateStarting ServerState = iota\n\tStateReady\n\tStateError\n)\n\n// GetServerState returns the current state of the LSP server\nfunc (c *Client) GetServerState() ServerState {\n\tif val := c.serverState.Load(); val != nil {\n\t\treturn val.(ServerState)\n\t}\n\treturn StateStarting\n}\n\n// SetServerState sets the current state of the LSP server\nfunc (c *Client) SetServerState(state ServerState) {\n\tc.serverState.Store(state)\n}\n\n// WaitForServerReady waits for the server to be ready by polling the server\n// with a simple request until it responds successfully or times out\nfunc (c *Client) WaitForServerReady(ctx context.Context) error {\n\tcnf := config.Get()\n\n\t// Set initial state\n\tc.SetServerState(StateStarting)\n\n\t// Create a context with timeout\n\tctx, cancel := context.WithTimeout(ctx, 30*time.Second)\n\tdefer cancel()\n\n\t// Try to ping the server with a simple request\n\tticker := time.NewTicker(500 * time.Millisecond)\n\tdefer ticker.Stop()\n\n\tif cnf.DebugLSP {\n\t\tlogging.Debug(\"Waiting for LSP server to be ready...\")\n\t}\n\n\t// Determine server type for specialized initialization\n\tserverType := c.detectServerType()\n\n\t// For TypeScript-like servers, we need to open some key files first\n\tif serverType == ServerTypeTypeScript {\n\t\tif cnf.DebugLSP {\n\t\t\tlogging.Debug(\"TypeScript-like server detected, opening key configuration files\")\n\t\t}\n\t\tc.openKeyConfigFiles(ctx)\n\t}\n\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\tc.SetServerState(StateError)\n\t\t\treturn fmt.Errorf(\"timeout waiting for LSP server to be ready\")\n\t\tcase <-ticker.C:\n\t\t\t// Try a ping method appropriate for this server type\n\t\t\terr := c.pingServerByType(ctx, serverType)\n\t\t\tif err == nil {\n\t\t\t\t// Server responded successfully\n\t\t\t\tc.SetServerState(StateReady)\n\t\t\t\tif cnf.DebugLSP {\n\t\t\t\t\tlogging.Debug(\"LSP server is ready\")\n\t\t\t\t}\n\t\t\t\treturn nil\n\t\t\t} else {\n\t\t\t\tlogging.Debug(\"LSP server not ready yet\", \"error\", err, \"serverType\", serverType)\n\t\t\t}\n\n\t\t\tif cnf.DebugLSP {\n\t\t\t\tlogging.Debug(\"LSP server not ready yet\", \"error\", err, \"serverType\", serverType)\n\t\t\t}\n\t\t}\n\t}\n}\n\n// ServerType represents the type of LSP server\ntype ServerType int\n\nconst (\n\tServerTypeUnknown ServerType = iota\n\tServerTypeGo\n\tServerTypeTypeScript\n\tServerTypeRust\n\tServerTypePython\n\tServerTypeGeneric\n)\n\n// detectServerType tries to determine what type of LSP server we're dealing with\nfunc (c *Client) detectServerType() ServerType {\n\tif c.Cmd == nil {\n\t\treturn ServerTypeUnknown\n\t}\n\n\tcmdPath := strings.ToLower(c.Cmd.Path)\n\n\tswitch {\n\tcase strings.Contains(cmdPath, \"gopls\"):\n\t\treturn ServerTypeGo\n\tcase strings.Contains(cmdPath, \"typescript\") || strings.Contains(cmdPath, \"vtsls\") || strings.Contains(cmdPath, \"tsserver\"):\n\t\treturn ServerTypeTypeScript\n\tcase strings.Contains(cmdPath, \"rust-analyzer\"):\n\t\treturn ServerTypeRust\n\tcase strings.Contains(cmdPath, \"pyright\") || strings.Contains(cmdPath, \"pylsp\") || strings.Contains(cmdPath, \"python\"):\n\t\treturn ServerTypePython\n\tdefault:\n\t\treturn ServerTypeGeneric\n\t}\n}\n\n// openKeyConfigFiles opens important configuration files that help initialize the server\nfunc (c *Client) openKeyConfigFiles(ctx context.Context) {\n\tworkDir := config.WorkingDirectory()\n\tserverType := c.detectServerType()\n\n\tvar filesToOpen []string\n\n\tswitch serverType {\n\tcase ServerTypeTypeScript:\n\t\t// TypeScript servers need these config files to properly initialize\n\t\tfilesToOpen = []string{\n\t\t\tfilepath.Join(workDir, \"tsconfig.json\"),\n\t\t\tfilepath.Join(workDir, \"package.json\"),\n\t\t\tfilepath.Join(workDir, \"jsconfig.json\"),\n\t\t}\n\n\t\t// Also find and open a few TypeScript files to help the server initialize\n\t\tc.openTypeScriptFiles(ctx, workDir)\n\tcase ServerTypeGo:\n\t\tfilesToOpen = []string{\n\t\t\tfilepath.Join(workDir, \"go.mod\"),\n\t\t\tfilepath.Join(workDir, \"go.sum\"),\n\t\t}\n\tcase ServerTypeRust:\n\t\tfilesToOpen = []string{\n\t\t\tfilepath.Join(workDir, \"Cargo.toml\"),\n\t\t\tfilepath.Join(workDir, \"Cargo.lock\"),\n\t\t}\n\t}\n\n\t// Try to open each file, ignoring errors if they don't exist\n\tfor _, file := range filesToOpen {\n\t\tif _, err := os.Stat(file); err == nil {\n\t\t\t// File exists, try to open it\n\t\t\tif err := c.OpenFile(ctx, file); err != nil {\n\t\t\t\tlogging.Debug(\"Failed to open key config file\", \"file\", file, \"error\", err)\n\t\t\t} else {\n\t\t\t\tlogging.Debug(\"Opened key config file for initialization\", \"file\", file)\n\t\t\t}\n\t\t}\n\t}\n}\n\n// pingServerByType sends a ping request appropriate for the server type\nfunc (c *Client) pingServerByType(ctx context.Context, serverType ServerType) error {\n\tswitch serverType {\n\tcase ServerTypeTypeScript:\n\t\t// For TypeScript, try a document symbol request on an open file\n\t\treturn c.pingTypeScriptServer(ctx)\n\tcase ServerTypeGo:\n\t\t// For Go, workspace/symbol works well\n\t\treturn c.pingWithWorkspaceSymbol(ctx)\n\tcase ServerTypeRust:\n\t\t// For Rust, workspace/symbol works well\n\t\treturn c.pingWithWorkspaceSymbol(ctx)\n\tdefault:\n\t\t// Default ping method\n\t\treturn c.pingWithWorkspaceSymbol(ctx)\n\t}\n}\n\n// pingTypeScriptServer tries to ping a TypeScript server with appropriate methods\nfunc (c *Client) pingTypeScriptServer(ctx context.Context) error {\n\t// First try workspace/symbol which works for many servers\n\tif err := c.pingWithWorkspaceSymbol(ctx); err == nil {\n\t\treturn nil\n\t}\n\n\t// If that fails, try to find an open file and request document symbols\n\tc.openFilesMu.RLock()\n\tdefer c.openFilesMu.RUnlock()\n\n\t// If we have any open files, try to get document symbols for one\n\tfor uri := range c.openFiles {\n\t\tfilePath := strings.TrimPrefix(uri, \"file://\")\n\t\tif strings.HasSuffix(filePath, \".ts\") || strings.HasSuffix(filePath, \".js\") ||\n\t\t\tstrings.HasSuffix(filePath, \".tsx\") || strings.HasSuffix(filePath, \".jsx\") {\n\t\t\tvar symbols []protocol.DocumentSymbol\n\t\t\terr := c.Call(ctx, \"textDocument/documentSymbol\", protocol.DocumentSymbolParams{\n\t\t\t\tTextDocument: protocol.TextDocumentIdentifier{\n\t\t\t\t\tURI: protocol.DocumentUri(uri),\n\t\t\t\t},\n\t\t\t}, &symbols)\n\t\t\tif err == nil {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\t}\n\n\t// If we have no open TypeScript files, try to find and open one\n\tworkDir := config.WorkingDirectory()\n\terr := filepath.WalkDir(workDir, func(path string, d os.DirEntry, err error) error {\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Skip directories and non-TypeScript files\n\t\tif d.IsDir() {\n\t\t\treturn nil\n\t\t}\n\n\t\text := filepath.Ext(path)\n\t\tif ext == \".ts\" || ext == \".js\" || ext == \".tsx\" || ext == \".jsx\" {\n\t\t\t// Found a TypeScript file, try to open it\n\t\t\tif err := c.OpenFile(ctx, path); err == nil {\n\t\t\t\t// Successfully opened, stop walking\n\t\t\t\treturn filepath.SkipAll\n\t\t\t}\n\t\t}\n\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\tlogging.Debug(\"Error walking directory for TypeScript files\", \"error\", err)\n\t}\n\n\t// Final fallback - just try a generic capability\n\treturn c.pingWithServerCapabilities(ctx)\n}\n\n// openTypeScriptFiles finds and opens TypeScript files to help initialize the server\nfunc (c *Client) openTypeScriptFiles(ctx context.Context, workDir string) {\n\tcnf := config.Get()\n\tfilesOpened := 0\n\tmaxFilesToOpen := 5 // Limit to a reasonable number of files\n\n\t// Find and open TypeScript files\n\terr := filepath.WalkDir(workDir, func(path string, d os.DirEntry, err error) error {\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Skip directories and non-TypeScript files\n\t\tif d.IsDir() {\n\t\t\t// Skip common directories to avoid wasting time\n\t\t\tif shouldSkipDir(path) {\n\t\t\t\treturn filepath.SkipDir\n\t\t\t}\n\t\t\treturn nil\n\t\t}\n\n\t\t// Check if we've opened enough files\n\t\tif filesOpened >= maxFilesToOpen {\n\t\t\treturn filepath.SkipAll\n\t\t}\n\n\t\t// Check file extension\n\t\text := filepath.Ext(path)\n\t\tif ext == \".ts\" || ext == \".tsx\" || ext == \".js\" || ext == \".jsx\" {\n\t\t\t// Try to open the file\n\t\t\tif err := c.OpenFile(ctx, path); err == nil {\n\t\t\t\tfilesOpened++\n\t\t\t\tif cnf.DebugLSP {\n\t\t\t\t\tlogging.Debug(\"Opened TypeScript file for initialization\", \"file\", path)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn nil\n\t})\n\n\tif err != nil && cnf.DebugLSP {\n\t\tlogging.Debug(\"Error walking directory for TypeScript files\", \"error\", err)\n\t}\n\n\tif cnf.DebugLSP {\n\t\tlogging.Debug(\"Opened TypeScript files for initialization\", \"count\", filesOpened)\n\t}\n}\n\n// shouldSkipDir returns true if the directory should be skipped during file search\nfunc shouldSkipDir(path string) bool {\n\tdirName := filepath.Base(path)\n\n\t// Skip hidden directories\n\tif strings.HasPrefix(dirName, \".\") {\n\t\treturn true\n\t}\n\n\t// Skip common directories that won't contain relevant source files\n\tskipDirs := map[string]bool{\n\t\t\"node_modules\": true,\n\t\t\"dist\": true,\n\t\t\"build\": true,\n\t\t\"coverage\": true,\n\t\t\"vendor\": true,\n\t\t\"target\": true,\n\t}\n\n\treturn skipDirs[dirName]\n}\n\n// pingWithWorkspaceSymbol tries a workspace/symbol request\nfunc (c *Client) pingWithWorkspaceSymbol(ctx context.Context) error {\n\tvar result []protocol.SymbolInformation\n\treturn c.Call(ctx, \"workspace/symbol\", protocol.WorkspaceSymbolParams{\n\t\tQuery: \"\",\n\t}, &result)\n}\n\n// pingWithServerCapabilities tries to get server capabilities\nfunc (c *Client) pingWithServerCapabilities(ctx context.Context) error {\n\t// This is a very lightweight request that should work for most servers\n\treturn c.Notify(ctx, \"$/cancelRequest\", struct{ ID int }{ID: -1})\n}\n\ntype OpenFileInfo struct {\n\tVersion int32\n\tURI protocol.DocumentUri\n}\n\nfunc (c *Client) OpenFile(ctx context.Context, filepath string) error {\n\turi := fmt.Sprintf(\"file://%s\", filepath)\n\n\tc.openFilesMu.Lock()\n\tif _, exists := c.openFiles[uri]; exists {\n\t\tc.openFilesMu.Unlock()\n\t\treturn nil // Already open\n\t}\n\tc.openFilesMu.Unlock()\n\n\t// Skip files that do not exist or cannot be read\n\tcontent, err := os.ReadFile(filepath)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error reading file: %w\", err)\n\t}\n\n\tparams := protocol.DidOpenTextDocumentParams{\n\t\tTextDocument: protocol.TextDocumentItem{\n\t\t\tURI: protocol.DocumentUri(uri),\n\t\t\tLanguageID: DetectLanguageID(uri),\n\t\t\tVersion: 1,\n\t\t\tText: string(content),\n\t\t},\n\t}\n\n\tif err := c.Notify(ctx, \"textDocument/didOpen\", params); err != nil {\n\t\treturn err\n\t}\n\n\tc.openFilesMu.Lock()\n\tc.openFiles[uri] = &OpenFileInfo{\n\t\tVersion: 1,\n\t\tURI: protocol.DocumentUri(uri),\n\t}\n\tc.openFilesMu.Unlock()\n\n\treturn nil\n}\n\nfunc (c *Client) NotifyChange(ctx context.Context, filepath string) error {\n\turi := fmt.Sprintf(\"file://%s\", filepath)\n\n\tcontent, err := os.ReadFile(filepath)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error reading file: %w\", err)\n\t}\n\n\tc.openFilesMu.Lock()\n\tfileInfo, isOpen := c.openFiles[uri]\n\tif !isOpen {\n\t\tc.openFilesMu.Unlock()\n\t\treturn fmt.Errorf(\"cannot notify change for unopened file: %s\", filepath)\n\t}\n\n\t// Increment version\n\tfileInfo.Version++\n\tversion := fileInfo.Version\n\tc.openFilesMu.Unlock()\n\n\tparams := protocol.DidChangeTextDocumentParams{\n\t\tTextDocument: protocol.VersionedTextDocumentIdentifier{\n\t\t\tTextDocumentIdentifier: protocol.TextDocumentIdentifier{\n\t\t\t\tURI: protocol.DocumentUri(uri),\n\t\t\t},\n\t\t\tVersion: version,\n\t\t},\n\t\tContentChanges: []protocol.TextDocumentContentChangeEvent{\n\t\t\t{\n\t\t\t\tValue: protocol.TextDocumentContentChangeWholeDocument{\n\t\t\t\t\tText: string(content),\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\treturn c.Notify(ctx, \"textDocument/didChange\", params)\n}\n\nfunc (c *Client) CloseFile(ctx context.Context, filepath string) error {\n\tcnf := config.Get()\n\turi := fmt.Sprintf(\"file://%s\", filepath)\n\n\tc.openFilesMu.Lock()\n\tif _, exists := c.openFiles[uri]; !exists {\n\t\tc.openFilesMu.Unlock()\n\t\treturn nil // Already closed\n\t}\n\tc.openFilesMu.Unlock()\n\n\tparams := protocol.DidCloseTextDocumentParams{\n\t\tTextDocument: protocol.TextDocumentIdentifier{\n\t\t\tURI: protocol.DocumentUri(uri),\n\t\t},\n\t}\n\n\tif cnf.DebugLSP {\n\t\tlogging.Debug(\"Closing file\", \"file\", filepath)\n\t}\n\tif err := c.Notify(ctx, \"textDocument/didClose\", params); err != nil {\n\t\treturn err\n\t}\n\n\tc.openFilesMu.Lock()\n\tdelete(c.openFiles, uri)\n\tc.openFilesMu.Unlock()\n\n\treturn nil\n}\n\nfunc (c *Client) IsFileOpen(filepath string) bool {\n\turi := fmt.Sprintf(\"file://%s\", filepath)\n\tc.openFilesMu.RLock()\n\tdefer c.openFilesMu.RUnlock()\n\t_, exists := c.openFiles[uri]\n\treturn exists\n}\n\n// CloseAllFiles closes all currently open files\nfunc (c *Client) CloseAllFiles(ctx context.Context) {\n\tcnf := config.Get()\n\tc.openFilesMu.Lock()\n\tfilesToClose := make([]string, 0, len(c.openFiles))\n\n\t// First collect all URIs that need to be closed\n\tfor uri := range c.openFiles {\n\t\t// Convert URI back to file path by trimming \"file://\" prefix\n\t\tfilePath := strings.TrimPrefix(uri, \"file://\")\n\t\tfilesToClose = append(filesToClose, filePath)\n\t}\n\tc.openFilesMu.Unlock()\n\n\t// Then close them all\n\tfor _, filePath := range filesToClose {\n\t\terr := c.CloseFile(ctx, filePath)\n\t\tif err != nil && cnf.DebugLSP {\n\t\t\tlogging.Warn(\"Error closing file\", \"file\", filePath, \"error\", err)\n\t\t}\n\t}\n\n\tif cnf.DebugLSP {\n\t\tlogging.Debug(\"Closed all files\", \"files\", filesToClose)\n\t}\n}\n\nfunc (c *Client) GetFileDiagnostics(uri protocol.DocumentUri) []protocol.Diagnostic {\n\tc.diagnosticsMu.RLock()\n\tdefer c.diagnosticsMu.RUnlock()\n\n\treturn c.diagnostics[uri]\n}\n\n// GetDiagnostics returns all diagnostics for all files\nfunc (c *Client) GetDiagnostics() map[protocol.DocumentUri][]protocol.Diagnostic {\n\treturn c.diagnostics\n}\n\n// OpenFileOnDemand opens a file only if it's not already open\n// This is used for lazy-loading files when they're actually needed\nfunc (c *Client) OpenFileOnDemand(ctx context.Context, filepath string) error {\n\t// Check if the file is already open\n\tif c.IsFileOpen(filepath) {\n\t\treturn nil\n\t}\n\n\t// Open the file\n\treturn c.OpenFile(ctx, filepath)\n}\n\n// GetDiagnosticsForFile ensures a file is open and returns its diagnostics\n// This is useful for on-demand diagnostics when using lazy loading\nfunc (c *Client) GetDiagnosticsForFile(ctx context.Context, filepath string) ([]protocol.Diagnostic, error) {\n\turi := fmt.Sprintf(\"file://%s\", filepath)\n\tdocumentUri := protocol.DocumentUri(uri)\n\n\t// Make sure the file is open\n\tif !c.IsFileOpen(filepath) {\n\t\tif err := c.OpenFile(ctx, filepath); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to open file for diagnostics: %w\", err)\n\t\t}\n\n\t\t// Give the LSP server a moment to process the file\n\t\ttime.Sleep(100 * time.Millisecond)\n\t}\n\n\t// Get diagnostics\n\tc.diagnosticsMu.RLock()\n\tdiagnostics := c.diagnostics[documentUri]\n\tc.diagnosticsMu.RUnlock()\n\n\treturn diagnostics, nil\n}\n\n// ClearDiagnosticsForURI removes diagnostics for a specific URI from the cache\nfunc (c *Client) ClearDiagnosticsForURI(uri protocol.DocumentUri) {\n\tc.diagnosticsMu.Lock()\n\tdefer c.diagnosticsMu.Unlock()\n\tdelete(c.diagnostics, uri)\n}\n"], ["/opencode/internal/diff/patch.go", "package diff\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"strings\"\n)\n\ntype ActionType string\n\nconst (\n\tActionAdd ActionType = \"add\"\n\tActionDelete ActionType = \"delete\"\n\tActionUpdate ActionType = \"update\"\n)\n\ntype FileChange struct {\n\tType ActionType\n\tOldContent *string\n\tNewContent *string\n\tMovePath *string\n}\n\ntype Commit struct {\n\tChanges map[string]FileChange\n}\n\ntype Chunk struct {\n\tOrigIndex int // line index of the first line in the original file\n\tDelLines []string // lines to delete\n\tInsLines []string // lines to insert\n}\n\ntype PatchAction struct {\n\tType ActionType\n\tNewFile *string\n\tChunks []Chunk\n\tMovePath *string\n}\n\ntype Patch struct {\n\tActions map[string]PatchAction\n}\n\ntype DiffError struct {\n\tmessage string\n}\n\nfunc (e DiffError) Error() string {\n\treturn e.message\n}\n\n// Helper functions for error handling\nfunc NewDiffError(message string) DiffError {\n\treturn DiffError{message: message}\n}\n\nfunc fileError(action, reason, path string) DiffError {\n\treturn NewDiffError(fmt.Sprintf(\"%s File Error: %s: %s\", action, reason, path))\n}\n\nfunc contextError(index int, context string, isEOF bool) DiffError {\n\tprefix := \"Invalid Context\"\n\tif isEOF {\n\t\tprefix = \"Invalid EOF Context\"\n\t}\n\treturn NewDiffError(fmt.Sprintf(\"%s %d:\\n%s\", prefix, index, context))\n}\n\ntype Parser struct {\n\tcurrentFiles map[string]string\n\tlines []string\n\tindex int\n\tpatch Patch\n\tfuzz int\n}\n\nfunc NewParser(currentFiles map[string]string, lines []string) *Parser {\n\treturn &Parser{\n\t\tcurrentFiles: currentFiles,\n\t\tlines: lines,\n\t\tindex: 0,\n\t\tpatch: Patch{Actions: make(map[string]PatchAction, len(currentFiles))},\n\t\tfuzz: 0,\n\t}\n}\n\nfunc (p *Parser) isDone(prefixes []string) bool {\n\tif p.index >= len(p.lines) {\n\t\treturn true\n\t}\n\tfor _, prefix := range prefixes {\n\t\tif strings.HasPrefix(p.lines[p.index], prefix) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc (p *Parser) startsWith(prefix any) bool {\n\tvar prefixes []string\n\tswitch v := prefix.(type) {\n\tcase string:\n\t\tprefixes = []string{v}\n\tcase []string:\n\t\tprefixes = v\n\t}\n\n\tfor _, pfx := range prefixes {\n\t\tif strings.HasPrefix(p.lines[p.index], pfx) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc (p *Parser) readStr(prefix string, returnEverything bool) string {\n\tif p.index >= len(p.lines) {\n\t\treturn \"\" // Changed from panic to return empty string for safer operation\n\t}\n\tif strings.HasPrefix(p.lines[p.index], prefix) {\n\t\tvar text string\n\t\tif returnEverything {\n\t\t\ttext = p.lines[p.index]\n\t\t} else {\n\t\t\ttext = p.lines[p.index][len(prefix):]\n\t\t}\n\t\tp.index++\n\t\treturn text\n\t}\n\treturn \"\"\n}\n\nfunc (p *Parser) Parse() error {\n\tendPatchPrefixes := []string{\"*** End Patch\"}\n\n\tfor !p.isDone(endPatchPrefixes) {\n\t\tpath := p.readStr(\"*** Update File: \", false)\n\t\tif path != \"\" {\n\t\t\tif _, exists := p.patch.Actions[path]; exists {\n\t\t\t\treturn fileError(\"Update\", \"Duplicate Path\", path)\n\t\t\t}\n\t\t\tmoveTo := p.readStr(\"*** Move to: \", false)\n\t\t\tif _, exists := p.currentFiles[path]; !exists {\n\t\t\t\treturn fileError(\"Update\", \"Missing File\", path)\n\t\t\t}\n\t\t\ttext := p.currentFiles[path]\n\t\t\taction, err := p.parseUpdateFile(text)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif moveTo != \"\" {\n\t\t\t\taction.MovePath = &moveTo\n\t\t\t}\n\t\t\tp.patch.Actions[path] = action\n\t\t\tcontinue\n\t\t}\n\n\t\tpath = p.readStr(\"*** Delete File: \", false)\n\t\tif path != \"\" {\n\t\t\tif _, exists := p.patch.Actions[path]; exists {\n\t\t\t\treturn fileError(\"Delete\", \"Duplicate Path\", path)\n\t\t\t}\n\t\t\tif _, exists := p.currentFiles[path]; !exists {\n\t\t\t\treturn fileError(\"Delete\", \"Missing File\", path)\n\t\t\t}\n\t\t\tp.patch.Actions[path] = PatchAction{Type: ActionDelete, Chunks: []Chunk{}}\n\t\t\tcontinue\n\t\t}\n\n\t\tpath = p.readStr(\"*** Add File: \", false)\n\t\tif path != \"\" {\n\t\t\tif _, exists := p.patch.Actions[path]; exists {\n\t\t\t\treturn fileError(\"Add\", \"Duplicate Path\", path)\n\t\t\t}\n\t\t\tif _, exists := p.currentFiles[path]; exists {\n\t\t\t\treturn fileError(\"Add\", \"File already exists\", path)\n\t\t\t}\n\t\t\taction, err := p.parseAddFile()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tp.patch.Actions[path] = action\n\t\t\tcontinue\n\t\t}\n\n\t\treturn NewDiffError(fmt.Sprintf(\"Unknown Line: %s\", p.lines[p.index]))\n\t}\n\n\tif !p.startsWith(\"*** End Patch\") {\n\t\treturn NewDiffError(\"Missing End Patch\")\n\t}\n\tp.index++\n\n\treturn nil\n}\n\nfunc (p *Parser) parseUpdateFile(text string) (PatchAction, error) {\n\taction := PatchAction{Type: ActionUpdate, Chunks: []Chunk{}}\n\tfileLines := strings.Split(text, \"\\n\")\n\tindex := 0\n\n\tendPrefixes := []string{\n\t\t\"*** End Patch\",\n\t\t\"*** Update File:\",\n\t\t\"*** Delete File:\",\n\t\t\"*** Add File:\",\n\t\t\"*** End of File\",\n\t}\n\n\tfor !p.isDone(endPrefixes) {\n\t\tdefStr := p.readStr(\"@@ \", false)\n\t\tsectionStr := \"\"\n\t\tif defStr == \"\" && p.index < len(p.lines) && p.lines[p.index] == \"@@\" {\n\t\t\tsectionStr = p.lines[p.index]\n\t\t\tp.index++\n\t\t}\n\t\tif defStr == \"\" && sectionStr == \"\" && index != 0 {\n\t\t\treturn action, NewDiffError(fmt.Sprintf(\"Invalid Line:\\n%s\", p.lines[p.index]))\n\t\t}\n\t\tif strings.TrimSpace(defStr) != \"\" {\n\t\t\tfound := false\n\t\t\tfor i := range fileLines[:index] {\n\t\t\t\tif fileLines[i] == defStr {\n\t\t\t\t\tfound = true\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif !found {\n\t\t\t\tfor i := index; i < len(fileLines); i++ {\n\t\t\t\t\tif fileLines[i] == defStr {\n\t\t\t\t\t\tindex = i + 1\n\t\t\t\t\t\tfound = true\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif !found {\n\t\t\t\tfor i := range fileLines[:index] {\n\t\t\t\t\tif strings.TrimSpace(fileLines[i]) == strings.TrimSpace(defStr) {\n\t\t\t\t\t\tfound = true\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif !found {\n\t\t\t\tfor i := index; i < len(fileLines); i++ {\n\t\t\t\t\tif strings.TrimSpace(fileLines[i]) == strings.TrimSpace(defStr) {\n\t\t\t\t\t\tindex = i + 1\n\t\t\t\t\t\tp.fuzz++\n\t\t\t\t\t\tfound = true\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tnextChunkContext, chunks, endPatchIndex, eof := peekNextSection(p.lines, p.index)\n\t\tnewIndex, fuzz := findContext(fileLines, nextChunkContext, index, eof)\n\t\tif newIndex == -1 {\n\t\t\tctxText := strings.Join(nextChunkContext, \"\\n\")\n\t\t\treturn action, contextError(index, ctxText, eof)\n\t\t}\n\t\tp.fuzz += fuzz\n\n\t\tfor _, ch := range chunks {\n\t\t\tch.OrigIndex += newIndex\n\t\t\taction.Chunks = append(action.Chunks, ch)\n\t\t}\n\t\tindex = newIndex + len(nextChunkContext)\n\t\tp.index = endPatchIndex\n\t}\n\treturn action, nil\n}\n\nfunc (p *Parser) parseAddFile() (PatchAction, error) {\n\tlines := make([]string, 0, 16) // Preallocate space for better performance\n\tendPrefixes := []string{\n\t\t\"*** End Patch\",\n\t\t\"*** Update File:\",\n\t\t\"*** Delete File:\",\n\t\t\"*** Add File:\",\n\t}\n\n\tfor !p.isDone(endPrefixes) {\n\t\ts := p.readStr(\"\", true)\n\t\tif !strings.HasPrefix(s, \"+\") {\n\t\t\treturn PatchAction{}, NewDiffError(fmt.Sprintf(\"Invalid Add File Line: %s\", s))\n\t\t}\n\t\tlines = append(lines, s[1:])\n\t}\n\n\tnewFile := strings.Join(lines, \"\\n\")\n\treturn PatchAction{\n\t\tType: ActionAdd,\n\t\tNewFile: &newFile,\n\t\tChunks: []Chunk{},\n\t}, nil\n}\n\n// Refactored to use a matcher function for each comparison type\nfunc findContextCore(lines []string, context []string, start int) (int, int) {\n\tif len(context) == 0 {\n\t\treturn start, 0\n\t}\n\n\t// Try exact match\n\tif idx, fuzz := tryFindMatch(lines, context, start, func(a, b string) bool {\n\t\treturn a == b\n\t}); idx >= 0 {\n\t\treturn idx, fuzz\n\t}\n\n\t// Try trimming right whitespace\n\tif idx, fuzz := tryFindMatch(lines, context, start, func(a, b string) bool {\n\t\treturn strings.TrimRight(a, \" \\t\") == strings.TrimRight(b, \" \\t\")\n\t}); idx >= 0 {\n\t\treturn idx, fuzz\n\t}\n\n\t// Try trimming all whitespace\n\tif idx, fuzz := tryFindMatch(lines, context, start, func(a, b string) bool {\n\t\treturn strings.TrimSpace(a) == strings.TrimSpace(b)\n\t}); idx >= 0 {\n\t\treturn idx, fuzz\n\t}\n\n\treturn -1, 0\n}\n\n// Helper function to DRY up the match logic\nfunc tryFindMatch(lines []string, context []string, start int,\n\tcompareFunc func(string, string) bool,\n) (int, int) {\n\tfor i := start; i < len(lines); i++ {\n\t\tif i+len(context) <= len(lines) {\n\t\t\tmatch := true\n\t\t\tfor j := range context {\n\t\t\t\tif !compareFunc(lines[i+j], context[j]) {\n\t\t\t\t\tmatch = false\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\tif match {\n\t\t\t\t// Return fuzz level: 0 for exact, 1 for trimRight, 100 for trimSpace\n\t\t\t\tvar fuzz int\n\t\t\t\tif compareFunc(\"a \", \"a\") && !compareFunc(\"a\", \"b\") {\n\t\t\t\t\tfuzz = 1\n\t\t\t\t} else if compareFunc(\"a \", \"a\") {\n\t\t\t\t\tfuzz = 100\n\t\t\t\t}\n\t\t\t\treturn i, fuzz\n\t\t\t}\n\t\t}\n\t}\n\treturn -1, 0\n}\n\nfunc findContext(lines []string, context []string, start int, eof bool) (int, int) {\n\tif eof {\n\t\tnewIndex, fuzz := findContextCore(lines, context, len(lines)-len(context))\n\t\tif newIndex != -1 {\n\t\t\treturn newIndex, fuzz\n\t\t}\n\t\tnewIndex, fuzz = findContextCore(lines, context, start)\n\t\treturn newIndex, fuzz + 10000\n\t}\n\treturn findContextCore(lines, context, start)\n}\n\nfunc peekNextSection(lines []string, initialIndex int) ([]string, []Chunk, int, bool) {\n\tindex := initialIndex\n\told := make([]string, 0, 32) // Preallocate for better performance\n\tdelLines := make([]string, 0, 8)\n\tinsLines := make([]string, 0, 8)\n\tchunks := make([]Chunk, 0, 4)\n\tmode := \"keep\"\n\n\t// End conditions for the section\n\tendSectionConditions := func(s string) bool {\n\t\treturn strings.HasPrefix(s, \"@@\") ||\n\t\t\tstrings.HasPrefix(s, \"*** End Patch\") ||\n\t\t\tstrings.HasPrefix(s, \"*** Update File:\") ||\n\t\t\tstrings.HasPrefix(s, \"*** Delete File:\") ||\n\t\t\tstrings.HasPrefix(s, \"*** Add File:\") ||\n\t\t\tstrings.HasPrefix(s, \"*** End of File\") ||\n\t\t\ts == \"***\" ||\n\t\t\tstrings.HasPrefix(s, \"***\")\n\t}\n\n\tfor index < len(lines) {\n\t\ts := lines[index]\n\t\tif endSectionConditions(s) {\n\t\t\tbreak\n\t\t}\n\t\tindex++\n\t\tlastMode := mode\n\t\tline := s\n\n\t\tif len(line) > 0 {\n\t\t\tswitch line[0] {\n\t\t\tcase '+':\n\t\t\t\tmode = \"add\"\n\t\t\tcase '-':\n\t\t\t\tmode = \"delete\"\n\t\t\tcase ' ':\n\t\t\t\tmode = \"keep\"\n\t\t\tdefault:\n\t\t\t\tmode = \"keep\"\n\t\t\t\tline = \" \" + line\n\t\t\t}\n\t\t} else {\n\t\t\tmode = \"keep\"\n\t\t\tline = \" \"\n\t\t}\n\n\t\tline = line[1:]\n\t\tif mode == \"keep\" && lastMode != mode {\n\t\t\tif len(insLines) > 0 || len(delLines) > 0 {\n\t\t\t\tchunks = append(chunks, Chunk{\n\t\t\t\t\tOrigIndex: len(old) - len(delLines),\n\t\t\t\t\tDelLines: delLines,\n\t\t\t\t\tInsLines: insLines,\n\t\t\t\t})\n\t\t\t}\n\t\t\tdelLines = make([]string, 0, 8)\n\t\t\tinsLines = make([]string, 0, 8)\n\t\t}\n\t\tswitch mode {\n\t\tcase \"delete\":\n\t\t\tdelLines = append(delLines, line)\n\t\t\told = append(old, line)\n\t\tcase \"add\":\n\t\t\tinsLines = append(insLines, line)\n\t\tdefault:\n\t\t\told = append(old, line)\n\t\t}\n\t}\n\n\tif len(insLines) > 0 || len(delLines) > 0 {\n\t\tchunks = append(chunks, Chunk{\n\t\t\tOrigIndex: len(old) - len(delLines),\n\t\t\tDelLines: delLines,\n\t\t\tInsLines: insLines,\n\t\t})\n\t}\n\n\tif index < len(lines) && lines[index] == \"*** End of File\" {\n\t\tindex++\n\t\treturn old, chunks, index, true\n\t}\n\treturn old, chunks, index, false\n}\n\nfunc TextToPatch(text string, orig map[string]string) (Patch, int, error) {\n\ttext = strings.TrimSpace(text)\n\tlines := strings.Split(text, \"\\n\")\n\tif len(lines) < 2 || !strings.HasPrefix(lines[0], \"*** Begin Patch\") || lines[len(lines)-1] != \"*** End Patch\" {\n\t\treturn Patch{}, 0, NewDiffError(\"Invalid patch text\")\n\t}\n\tparser := NewParser(orig, lines)\n\tparser.index = 1\n\tif err := parser.Parse(); err != nil {\n\t\treturn Patch{}, 0, err\n\t}\n\treturn parser.patch, parser.fuzz, nil\n}\n\nfunc IdentifyFilesNeeded(text string) []string {\n\ttext = strings.TrimSpace(text)\n\tlines := strings.Split(text, \"\\n\")\n\tresult := make(map[string]bool)\n\n\tfor _, line := range lines {\n\t\tif strings.HasPrefix(line, \"*** Update File: \") {\n\t\t\tresult[line[len(\"*** Update File: \"):]] = true\n\t\t}\n\t\tif strings.HasPrefix(line, \"*** Delete File: \") {\n\t\t\tresult[line[len(\"*** Delete File: \"):]] = true\n\t\t}\n\t}\n\n\tfiles := make([]string, 0, len(result))\n\tfor file := range result {\n\t\tfiles = append(files, file)\n\t}\n\treturn files\n}\n\nfunc IdentifyFilesAdded(text string) []string {\n\ttext = strings.TrimSpace(text)\n\tlines := strings.Split(text, \"\\n\")\n\tresult := make(map[string]bool)\n\n\tfor _, line := range lines {\n\t\tif strings.HasPrefix(line, \"*** Add File: \") {\n\t\t\tresult[line[len(\"*** Add File: \"):]] = true\n\t\t}\n\t}\n\n\tfiles := make([]string, 0, len(result))\n\tfor file := range result {\n\t\tfiles = append(files, file)\n\t}\n\treturn files\n}\n\nfunc getUpdatedFile(text string, action PatchAction, path string) (string, error) {\n\tif action.Type != ActionUpdate {\n\t\treturn \"\", errors.New(\"expected UPDATE action\")\n\t}\n\torigLines := strings.Split(text, \"\\n\")\n\tdestLines := make([]string, 0, len(origLines)) // Preallocate with capacity\n\torigIndex := 0\n\n\tfor _, chunk := range action.Chunks {\n\t\tif chunk.OrigIndex > len(origLines) {\n\t\t\treturn \"\", NewDiffError(fmt.Sprintf(\"%s: chunk.orig_index %d > len(lines) %d\", path, chunk.OrigIndex, len(origLines)))\n\t\t}\n\t\tif origIndex > chunk.OrigIndex {\n\t\t\treturn \"\", NewDiffError(fmt.Sprintf(\"%s: orig_index %d > chunk.orig_index %d\", path, origIndex, chunk.OrigIndex))\n\t\t}\n\t\tdestLines = append(destLines, origLines[origIndex:chunk.OrigIndex]...)\n\t\tdelta := chunk.OrigIndex - origIndex\n\t\torigIndex += delta\n\n\t\tif len(chunk.InsLines) > 0 {\n\t\t\tdestLines = append(destLines, chunk.InsLines...)\n\t\t}\n\t\torigIndex += len(chunk.DelLines)\n\t}\n\n\tdestLines = append(destLines, origLines[origIndex:]...)\n\treturn strings.Join(destLines, \"\\n\"), nil\n}\n\nfunc PatchToCommit(patch Patch, orig map[string]string) (Commit, error) {\n\tcommit := Commit{Changes: make(map[string]FileChange, len(patch.Actions))}\n\tfor pathKey, action := range patch.Actions {\n\t\tswitch action.Type {\n\t\tcase ActionDelete:\n\t\t\toldContent := orig[pathKey]\n\t\t\tcommit.Changes[pathKey] = FileChange{\n\t\t\t\tType: ActionDelete,\n\t\t\t\tOldContent: &oldContent,\n\t\t\t}\n\t\tcase ActionAdd:\n\t\t\tcommit.Changes[pathKey] = FileChange{\n\t\t\t\tType: ActionAdd,\n\t\t\t\tNewContent: action.NewFile,\n\t\t\t}\n\t\tcase ActionUpdate:\n\t\t\tnewContent, err := getUpdatedFile(orig[pathKey], action, pathKey)\n\t\t\tif err != nil {\n\t\t\t\treturn Commit{}, err\n\t\t\t}\n\t\t\toldContent := orig[pathKey]\n\t\t\tfileChange := FileChange{\n\t\t\t\tType: ActionUpdate,\n\t\t\t\tOldContent: &oldContent,\n\t\t\t\tNewContent: &newContent,\n\t\t\t}\n\t\t\tif action.MovePath != nil {\n\t\t\t\tfileChange.MovePath = action.MovePath\n\t\t\t}\n\t\t\tcommit.Changes[pathKey] = fileChange\n\t\t}\n\t}\n\treturn commit, nil\n}\n\nfunc AssembleChanges(orig map[string]string, updatedFiles map[string]string) Commit {\n\tcommit := Commit{Changes: make(map[string]FileChange, len(updatedFiles))}\n\tfor p, newContent := range updatedFiles {\n\t\toldContent, exists := orig[p]\n\t\tif exists && oldContent == newContent {\n\t\t\tcontinue\n\t\t}\n\n\t\tif exists && newContent != \"\" {\n\t\t\tcommit.Changes[p] = FileChange{\n\t\t\t\tType: ActionUpdate,\n\t\t\t\tOldContent: &oldContent,\n\t\t\t\tNewContent: &newContent,\n\t\t\t}\n\t\t} else if newContent != \"\" {\n\t\t\tcommit.Changes[p] = FileChange{\n\t\t\t\tType: ActionAdd,\n\t\t\t\tNewContent: &newContent,\n\t\t\t}\n\t\t} else if exists {\n\t\t\tcommit.Changes[p] = FileChange{\n\t\t\t\tType: ActionDelete,\n\t\t\t\tOldContent: &oldContent,\n\t\t\t}\n\t\t} else {\n\t\t\treturn commit // Changed from panic to simply return current commit\n\t\t}\n\t}\n\treturn commit\n}\n\nfunc LoadFiles(paths []string, openFn func(string) (string, error)) (map[string]string, error) {\n\torig := make(map[string]string, len(paths))\n\tfor _, p := range paths {\n\t\tcontent, err := openFn(p)\n\t\tif err != nil {\n\t\t\treturn nil, fileError(\"Open\", \"File not found\", p)\n\t\t}\n\t\torig[p] = content\n\t}\n\treturn orig, nil\n}\n\nfunc ApplyCommit(commit Commit, writeFn func(string, string) error, removeFn func(string) error) error {\n\tfor p, change := range commit.Changes {\n\t\tswitch change.Type {\n\t\tcase ActionDelete:\n\t\t\tif err := removeFn(p); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\tcase ActionAdd:\n\t\t\tif change.NewContent == nil {\n\t\t\t\treturn NewDiffError(fmt.Sprintf(\"Add action for %s has nil new_content\", p))\n\t\t\t}\n\t\t\tif err := writeFn(p, *change.NewContent); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\tcase ActionUpdate:\n\t\t\tif change.NewContent == nil {\n\t\t\t\treturn NewDiffError(fmt.Sprintf(\"Update action for %s has nil new_content\", p))\n\t\t\t}\n\t\t\tif change.MovePath != nil {\n\t\t\t\tif err := writeFn(*change.MovePath, *change.NewContent); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tif err := removeFn(p); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif err := writeFn(p, *change.NewContent); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc ProcessPatch(text string, openFn func(string) (string, error), writeFn func(string, string) error, removeFn func(string) error) (string, error) {\n\tif !strings.HasPrefix(text, \"*** Begin Patch\") {\n\t\treturn \"\", NewDiffError(\"Patch must start with *** Begin Patch\")\n\t}\n\tpaths := IdentifyFilesNeeded(text)\n\torig, err := LoadFiles(paths, openFn)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tpatch, fuzz, err := TextToPatch(text, orig)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif fuzz > 0 {\n\t\treturn \"\", NewDiffError(fmt.Sprintf(\"Patch contains fuzzy matches (fuzz level: %d)\", fuzz))\n\t}\n\n\tcommit, err := PatchToCommit(patch, orig)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif err := ApplyCommit(commit, writeFn, removeFn); err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn \"Patch applied successfully\", nil\n}\n\nfunc OpenFile(p string) (string, error) {\n\tdata, err := os.ReadFile(p)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn string(data), nil\n}\n\nfunc WriteFile(p string, content string) error {\n\tif filepath.IsAbs(p) {\n\t\treturn NewDiffError(\"We do not support absolute paths.\")\n\t}\n\n\tdir := filepath.Dir(p)\n\tif dir != \".\" {\n\t\tif err := os.MkdirAll(dir, 0o755); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn os.WriteFile(p, []byte(content), 0o644)\n}\n\nfunc RemoveFile(p string) error {\n\treturn os.Remove(p)\n}\n\nfunc ValidatePatch(patchText string, files map[string]string) (bool, string, error) {\n\tif !strings.HasPrefix(patchText, \"*** Begin Patch\") {\n\t\treturn false, \"Patch must start with *** Begin Patch\", nil\n\t}\n\n\tneededFiles := IdentifyFilesNeeded(patchText)\n\tfor _, filePath := range neededFiles {\n\t\tif _, exists := files[filePath]; !exists {\n\t\t\treturn false, fmt.Sprintf(\"File not found: %s\", filePath), nil\n\t\t}\n\t}\n\n\tpatch, fuzz, err := TextToPatch(patchText, files)\n\tif err != nil {\n\t\treturn false, err.Error(), nil\n\t}\n\n\tif fuzz > 0 {\n\t\treturn false, fmt.Sprintf(\"Patch contains fuzzy matches (fuzz level: %d)\", fuzz), nil\n\t}\n\n\t_, err = PatchToCommit(patch, files)\n\tif err != nil {\n\t\treturn false, err.Error(), nil\n\t}\n\n\treturn true, \"Patch is valid\", nil\n}\n"], ["/opencode/internal/app/app.go", "package app\n\nimport (\n\t\"context\"\n\t\"database/sql\"\n\t\"errors\"\n\t\"fmt\"\n\t\"maps\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/db\"\n\t\"github.com/opencode-ai/opencode/internal/format\"\n\t\"github.com/opencode-ai/opencode/internal/history\"\n\t\"github.com/opencode-ai/opencode/internal/llm/agent\"\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n\t\"github.com/opencode-ai/opencode/internal/lsp\"\n\t\"github.com/opencode-ai/opencode/internal/message\"\n\t\"github.com/opencode-ai/opencode/internal/permission\"\n\t\"github.com/opencode-ai/opencode/internal/session\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n)\n\ntype App struct {\n\tSessions session.Service\n\tMessages message.Service\n\tHistory history.Service\n\tPermissions permission.Service\n\n\tCoderAgent agent.Service\n\n\tLSPClients map[string]*lsp.Client\n\n\tclientsMutex sync.RWMutex\n\n\twatcherCancelFuncs []context.CancelFunc\n\tcancelFuncsMutex sync.Mutex\n\twatcherWG sync.WaitGroup\n}\n\nfunc New(ctx context.Context, conn *sql.DB) (*App, error) {\n\tq := db.New(conn)\n\tsessions := session.NewService(q)\n\tmessages := message.NewService(q)\n\tfiles := history.NewService(q, conn)\n\n\tapp := &App{\n\t\tSessions: sessions,\n\t\tMessages: messages,\n\t\tHistory: files,\n\t\tPermissions: permission.NewPermissionService(),\n\t\tLSPClients: make(map[string]*lsp.Client),\n\t}\n\n\t// Initialize theme based on configuration\n\tapp.initTheme()\n\n\t// Initialize LSP clients in the background\n\tgo app.initLSPClients(ctx)\n\n\tvar err error\n\tapp.CoderAgent, err = agent.NewAgent(\n\t\tconfig.AgentCoder,\n\t\tapp.Sessions,\n\t\tapp.Messages,\n\t\tagent.CoderAgentTools(\n\t\t\tapp.Permissions,\n\t\t\tapp.Sessions,\n\t\t\tapp.Messages,\n\t\t\tapp.History,\n\t\t\tapp.LSPClients,\n\t\t),\n\t)\n\tif err != nil {\n\t\tlogging.Error(\"Failed to create coder agent\", err)\n\t\treturn nil, err\n\t}\n\n\treturn app, nil\n}\n\n// initTheme sets the application theme based on the configuration\nfunc (app *App) initTheme() {\n\tcfg := config.Get()\n\tif cfg == nil || cfg.TUI.Theme == \"\" {\n\t\treturn // Use default theme\n\t}\n\n\t// Try to set the theme from config\n\terr := theme.SetTheme(cfg.TUI.Theme)\n\tif err != nil {\n\t\tlogging.Warn(\"Failed to set theme from config, using default theme\", \"theme\", cfg.TUI.Theme, \"error\", err)\n\t} else {\n\t\tlogging.Debug(\"Set theme from config\", \"theme\", cfg.TUI.Theme)\n\t}\n}\n\n// RunNonInteractive handles the execution flow when a prompt is provided via CLI flag.\nfunc (a *App) RunNonInteractive(ctx context.Context, prompt string, outputFormat string, quiet bool) error {\n\tlogging.Info(\"Running in non-interactive mode\")\n\n\t// Start spinner if not in quiet mode\n\tvar spinner *format.Spinner\n\tif !quiet {\n\t\tspinner = format.NewSpinner(\"Thinking...\")\n\t\tspinner.Start()\n\t\tdefer spinner.Stop()\n\t}\n\n\tconst maxPromptLengthForTitle = 100\n\ttitlePrefix := \"Non-interactive: \"\n\tvar titleSuffix string\n\n\tif len(prompt) > maxPromptLengthForTitle {\n\t\ttitleSuffix = prompt[:maxPromptLengthForTitle] + \"...\"\n\t} else {\n\t\ttitleSuffix = prompt\n\t}\n\ttitle := titlePrefix + titleSuffix\n\n\tsess, err := a.Sessions.Create(ctx, title)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to create session for non-interactive mode: %w\", err)\n\t}\n\tlogging.Info(\"Created session for non-interactive run\", \"session_id\", sess.ID)\n\n\t// Automatically approve all permission requests for this non-interactive session\n\ta.Permissions.AutoApproveSession(sess.ID)\n\n\tdone, err := a.CoderAgent.Run(ctx, sess.ID, prompt)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to start agent processing stream: %w\", err)\n\t}\n\n\tresult := <-done\n\tif result.Error != nil {\n\t\tif errors.Is(result.Error, context.Canceled) || errors.Is(result.Error, agent.ErrRequestCancelled) {\n\t\t\tlogging.Info(\"Agent processing cancelled\", \"session_id\", sess.ID)\n\t\t\treturn nil\n\t\t}\n\t\treturn fmt.Errorf(\"agent processing failed: %w\", result.Error)\n\t}\n\n\t// Stop spinner before printing output\n\tif !quiet && spinner != nil {\n\t\tspinner.Stop()\n\t}\n\n\t// Get the text content from the response\n\tcontent := \"No content available\"\n\tif result.Message.Content().String() != \"\" {\n\t\tcontent = result.Message.Content().String()\n\t}\n\n\tfmt.Println(format.FormatOutput(content, outputFormat))\n\n\tlogging.Info(\"Non-interactive run completed\", \"session_id\", sess.ID)\n\n\treturn nil\n}\n\n// Shutdown performs a clean shutdown of the application\nfunc (app *App) Shutdown() {\n\t// Cancel all watcher goroutines\n\tapp.cancelFuncsMutex.Lock()\n\tfor _, cancel := range app.watcherCancelFuncs {\n\t\tcancel()\n\t}\n\tapp.cancelFuncsMutex.Unlock()\n\tapp.watcherWG.Wait()\n\n\t// Perform additional cleanup for LSP clients\n\tapp.clientsMutex.RLock()\n\tclients := make(map[string]*lsp.Client, len(app.LSPClients))\n\tmaps.Copy(clients, app.LSPClients)\n\tapp.clientsMutex.RUnlock()\n\n\tfor name, client := range clients {\n\t\tshutdownCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)\n\t\tif err := client.Shutdown(shutdownCtx); err != nil {\n\t\t\tlogging.Error(\"Failed to shutdown LSP client\", \"name\", name, \"error\", err)\n\t\t}\n\t\tcancel()\n\t}\n}\n"], ["/opencode/internal/lsp/transport.go", "package lsp\n\nimport (\n\t\"bufio\"\n\t\"context\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"strings\"\n\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n)\n\n// Write writes an LSP message to the given writer\nfunc WriteMessage(w io.Writer, msg *Message) error {\n\tdata, err := json.Marshal(msg)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to marshal message: %w\", err)\n\t}\n\tcnf := config.Get()\n\n\tif cnf.DebugLSP {\n\t\tlogging.Debug(\"Sending message to server\", \"method\", msg.Method, \"id\", msg.ID)\n\t}\n\n\t_, err = fmt.Fprintf(w, \"Content-Length: %d\\r\\n\\r\\n\", len(data))\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to write header: %w\", err)\n\t}\n\n\t_, err = w.Write(data)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to write message: %w\", err)\n\t}\n\n\treturn nil\n}\n\n// ReadMessage reads a single LSP message from the given reader\nfunc ReadMessage(r *bufio.Reader) (*Message, error) {\n\tcnf := config.Get()\n\t// Read headers\n\tvar contentLength int\n\tfor {\n\t\tline, err := r.ReadString('\\n')\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to read header: %w\", err)\n\t\t}\n\t\tline = strings.TrimSpace(line)\n\n\t\tif cnf.DebugLSP {\n\t\t\tlogging.Debug(\"Received header\", \"line\", line)\n\t\t}\n\n\t\tif line == \"\" {\n\t\t\tbreak // End of headers\n\t\t}\n\n\t\tif strings.HasPrefix(line, \"Content-Length: \") {\n\t\t\t_, err := fmt.Sscanf(line, \"Content-Length: %d\", &contentLength)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"invalid Content-Length: %w\", err)\n\t\t\t}\n\t\t}\n\t}\n\n\tif cnf.DebugLSP {\n\t\tlogging.Debug(\"Content-Length\", \"length\", contentLength)\n\t}\n\n\t// Read content\n\tcontent := make([]byte, contentLength)\n\t_, err := io.ReadFull(r, content)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to read content: %w\", err)\n\t}\n\n\tif cnf.DebugLSP {\n\t\tlogging.Debug(\"Received content\", \"content\", string(content))\n\t}\n\n\t// Parse message\n\tvar msg Message\n\tif err := json.Unmarshal(content, &msg); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to unmarshal message: %w\", err)\n\t}\n\n\treturn &msg, nil\n}\n\n// handleMessages reads and dispatches messages in a loop\nfunc (c *Client) handleMessages() {\n\tcnf := config.Get()\n\tfor {\n\t\tmsg, err := ReadMessage(c.stdout)\n\t\tif err != nil {\n\t\t\tif cnf.DebugLSP {\n\t\t\t\tlogging.Error(\"Error reading message\", \"error\", err)\n\t\t\t}\n\t\t\treturn\n\t\t}\n\n\t\t// Handle server->client request (has both Method and ID)\n\t\tif msg.Method != \"\" && msg.ID != 0 {\n\t\t\tif cnf.DebugLSP {\n\t\t\t\tlogging.Debug(\"Received request from server\", \"method\", msg.Method, \"id\", msg.ID)\n\t\t\t}\n\n\t\t\tresponse := &Message{\n\t\t\t\tJSONRPC: \"2.0\",\n\t\t\t\tID: msg.ID,\n\t\t\t}\n\n\t\t\t// Look up handler for this method\n\t\t\tc.serverHandlersMu.RLock()\n\t\t\thandler, ok := c.serverRequestHandlers[msg.Method]\n\t\t\tc.serverHandlersMu.RUnlock()\n\n\t\t\tif ok {\n\t\t\t\tresult, err := handler(msg.Params)\n\t\t\t\tif err != nil {\n\t\t\t\t\tresponse.Error = &ResponseError{\n\t\t\t\t\t\tCode: -32603,\n\t\t\t\t\t\tMessage: err.Error(),\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\trawJSON, err := json.Marshal(result)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tresponse.Error = &ResponseError{\n\t\t\t\t\t\t\tCode: -32603,\n\t\t\t\t\t\t\tMessage: fmt.Sprintf(\"failed to marshal response: %v\", err),\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tresponse.Result = rawJSON\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tresponse.Error = &ResponseError{\n\t\t\t\t\tCode: -32601,\n\t\t\t\t\tMessage: fmt.Sprintf(\"method not found: %s\", msg.Method),\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Send response back to server\n\t\t\tif err := WriteMessage(c.stdin, response); err != nil {\n\t\t\t\tlogging.Error(\"Error sending response to server\", \"error\", err)\n\t\t\t}\n\n\t\t\tcontinue\n\t\t}\n\n\t\t// Handle notification (has Method but no ID)\n\t\tif msg.Method != \"\" && msg.ID == 0 {\n\t\t\tc.notificationMu.RLock()\n\t\t\thandler, ok := c.notificationHandlers[msg.Method]\n\t\t\tc.notificationMu.RUnlock()\n\n\t\t\tif ok {\n\t\t\t\tif cnf.DebugLSP {\n\t\t\t\t\tlogging.Debug(\"Handling notification\", \"method\", msg.Method)\n\t\t\t\t}\n\t\t\t\tgo handler(msg.Params)\n\t\t\t} else if cnf.DebugLSP {\n\t\t\t\tlogging.Debug(\"No handler for notification\", \"method\", msg.Method)\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\t// Handle response to our request (has ID but no Method)\n\t\tif msg.ID != 0 && msg.Method == \"\" {\n\t\t\tc.handlersMu.RLock()\n\t\t\tch, ok := c.handlers[msg.ID]\n\t\t\tc.handlersMu.RUnlock()\n\n\t\t\tif ok {\n\t\t\t\tif cnf.DebugLSP {\n\t\t\t\t\tlogging.Debug(\"Received response for request\", \"id\", msg.ID)\n\t\t\t\t}\n\t\t\t\tch <- msg\n\t\t\t\tclose(ch)\n\t\t\t} else if cnf.DebugLSP {\n\t\t\t\tlogging.Debug(\"No handler for response\", \"id\", msg.ID)\n\t\t\t}\n\t\t}\n\t}\n}\n\n// Call makes a request and waits for the response\nfunc (c *Client) Call(ctx context.Context, method string, params any, result any) error {\n\tcnf := config.Get()\n\tid := c.nextID.Add(1)\n\n\tif cnf.DebugLSP {\n\t\tlogging.Debug(\"Making call\", \"method\", method, \"id\", id)\n\t}\n\n\tmsg, err := NewRequest(id, method, params)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to create request: %w\", err)\n\t}\n\n\t// Create response channel\n\tch := make(chan *Message, 1)\n\tc.handlersMu.Lock()\n\tc.handlers[id] = ch\n\tc.handlersMu.Unlock()\n\n\tdefer func() {\n\t\tc.handlersMu.Lock()\n\t\tdelete(c.handlers, id)\n\t\tc.handlersMu.Unlock()\n\t}()\n\n\t// Send request\n\tif err := WriteMessage(c.stdin, msg); err != nil {\n\t\treturn fmt.Errorf(\"failed to send request: %w\", err)\n\t}\n\n\tif cnf.DebugLSP {\n\t\tlogging.Debug(\"Request sent\", \"method\", method, \"id\", id)\n\t}\n\n\t// Wait for response\n\tresp := <-ch\n\n\tif cnf.DebugLSP {\n\t\tlogging.Debug(\"Received response\", \"id\", id)\n\t}\n\n\tif resp.Error != nil {\n\t\treturn fmt.Errorf(\"request failed: %s (code: %d)\", resp.Error.Message, resp.Error.Code)\n\t}\n\n\tif result != nil {\n\t\t// If result is a json.RawMessage, just copy the raw bytes\n\t\tif rawMsg, ok := result.(*json.RawMessage); ok {\n\t\t\t*rawMsg = resp.Result\n\t\t\treturn nil\n\t\t}\n\t\t// Otherwise unmarshal into the provided type\n\t\tif err := json.Unmarshal(resp.Result, result); err != nil {\n\t\t\treturn fmt.Errorf(\"failed to unmarshal result: %w\", err)\n\t\t}\n\t}\n\n\treturn nil\n}\n\n// Notify sends a notification (a request without an ID that doesn't expect a response)\nfunc (c *Client) Notify(ctx context.Context, method string, params any) error {\n\tcnf := config.Get()\n\tif cnf.DebugLSP {\n\t\tlogging.Debug(\"Sending notification\", \"method\", method)\n\t}\n\n\tmsg, err := NewNotification(method, params)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to create notification: %w\", err)\n\t}\n\n\tif err := WriteMessage(c.stdin, msg); err != nil {\n\t\treturn fmt.Errorf(\"failed to send notification: %w\", err)\n\t}\n\n\treturn nil\n}\n\ntype (\n\tNotificationHandler func(params json.RawMessage)\n\tServerRequestHandler func(params json.RawMessage) (any, error)\n)\n"], ["/opencode/internal/tui/components/dialog/custom_commands.go", "package dialog\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"regexp\"\n\t\"strings\"\n\n\ttea \"github.com/charmbracelet/bubbletea\"\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/tui/util\"\n)\n\n// Command prefix constants\nconst (\n\tUserCommandPrefix = \"user:\"\n\tProjectCommandPrefix = \"project:\"\n)\n\n// namedArgPattern is a regex pattern to find named arguments in the format $NAME\nvar namedArgPattern = regexp.MustCompile(`\\$([A-Z][A-Z0-9_]*)`)\n\n// LoadCustomCommands loads custom commands from both XDG_CONFIG_HOME and project data directory\nfunc LoadCustomCommands() ([]Command, error) {\n\tcfg := config.Get()\n\tif cfg == nil {\n\t\treturn nil, fmt.Errorf(\"config not loaded\")\n\t}\n\n\tvar commands []Command\n\n\t// Load user commands from XDG_CONFIG_HOME/opencode/commands\n\txdgConfigHome := os.Getenv(\"XDG_CONFIG_HOME\")\n\tif xdgConfigHome == \"\" {\n\t\t// Default to ~/.config if XDG_CONFIG_HOME is not set\n\t\thome, err := os.UserHomeDir()\n\t\tif err == nil {\n\t\t\txdgConfigHome = filepath.Join(home, \".config\")\n\t\t}\n\t}\n\n\tif xdgConfigHome != \"\" {\n\t\tuserCommandsDir := filepath.Join(xdgConfigHome, \"opencode\", \"commands\")\n\t\tuserCommands, err := loadCommandsFromDir(userCommandsDir, UserCommandPrefix)\n\t\tif err != nil {\n\t\t\t// Log error but continue - we'll still try to load other commands\n\t\t\tfmt.Printf(\"Warning: failed to load user commands from XDG_CONFIG_HOME: %v\\n\", err)\n\t\t} else {\n\t\t\tcommands = append(commands, userCommands...)\n\t\t}\n\t}\n\n\t// Load commands from $HOME/.opencode/commands\n\thome, err := os.UserHomeDir()\n\tif err == nil {\n\t\thomeCommandsDir := filepath.Join(home, \".opencode\", \"commands\")\n\t\thomeCommands, err := loadCommandsFromDir(homeCommandsDir, UserCommandPrefix)\n\t\tif err != nil {\n\t\t\t// Log error but continue - we'll still try to load other commands\n\t\t\tfmt.Printf(\"Warning: failed to load home commands: %v\\n\", err)\n\t\t} else {\n\t\t\tcommands = append(commands, homeCommands...)\n\t\t}\n\t}\n\n\t// Load project commands from data directory\n\tprojectCommandsDir := filepath.Join(cfg.Data.Directory, \"commands\")\n\tprojectCommands, err := loadCommandsFromDir(projectCommandsDir, ProjectCommandPrefix)\n\tif err != nil {\n\t\t// Log error but return what we have so far\n\t\tfmt.Printf(\"Warning: failed to load project commands: %v\\n\", err)\n\t} else {\n\t\tcommands = append(commands, projectCommands...)\n\t}\n\n\treturn commands, nil\n}\n\n// loadCommandsFromDir loads commands from a specific directory with the given prefix\nfunc loadCommandsFromDir(commandsDir string, prefix string) ([]Command, error) {\n\t// Check if the commands directory exists\n\tif _, err := os.Stat(commandsDir); os.IsNotExist(err) {\n\t\t// Create the commands directory if it doesn't exist\n\t\tif err := os.MkdirAll(commandsDir, 0755); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to create commands directory %s: %w\", commandsDir, err)\n\t\t}\n\t\t// Return empty list since we just created the directory\n\t\treturn []Command{}, nil\n\t}\n\n\tvar commands []Command\n\n\t// Walk through the commands directory and load all .md files\n\terr := filepath.Walk(commandsDir, func(path string, info os.FileInfo, err error) error {\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Skip directories\n\t\tif info.IsDir() {\n\t\t\treturn nil\n\t\t}\n\n\t\t// Only process markdown files\n\t\tif !strings.HasSuffix(strings.ToLower(info.Name()), \".md\") {\n\t\t\treturn nil\n\t\t}\n\n\t\t// Read the file content\n\t\tcontent, err := os.ReadFile(path)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to read command file %s: %w\", path, err)\n\t\t}\n\n\t\t// Get the command ID from the file name without the .md extension\n\t\tcommandID := strings.TrimSuffix(info.Name(), filepath.Ext(info.Name()))\n\n\t\t// Get relative path from commands directory\n\t\trelPath, err := filepath.Rel(commandsDir, path)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to get relative path for %s: %w\", path, err)\n\t\t}\n\n\t\t// Create the command ID from the relative path\n\t\t// Replace directory separators with colons\n\t\tcommandIDPath := strings.ReplaceAll(filepath.Dir(relPath), string(filepath.Separator), \":\")\n\t\tif commandIDPath != \".\" {\n\t\t\tcommandID = commandIDPath + \":\" + commandID\n\t\t}\n\n\t\t// Create a command\n\t\tcommand := Command{\n\t\t\tID: prefix + commandID,\n\t\t\tTitle: prefix + commandID,\n\t\t\tDescription: fmt.Sprintf(\"Custom command from %s\", relPath),\n\t\t\tHandler: func(cmd Command) tea.Cmd {\n\t\t\t\tcommandContent := string(content)\n\n\t\t\t\t// Check for named arguments\n\t\t\t\tmatches := namedArgPattern.FindAllStringSubmatch(commandContent, -1)\n\t\t\t\tif len(matches) > 0 {\n\t\t\t\t\t// Extract unique argument names\n\t\t\t\t\targNames := make([]string, 0)\n\t\t\t\t\targMap := make(map[string]bool)\n\n\t\t\t\t\tfor _, match := range matches {\n\t\t\t\t\t\targName := match[1] // Group 1 is the name without $\n\t\t\t\t\t\tif !argMap[argName] {\n\t\t\t\t\t\t\targMap[argName] = true\n\t\t\t\t\t\t\targNames = append(argNames, argName)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\t// Show multi-arguments dialog for all named arguments\n\t\t\t\t\treturn util.CmdHandler(ShowMultiArgumentsDialogMsg{\n\t\t\t\t\t\tCommandID: cmd.ID,\n\t\t\t\t\t\tContent: commandContent,\n\t\t\t\t\t\tArgNames: argNames,\n\t\t\t\t\t})\n\t\t\t\t}\n\n\t\t\t\t// No arguments needed, run command directly\n\t\t\t\treturn util.CmdHandler(CommandRunCustomMsg{\n\t\t\t\t\tContent: commandContent,\n\t\t\t\t\tArgs: nil, // No arguments\n\t\t\t\t})\n\t\t\t},\n\t\t}\n\n\t\tcommands = append(commands, command)\n\t\treturn nil\n\t})\n\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to load custom commands from %s: %w\", commandsDir, err)\n\t}\n\n\treturn commands, nil\n}\n\n// CommandRunCustomMsg is sent when a custom command is executed\ntype CommandRunCustomMsg struct {\n\tContent string\n\tArgs map[string]string // Map of argument names to values\n}\n"], ["/opencode/internal/llm/agent/agent-tool.go", "package agent\n\nimport (\n\t\"context\"\n\t\"encoding/json\"\n\t\"fmt\"\n\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/llm/tools\"\n\t\"github.com/opencode-ai/opencode/internal/lsp\"\n\t\"github.com/opencode-ai/opencode/internal/message\"\n\t\"github.com/opencode-ai/opencode/internal/session\"\n)\n\ntype agentTool struct {\n\tsessions session.Service\n\tmessages message.Service\n\tlspClients map[string]*lsp.Client\n}\n\nconst (\n\tAgentToolName = \"agent\"\n)\n\ntype AgentParams struct {\n\tPrompt string `json:\"prompt\"`\n}\n\nfunc (b *agentTool) Info() tools.ToolInfo {\n\treturn tools.ToolInfo{\n\t\tName: AgentToolName,\n\t\tDescription: \"Launch a new agent that has access to the following tools: GlobTool, GrepTool, LS, View. When you are searching for a keyword or file and are not confident that you will find the right match on the first try, use the Agent tool to perform the search for you. For example:\\n\\n- If you are searching for a keyword like \\\"config\\\" or \\\"logger\\\", or for questions like \\\"which file does X?\\\", the Agent tool is strongly recommended\\n- If you want to read a specific file path, use the View or GlobTool tool instead of the Agent tool, to find the match more quickly\\n- If you are searching for a specific class definition like \\\"class Foo\\\", use the GlobTool tool instead, to find the match more quickly\\n\\nUsage notes:\\n1. Launch multiple agents concurrently whenever possible, to maximize performance; to do that, use a single message with multiple tool uses\\n2. When the agent is done, it will return a single message back to you. The result returned by the agent is not visible to the user. To show the user the result, you should send a text message back to the user with a concise summary of the result.\\n3. Each agent invocation is stateless. You will not be able to send additional messages to the agent, nor will the agent be able to communicate with you outside of its final report. Therefore, your prompt should contain a highly detailed task description for the agent to perform autonomously and you should specify exactly what information the agent should return back to you in its final and only message to you.\\n4. The agent's outputs should generally be trusted\\n5. IMPORTANT: The agent can not use Bash, Replace, Edit, so can not modify files. If you want to use these tools, use them directly instead of going through the agent.\",\n\t\tParameters: map[string]any{\n\t\t\t\"prompt\": map[string]any{\n\t\t\t\t\"type\": \"string\",\n\t\t\t\t\"description\": \"The task for the agent to perform\",\n\t\t\t},\n\t\t},\n\t\tRequired: []string{\"prompt\"},\n\t}\n}\n\nfunc (b *agentTool) Run(ctx context.Context, call tools.ToolCall) (tools.ToolResponse, error) {\n\tvar params AgentParams\n\tif err := json.Unmarshal([]byte(call.Input), ¶ms); err != nil {\n\t\treturn tools.NewTextErrorResponse(fmt.Sprintf(\"error parsing parameters: %s\", err)), nil\n\t}\n\tif params.Prompt == \"\" {\n\t\treturn tools.NewTextErrorResponse(\"prompt is required\"), nil\n\t}\n\n\tsessionID, messageID := tools.GetContextValues(ctx)\n\tif sessionID == \"\" || messageID == \"\" {\n\t\treturn tools.ToolResponse{}, fmt.Errorf(\"session_id and message_id are required\")\n\t}\n\n\tagent, err := NewAgent(config.AgentTask, b.sessions, b.messages, TaskAgentTools(b.lspClients))\n\tif err != nil {\n\t\treturn tools.ToolResponse{}, fmt.Errorf(\"error creating agent: %s\", err)\n\t}\n\n\tsession, err := b.sessions.CreateTaskSession(ctx, call.ID, sessionID, \"New Agent Session\")\n\tif err != nil {\n\t\treturn tools.ToolResponse{}, fmt.Errorf(\"error creating session: %s\", err)\n\t}\n\n\tdone, err := agent.Run(ctx, session.ID, params.Prompt)\n\tif err != nil {\n\t\treturn tools.ToolResponse{}, fmt.Errorf(\"error generating agent: %s\", err)\n\t}\n\tresult := <-done\n\tif result.Error != nil {\n\t\treturn tools.ToolResponse{}, fmt.Errorf(\"error generating agent: %s\", result.Error)\n\t}\n\n\tresponse := result.Message\n\tif response.Role != message.Assistant {\n\t\treturn tools.NewTextErrorResponse(\"no response\"), nil\n\t}\n\n\tupdatedSession, err := b.sessions.Get(ctx, session.ID)\n\tif err != nil {\n\t\treturn tools.ToolResponse{}, fmt.Errorf(\"error getting session: %s\", err)\n\t}\n\tparentSession, err := b.sessions.Get(ctx, sessionID)\n\tif err != nil {\n\t\treturn tools.ToolResponse{}, fmt.Errorf(\"error getting parent session: %s\", err)\n\t}\n\n\tparentSession.Cost += updatedSession.Cost\n\n\t_, err = b.sessions.Save(ctx, parentSession)\n\tif err != nil {\n\t\treturn tools.ToolResponse{}, fmt.Errorf(\"error saving parent session: %s\", err)\n\t}\n\treturn tools.NewTextResponse(response.Content().String()), nil\n}\n\nfunc NewAgentTool(\n\tSessions session.Service,\n\tMessages message.Service,\n\tLspClients map[string]*lsp.Client,\n) tools.BaseTool {\n\treturn &agentTool{\n\t\tsessions: Sessions,\n\t\tmessages: Messages,\n\t\tlspClients: LspClients,\n\t}\n}\n"], ["/opencode/internal/fileutil/fileutil.go", "package fileutil\n\nimport (\n\t\"fmt\"\n\t\"io/fs\"\n\t\"os\"\n\t\"os/exec\"\n\t\"path/filepath\"\n\t\"sort\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/bmatcuk/doublestar/v4\"\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n)\n\nvar (\n\trgPath string\n\tfzfPath string\n)\n\nfunc init() {\n\tvar err error\n\trgPath, err = exec.LookPath(\"rg\")\n\tif err != nil {\n\t\tlogging.Warn(\"Ripgrep (rg) not found in $PATH. Some features might be limited or slower.\")\n\t\trgPath = \"\"\n\t}\n\tfzfPath, err = exec.LookPath(\"fzf\")\n\tif err != nil {\n\t\tlogging.Warn(\"FZF not found in $PATH. Some features might be limited or slower.\")\n\t\tfzfPath = \"\"\n\t}\n}\n\nfunc GetRgCmd(globPattern string) *exec.Cmd {\n\tif rgPath == \"\" {\n\t\treturn nil\n\t}\n\trgArgs := []string{\n\t\t\"--files\",\n\t\t\"-L\",\n\t\t\"--null\",\n\t}\n\tif globPattern != \"\" {\n\t\tif !filepath.IsAbs(globPattern) && !strings.HasPrefix(globPattern, \"/\") {\n\t\t\tglobPattern = \"/\" + globPattern\n\t\t}\n\t\trgArgs = append(rgArgs, \"--glob\", globPattern)\n\t}\n\tcmd := exec.Command(rgPath, rgArgs...)\n\tcmd.Dir = \".\"\n\treturn cmd\n}\n\nfunc GetFzfCmd(query string) *exec.Cmd {\n\tif fzfPath == \"\" {\n\t\treturn nil\n\t}\n\tfzfArgs := []string{\n\t\t\"--filter\",\n\t\tquery,\n\t\t\"--read0\",\n\t\t\"--print0\",\n\t}\n\tcmd := exec.Command(fzfPath, fzfArgs...)\n\tcmd.Dir = \".\"\n\treturn cmd\n}\n\ntype FileInfo struct {\n\tPath string\n\tModTime time.Time\n}\n\nfunc SkipHidden(path string) bool {\n\t// Check for hidden files (starting with a dot)\n\tbase := filepath.Base(path)\n\tif base != \".\" && strings.HasPrefix(base, \".\") {\n\t\treturn true\n\t}\n\n\tcommonIgnoredDirs := map[string]bool{\n\t\t\".opencode\": true,\n\t\t\"node_modules\": true,\n\t\t\"vendor\": true,\n\t\t\"dist\": true,\n\t\t\"build\": true,\n\t\t\"target\": true,\n\t\t\".git\": true,\n\t\t\".idea\": true,\n\t\t\".vscode\": true,\n\t\t\"__pycache__\": true,\n\t\t\"bin\": true,\n\t\t\"obj\": true,\n\t\t\"out\": true,\n\t\t\"coverage\": true,\n\t\t\"tmp\": true,\n\t\t\"temp\": true,\n\t\t\"logs\": true,\n\t\t\"generated\": true,\n\t\t\"bower_components\": true,\n\t\t\"jspm_packages\": true,\n\t}\n\n\tparts := strings.Split(path, string(os.PathSeparator))\n\tfor _, part := range parts {\n\t\tif commonIgnoredDirs[part] {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc GlobWithDoublestar(pattern, searchPath string, limit int) ([]string, bool, error) {\n\tfsys := os.DirFS(searchPath)\n\trelPattern := strings.TrimPrefix(pattern, \"/\")\n\tvar matches []FileInfo\n\n\terr := doublestar.GlobWalk(fsys, relPattern, func(path string, d fs.DirEntry) error {\n\t\tif d.IsDir() {\n\t\t\treturn nil\n\t\t}\n\t\tif SkipHidden(path) {\n\t\t\treturn nil\n\t\t}\n\t\tinfo, err := d.Info()\n\t\tif err != nil {\n\t\t\treturn nil\n\t\t}\n\t\tabsPath := path\n\t\tif !strings.HasPrefix(absPath, searchPath) && searchPath != \".\" {\n\t\t\tabsPath = filepath.Join(searchPath, absPath)\n\t\t} else if !strings.HasPrefix(absPath, \"/\") && searchPath == \".\" {\n\t\t\tabsPath = filepath.Join(searchPath, absPath) // Ensure relative paths are joined correctly\n\t\t}\n\n\t\tmatches = append(matches, FileInfo{Path: absPath, ModTime: info.ModTime()})\n\t\tif limit > 0 && len(matches) >= limit*2 {\n\t\t\treturn fs.SkipAll\n\t\t}\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\treturn nil, false, fmt.Errorf(\"glob walk error: %w\", err)\n\t}\n\n\tsort.Slice(matches, func(i, j int) bool {\n\t\treturn matches[i].ModTime.After(matches[j].ModTime)\n\t})\n\n\ttruncated := false\n\tif limit > 0 && len(matches) > limit {\n\t\tmatches = matches[:limit]\n\t\ttruncated = true\n\t}\n\n\tresults := make([]string, len(matches))\n\tfor i, m := range matches {\n\t\tresults[i] = m.Path\n\t}\n\treturn results, truncated, nil\n}\n"], ["/opencode/internal/completions/files-folders.go", "package completions\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"os/exec\"\n\t\"path/filepath\"\n\n\t\"github.com/lithammer/fuzzysearch/fuzzy\"\n\t\"github.com/opencode-ai/opencode/internal/fileutil\"\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n\t\"github.com/opencode-ai/opencode/internal/tui/components/dialog\"\n)\n\ntype filesAndFoldersContextGroup struct {\n\tprefix string\n}\n\nfunc (cg *filesAndFoldersContextGroup) GetId() string {\n\treturn cg.prefix\n}\n\nfunc (cg *filesAndFoldersContextGroup) GetEntry() dialog.CompletionItemI {\n\treturn dialog.NewCompletionItem(dialog.CompletionItem{\n\t\tTitle: \"Files & Folders\",\n\t\tValue: \"files\",\n\t})\n}\n\nfunc processNullTerminatedOutput(outputBytes []byte) []string {\n\tif len(outputBytes) > 0 && outputBytes[len(outputBytes)-1] == 0 {\n\t\toutputBytes = outputBytes[:len(outputBytes)-1]\n\t}\n\n\tif len(outputBytes) == 0 {\n\t\treturn []string{}\n\t}\n\n\tsplit := bytes.Split(outputBytes, []byte{0})\n\tmatches := make([]string, 0, len(split))\n\n\tfor _, p := range split {\n\t\tif len(p) == 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\tpath := string(p)\n\t\tpath = filepath.Join(\".\", path)\n\n\t\tif !fileutil.SkipHidden(path) {\n\t\t\tmatches = append(matches, path)\n\t\t}\n\t}\n\n\treturn matches\n}\n\nfunc (cg *filesAndFoldersContextGroup) getFiles(query string) ([]string, error) {\n\tcmdRg := fileutil.GetRgCmd(\"\") // No glob pattern for this use case\n\tcmdFzf := fileutil.GetFzfCmd(query)\n\n\tvar matches []string\n\t// Case 1: Both rg and fzf available\n\tif cmdRg != nil && cmdFzf != nil {\n\t\trgPipe, err := cmdRg.StdoutPipe()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to get rg stdout pipe: %w\", err)\n\t\t}\n\t\tdefer rgPipe.Close()\n\n\t\tcmdFzf.Stdin = rgPipe\n\t\tvar fzfOut bytes.Buffer\n\t\tvar fzfErr bytes.Buffer\n\t\tcmdFzf.Stdout = &fzfOut\n\t\tcmdFzf.Stderr = &fzfErr\n\n\t\tif err := cmdFzf.Start(); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to start fzf: %w\", err)\n\t\t}\n\n\t\terrRg := cmdRg.Run()\n\t\terrFzf := cmdFzf.Wait()\n\n\t\tif errRg != nil {\n\t\t\tlogging.Warn(fmt.Sprintf(\"rg command failed during pipe: %v\", errRg))\n\t\t}\n\n\t\tif errFzf != nil {\n\t\t\tif exitErr, ok := errFzf.(*exec.ExitError); ok && exitErr.ExitCode() == 1 {\n\t\t\t\treturn []string{}, nil // No matches from fzf\n\t\t\t}\n\t\t\treturn nil, fmt.Errorf(\"fzf command failed: %w\\nStderr: %s\", errFzf, fzfErr.String())\n\t\t}\n\n\t\tmatches = processNullTerminatedOutput(fzfOut.Bytes())\n\n\t\t// Case 2: Only rg available\n\t} else if cmdRg != nil {\n\t\tlogging.Debug(\"Using Ripgrep with fuzzy match fallback for file completions\")\n\t\tvar rgOut bytes.Buffer\n\t\tvar rgErr bytes.Buffer\n\t\tcmdRg.Stdout = &rgOut\n\t\tcmdRg.Stderr = &rgErr\n\n\t\tif err := cmdRg.Run(); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"rg command failed: %w\\nStderr: %s\", err, rgErr.String())\n\t\t}\n\n\t\tallFiles := processNullTerminatedOutput(rgOut.Bytes())\n\t\tmatches = fuzzy.Find(query, allFiles)\n\n\t\t// Case 3: Only fzf available\n\t} else if cmdFzf != nil {\n\t\tlogging.Debug(\"Using FZF with doublestar fallback for file completions\")\n\t\tfiles, _, err := fileutil.GlobWithDoublestar(\"**/*\", \".\", 0)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to list files for fzf: %w\", err)\n\t\t}\n\n\t\tallFiles := make([]string, 0, len(files))\n\t\tfor _, file := range files {\n\t\t\tif !fileutil.SkipHidden(file) {\n\t\t\t\tallFiles = append(allFiles, file)\n\t\t\t}\n\t\t}\n\n\t\tvar fzfIn bytes.Buffer\n\t\tfor _, file := range allFiles {\n\t\t\tfzfIn.WriteString(file)\n\t\t\tfzfIn.WriteByte(0)\n\t\t}\n\n\t\tcmdFzf.Stdin = &fzfIn\n\t\tvar fzfOut bytes.Buffer\n\t\tvar fzfErr bytes.Buffer\n\t\tcmdFzf.Stdout = &fzfOut\n\t\tcmdFzf.Stderr = &fzfErr\n\n\t\tif err := cmdFzf.Run(); err != nil {\n\t\t\tif exitErr, ok := err.(*exec.ExitError); ok && exitErr.ExitCode() == 1 {\n\t\t\t\treturn []string{}, nil\n\t\t\t}\n\t\t\treturn nil, fmt.Errorf(\"fzf command failed: %w\\nStderr: %s\", err, fzfErr.String())\n\t\t}\n\n\t\tmatches = processNullTerminatedOutput(fzfOut.Bytes())\n\n\t\t// Case 4: Fallback to doublestar with fuzzy match\n\t} else {\n\t\tlogging.Debug(\"Using doublestar with fuzzy match for file completions\")\n\t\tallFiles, _, err := fileutil.GlobWithDoublestar(\"**/*\", \".\", 0)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to glob files: %w\", err)\n\t\t}\n\n\t\tfilteredFiles := make([]string, 0, len(allFiles))\n\t\tfor _, file := range allFiles {\n\t\t\tif !fileutil.SkipHidden(file) {\n\t\t\t\tfilteredFiles = append(filteredFiles, file)\n\t\t\t}\n\t\t}\n\n\t\tmatches = fuzzy.Find(query, filteredFiles)\n\t}\n\n\treturn matches, nil\n}\n\nfunc (cg *filesAndFoldersContextGroup) GetChildEntries(query string) ([]dialog.CompletionItemI, error) {\n\tmatches, err := cg.getFiles(query)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\titems := make([]dialog.CompletionItemI, 0, len(matches))\n\tfor _, file := range matches {\n\t\titem := dialog.NewCompletionItem(dialog.CompletionItem{\n\t\t\tTitle: file,\n\t\t\tValue: file,\n\t\t})\n\t\titems = append(items, item)\n\t}\n\n\treturn items, nil\n}\n\nfunc NewFileAndFolderContextGroup() dialog.CompletionProvider {\n\treturn &filesAndFoldersContextGroup{\n\t\tprefix: \"file\",\n\t}\n}\n"], ["/opencode/internal/history/file.go", "package history\n\nimport (\n\t\"context\"\n\t\"database/sql\"\n\t\"fmt\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/google/uuid\"\n\t\"github.com/opencode-ai/opencode/internal/db\"\n\t\"github.com/opencode-ai/opencode/internal/pubsub\"\n)\n\nconst (\n\tInitialVersion = \"initial\"\n)\n\ntype File struct {\n\tID string\n\tSessionID string\n\tPath string\n\tContent string\n\tVersion string\n\tCreatedAt int64\n\tUpdatedAt int64\n}\n\ntype Service interface {\n\tpubsub.Suscriber[File]\n\tCreate(ctx context.Context, sessionID, path, content string) (File, error)\n\tCreateVersion(ctx context.Context, sessionID, path, content string) (File, error)\n\tGet(ctx context.Context, id string) (File, error)\n\tGetByPathAndSession(ctx context.Context, path, sessionID string) (File, error)\n\tListBySession(ctx context.Context, sessionID string) ([]File, error)\n\tListLatestSessionFiles(ctx context.Context, sessionID string) ([]File, error)\n\tUpdate(ctx context.Context, file File) (File, error)\n\tDelete(ctx context.Context, id string) error\n\tDeleteSessionFiles(ctx context.Context, sessionID string) error\n}\n\ntype service struct {\n\t*pubsub.Broker[File]\n\tdb *sql.DB\n\tq *db.Queries\n}\n\nfunc NewService(q *db.Queries, db *sql.DB) Service {\n\treturn &service{\n\t\tBroker: pubsub.NewBroker[File](),\n\t\tq: q,\n\t\tdb: db,\n\t}\n}\n\nfunc (s *service) Create(ctx context.Context, sessionID, path, content string) (File, error) {\n\treturn s.createWithVersion(ctx, sessionID, path, content, InitialVersion)\n}\n\nfunc (s *service) CreateVersion(ctx context.Context, sessionID, path, content string) (File, error) {\n\t// Get the latest version for this path\n\tfiles, err := s.q.ListFilesByPath(ctx, path)\n\tif err != nil {\n\t\treturn File{}, err\n\t}\n\n\tif len(files) == 0 {\n\t\t// No previous versions, create initial\n\t\treturn s.Create(ctx, sessionID, path, content)\n\t}\n\n\t// Get the latest version\n\tlatestFile := files[0] // Files are ordered by created_at DESC\n\tlatestVersion := latestFile.Version\n\n\t// Generate the next version\n\tvar nextVersion string\n\tif latestVersion == InitialVersion {\n\t\tnextVersion = \"v1\"\n\t} else if strings.HasPrefix(latestVersion, \"v\") {\n\t\tversionNum, err := strconv.Atoi(latestVersion[1:])\n\t\tif err != nil {\n\t\t\t// If we can't parse the version, just use a timestamp-based version\n\t\t\tnextVersion = fmt.Sprintf(\"v%d\", latestFile.CreatedAt)\n\t\t} else {\n\t\t\tnextVersion = fmt.Sprintf(\"v%d\", versionNum+1)\n\t\t}\n\t} else {\n\t\t// If the version format is unexpected, use a timestamp-based version\n\t\tnextVersion = fmt.Sprintf(\"v%d\", latestFile.CreatedAt)\n\t}\n\n\treturn s.createWithVersion(ctx, sessionID, path, content, nextVersion)\n}\n\nfunc (s *service) createWithVersion(ctx context.Context, sessionID, path, content, version string) (File, error) {\n\t// Maximum number of retries for transaction conflicts\n\tconst maxRetries = 3\n\tvar file File\n\tvar err error\n\n\t// Retry loop for transaction conflicts\n\tfor attempt := range maxRetries {\n\t\t// Start a transaction\n\t\ttx, txErr := s.db.Begin()\n\t\tif txErr != nil {\n\t\t\treturn File{}, fmt.Errorf(\"failed to begin transaction: %w\", txErr)\n\t\t}\n\n\t\t// Create a new queries instance with the transaction\n\t\tqtx := s.q.WithTx(tx)\n\n\t\t// Try to create the file within the transaction\n\t\tdbFile, txErr := qtx.CreateFile(ctx, db.CreateFileParams{\n\t\t\tID: uuid.New().String(),\n\t\t\tSessionID: sessionID,\n\t\t\tPath: path,\n\t\t\tContent: content,\n\t\t\tVersion: version,\n\t\t})\n\t\tif txErr != nil {\n\t\t\t// Rollback the transaction\n\t\t\ttx.Rollback()\n\n\t\t\t// Check if this is a uniqueness constraint violation\n\t\t\tif strings.Contains(txErr.Error(), \"UNIQUE constraint failed\") {\n\t\t\t\tif attempt < maxRetries-1 {\n\t\t\t\t\t// If we have retries left, generate a new version and try again\n\t\t\t\t\tif strings.HasPrefix(version, \"v\") {\n\t\t\t\t\t\tversionNum, parseErr := strconv.Atoi(version[1:])\n\t\t\t\t\t\tif parseErr == nil {\n\t\t\t\t\t\t\tversion = fmt.Sprintf(\"v%d\", versionNum+1)\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t// If we can't parse the version, use a timestamp-based version\n\t\t\t\t\tversion = fmt.Sprintf(\"v%d\", time.Now().Unix())\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn File{}, txErr\n\t\t}\n\n\t\t// Commit the transaction\n\t\tif txErr = tx.Commit(); txErr != nil {\n\t\t\treturn File{}, fmt.Errorf(\"failed to commit transaction: %w\", txErr)\n\t\t}\n\n\t\tfile = s.fromDBItem(dbFile)\n\t\ts.Publish(pubsub.CreatedEvent, file)\n\t\treturn file, nil\n\t}\n\n\treturn file, err\n}\n\nfunc (s *service) Get(ctx context.Context, id string) (File, error) {\n\tdbFile, err := s.q.GetFile(ctx, id)\n\tif err != nil {\n\t\treturn File{}, err\n\t}\n\treturn s.fromDBItem(dbFile), nil\n}\n\nfunc (s *service) GetByPathAndSession(ctx context.Context, path, sessionID string) (File, error) {\n\tdbFile, err := s.q.GetFileByPathAndSession(ctx, db.GetFileByPathAndSessionParams{\n\t\tPath: path,\n\t\tSessionID: sessionID,\n\t})\n\tif err != nil {\n\t\treturn File{}, err\n\t}\n\treturn s.fromDBItem(dbFile), nil\n}\n\nfunc (s *service) ListBySession(ctx context.Context, sessionID string) ([]File, error) {\n\tdbFiles, err := s.q.ListFilesBySession(ctx, sessionID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfiles := make([]File, len(dbFiles))\n\tfor i, dbFile := range dbFiles {\n\t\tfiles[i] = s.fromDBItem(dbFile)\n\t}\n\treturn files, nil\n}\n\nfunc (s *service) ListLatestSessionFiles(ctx context.Context, sessionID string) ([]File, error) {\n\tdbFiles, err := s.q.ListLatestSessionFiles(ctx, sessionID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfiles := make([]File, len(dbFiles))\n\tfor i, dbFile := range dbFiles {\n\t\tfiles[i] = s.fromDBItem(dbFile)\n\t}\n\treturn files, nil\n}\n\nfunc (s *service) Update(ctx context.Context, file File) (File, error) {\n\tdbFile, err := s.q.UpdateFile(ctx, db.UpdateFileParams{\n\t\tID: file.ID,\n\t\tContent: file.Content,\n\t\tVersion: file.Version,\n\t})\n\tif err != nil {\n\t\treturn File{}, err\n\t}\n\tupdatedFile := s.fromDBItem(dbFile)\n\ts.Publish(pubsub.UpdatedEvent, updatedFile)\n\treturn updatedFile, nil\n}\n\nfunc (s *service) Delete(ctx context.Context, id string) error {\n\tfile, err := s.Get(ctx, id)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = s.q.DeleteFile(ctx, id)\n\tif err != nil {\n\t\treturn err\n\t}\n\ts.Publish(pubsub.DeletedEvent, file)\n\treturn nil\n}\n\nfunc (s *service) DeleteSessionFiles(ctx context.Context, sessionID string) error {\n\tfiles, err := s.ListBySession(ctx, sessionID)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor _, file := range files {\n\t\terr = s.Delete(ctx, file.ID)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (s *service) fromDBItem(item db.File) File {\n\treturn File{\n\t\tID: item.ID,\n\t\tSessionID: item.SessionID,\n\t\tPath: item.Path,\n\t\tContent: item.Content,\n\t\tVersion: item.Version,\n\t\tCreatedAt: item.CreatedAt,\n\t\tUpdatedAt: item.UpdatedAt,\n\t}\n}\n"], ["/opencode/internal/llm/prompt/prompt.go", "package prompt\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"strings\"\n\t\"sync\"\n\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/llm/models\"\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n)\n\nfunc GetAgentPrompt(agentName config.AgentName, provider models.ModelProvider) string {\n\tbasePrompt := \"\"\n\tswitch agentName {\n\tcase config.AgentCoder:\n\t\tbasePrompt = CoderPrompt(provider)\n\tcase config.AgentTitle:\n\t\tbasePrompt = TitlePrompt(provider)\n\tcase config.AgentTask:\n\t\tbasePrompt = TaskPrompt(provider)\n\tcase config.AgentSummarizer:\n\t\tbasePrompt = SummarizerPrompt(provider)\n\tdefault:\n\t\tbasePrompt = \"You are a helpful assistant\"\n\t}\n\n\tif agentName == config.AgentCoder || agentName == config.AgentTask {\n\t\t// Add context from project-specific instruction files if they exist\n\t\tcontextContent := getContextFromPaths()\n\t\tlogging.Debug(\"Context content\", \"Context\", contextContent)\n\t\tif contextContent != \"\" {\n\t\t\treturn fmt.Sprintf(\"%s\\n\\n# Project-Specific Context\\n Make sure to follow the instructions in the context below\\n%s\", basePrompt, contextContent)\n\t\t}\n\t}\n\treturn basePrompt\n}\n\nvar (\n\tonceContext sync.Once\n\tcontextContent string\n)\n\nfunc getContextFromPaths() string {\n\tonceContext.Do(func() {\n\t\tvar (\n\t\t\tcfg = config.Get()\n\t\t\tworkDir = cfg.WorkingDir\n\t\t\tcontextPaths = cfg.ContextPaths\n\t\t)\n\n\t\tcontextContent = processContextPaths(workDir, contextPaths)\n\t})\n\n\treturn contextContent\n}\n\nfunc processContextPaths(workDir string, paths []string) string {\n\tvar (\n\t\twg sync.WaitGroup\n\t\tresultCh = make(chan string)\n\t)\n\n\t// Track processed files to avoid duplicates\n\tprocessedFiles := make(map[string]bool)\n\tvar processedMutex sync.Mutex\n\n\tfor _, path := range paths {\n\t\twg.Add(1)\n\t\tgo func(p string) {\n\t\t\tdefer wg.Done()\n\n\t\t\tif strings.HasSuffix(p, \"/\") {\n\t\t\t\tfilepath.WalkDir(filepath.Join(workDir, p), func(path string, d os.DirEntry, err error) error {\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn err\n\t\t\t\t\t}\n\t\t\t\t\tif !d.IsDir() {\n\t\t\t\t\t\t// Check if we've already processed this file (case-insensitive)\n\t\t\t\t\t\tprocessedMutex.Lock()\n\t\t\t\t\t\tlowerPath := strings.ToLower(path)\n\t\t\t\t\t\tif !processedFiles[lowerPath] {\n\t\t\t\t\t\t\tprocessedFiles[lowerPath] = true\n\t\t\t\t\t\t\tprocessedMutex.Unlock()\n\n\t\t\t\t\t\t\tif result := processFile(path); result != \"\" {\n\t\t\t\t\t\t\t\tresultCh <- result\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tprocessedMutex.Unlock()\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\treturn nil\n\t\t\t\t})\n\t\t\t} else {\n\t\t\t\tfullPath := filepath.Join(workDir, p)\n\n\t\t\t\t// Check if we've already processed this file (case-insensitive)\n\t\t\t\tprocessedMutex.Lock()\n\t\t\t\tlowerPath := strings.ToLower(fullPath)\n\t\t\t\tif !processedFiles[lowerPath] {\n\t\t\t\t\tprocessedFiles[lowerPath] = true\n\t\t\t\t\tprocessedMutex.Unlock()\n\n\t\t\t\t\tresult := processFile(fullPath)\n\t\t\t\t\tif result != \"\" {\n\t\t\t\t\t\tresultCh <- result\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tprocessedMutex.Unlock()\n\t\t\t\t}\n\t\t\t}\n\t\t}(path)\n\t}\n\n\tgo func() {\n\t\twg.Wait()\n\t\tclose(resultCh)\n\t}()\n\n\tresults := make([]string, 0)\n\tfor result := range resultCh {\n\t\tresults = append(results, result)\n\t}\n\n\treturn strings.Join(results, \"\\n\")\n}\n\nfunc processFile(filePath string) string {\n\tcontent, err := os.ReadFile(filePath)\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\treturn \"# From:\" + filePath + \"\\n\" + string(content)\n}\n"], ["/opencode/internal/permission/permission.go", "package permission\n\nimport (\n\t\"errors\"\n\t\"path/filepath\"\n\t\"slices\"\n\t\"sync\"\n\n\t\"github.com/google/uuid\"\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/pubsub\"\n)\n\nvar ErrorPermissionDenied = errors.New(\"permission denied\")\n\ntype CreatePermissionRequest struct {\n\tSessionID string `json:\"session_id\"`\n\tToolName string `json:\"tool_name\"`\n\tDescription string `json:\"description\"`\n\tAction string `json:\"action\"`\n\tParams any `json:\"params\"`\n\tPath string `json:\"path\"`\n}\n\ntype PermissionRequest struct {\n\tID string `json:\"id\"`\n\tSessionID string `json:\"session_id\"`\n\tToolName string `json:\"tool_name\"`\n\tDescription string `json:\"description\"`\n\tAction string `json:\"action\"`\n\tParams any `json:\"params\"`\n\tPath string `json:\"path\"`\n}\n\ntype Service interface {\n\tpubsub.Suscriber[PermissionRequest]\n\tGrantPersistant(permission PermissionRequest)\n\tGrant(permission PermissionRequest)\n\tDeny(permission PermissionRequest)\n\tRequest(opts CreatePermissionRequest) bool\n\tAutoApproveSession(sessionID string)\n}\n\ntype permissionService struct {\n\t*pubsub.Broker[PermissionRequest]\n\n\tsessionPermissions []PermissionRequest\n\tpendingRequests sync.Map\n\tautoApproveSessions []string\n}\n\nfunc (s *permissionService) GrantPersistant(permission PermissionRequest) {\n\trespCh, ok := s.pendingRequests.Load(permission.ID)\n\tif ok {\n\t\trespCh.(chan bool) <- true\n\t}\n\ts.sessionPermissions = append(s.sessionPermissions, permission)\n}\n\nfunc (s *permissionService) Grant(permission PermissionRequest) {\n\trespCh, ok := s.pendingRequests.Load(permission.ID)\n\tif ok {\n\t\trespCh.(chan bool) <- true\n\t}\n}\n\nfunc (s *permissionService) Deny(permission PermissionRequest) {\n\trespCh, ok := s.pendingRequests.Load(permission.ID)\n\tif ok {\n\t\trespCh.(chan bool) <- false\n\t}\n}\n\nfunc (s *permissionService) Request(opts CreatePermissionRequest) bool {\n\tif slices.Contains(s.autoApproveSessions, opts.SessionID) {\n\t\treturn true\n\t}\n\tdir := filepath.Dir(opts.Path)\n\tif dir == \".\" {\n\t\tdir = config.WorkingDirectory()\n\t}\n\tpermission := PermissionRequest{\n\t\tID: uuid.New().String(),\n\t\tPath: dir,\n\t\tSessionID: opts.SessionID,\n\t\tToolName: opts.ToolName,\n\t\tDescription: opts.Description,\n\t\tAction: opts.Action,\n\t\tParams: opts.Params,\n\t}\n\n\tfor _, p := range s.sessionPermissions {\n\t\tif p.ToolName == permission.ToolName && p.Action == permission.Action && p.SessionID == permission.SessionID && p.Path == permission.Path {\n\t\t\treturn true\n\t\t}\n\t}\n\n\trespCh := make(chan bool, 1)\n\n\ts.pendingRequests.Store(permission.ID, respCh)\n\tdefer s.pendingRequests.Delete(permission.ID)\n\n\ts.Publish(pubsub.CreatedEvent, permission)\n\n\t// Wait for the response with a timeout\n\tresp := <-respCh\n\treturn resp\n}\n\nfunc (s *permissionService) AutoApproveSession(sessionID string) {\n\ts.autoApproveSessions = append(s.autoApproveSessions, sessionID)\n}\n\nfunc NewPermissionService() Service {\n\treturn &permissionService{\n\t\tBroker: pubsub.NewBroker[PermissionRequest](),\n\t\tsessionPermissions: make([]PermissionRequest, 0),\n\t}\n}\n"], ["/opencode/internal/tui/styles/markdown.go", "package styles\n\nimport (\n\t\"github.com/charmbracelet/glamour\"\n\t\"github.com/charmbracelet/glamour/ansi\"\n\t\"github.com/charmbracelet/lipgloss\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n)\n\nconst defaultMargin = 1\n\n// Helper functions for style pointers\nfunc boolPtr(b bool) *bool { return &b }\nfunc stringPtr(s string) *string { return &s }\nfunc uintPtr(u uint) *uint { return &u }\n\n// returns a glamour TermRenderer configured with the current theme\nfunc GetMarkdownRenderer(width int) *glamour.TermRenderer {\n\tr, _ := glamour.NewTermRenderer(\n\t\tglamour.WithStyles(generateMarkdownStyleConfig()),\n\t\tglamour.WithWordWrap(width),\n\t)\n\treturn r\n}\n\n// creates an ansi.StyleConfig for markdown rendering\n// using adaptive colors from the provided theme.\nfunc generateMarkdownStyleConfig() ansi.StyleConfig {\n\tt := theme.CurrentTheme()\n\n\treturn ansi.StyleConfig{\n\t\tDocument: ansi.StyleBlock{\n\t\t\tStylePrimitive: ansi.StylePrimitive{\n\t\t\t\tBlockPrefix: \"\",\n\t\t\t\tBlockSuffix: \"\",\n\t\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownText())),\n\t\t\t},\n\t\t\tMargin: uintPtr(defaultMargin),\n\t\t},\n\t\tBlockQuote: ansi.StyleBlock{\n\t\t\tStylePrimitive: ansi.StylePrimitive{\n\t\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownBlockQuote())),\n\t\t\t\tItalic: boolPtr(true),\n\t\t\t\tPrefix: \"┃ \",\n\t\t\t},\n\t\t\tIndent: uintPtr(1),\n\t\t\tIndentToken: stringPtr(BaseStyle().Render(\" \")),\n\t\t},\n\t\tList: ansi.StyleList{\n\t\t\tLevelIndent: defaultMargin,\n\t\t\tStyleBlock: ansi.StyleBlock{\n\t\t\t\tIndentToken: stringPtr(BaseStyle().Render(\" \")),\n\t\t\t\tStylePrimitive: ansi.StylePrimitive{\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownText())),\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\tHeading: ansi.StyleBlock{\n\t\t\tStylePrimitive: ansi.StylePrimitive{\n\t\t\t\tBlockSuffix: \"\\n\",\n\t\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownHeading())),\n\t\t\t\tBold: boolPtr(true),\n\t\t\t},\n\t\t},\n\t\tH1: ansi.StyleBlock{\n\t\t\tStylePrimitive: ansi.StylePrimitive{\n\t\t\t\tPrefix: \"# \",\n\t\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownHeading())),\n\t\t\t\tBold: boolPtr(true),\n\t\t\t},\n\t\t},\n\t\tH2: ansi.StyleBlock{\n\t\t\tStylePrimitive: ansi.StylePrimitive{\n\t\t\t\tPrefix: \"## \",\n\t\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownHeading())),\n\t\t\t\tBold: boolPtr(true),\n\t\t\t},\n\t\t},\n\t\tH3: ansi.StyleBlock{\n\t\t\tStylePrimitive: ansi.StylePrimitive{\n\t\t\t\tPrefix: \"### \",\n\t\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownHeading())),\n\t\t\t\tBold: boolPtr(true),\n\t\t\t},\n\t\t},\n\t\tH4: ansi.StyleBlock{\n\t\t\tStylePrimitive: ansi.StylePrimitive{\n\t\t\t\tPrefix: \"#### \",\n\t\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownHeading())),\n\t\t\t\tBold: boolPtr(true),\n\t\t\t},\n\t\t},\n\t\tH5: ansi.StyleBlock{\n\t\t\tStylePrimitive: ansi.StylePrimitive{\n\t\t\t\tPrefix: \"##### \",\n\t\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownHeading())),\n\t\t\t\tBold: boolPtr(true),\n\t\t\t},\n\t\t},\n\t\tH6: ansi.StyleBlock{\n\t\t\tStylePrimitive: ansi.StylePrimitive{\n\t\t\t\tPrefix: \"###### \",\n\t\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownHeading())),\n\t\t\t\tBold: boolPtr(true),\n\t\t\t},\n\t\t},\n\t\tStrikethrough: ansi.StylePrimitive{\n\t\t\tCrossedOut: boolPtr(true),\n\t\t\tColor: stringPtr(adaptiveColorToString(t.TextMuted())),\n\t\t},\n\t\tEmph: ansi.StylePrimitive{\n\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownEmph())),\n\t\t\tItalic: boolPtr(true),\n\t\t},\n\t\tStrong: ansi.StylePrimitive{\n\t\t\tBold: boolPtr(true),\n\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownStrong())),\n\t\t},\n\t\tHorizontalRule: ansi.StylePrimitive{\n\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownHorizontalRule())),\n\t\t\tFormat: \"\\n─────────────────────────────────────────\\n\",\n\t\t},\n\t\tItem: ansi.StylePrimitive{\n\t\t\tBlockPrefix: \"• \",\n\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownListItem())),\n\t\t},\n\t\tEnumeration: ansi.StylePrimitive{\n\t\t\tBlockPrefix: \". \",\n\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownListEnumeration())),\n\t\t},\n\t\tTask: ansi.StyleTask{\n\t\t\tStylePrimitive: ansi.StylePrimitive{},\n\t\t\tTicked: \"[✓] \",\n\t\t\tUnticked: \"[ ] \",\n\t\t},\n\t\tLink: ansi.StylePrimitive{\n\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownLink())),\n\t\t\tUnderline: boolPtr(true),\n\t\t},\n\t\tLinkText: ansi.StylePrimitive{\n\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownLinkText())),\n\t\t\tBold: boolPtr(true),\n\t\t},\n\t\tImage: ansi.StylePrimitive{\n\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownImage())),\n\t\t\tUnderline: boolPtr(true),\n\t\t\tFormat: \"🖼 {{.text}}\",\n\t\t},\n\t\tImageText: ansi.StylePrimitive{\n\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownImageText())),\n\t\t\tFormat: \"{{.text}}\",\n\t\t},\n\t\tCode: ansi.StyleBlock{\n\t\t\tStylePrimitive: ansi.StylePrimitive{\n\t\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownCode())),\n\t\t\t\tPrefix: \"\",\n\t\t\t\tSuffix: \"\",\n\t\t\t},\n\t\t},\n\t\tCodeBlock: ansi.StyleCodeBlock{\n\t\t\tStyleBlock: ansi.StyleBlock{\n\t\t\t\tStylePrimitive: ansi.StylePrimitive{\n\t\t\t\t\tPrefix: \" \",\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownCodeBlock())),\n\t\t\t\t},\n\t\t\t\tMargin: uintPtr(defaultMargin),\n\t\t\t},\n\t\t\tChroma: &ansi.Chroma{\n\t\t\t\tText: ansi.StylePrimitive{\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownText())),\n\t\t\t\t},\n\t\t\t\tError: ansi.StylePrimitive{\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.Error())),\n\t\t\t\t},\n\t\t\t\tComment: ansi.StylePrimitive{\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.SyntaxComment())),\n\t\t\t\t},\n\t\t\t\tCommentPreproc: ansi.StylePrimitive{\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.SyntaxKeyword())),\n\t\t\t\t},\n\t\t\t\tKeyword: ansi.StylePrimitive{\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.SyntaxKeyword())),\n\t\t\t\t},\n\t\t\t\tKeywordReserved: ansi.StylePrimitive{\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.SyntaxKeyword())),\n\t\t\t\t},\n\t\t\t\tKeywordNamespace: ansi.StylePrimitive{\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.SyntaxKeyword())),\n\t\t\t\t},\n\t\t\t\tKeywordType: ansi.StylePrimitive{\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.SyntaxType())),\n\t\t\t\t},\n\t\t\t\tOperator: ansi.StylePrimitive{\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.SyntaxOperator())),\n\t\t\t\t},\n\t\t\t\tPunctuation: ansi.StylePrimitive{\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.SyntaxPunctuation())),\n\t\t\t\t},\n\t\t\t\tName: ansi.StylePrimitive{\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.SyntaxVariable())),\n\t\t\t\t},\n\t\t\t\tNameBuiltin: ansi.StylePrimitive{\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.SyntaxVariable())),\n\t\t\t\t},\n\t\t\t\tNameTag: ansi.StylePrimitive{\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.SyntaxKeyword())),\n\t\t\t\t},\n\t\t\t\tNameAttribute: ansi.StylePrimitive{\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.SyntaxFunction())),\n\t\t\t\t},\n\t\t\t\tNameClass: ansi.StylePrimitive{\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.SyntaxType())),\n\t\t\t\t},\n\t\t\t\tNameConstant: ansi.StylePrimitive{\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.SyntaxVariable())),\n\t\t\t\t},\n\t\t\t\tNameDecorator: ansi.StylePrimitive{\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.SyntaxFunction())),\n\t\t\t\t},\n\t\t\t\tNameFunction: ansi.StylePrimitive{\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.SyntaxFunction())),\n\t\t\t\t},\n\t\t\t\tLiteralNumber: ansi.StylePrimitive{\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.SyntaxNumber())),\n\t\t\t\t},\n\t\t\t\tLiteralString: ansi.StylePrimitive{\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.SyntaxString())),\n\t\t\t\t},\n\t\t\t\tLiteralStringEscape: ansi.StylePrimitive{\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.SyntaxKeyword())),\n\t\t\t\t},\n\t\t\t\tGenericDeleted: ansi.StylePrimitive{\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.DiffRemoved())),\n\t\t\t\t},\n\t\t\t\tGenericEmph: ansi.StylePrimitive{\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownEmph())),\n\t\t\t\t\tItalic: boolPtr(true),\n\t\t\t\t},\n\t\t\t\tGenericInserted: ansi.StylePrimitive{\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.DiffAdded())),\n\t\t\t\t},\n\t\t\t\tGenericStrong: ansi.StylePrimitive{\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownStrong())),\n\t\t\t\t\tBold: boolPtr(true),\n\t\t\t\t},\n\t\t\t\tGenericSubheading: ansi.StylePrimitive{\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownHeading())),\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\tTable: ansi.StyleTable{\n\t\t\tStyleBlock: ansi.StyleBlock{\n\t\t\t\tStylePrimitive: ansi.StylePrimitive{\n\t\t\t\t\tBlockPrefix: \"\\n\",\n\t\t\t\t\tBlockSuffix: \"\\n\",\n\t\t\t\t},\n\t\t\t},\n\t\t\tCenterSeparator: stringPtr(\"┼\"),\n\t\t\tColumnSeparator: stringPtr(\"│\"),\n\t\t\tRowSeparator: stringPtr(\"─\"),\n\t\t},\n\t\tDefinitionDescription: ansi.StylePrimitive{\n\t\t\tBlockPrefix: \"\\n ❯ \",\n\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownLinkText())),\n\t\t},\n\t\tText: ansi.StylePrimitive{\n\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownText())),\n\t\t},\n\t\tParagraph: ansi.StyleBlock{\n\t\t\tStylePrimitive: ansi.StylePrimitive{\n\t\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownText())),\n\t\t\t},\n\t\t},\n\t}\n}\n\n// adaptiveColorToString converts a lipgloss.AdaptiveColor to the appropriate\n// hex color string based on the current terminal background\nfunc adaptiveColorToString(color lipgloss.AdaptiveColor) string {\n\tif lipgloss.HasDarkBackground() {\n\t\treturn color.Dark\n\t}\n\treturn color.Light\n}\n"], ["/opencode/internal/lsp/util/edit.go", "package util\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"os\"\n\t\"sort\"\n\t\"strings\"\n\n\t\"github.com/opencode-ai/opencode/internal/lsp/protocol\"\n)\n\nfunc applyTextEdits(uri protocol.DocumentUri, edits []protocol.TextEdit) error {\n\tpath := strings.TrimPrefix(string(uri), \"file://\")\n\n\t// Read the file content\n\tcontent, err := os.ReadFile(path)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to read file: %w\", err)\n\t}\n\n\t// Detect line ending style\n\tvar lineEnding string\n\tif bytes.Contains(content, []byte(\"\\r\\n\")) {\n\t\tlineEnding = \"\\r\\n\"\n\t} else {\n\t\tlineEnding = \"\\n\"\n\t}\n\n\t// Track if file ends with a newline\n\tendsWithNewline := len(content) > 0 && bytes.HasSuffix(content, []byte(lineEnding))\n\n\t// Split into lines without the endings\n\tlines := strings.Split(string(content), lineEnding)\n\n\t// Check for overlapping edits\n\tfor i, edit1 := range edits {\n\t\tfor j := i + 1; j < len(edits); j++ {\n\t\t\tif rangesOverlap(edit1.Range, edits[j].Range) {\n\t\t\t\treturn fmt.Errorf(\"overlapping edits detected between edit %d and %d\", i, j)\n\t\t\t}\n\t\t}\n\t}\n\n\t// Sort edits in reverse order\n\tsortedEdits := make([]protocol.TextEdit, len(edits))\n\tcopy(sortedEdits, edits)\n\tsort.Slice(sortedEdits, func(i, j int) bool {\n\t\tif sortedEdits[i].Range.Start.Line != sortedEdits[j].Range.Start.Line {\n\t\t\treturn sortedEdits[i].Range.Start.Line > sortedEdits[j].Range.Start.Line\n\t\t}\n\t\treturn sortedEdits[i].Range.Start.Character > sortedEdits[j].Range.Start.Character\n\t})\n\n\t// Apply each edit\n\tfor _, edit := range sortedEdits {\n\t\tnewLines, err := applyTextEdit(lines, edit)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to apply edit: %w\", err)\n\t\t}\n\t\tlines = newLines\n\t}\n\n\t// Join lines with proper line endings\n\tvar newContent strings.Builder\n\tfor i, line := range lines {\n\t\tif i > 0 {\n\t\t\tnewContent.WriteString(lineEnding)\n\t\t}\n\t\tnewContent.WriteString(line)\n\t}\n\n\t// Only add a newline if the original file had one and we haven't already added it\n\tif endsWithNewline && !strings.HasSuffix(newContent.String(), lineEnding) {\n\t\tnewContent.WriteString(lineEnding)\n\t}\n\n\tif err := os.WriteFile(path, []byte(newContent.String()), 0o644); err != nil {\n\t\treturn fmt.Errorf(\"failed to write file: %w\", err)\n\t}\n\n\treturn nil\n}\n\nfunc applyTextEdit(lines []string, edit protocol.TextEdit) ([]string, error) {\n\tstartLine := int(edit.Range.Start.Line)\n\tendLine := int(edit.Range.End.Line)\n\tstartChar := int(edit.Range.Start.Character)\n\tendChar := int(edit.Range.End.Character)\n\n\t// Validate positions\n\tif startLine < 0 || startLine >= len(lines) {\n\t\treturn nil, fmt.Errorf(\"invalid start line: %d\", startLine)\n\t}\n\tif endLine < 0 || endLine >= len(lines) {\n\t\tendLine = len(lines) - 1\n\t}\n\n\t// Create result slice with initial capacity\n\tresult := make([]string, 0, len(lines))\n\n\t// Copy lines before edit\n\tresult = append(result, lines[:startLine]...)\n\n\t// Get the prefix of the start line\n\tstartLineContent := lines[startLine]\n\tif startChar < 0 || startChar > len(startLineContent) {\n\t\tstartChar = len(startLineContent)\n\t}\n\tprefix := startLineContent[:startChar]\n\n\t// Get the suffix of the end line\n\tendLineContent := lines[endLine]\n\tif endChar < 0 || endChar > len(endLineContent) {\n\t\tendChar = len(endLineContent)\n\t}\n\tsuffix := endLineContent[endChar:]\n\n\t// Handle the edit\n\tif edit.NewText == \"\" {\n\t\tif prefix+suffix != \"\" {\n\t\t\tresult = append(result, prefix+suffix)\n\t\t}\n\t} else {\n\t\t// Split new text into lines, being careful not to add extra newlines\n\t\t// newLines := strings.Split(strings.TrimRight(edit.NewText, \"\\n\"), \"\\n\")\n\t\tnewLines := strings.Split(edit.NewText, \"\\n\")\n\n\t\tif len(newLines) == 1 {\n\t\t\t// Single line change\n\t\t\tresult = append(result, prefix+newLines[0]+suffix)\n\t\t} else {\n\t\t\t// Multi-line change\n\t\t\tresult = append(result, prefix+newLines[0])\n\t\t\tresult = append(result, newLines[1:len(newLines)-1]...)\n\t\t\tresult = append(result, newLines[len(newLines)-1]+suffix)\n\t\t}\n\t}\n\n\t// Add remaining lines\n\tif endLine+1 < len(lines) {\n\t\tresult = append(result, lines[endLine+1:]...)\n\t}\n\n\treturn result, nil\n}\n\n// applyDocumentChange applies a DocumentChange (create/rename/delete operations)\nfunc applyDocumentChange(change protocol.DocumentChange) error {\n\tif change.CreateFile != nil {\n\t\tpath := strings.TrimPrefix(string(change.CreateFile.URI), \"file://\")\n\t\tif change.CreateFile.Options != nil {\n\t\t\tif change.CreateFile.Options.Overwrite {\n\t\t\t\t// Proceed with overwrite\n\t\t\t} else if change.CreateFile.Options.IgnoreIfExists {\n\t\t\t\tif _, err := os.Stat(path); err == nil {\n\t\t\t\t\treturn nil // File exists and we're ignoring it\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif err := os.WriteFile(path, []byte(\"\"), 0o644); err != nil {\n\t\t\treturn fmt.Errorf(\"failed to create file: %w\", err)\n\t\t}\n\t}\n\n\tif change.DeleteFile != nil {\n\t\tpath := strings.TrimPrefix(string(change.DeleteFile.URI), \"file://\")\n\t\tif change.DeleteFile.Options != nil && change.DeleteFile.Options.Recursive {\n\t\t\tif err := os.RemoveAll(path); err != nil {\n\t\t\t\treturn fmt.Errorf(\"failed to delete directory recursively: %w\", err)\n\t\t\t}\n\t\t} else {\n\t\t\tif err := os.Remove(path); err != nil {\n\t\t\t\treturn fmt.Errorf(\"failed to delete file: %w\", err)\n\t\t\t}\n\t\t}\n\t}\n\n\tif change.RenameFile != nil {\n\t\toldPath := strings.TrimPrefix(string(change.RenameFile.OldURI), \"file://\")\n\t\tnewPath := strings.TrimPrefix(string(change.RenameFile.NewURI), \"file://\")\n\t\tif change.RenameFile.Options != nil {\n\t\t\tif !change.RenameFile.Options.Overwrite {\n\t\t\t\tif _, err := os.Stat(newPath); err == nil {\n\t\t\t\t\treturn fmt.Errorf(\"target file already exists and overwrite is not allowed: %s\", newPath)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif err := os.Rename(oldPath, newPath); err != nil {\n\t\t\treturn fmt.Errorf(\"failed to rename file: %w\", err)\n\t\t}\n\t}\n\n\tif change.TextDocumentEdit != nil {\n\t\ttextEdits := make([]protocol.TextEdit, len(change.TextDocumentEdit.Edits))\n\t\tfor i, edit := range change.TextDocumentEdit.Edits {\n\t\t\tvar err error\n\t\t\ttextEdits[i], err = edit.AsTextEdit()\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"invalid edit type: %w\", err)\n\t\t\t}\n\t\t}\n\t\treturn applyTextEdits(change.TextDocumentEdit.TextDocument.URI, textEdits)\n\t}\n\n\treturn nil\n}\n\n// ApplyWorkspaceEdit applies the given WorkspaceEdit to the filesystem\nfunc ApplyWorkspaceEdit(edit protocol.WorkspaceEdit) error {\n\t// Handle Changes field\n\tfor uri, textEdits := range edit.Changes {\n\t\tif err := applyTextEdits(uri, textEdits); err != nil {\n\t\t\treturn fmt.Errorf(\"failed to apply text edits: %w\", err)\n\t\t}\n\t}\n\n\t// Handle DocumentChanges field\n\tfor _, change := range edit.DocumentChanges {\n\t\tif err := applyDocumentChange(change); err != nil {\n\t\t\treturn fmt.Errorf(\"failed to apply document change: %w\", err)\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc rangesOverlap(r1, r2 protocol.Range) bool {\n\tif r1.Start.Line > r2.End.Line || r2.Start.Line > r1.End.Line {\n\t\treturn false\n\t}\n\tif r1.Start.Line == r2.End.Line && r1.Start.Character > r2.End.Character {\n\t\treturn false\n\t}\n\tif r2.Start.Line == r1.End.Line && r2.Start.Character > r1.End.Character {\n\t\treturn false\n\t}\n\treturn true\n}\n"], ["/opencode/internal/tui/image/images.go", "package image\n\nimport (\n\t\"fmt\"\n\t\"image\"\n\t\"os\"\n\t\"strings\"\n\n\t\"github.com/charmbracelet/lipgloss\"\n\t\"github.com/disintegration/imaging\"\n\t\"github.com/lucasb-eyer/go-colorful\"\n)\n\nfunc ValidateFileSize(filePath string, sizeLimit int64) (bool, error) {\n\tfileInfo, err := os.Stat(filePath)\n\tif err != nil {\n\t\treturn false, fmt.Errorf(\"error getting file info: %w\", err)\n\t}\n\n\tif fileInfo.Size() > sizeLimit {\n\t\treturn true, nil\n\t}\n\n\treturn false, nil\n}\n\nfunc ToString(width int, img image.Image) string {\n\timg = imaging.Resize(img, width, 0, imaging.Lanczos)\n\tb := img.Bounds()\n\timageWidth := b.Max.X\n\th := b.Max.Y\n\tstr := strings.Builder{}\n\n\tfor heightCounter := 0; heightCounter < h; heightCounter += 2 {\n\t\tfor x := range imageWidth {\n\t\t\tc1, _ := colorful.MakeColor(img.At(x, heightCounter))\n\t\t\tcolor1 := lipgloss.Color(c1.Hex())\n\n\t\t\tvar color2 lipgloss.Color\n\t\t\tif heightCounter+1 < h {\n\t\t\t\tc2, _ := colorful.MakeColor(img.At(x, heightCounter+1))\n\t\t\t\tcolor2 = lipgloss.Color(c2.Hex())\n\t\t\t} else {\n\t\t\t\tcolor2 = color1\n\t\t\t}\n\n\t\t\tstr.WriteString(lipgloss.NewStyle().Foreground(color1).\n\t\t\t\tBackground(color2).Render(\"▀\"))\n\t\t}\n\n\t\tstr.WriteString(\"\\n\")\n\t}\n\n\treturn str.String()\n}\n\nfunc ImagePreview(width int, filename string) (string, error) {\n\timageContent, err := os.Open(filename)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer imageContent.Close()\n\n\timg, _, err := image.Decode(imageContent)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\timageString := ToString(width, img)\n\n\treturn imageString, nil\n}\n"], ["/opencode/internal/session/session.go", "package session\n\nimport (\n\t\"context\"\n\t\"database/sql\"\n\n\t\"github.com/google/uuid\"\n\t\"github.com/opencode-ai/opencode/internal/db\"\n\t\"github.com/opencode-ai/opencode/internal/pubsub\"\n)\n\ntype Session struct {\n\tID string\n\tParentSessionID string\n\tTitle string\n\tMessageCount int64\n\tPromptTokens int64\n\tCompletionTokens int64\n\tSummaryMessageID string\n\tCost float64\n\tCreatedAt int64\n\tUpdatedAt int64\n}\n\ntype Service interface {\n\tpubsub.Suscriber[Session]\n\tCreate(ctx context.Context, title string) (Session, error)\n\tCreateTitleSession(ctx context.Context, parentSessionID string) (Session, error)\n\tCreateTaskSession(ctx context.Context, toolCallID, parentSessionID, title string) (Session, error)\n\tGet(ctx context.Context, id string) (Session, error)\n\tList(ctx context.Context) ([]Session, error)\n\tSave(ctx context.Context, session Session) (Session, error)\n\tDelete(ctx context.Context, id string) error\n}\n\ntype service struct {\n\t*pubsub.Broker[Session]\n\tq db.Querier\n}\n\nfunc (s *service) Create(ctx context.Context, title string) (Session, error) {\n\tdbSession, err := s.q.CreateSession(ctx, db.CreateSessionParams{\n\t\tID: uuid.New().String(),\n\t\tTitle: title,\n\t})\n\tif err != nil {\n\t\treturn Session{}, err\n\t}\n\tsession := s.fromDBItem(dbSession)\n\ts.Publish(pubsub.CreatedEvent, session)\n\treturn session, nil\n}\n\nfunc (s *service) CreateTaskSession(ctx context.Context, toolCallID, parentSessionID, title string) (Session, error) {\n\tdbSession, err := s.q.CreateSession(ctx, db.CreateSessionParams{\n\t\tID: toolCallID,\n\t\tParentSessionID: sql.NullString{String: parentSessionID, Valid: true},\n\t\tTitle: title,\n\t})\n\tif err != nil {\n\t\treturn Session{}, err\n\t}\n\tsession := s.fromDBItem(dbSession)\n\ts.Publish(pubsub.CreatedEvent, session)\n\treturn session, nil\n}\n\nfunc (s *service) CreateTitleSession(ctx context.Context, parentSessionID string) (Session, error) {\n\tdbSession, err := s.q.CreateSession(ctx, db.CreateSessionParams{\n\t\tID: \"title-\" + parentSessionID,\n\t\tParentSessionID: sql.NullString{String: parentSessionID, Valid: true},\n\t\tTitle: \"Generate a title\",\n\t})\n\tif err != nil {\n\t\treturn Session{}, err\n\t}\n\tsession := s.fromDBItem(dbSession)\n\ts.Publish(pubsub.CreatedEvent, session)\n\treturn session, nil\n}\n\nfunc (s *service) Delete(ctx context.Context, id string) error {\n\tsession, err := s.Get(ctx, id)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = s.q.DeleteSession(ctx, session.ID)\n\tif err != nil {\n\t\treturn err\n\t}\n\ts.Publish(pubsub.DeletedEvent, session)\n\treturn nil\n}\n\nfunc (s *service) Get(ctx context.Context, id string) (Session, error) {\n\tdbSession, err := s.q.GetSessionByID(ctx, id)\n\tif err != nil {\n\t\treturn Session{}, err\n\t}\n\treturn s.fromDBItem(dbSession), nil\n}\n\nfunc (s *service) Save(ctx context.Context, session Session) (Session, error) {\n\tdbSession, err := s.q.UpdateSession(ctx, db.UpdateSessionParams{\n\t\tID: session.ID,\n\t\tTitle: session.Title,\n\t\tPromptTokens: session.PromptTokens,\n\t\tCompletionTokens: session.CompletionTokens,\n\t\tSummaryMessageID: sql.NullString{\n\t\t\tString: session.SummaryMessageID,\n\t\t\tValid: session.SummaryMessageID != \"\",\n\t\t},\n\t\tCost: session.Cost,\n\t})\n\tif err != nil {\n\t\treturn Session{}, err\n\t}\n\tsession = s.fromDBItem(dbSession)\n\ts.Publish(pubsub.UpdatedEvent, session)\n\treturn session, nil\n}\n\nfunc (s *service) List(ctx context.Context) ([]Session, error) {\n\tdbSessions, err := s.q.ListSessions(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsessions := make([]Session, len(dbSessions))\n\tfor i, dbSession := range dbSessions {\n\t\tsessions[i] = s.fromDBItem(dbSession)\n\t}\n\treturn sessions, nil\n}\n\nfunc (s service) fromDBItem(item db.Session) Session {\n\treturn Session{\n\t\tID: item.ID,\n\t\tParentSessionID: item.ParentSessionID.String,\n\t\tTitle: item.Title,\n\t\tMessageCount: item.MessageCount,\n\t\tPromptTokens: item.PromptTokens,\n\t\tCompletionTokens: item.CompletionTokens,\n\t\tSummaryMessageID: item.SummaryMessageID.String,\n\t\tCost: item.Cost,\n\t\tCreatedAt: item.CreatedAt,\n\t\tUpdatedAt: item.UpdatedAt,\n\t}\n}\n\nfunc NewService(q db.Querier) Service {\n\tbroker := pubsub.NewBroker[Session]()\n\treturn &service{\n\t\tbroker,\n\t\tq,\n\t}\n}\n"], ["/opencode/internal/llm/prompt/coder.go", "package prompt\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"runtime\"\n\t\"time\"\n\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/llm/models\"\n\t\"github.com/opencode-ai/opencode/internal/llm/tools\"\n)\n\nfunc CoderPrompt(provider models.ModelProvider) string {\n\tbasePrompt := baseAnthropicCoderPrompt\n\tswitch provider {\n\tcase models.ProviderOpenAI:\n\t\tbasePrompt = baseOpenAICoderPrompt\n\t}\n\tenvInfo := getEnvironmentInfo()\n\n\treturn fmt.Sprintf(\"%s\\n\\n%s\\n%s\", basePrompt, envInfo, lspInformation())\n}\n\nconst baseOpenAICoderPrompt = `\nYou are operating as and within the OpenCode CLI, a terminal-based agentic coding assistant built by OpenAI. It wraps OpenAI models to enable natural language interaction with a local codebase. You are expected to be precise, safe, and helpful.\n\nYou can:\n- Receive user prompts, project context, and files.\n- Stream responses and emit function calls (e.g., shell commands, code edits).\n- Apply patches, run commands, and manage user approvals based on policy.\n- Work inside a sandboxed, git-backed workspace with rollback support.\n- Log telemetry so sessions can be replayed or inspected later.\n- More details on your functionality are available at \"opencode --help\"\n\n\nYou are an agent - please keep going until the user's query is completely resolved, before ending your turn and yielding back to the user. Only terminate your turn when you are sure that the problem is solved. If you are not sure about file content or codebase structure pertaining to the user's request, use your tools to read files and gather the relevant information: do NOT guess or make up an answer.\n\nPlease resolve the user's task by editing and testing the code files in your current code execution session. You are a deployed coding agent. Your session allows for you to modify and run code. The repo(s) are already cloned in your working directory, and you must fully solve the problem for your answer to be considered correct.\n\nYou MUST adhere to the following criteria when executing the task:\n- Working on the repo(s) in the current environment is allowed, even if they are proprietary.\n- Analyzing code for vulnerabilities is allowed.\n- Showing user code and tool call details is allowed.\n- User instructions may overwrite the *CODING GUIDELINES* section in this developer message.\n- If completing the user's task requires writing or modifying files:\n - Your code and final answer should follow these *CODING GUIDELINES*:\n - Fix the problem at the root cause rather than applying surface-level patches, when possible.\n - Avoid unneeded complexity in your solution.\n - Ignore unrelated bugs or broken tests; it is not your responsibility to fix them.\n - Update documentation as necessary.\n - Keep changes consistent with the style of the existing codebase. Changes should be minimal and focused on the task.\n - Use \"git log\" and \"git blame\" to search the history of the codebase if additional context is required; internet access is disabled.\n - NEVER add copyright or license headers unless specifically requested.\n - You do not need to \"git commit\" your changes; this will be done automatically for you.\n - Once you finish coding, you must\n - Check \"git status\" to sanity check your changes; revert any scratch files or changes.\n - Remove all inline comments you added as much as possible, even if they look normal. Check using \"git diff\". Inline comments must be generally avoided, unless active maintainers of the repo, after long careful study of the code and the issue, will still misinterpret the code without the comments.\n - Check if you accidentally add copyright or license headers. If so, remove them.\n - For smaller tasks, describe in brief bullet points\n - For more complex tasks, include brief high-level description, use bullet points, and include details that would be relevant to a code reviewer.\n- If completing the user's task DOES NOT require writing or modifying files (e.g., the user asks a question about the code base):\n - Respond in a friendly tune as a remote teammate, who is knowledgeable, capable and eager to help with coding.\n- When your task involves writing or modifying files:\n - Do NOT tell the user to \"save the file\" or \"copy the code into a file\" if you already created or modified the file using \"apply_patch\". Instead, reference the file as already saved.\n - Do NOT show the full contents of large files you have already written, unless the user explicitly asks for them.\n- When doing things with paths, always use use the full path, if the working directory is /abc/xyz and you want to edit the file abc.go in the working dir refer to it as /abc/xyz/abc.go.\n- If you send a path not including the working dir, the working dir will be prepended to it.\n- Remember the user does not see the full output of tools\n`\n\nconst baseAnthropicCoderPrompt = `You are OpenCode, an interactive CLI tool that helps users with software engineering tasks. Use the instructions below and the tools available to you to assist the user.\n\nIMPORTANT: Before you begin work, think about what the code you're editing is supposed to do based on the filenames directory structure.\n\n# Memory\nIf the current working directory contains a file called OpenCode.md, it will be automatically added to your context. This file serves multiple purposes:\n1. Storing frequently used bash commands (build, test, lint, etc.) so you can use them without searching each time\n2. Recording the user's code style preferences (naming conventions, preferred libraries, etc.)\n3. Maintaining useful information about the codebase structure and organization\n\nWhen you spend time searching for commands to typecheck, lint, build, or test, you should ask the user if it's okay to add those commands to OpenCode.md. Similarly, when learning about code style preferences or important codebase information, ask if it's okay to add that to OpenCode.md so you can remember it for next time.\n\n# Tone and style\nYou should be concise, direct, and to the point. When you run a non-trivial bash command, you should explain what the command does and why you are running it, to make sure the user understands what you are doing (this is especially important when you are running a command that will make changes to the user's system).\nRemember that your output will be displayed on a command line interface. Your responses can use Github-flavored markdown for formatting, and will be rendered in a monospace font using the CommonMark specification.\nOutput text to communicate with the user; all text you output outside of tool use is displayed to the user. Only use tools to complete tasks. Never use tools like Bash or code comments as means to communicate with the user during the session.\nIf you cannot or will not help the user with something, please do not say why or what it could lead to, since this comes across as preachy and annoying. Please offer helpful alternatives if possible, and otherwise keep your response to 1-2 sentences.\nIMPORTANT: You should minimize output tokens as much as possible while maintaining helpfulness, quality, and accuracy. Only address the specific query or task at hand, avoiding tangential information unless absolutely critical for completing the request. If you can answer in 1-3 sentences or a short paragraph, please do.\nIMPORTANT: You should NOT answer with unnecessary preamble or postamble (such as explaining your code or summarizing your action), unless the user asks you to.\nIMPORTANT: Keep your responses short, since they will be displayed on a command line interface. You MUST answer concisely with fewer than 4 lines (not including tool use or code generation), unless user asks for detail. Answer the user's question directly, without elaboration, explanation, or details. One word answers are best. Avoid introductions, conclusions, and explanations. You MUST avoid text before/after your response, such as \"The answer is .\", \"Here is the content of the file...\" or \"Based on the information provided, the answer is...\" or \"Here is what I will do next...\". Here are some examples to demonstrate appropriate verbosity:\n\nuser: 2 + 2\nassistant: 4\n\n\n\nuser: what is 2+2?\nassistant: 4\n\n\n\nuser: is 11 a prime number?\nassistant: true\n\n\n\nuser: what command should I run to list files in the current directory?\nassistant: ls\n\n\n\nuser: what command should I run to watch files in the current directory?\nassistant: [use the ls tool to list the files in the current directory, then read docs/commands in the relevant file to find out how to watch files]\nnpm run dev\n\n\n\nuser: How many golf balls fit inside a jetta?\nassistant: 150000\n\n\n\nuser: what files are in the directory src/?\nassistant: [runs ls and sees foo.c, bar.c, baz.c]\nuser: which file contains the implementation of foo?\nassistant: src/foo.c\n\n\n\nuser: write tests for new feature\nassistant: [uses grep and glob search tools to find where similar tests are defined, uses concurrent read file tool use blocks in one tool call to read relevant files at the same time, uses edit/patch file tool to write new tests]\n\n\n# Proactiveness\nYou are allowed to be proactive, but only when the user asks you to do something. You should strive to strike a balance between:\n1. Doing the right thing when asked, including taking actions and follow-up actions\n2. Not surprising the user with actions you take without asking\nFor example, if the user asks you how to approach something, you should do your best to answer their question first, and not immediately jump into taking actions.\n3. Do not add additional code explanation summary unless requested by the user. After working on a file, just stop, rather than providing an explanation of what you did.\n\n# Following conventions\nWhen making changes to files, first understand the file's code conventions. Mimic code style, use existing libraries and utilities, and follow existing patterns.\n- NEVER assume that a given library is available, even if it is well known. Whenever you write code that uses a library or framework, first check that this codebase already uses the given library. For example, you might look at neighboring files, or check the package.json (or cargo.toml, and so on depending on the language).\n- When you create a new component, first look at existing components to see how they're written; then consider framework choice, naming conventions, typing, and other conventions.\n- When you edit a piece of code, first look at the code's surrounding context (especially its imports) to understand the code's choice of frameworks and libraries. Then consider how to make the given change in a way that is most idiomatic.\n- Always follow security best practices. Never introduce code that exposes or logs secrets and keys. Never commit secrets or keys to the repository.\n\n# Code style\n- Do not add comments to the code you write, unless the user asks you to, or the code is complex and requires additional context.\n\n# Doing tasks\nThe user will primarily request you perform software engineering tasks. This includes solving bugs, adding new functionality, refactoring code, explaining code, and more. For these tasks the following steps are recommended:\n1. Use the available search tools to understand the codebase and the user's query. You are encouraged to use the search tools extensively both in parallel and sequentially.\n2. Implement the solution using all tools available to you\n3. Verify the solution if possible with tests. NEVER assume specific test framework or test script. Check the README or search codebase to determine the testing approach.\n4. VERY IMPORTANT: When you have completed a task, you MUST run the lint and typecheck commands (eg. npm run lint, npm run typecheck, ruff, etc.) if they were provided to you to ensure your code is correct. If you are unable to find the correct command, ask the user for the command to run and if they supply it, proactively suggest writing it to opencode.md so that you will know to run it next time.\n\nNEVER commit changes unless the user explicitly asks you to. It is VERY IMPORTANT to only commit when explicitly asked, otherwise the user will feel that you are being too proactive.\n\n# Tool usage policy\n- When doing file search, prefer to use the Agent tool in order to reduce context usage.\n- If you intend to call multiple tools and there are no dependencies between the calls, make all of the independent calls in the same function_calls block.\n- IMPORTANT: The user does not see the full output of the tool responses, so if you need the output of the tool for the response make sure to summarize it for the user.\n\nYou MUST answer concisely with fewer than 4 lines of text (not including tool use or code generation), unless user asks for detail.`\n\nfunc getEnvironmentInfo() string {\n\tcwd := config.WorkingDirectory()\n\tisGit := isGitRepo(cwd)\n\tplatform := runtime.GOOS\n\tdate := time.Now().Format(\"1/2/2006\")\n\tls := tools.NewLsTool()\n\tr, _ := ls.Run(context.Background(), tools.ToolCall{\n\t\tInput: `{\"path\":\".\"}`,\n\t})\n\treturn fmt.Sprintf(`Here is useful information about the environment you are running in:\n\nWorking directory: %s\nIs directory a git repo: %s\nPlatform: %s\nToday's date: %s\n\n\n%s\n\n\t\t`, cwd, boolToYesNo(isGit), platform, date, r.Content)\n}\n\nfunc isGitRepo(dir string) bool {\n\t_, err := os.Stat(filepath.Join(dir, \".git\"))\n\treturn err == nil\n}\n\nfunc lspInformation() string {\n\tcfg := config.Get()\n\thasLSP := false\n\tfor _, v := range cfg.LSP {\n\t\tif !v.Disabled {\n\t\t\thasLSP = true\n\t\t\tbreak\n\t\t}\n\t}\n\tif !hasLSP {\n\t\treturn \"\"\n\t}\n\treturn `# LSP Information\nTools that support it will also include useful diagnostics such as linting and typechecking.\n- These diagnostics will be automatically enabled when you run the tool, and will be displayed in the output at the bottom within the and tags.\n- Take necessary actions to fix the issues.\n- You should ignore diagnostics of files that you did not change or are not related or caused by your changes unless the user explicitly asks you to fix them.\n`\n}\n\nfunc boolToYesNo(b bool) string {\n\tif b {\n\t\treturn \"Yes\"\n\t}\n\treturn \"No\"\n}\n"], ["/opencode/internal/logging/logger.go", "package logging\n\nimport (\n\t\"fmt\"\n\t\"log/slog\"\n\t\"os\"\n\t// \"path/filepath\"\n\t\"encoding/json\"\n\t\"runtime\"\n\t\"runtime/debug\"\n\t\"sync\"\n\t\"time\"\n)\n\nfunc getCaller() string {\n\tvar caller string\n\tif _, file, line, ok := runtime.Caller(2); ok {\n\t\t// caller = fmt.Sprintf(\"%s:%d\", filepath.Base(file), line)\n\t\tcaller = fmt.Sprintf(\"%s:%d\", file, line)\n\t} else {\n\t\tcaller = \"unknown\"\n\t}\n\treturn caller\n}\nfunc Info(msg string, args ...any) {\n\tsource := getCaller()\n\tslog.Info(msg, append([]any{\"source\", source}, args...)...)\n}\n\nfunc Debug(msg string, args ...any) {\n\t// slog.Debug(msg, args...)\n\tsource := getCaller()\n\tslog.Debug(msg, append([]any{\"source\", source}, args...)...)\n}\n\nfunc Warn(msg string, args ...any) {\n\tslog.Warn(msg, args...)\n}\n\nfunc Error(msg string, args ...any) {\n\tslog.Error(msg, args...)\n}\n\nfunc InfoPersist(msg string, args ...any) {\n\targs = append(args, persistKeyArg, true)\n\tslog.Info(msg, args...)\n}\n\nfunc DebugPersist(msg string, args ...any) {\n\targs = append(args, persistKeyArg, true)\n\tslog.Debug(msg, args...)\n}\n\nfunc WarnPersist(msg string, args ...any) {\n\targs = append(args, persistKeyArg, true)\n\tslog.Warn(msg, args...)\n}\n\nfunc ErrorPersist(msg string, args ...any) {\n\targs = append(args, persistKeyArg, true)\n\tslog.Error(msg, args...)\n}\n\n// RecoverPanic is a common function to handle panics gracefully.\n// It logs the error, creates a panic log file with stack trace,\n// and executes an optional cleanup function before returning.\nfunc RecoverPanic(name string, cleanup func()) {\n\tif r := recover(); r != nil {\n\t\t// Log the panic\n\t\tErrorPersist(fmt.Sprintf(\"Panic in %s: %v\", name, r))\n\n\t\t// Create a timestamped panic log file\n\t\ttimestamp := time.Now().Format(\"20060102-150405\")\n\t\tfilename := fmt.Sprintf(\"opencode-panic-%s-%s.log\", name, timestamp)\n\n\t\tfile, err := os.Create(filename)\n\t\tif err != nil {\n\t\t\tErrorPersist(fmt.Sprintf(\"Failed to create panic log: %v\", err))\n\t\t} else {\n\t\t\tdefer file.Close()\n\n\t\t\t// Write panic information and stack trace\n\t\t\tfmt.Fprintf(file, \"Panic in %s: %v\\n\\n\", name, r)\n\t\t\tfmt.Fprintf(file, \"Time: %s\\n\\n\", time.Now().Format(time.RFC3339))\n\t\t\tfmt.Fprintf(file, \"Stack Trace:\\n%s\\n\", debug.Stack())\n\n\t\t\tInfoPersist(fmt.Sprintf(\"Panic details written to %s\", filename))\n\t\t}\n\n\t\t// Execute cleanup function if provided\n\t\tif cleanup != nil {\n\t\t\tcleanup()\n\t\t}\n\t}\n}\n\n// Message Logging for Debug\nvar MessageDir string\n\nfunc GetSessionPrefix(sessionId string) string {\n\treturn sessionId[:8]\n}\n\nvar sessionLogMutex sync.Mutex\n\nfunc AppendToSessionLogFile(sessionId string, filename string, content string) string {\n\tif MessageDir == \"\" || sessionId == \"\" {\n\t\treturn \"\"\n\t}\n\tsessionPrefix := GetSessionPrefix(sessionId)\n\n\tsessionLogMutex.Lock()\n\tdefer sessionLogMutex.Unlock()\n\n\tsessionPath := fmt.Sprintf(\"%s/%s\", MessageDir, sessionPrefix)\n\tif _, err := os.Stat(sessionPath); os.IsNotExist(err) {\n\t\tif err := os.MkdirAll(sessionPath, 0o766); err != nil {\n\t\t\tError(\"Failed to create session directory\", \"dirpath\", sessionPath, \"error\", err)\n\t\t\treturn \"\"\n\t\t}\n\t}\n\n\tfilePath := fmt.Sprintf(\"%s/%s\", sessionPath, filename)\n\n\tf, err := os.OpenFile(filePath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)\n\tif err != nil {\n\t\tError(\"Failed to open session log file\", \"filepath\", filePath, \"error\", err)\n\t\treturn \"\"\n\t}\n\tdefer f.Close()\n\n\t// Append chunk to file\n\t_, err = f.WriteString(content)\n\tif err != nil {\n\t\tError(\"Failed to write chunk to session log file\", \"filepath\", filePath, \"error\", err)\n\t\treturn \"\"\n\t}\n\treturn filePath\n}\n\nfunc WriteRequestMessageJson(sessionId string, requestSeqId int, message any) string {\n\tif MessageDir == \"\" || sessionId == \"\" || requestSeqId <= 0 {\n\t\treturn \"\"\n\t}\n\tmsgJson, err := json.Marshal(message)\n\tif err != nil {\n\t\tError(\"Failed to marshal message\", \"session_id\", sessionId, \"request_seq_id\", requestSeqId, \"error\", err)\n\t\treturn \"\"\n\t}\n\treturn WriteRequestMessage(sessionId, requestSeqId, string(msgJson))\n}\n\nfunc WriteRequestMessage(sessionId string, requestSeqId int, message string) string {\n\tif MessageDir == \"\" || sessionId == \"\" || requestSeqId <= 0 {\n\t\treturn \"\"\n\t}\n\tfilename := fmt.Sprintf(\"%d_request.json\", requestSeqId)\n\n\treturn AppendToSessionLogFile(sessionId, filename, message)\n}\n\nfunc AppendToStreamSessionLogJson(sessionId string, requestSeqId int, jsonableChunk any) string {\n\tif MessageDir == \"\" || sessionId == \"\" || requestSeqId <= 0 {\n\t\treturn \"\"\n\t}\n\tchunkJson, err := json.Marshal(jsonableChunk)\n\tif err != nil {\n\t\tError(\"Failed to marshal message\", \"session_id\", sessionId, \"request_seq_id\", requestSeqId, \"error\", err)\n\t\treturn \"\"\n\t}\n\treturn AppendToStreamSessionLog(sessionId, requestSeqId, string(chunkJson))\n}\n\nfunc AppendToStreamSessionLog(sessionId string, requestSeqId int, chunk string) string {\n\tif MessageDir == \"\" || sessionId == \"\" || requestSeqId <= 0 {\n\t\treturn \"\"\n\t}\n\tfilename := fmt.Sprintf(\"%d_response_stream.log\", requestSeqId)\n\treturn AppendToSessionLogFile(sessionId, filename, chunk)\n}\n\nfunc WriteChatResponseJson(sessionId string, requestSeqId int, response any) string {\n\tif MessageDir == \"\" || sessionId == \"\" || requestSeqId <= 0 {\n\t\treturn \"\"\n\t}\n\tresponseJson, err := json.Marshal(response)\n\tif err != nil {\n\t\tError(\"Failed to marshal response\", \"session_id\", sessionId, \"request_seq_id\", requestSeqId, \"error\", err)\n\t\treturn \"\"\n\t}\n\tfilename := fmt.Sprintf(\"%d_response.json\", requestSeqId)\n\n\treturn AppendToSessionLogFile(sessionId, filename, string(responseJson))\n}\n\nfunc WriteToolResultsJson(sessionId string, requestSeqId int, toolResults any) string {\n\tif MessageDir == \"\" || sessionId == \"\" || requestSeqId <= 0 {\n\t\treturn \"\"\n\t}\n\ttoolResultsJson, err := json.Marshal(toolResults)\n\tif err != nil {\n\t\tError(\"Failed to marshal tool results\", \"session_id\", sessionId, \"request_seq_id\", requestSeqId, \"error\", err)\n\t\treturn \"\"\n\t}\n\tfilename := fmt.Sprintf(\"%d_tool_results.json\", requestSeqId)\n\treturn AppendToSessionLogFile(sessionId, filename, string(toolResultsJson))\n}\n"], ["/opencode/internal/lsp/handlers.go", "package lsp\n\nimport (\n\t\"encoding/json\"\n\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n\t\"github.com/opencode-ai/opencode/internal/lsp/protocol\"\n\t\"github.com/opencode-ai/opencode/internal/lsp/util\"\n)\n\n// Requests\n\nfunc HandleWorkspaceConfiguration(params json.RawMessage) (any, error) {\n\treturn []map[string]any{{}}, nil\n}\n\nfunc HandleRegisterCapability(params json.RawMessage) (any, error) {\n\tvar registerParams protocol.RegistrationParams\n\tif err := json.Unmarshal(params, ®isterParams); err != nil {\n\t\tlogging.Error(\"Error unmarshaling registration params\", \"error\", err)\n\t\treturn nil, err\n\t}\n\n\tfor _, reg := range registerParams.Registrations {\n\t\tswitch reg.Method {\n\t\tcase \"workspace/didChangeWatchedFiles\":\n\t\t\t// Parse the registration options\n\t\t\toptionsJSON, err := json.Marshal(reg.RegisterOptions)\n\t\t\tif err != nil {\n\t\t\t\tlogging.Error(\"Error marshaling registration options\", \"error\", err)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tvar options protocol.DidChangeWatchedFilesRegistrationOptions\n\t\t\tif err := json.Unmarshal(optionsJSON, &options); err != nil {\n\t\t\t\tlogging.Error(\"Error unmarshaling registration options\", \"error\", err)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// Store the file watchers registrations\n\t\t\tnotifyFileWatchRegistration(reg.ID, options.Watchers)\n\t\t}\n\t}\n\n\treturn nil, nil\n}\n\nfunc HandleApplyEdit(params json.RawMessage) (any, error) {\n\tvar edit protocol.ApplyWorkspaceEditParams\n\tif err := json.Unmarshal(params, &edit); err != nil {\n\t\treturn nil, err\n\t}\n\n\terr := util.ApplyWorkspaceEdit(edit.Edit)\n\tif err != nil {\n\t\tlogging.Error(\"Error applying workspace edit\", \"error\", err)\n\t\treturn protocol.ApplyWorkspaceEditResult{Applied: false, FailureReason: err.Error()}, nil\n\t}\n\n\treturn protocol.ApplyWorkspaceEditResult{Applied: true}, nil\n}\n\n// FileWatchRegistrationHandler is a function that will be called when file watch registrations are received\ntype FileWatchRegistrationHandler func(id string, watchers []protocol.FileSystemWatcher)\n\n// fileWatchHandler holds the current handler for file watch registrations\nvar fileWatchHandler FileWatchRegistrationHandler\n\n// RegisterFileWatchHandler sets the handler for file watch registrations\nfunc RegisterFileWatchHandler(handler FileWatchRegistrationHandler) {\n\tfileWatchHandler = handler\n}\n\n// notifyFileWatchRegistration notifies the handler about new file watch registrations\nfunc notifyFileWatchRegistration(id string, watchers []protocol.FileSystemWatcher) {\n\tif fileWatchHandler != nil {\n\t\tfileWatchHandler(id, watchers)\n\t}\n}\n\n// Notifications\n\nfunc HandleServerMessage(params json.RawMessage) {\n\tcnf := config.Get()\n\tvar msg struct {\n\t\tType int `json:\"type\"`\n\t\tMessage string `json:\"message\"`\n\t}\n\tif err := json.Unmarshal(params, &msg); err == nil {\n\t\tif cnf.DebugLSP {\n\t\t\tlogging.Debug(\"Server message\", \"type\", msg.Type, \"message\", msg.Message)\n\t\t}\n\t}\n}\n\nfunc HandleDiagnostics(client *Client, params json.RawMessage) {\n\tvar diagParams protocol.PublishDiagnosticsParams\n\tif err := json.Unmarshal(params, &diagParams); err != nil {\n\t\tlogging.Error(\"Error unmarshaling diagnostics params\", \"error\", err)\n\t\treturn\n\t}\n\n\tclient.diagnosticsMu.Lock()\n\tdefer client.diagnosticsMu.Unlock()\n\n\tclient.diagnostics[diagParams.URI] = diagParams.Diagnostics\n}\n"], ["/opencode/internal/db/messages.sql.go", "// Code generated by sqlc. DO NOT EDIT.\n// versions:\n// sqlc v1.29.0\n// source: messages.sql\n\npackage db\n\nimport (\n\t\"context\"\n\t\"database/sql\"\n)\n\nconst createMessage = `-- name: CreateMessage :one\nINSERT INTO messages (\n id,\n session_id,\n role,\n parts,\n model,\n created_at,\n updated_at\n) VALUES (\n ?, ?, ?, ?, ?, strftime('%s', 'now'), strftime('%s', 'now')\n)\nRETURNING id, session_id, role, parts, model, created_at, updated_at, finished_at\n`\n\ntype CreateMessageParams struct {\n\tID string `json:\"id\"`\n\tSessionID string `json:\"session_id\"`\n\tRole string `json:\"role\"`\n\tParts string `json:\"parts\"`\n\tModel sql.NullString `json:\"model\"`\n}\n\nfunc (q *Queries) CreateMessage(ctx context.Context, arg CreateMessageParams) (Message, error) {\n\trow := q.queryRow(ctx, q.createMessageStmt, createMessage,\n\t\targ.ID,\n\t\targ.SessionID,\n\t\targ.Role,\n\t\targ.Parts,\n\t\targ.Model,\n\t)\n\tvar i Message\n\terr := row.Scan(\n\t\t&i.ID,\n\t\t&i.SessionID,\n\t\t&i.Role,\n\t\t&i.Parts,\n\t\t&i.Model,\n\t\t&i.CreatedAt,\n\t\t&i.UpdatedAt,\n\t\t&i.FinishedAt,\n\t)\n\treturn i, err\n}\n\nconst deleteMessage = `-- name: DeleteMessage :exec\nDELETE FROM messages\nWHERE id = ?\n`\n\nfunc (q *Queries) DeleteMessage(ctx context.Context, id string) error {\n\t_, err := q.exec(ctx, q.deleteMessageStmt, deleteMessage, id)\n\treturn err\n}\n\nconst deleteSessionMessages = `-- name: DeleteSessionMessages :exec\nDELETE FROM messages\nWHERE session_id = ?\n`\n\nfunc (q *Queries) DeleteSessionMessages(ctx context.Context, sessionID string) error {\n\t_, err := q.exec(ctx, q.deleteSessionMessagesStmt, deleteSessionMessages, sessionID)\n\treturn err\n}\n\nconst getMessage = `-- name: GetMessage :one\nSELECT id, session_id, role, parts, model, created_at, updated_at, finished_at\nFROM messages\nWHERE id = ? LIMIT 1\n`\n\nfunc (q *Queries) GetMessage(ctx context.Context, id string) (Message, error) {\n\trow := q.queryRow(ctx, q.getMessageStmt, getMessage, id)\n\tvar i Message\n\terr := row.Scan(\n\t\t&i.ID,\n\t\t&i.SessionID,\n\t\t&i.Role,\n\t\t&i.Parts,\n\t\t&i.Model,\n\t\t&i.CreatedAt,\n\t\t&i.UpdatedAt,\n\t\t&i.FinishedAt,\n\t)\n\treturn i, err\n}\n\nconst listMessagesBySession = `-- name: ListMessagesBySession :many\nSELECT id, session_id, role, parts, model, created_at, updated_at, finished_at\nFROM messages\nWHERE session_id = ?\nORDER BY created_at ASC\n`\n\nfunc (q *Queries) ListMessagesBySession(ctx context.Context, sessionID string) ([]Message, error) {\n\trows, err := q.query(ctx, q.listMessagesBySessionStmt, listMessagesBySession, sessionID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer rows.Close()\n\titems := []Message{}\n\tfor rows.Next() {\n\t\tvar i Message\n\t\tif err := rows.Scan(\n\t\t\t&i.ID,\n\t\t\t&i.SessionID,\n\t\t\t&i.Role,\n\t\t\t&i.Parts,\n\t\t\t&i.Model,\n\t\t\t&i.CreatedAt,\n\t\t\t&i.UpdatedAt,\n\t\t\t&i.FinishedAt,\n\t\t); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\titems = append(items, i)\n\t}\n\tif err := rows.Close(); err != nil {\n\t\treturn nil, err\n\t}\n\tif err := rows.Err(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn items, nil\n}\n\nconst updateMessage = `-- name: UpdateMessage :exec\nUPDATE messages\nSET\n parts = ?,\n finished_at = ?,\n updated_at = strftime('%s', 'now')\nWHERE id = ?\n`\n\ntype UpdateMessageParams struct {\n\tParts string `json:\"parts\"`\n\tFinishedAt sql.NullInt64 `json:\"finished_at\"`\n\tID string `json:\"id\"`\n}\n\nfunc (q *Queries) UpdateMessage(ctx context.Context, arg UpdateMessageParams) error {\n\t_, err := q.exec(ctx, q.updateMessageStmt, updateMessage, arg.Parts, arg.FinishedAt, arg.ID)\n\treturn err\n}\n"], ["/opencode/internal/tui/theme/manager.go", "package theme\n\nimport (\n\t\"fmt\"\n\t\"slices\"\n\t\"strings\"\n\t\"sync\"\n\n\t\"github.com/alecthomas/chroma/v2/styles\"\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n)\n\n// Manager handles theme registration, selection, and retrieval.\n// It maintains a registry of available themes and tracks the currently active theme.\ntype Manager struct {\n\tthemes map[string]Theme\n\tcurrentName string\n\tmu sync.RWMutex\n}\n\n// Global instance of the theme manager\nvar globalManager = &Manager{\n\tthemes: make(map[string]Theme),\n\tcurrentName: \"\",\n}\n\n// RegisterTheme adds a new theme to the registry.\n// If this is the first theme registered, it becomes the default.\nfunc RegisterTheme(name string, theme Theme) {\n\tglobalManager.mu.Lock()\n\tdefer globalManager.mu.Unlock()\n\n\tglobalManager.themes[name] = theme\n\n\t// If this is the first theme, make it the default\n\tif globalManager.currentName == \"\" {\n\t\tglobalManager.currentName = name\n\t}\n}\n\n// SetTheme changes the active theme to the one with the specified name.\n// Returns an error if the theme doesn't exist.\nfunc SetTheme(name string) error {\n\tglobalManager.mu.Lock()\n\tdefer globalManager.mu.Unlock()\n\n\tdelete(styles.Registry, \"charm\")\n\tif _, exists := globalManager.themes[name]; !exists {\n\t\treturn fmt.Errorf(\"theme '%s' not found\", name)\n\t}\n\n\tglobalManager.currentName = name\n\n\t// Update the config file using viper\n\tif err := updateConfigTheme(name); err != nil {\n\t\t// Log the error but don't fail the theme change\n\t\tlogging.Warn(\"Warning: Failed to update config file with new theme\", \"err\", err)\n\t}\n\n\treturn nil\n}\n\n// CurrentTheme returns the currently active theme.\n// If no theme is set, it returns nil.\nfunc CurrentTheme() Theme {\n\tglobalManager.mu.RLock()\n\tdefer globalManager.mu.RUnlock()\n\n\tif globalManager.currentName == \"\" {\n\t\treturn nil\n\t}\n\n\treturn globalManager.themes[globalManager.currentName]\n}\n\n// CurrentThemeName returns the name of the currently active theme.\nfunc CurrentThemeName() string {\n\tglobalManager.mu.RLock()\n\tdefer globalManager.mu.RUnlock()\n\n\treturn globalManager.currentName\n}\n\n// AvailableThemes returns a list of all registered theme names.\nfunc AvailableThemes() []string {\n\tglobalManager.mu.RLock()\n\tdefer globalManager.mu.RUnlock()\n\n\tnames := make([]string, 0, len(globalManager.themes))\n\tfor name := range globalManager.themes {\n\t\tnames = append(names, name)\n\t}\n\tslices.SortFunc(names, func(a, b string) int {\n\t\tif a == \"opencode\" {\n\t\t\treturn -1\n\t\t} else if b == \"opencode\" {\n\t\t\treturn 1\n\t\t}\n\t\treturn strings.Compare(a, b)\n\t})\n\treturn names\n}\n\n// GetTheme returns a specific theme by name.\n// Returns nil if the theme doesn't exist.\nfunc GetTheme(name string) Theme {\n\tglobalManager.mu.RLock()\n\tdefer globalManager.mu.RUnlock()\n\n\treturn globalManager.themes[name]\n}\n\n// updateConfigTheme updates the theme setting in the configuration file\nfunc updateConfigTheme(themeName string) error {\n\t// Use the config package to update the theme\n\treturn config.UpdateTheme(themeName)\n}\n"], ["/opencode/internal/llm/provider/bedrock.go", "package provider\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"os\"\n\t\"strings\"\n\n\t\"github.com/opencode-ai/opencode/internal/llm/tools\"\n\t\"github.com/opencode-ai/opencode/internal/message\"\n)\n\ntype bedrockOptions struct {\n\t// Bedrock specific options can be added here\n}\n\ntype BedrockOption func(*bedrockOptions)\n\ntype bedrockClient struct {\n\tproviderOptions providerClientOptions\n\toptions bedrockOptions\n\tchildProvider ProviderClient\n}\n\ntype BedrockClient ProviderClient\n\nfunc newBedrockClient(opts providerClientOptions) BedrockClient {\n\tbedrockOpts := bedrockOptions{}\n\t// Apply bedrock specific options if they are added in the future\n\n\t// Get AWS region from environment\n\tregion := os.Getenv(\"AWS_REGION\")\n\tif region == \"\" {\n\t\tregion = os.Getenv(\"AWS_DEFAULT_REGION\")\n\t}\n\n\tif region == \"\" {\n\t\tregion = \"us-east-1\" // default region\n\t}\n\tif len(region) < 2 {\n\t\treturn &bedrockClient{\n\t\t\tproviderOptions: opts,\n\t\t\toptions: bedrockOpts,\n\t\t\tchildProvider: nil, // Will cause an error when used\n\t\t}\n\t}\n\n\t// Prefix the model name with region\n\tregionPrefix := region[:2]\n\tmodelName := opts.model.APIModel\n\topts.model.APIModel = fmt.Sprintf(\"%s.%s\", regionPrefix, modelName)\n\n\t// Determine which provider to use based on the model\n\tif strings.Contains(string(opts.model.APIModel), \"anthropic\") {\n\t\t// Create Anthropic client with Bedrock configuration\n\t\tanthropicOpts := opts\n\t\tanthropicOpts.anthropicOptions = append(anthropicOpts.anthropicOptions,\n\t\t\tWithAnthropicBedrock(true),\n\t\t\tWithAnthropicDisableCache(),\n\t\t)\n\t\treturn &bedrockClient{\n\t\t\tproviderOptions: opts,\n\t\t\toptions: bedrockOpts,\n\t\t\tchildProvider: newAnthropicClient(anthropicOpts),\n\t\t}\n\t}\n\n\t// Return client with nil childProvider if model is not supported\n\t// This will cause an error when used\n\treturn &bedrockClient{\n\t\tproviderOptions: opts,\n\t\toptions: bedrockOpts,\n\t\tchildProvider: nil,\n\t}\n}\n\nfunc (b *bedrockClient) send(ctx context.Context, messages []message.Message, tools []tools.BaseTool) (*ProviderResponse, error) {\n\tif b.childProvider == nil {\n\t\treturn nil, errors.New(\"unsupported model for bedrock provider\")\n\t}\n\treturn b.childProvider.send(ctx, messages, tools)\n}\n\nfunc (b *bedrockClient) stream(ctx context.Context, messages []message.Message, tools []tools.BaseTool) <-chan ProviderEvent {\n\teventChan := make(chan ProviderEvent)\n\n\tif b.childProvider == nil {\n\t\tgo func() {\n\t\t\teventChan <- ProviderEvent{\n\t\t\t\tType: EventError,\n\t\t\t\tError: errors.New(\"unsupported model for bedrock provider\"),\n\t\t\t}\n\t\t\tclose(eventChan)\n\t\t}()\n\t\treturn eventChan\n\t}\n\n\treturn b.childProvider.stream(ctx, messages, tools)\n}\n\n"], ["/opencode/internal/lsp/protocol/uri.go", "// Copyright 2023 The Go Authors. All rights reserved.\n// Use of this source code is governed by a BSD-style\n// license that can be found in the LICENSE file.\n\npackage protocol\n\n// This file declares URI, DocumentUri, and its methods.\n//\n// For the LSP definition of these types, see\n// https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#uri\n\nimport (\n\t\"fmt\"\n\t\"net/url\"\n\t\"path/filepath\"\n\t\"strings\"\n\t\"unicode\"\n)\n\n// A DocumentUri is the URI of a client editor document.\n//\n// According to the LSP specification:\n//\n//\tCare should be taken to handle encoding in URIs. For\n//\texample, some clients (such as VS Code) may encode colons\n//\tin drive letters while others do not. The URIs below are\n//\tboth valid, but clients and servers should be consistent\n//\twith the form they use themselves to ensure the other party\n//\tdoesn’t interpret them as distinct URIs. Clients and\n//\tservers should not assume that each other are encoding the\n//\tsame way (for example a client encoding colons in drive\n//\tletters cannot assume server responses will have encoded\n//\tcolons). The same applies to casing of drive letters - one\n//\tparty should not assume the other party will return paths\n//\twith drive letters cased the same as it.\n//\n//\tfile:///c:/project/readme.md\n//\tfile:///C%3A/project/readme.md\n//\n// This is done during JSON unmarshalling;\n// see [DocumentUri.UnmarshalText] for details.\ntype DocumentUri string\n\n// A URI is an arbitrary URL (e.g. https), not necessarily a file.\ntype URI = string\n\n// UnmarshalText implements decoding of DocumentUri values.\n//\n// In particular, it implements a systematic correction of various odd\n// features of the definition of DocumentUri in the LSP spec that\n// appear to be workarounds for bugs in VS Code. For example, it may\n// URI-encode the URI itself, so that colon becomes %3A, and it may\n// send file://foo.go URIs that have two slashes (not three) and no\n// hostname.\n//\n// We use UnmarshalText, not UnmarshalJSON, because it is called even\n// for non-addressable values such as keys and values of map[K]V,\n// where there is no pointer of type *K or *V on which to call\n// UnmarshalJSON. (See Go issue #28189 for more detail.)\n//\n// Non-empty DocumentUris are valid \"file\"-scheme URIs.\n// The empty DocumentUri is valid.\nfunc (uri *DocumentUri) UnmarshalText(data []byte) (err error) {\n\t*uri, err = ParseDocumentUri(string(data))\n\treturn\n}\n\n// Path returns the file path for the given URI.\n//\n// DocumentUri(\"\").Path() returns the empty string.\n//\n// Path panics if called on a URI that is not a valid filename.\nfunc (uri DocumentUri) Path() string {\n\tfilename, err := filename(uri)\n\tif err != nil {\n\t\t// e.g. ParseRequestURI failed.\n\t\t//\n\t\t// This can only affect DocumentUris created by\n\t\t// direct string manipulation; all DocumentUris\n\t\t// received from the client pass through\n\t\t// ParseRequestURI, which ensures validity.\n\t\tpanic(err)\n\t}\n\treturn filepath.FromSlash(filename)\n}\n\n// Dir returns the URI for the directory containing the receiver.\nfunc (uri DocumentUri) Dir() DocumentUri {\n\t// This function could be more efficiently implemented by avoiding any call\n\t// to Path(), but at least consolidates URI manipulation.\n\treturn URIFromPath(uri.DirPath())\n}\n\n// DirPath returns the file path to the directory containing this URI, which\n// must be a file URI.\nfunc (uri DocumentUri) DirPath() string {\n\treturn filepath.Dir(uri.Path())\n}\n\nfunc filename(uri DocumentUri) (string, error) {\n\tif uri == \"\" {\n\t\treturn \"\", nil\n\t}\n\n\t// This conservative check for the common case\n\t// of a simple non-empty absolute POSIX filename\n\t// avoids the allocation of a net.URL.\n\tif strings.HasPrefix(string(uri), \"file:///\") {\n\t\trest := string(uri)[len(\"file://\"):] // leave one slash\n\t\tfor i := range len(rest) {\n\t\t\tb := rest[i]\n\t\t\t// Reject these cases:\n\t\t\tif b < ' ' || b == 0x7f || // control character\n\t\t\t\tb == '%' || b == '+' || // URI escape\n\t\t\t\tb == ':' || // Windows drive letter\n\t\t\t\tb == '@' || b == '&' || b == '?' { // authority or query\n\t\t\t\tgoto slow\n\t\t\t}\n\t\t}\n\t\treturn rest, nil\n\t}\nslow:\n\n\tu, err := url.ParseRequestURI(string(uri))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tif u.Scheme != fileScheme {\n\t\treturn \"\", fmt.Errorf(\"only file URIs are supported, got %q from %q\", u.Scheme, uri)\n\t}\n\t// If the URI is a Windows URI, we trim the leading \"/\" and uppercase\n\t// the drive letter, which will never be case sensitive.\n\tif isWindowsDriveURIPath(u.Path) {\n\t\tu.Path = strings.ToUpper(string(u.Path[1])) + u.Path[2:]\n\t}\n\n\treturn u.Path, nil\n}\n\n// ParseDocumentUri interprets a string as a DocumentUri, applying VS\n// Code workarounds; see [DocumentUri.UnmarshalText] for details.\nfunc ParseDocumentUri(s string) (DocumentUri, error) {\n\tif s == \"\" {\n\t\treturn \"\", nil\n\t}\n\n\tif !strings.HasPrefix(s, \"file://\") {\n\t\treturn \"\", fmt.Errorf(\"DocumentUri scheme is not 'file': %s\", s)\n\t}\n\n\t// VS Code sends URLs with only two slashes,\n\t// which are invalid. golang/go#39789.\n\tif !strings.HasPrefix(s, \"file:///\") {\n\t\ts = \"file:///\" + s[len(\"file://\"):]\n\t}\n\n\t// Even though the input is a URI, it may not be in canonical form. VS Code\n\t// in particular over-escapes :, @, etc. Unescape and re-encode to canonicalize.\n\tpath, err := url.PathUnescape(s[len(\"file://\"):])\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t// File URIs from Windows may have lowercase drive letters.\n\t// Since drive letters are guaranteed to be case insensitive,\n\t// we change them to uppercase to remain consistent.\n\t// For example, file:///c:/x/y/z becomes file:///C:/x/y/z.\n\tif isWindowsDriveURIPath(path) {\n\t\tpath = path[:1] + strings.ToUpper(string(path[1])) + path[2:]\n\t}\n\tu := url.URL{Scheme: fileScheme, Path: path}\n\treturn DocumentUri(u.String()), nil\n}\n\n// URIFromPath returns DocumentUri for the supplied file path.\n// Given \"\", it returns \"\".\nfunc URIFromPath(path string) DocumentUri {\n\tif path == \"\" {\n\t\treturn \"\"\n\t}\n\tif !isWindowsDrivePath(path) {\n\t\tif abs, err := filepath.Abs(path); err == nil {\n\t\t\tpath = abs\n\t\t}\n\t}\n\t// Check the file path again, in case it became absolute.\n\tif isWindowsDrivePath(path) {\n\t\tpath = \"/\" + strings.ToUpper(string(path[0])) + path[1:]\n\t}\n\tpath = filepath.ToSlash(path)\n\tu := url.URL{\n\t\tScheme: fileScheme,\n\t\tPath: path,\n\t}\n\treturn DocumentUri(u.String())\n}\n\nconst fileScheme = \"file\"\n\n// isWindowsDrivePath returns true if the file path is of the form used by\n// Windows. We check if the path begins with a drive letter, followed by a \":\".\n// For example: C:/x/y/z.\nfunc isWindowsDrivePath(path string) bool {\n\tif len(path) < 3 {\n\t\treturn false\n\t}\n\treturn unicode.IsLetter(rune(path[0])) && path[1] == ':'\n}\n\n// isWindowsDriveURIPath returns true if the file URI is of the format used by\n// Windows URIs. The url.Parse package does not specially handle Windows paths\n// (see golang/go#6027), so we check if the URI path has a drive prefix (e.g. \"/C:\").\nfunc isWindowsDriveURIPath(uri string) bool {\n\tif len(uri) < 4 {\n\t\treturn false\n\t}\n\treturn uri[0] == '/' && unicode.IsLetter(rune(uri[1])) && uri[2] == ':'\n}\n"], ["/opencode/internal/llm/agent/tools.go", "package agent\n\nimport (\n\t\"context\"\n\n\t\"github.com/opencode-ai/opencode/internal/history\"\n\t\"github.com/opencode-ai/opencode/internal/llm/tools\"\n\t\"github.com/opencode-ai/opencode/internal/lsp\"\n\t\"github.com/opencode-ai/opencode/internal/message\"\n\t\"github.com/opencode-ai/opencode/internal/permission\"\n\t\"github.com/opencode-ai/opencode/internal/session\"\n)\n\nfunc CoderAgentTools(\n\tpermissions permission.Service,\n\tsessions session.Service,\n\tmessages message.Service,\n\thistory history.Service,\n\tlspClients map[string]*lsp.Client,\n) []tools.BaseTool {\n\tctx := context.Background()\n\totherTools := GetMcpTools(ctx, permissions)\n\tif len(lspClients) > 0 {\n\t\totherTools = append(otherTools, tools.NewDiagnosticsTool(lspClients))\n\t}\n\treturn append(\n\t\t[]tools.BaseTool{\n\t\t\ttools.NewBashTool(permissions),\n\t\t\ttools.NewEditTool(lspClients, permissions, history),\n\t\t\ttools.NewFetchTool(permissions),\n\t\t\ttools.NewGlobTool(),\n\t\t\ttools.NewGrepTool(),\n\t\t\ttools.NewLsTool(),\n\t\t\ttools.NewSourcegraphTool(),\n\t\t\ttools.NewViewTool(lspClients),\n\t\t\ttools.NewPatchTool(lspClients, permissions, history),\n\t\t\ttools.NewWriteTool(lspClients, permissions, history),\n\t\t\tNewAgentTool(sessions, messages, lspClients),\n\t\t}, otherTools...,\n\t)\n}\n\nfunc TaskAgentTools(lspClients map[string]*lsp.Client) []tools.BaseTool {\n\treturn []tools.BaseTool{\n\t\ttools.NewGlobTool(),\n\t\ttools.NewGrepTool(),\n\t\ttools.NewLsTool(),\n\t\ttools.NewSourcegraphTool(),\n\t\ttools.NewViewTool(lspClients),\n\t}\n}\n"], ["/opencode/cmd/schema/main.go", "package main\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"os\"\n\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/llm/models\"\n)\n\n// JSONSchemaType represents a JSON Schema type\ntype JSONSchemaType struct {\n\tType string `json:\"type,omitempty\"`\n\tDescription string `json:\"description,omitempty\"`\n\tProperties map[string]any `json:\"properties,omitempty\"`\n\tRequired []string `json:\"required,omitempty\"`\n\tAdditionalProperties any `json:\"additionalProperties,omitempty\"`\n\tEnum []any `json:\"enum,omitempty\"`\n\tItems map[string]any `json:\"items,omitempty\"`\n\tOneOf []map[string]any `json:\"oneOf,omitempty\"`\n\tAnyOf []map[string]any `json:\"anyOf,omitempty\"`\n\tDefault any `json:\"default,omitempty\"`\n}\n\nfunc main() {\n\tschema := generateSchema()\n\n\t// Pretty print the schema\n\tencoder := json.NewEncoder(os.Stdout)\n\tencoder.SetIndent(\"\", \" \")\n\tif err := encoder.Encode(schema); err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"Error encoding schema: %v\\n\", err)\n\t\tos.Exit(1)\n\t}\n}\n\nfunc generateSchema() map[string]any {\n\tschema := map[string]any{\n\t\t\"$schema\": \"http://json-schema.org/draft-07/schema#\",\n\t\t\"title\": \"OpenCode Configuration\",\n\t\t\"description\": \"Configuration schema for the OpenCode application\",\n\t\t\"type\": \"object\",\n\t\t\"properties\": map[string]any{},\n\t}\n\n\t// Add Data configuration\n\tschema[\"properties\"].(map[string]any)[\"data\"] = map[string]any{\n\t\t\"type\": \"object\",\n\t\t\"description\": \"Storage configuration\",\n\t\t\"properties\": map[string]any{\n\t\t\t\"directory\": map[string]any{\n\t\t\t\t\"type\": \"string\",\n\t\t\t\t\"description\": \"Directory where application data is stored\",\n\t\t\t\t\"default\": \".opencode\",\n\t\t\t},\n\t\t},\n\t\t\"required\": []string{\"directory\"},\n\t}\n\n\t// Add working directory\n\tschema[\"properties\"].(map[string]any)[\"wd\"] = map[string]any{\n\t\t\"type\": \"string\",\n\t\t\"description\": \"Working directory for the application\",\n\t}\n\n\t// Add debug flags\n\tschema[\"properties\"].(map[string]any)[\"debug\"] = map[string]any{\n\t\t\"type\": \"boolean\",\n\t\t\"description\": \"Enable debug mode\",\n\t\t\"default\": false,\n\t}\n\n\tschema[\"properties\"].(map[string]any)[\"debugLSP\"] = map[string]any{\n\t\t\"type\": \"boolean\",\n\t\t\"description\": \"Enable LSP debug mode\",\n\t\t\"default\": false,\n\t}\n\n\tschema[\"properties\"].(map[string]any)[\"contextPaths\"] = map[string]any{\n\t\t\"type\": \"array\",\n\t\t\"description\": \"Context paths for the application\",\n\t\t\"items\": map[string]any{\n\t\t\t\"type\": \"string\",\n\t\t},\n\t\t\"default\": []string{\n\t\t\t\".github/copilot-instructions.md\",\n\t\t\t\".cursorrules\",\n\t\t\t\".cursor/rules/\",\n\t\t\t\"CLAUDE.md\",\n\t\t\t\"CLAUDE.local.md\",\n\t\t\t\"opencode.md\",\n\t\t\t\"opencode.local.md\",\n\t\t\t\"OpenCode.md\",\n\t\t\t\"OpenCode.local.md\",\n\t\t\t\"OPENCODE.md\",\n\t\t\t\"OPENCODE.local.md\",\n\t\t},\n\t}\n\n\tschema[\"properties\"].(map[string]any)[\"tui\"] = map[string]any{\n\t\t\"type\": \"object\",\n\t\t\"description\": \"Terminal User Interface configuration\",\n\t\t\"properties\": map[string]any{\n\t\t\t\"theme\": map[string]any{\n\t\t\t\t\"type\": \"string\",\n\t\t\t\t\"description\": \"TUI theme name\",\n\t\t\t\t\"default\": \"opencode\",\n\t\t\t\t\"enum\": []string{\n\t\t\t\t\t\"opencode\",\n\t\t\t\t\t\"catppuccin\",\n\t\t\t\t\t\"dracula\",\n\t\t\t\t\t\"flexoki\",\n\t\t\t\t\t\"gruvbox\",\n\t\t\t\t\t\"monokai\",\n\t\t\t\t\t\"onedark\",\n\t\t\t\t\t\"tokyonight\",\n\t\t\t\t\t\"tron\",\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\t// Add MCP servers\n\tschema[\"properties\"].(map[string]any)[\"mcpServers\"] = map[string]any{\n\t\t\"type\": \"object\",\n\t\t\"description\": \"Model Control Protocol server configurations\",\n\t\t\"additionalProperties\": map[string]any{\n\t\t\t\"type\": \"object\",\n\t\t\t\"description\": \"MCP server configuration\",\n\t\t\t\"properties\": map[string]any{\n\t\t\t\t\"command\": map[string]any{\n\t\t\t\t\t\"type\": \"string\",\n\t\t\t\t\t\"description\": \"Command to execute for the MCP server\",\n\t\t\t\t},\n\t\t\t\t\"env\": map[string]any{\n\t\t\t\t\t\"type\": \"array\",\n\t\t\t\t\t\"description\": \"Environment variables for the MCP server\",\n\t\t\t\t\t\"items\": map[string]any{\n\t\t\t\t\t\t\"type\": \"string\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t\"args\": map[string]any{\n\t\t\t\t\t\"type\": \"array\",\n\t\t\t\t\t\"description\": \"Command arguments for the MCP server\",\n\t\t\t\t\t\"items\": map[string]any{\n\t\t\t\t\t\t\"type\": \"string\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t\"type\": map[string]any{\n\t\t\t\t\t\"type\": \"string\",\n\t\t\t\t\t\"description\": \"Type of MCP server\",\n\t\t\t\t\t\"enum\": []string{\"stdio\", \"sse\"},\n\t\t\t\t\t\"default\": \"stdio\",\n\t\t\t\t},\n\t\t\t\t\"url\": map[string]any{\n\t\t\t\t\t\"type\": \"string\",\n\t\t\t\t\t\"description\": \"URL for SSE type MCP servers\",\n\t\t\t\t},\n\t\t\t\t\"headers\": map[string]any{\n\t\t\t\t\t\"type\": \"object\",\n\t\t\t\t\t\"description\": \"HTTP headers for SSE type MCP servers\",\n\t\t\t\t\t\"additionalProperties\": map[string]any{\n\t\t\t\t\t\t\"type\": \"string\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\t\"required\": []string{\"command\"},\n\t\t},\n\t}\n\n\t// Add providers\n\tproviderSchema := map[string]any{\n\t\t\"type\": \"object\",\n\t\t\"description\": \"LLM provider configurations\",\n\t\t\"additionalProperties\": map[string]any{\n\t\t\t\"type\": \"object\",\n\t\t\t\"description\": \"Provider configuration\",\n\t\t\t\"properties\": map[string]any{\n\t\t\t\t\"apiKey\": map[string]any{\n\t\t\t\t\t\"type\": \"string\",\n\t\t\t\t\t\"description\": \"API key for the provider\",\n\t\t\t\t},\n\t\t\t\t\"disabled\": map[string]any{\n\t\t\t\t\t\"type\": \"boolean\",\n\t\t\t\t\t\"description\": \"Whether the provider is disabled\",\n\t\t\t\t\t\"default\": false,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\t// Add known providers\n\tknownProviders := []string{\n\t\tstring(models.ProviderAnthropic),\n\t\tstring(models.ProviderOpenAI),\n\t\tstring(models.ProviderGemini),\n\t\tstring(models.ProviderGROQ),\n\t\tstring(models.ProviderOpenRouter),\n\t\tstring(models.ProviderBedrock),\n\t\tstring(models.ProviderAzure),\n\t\tstring(models.ProviderVertexAI),\n\t}\n\n\tproviderSchema[\"additionalProperties\"].(map[string]any)[\"properties\"].(map[string]any)[\"provider\"] = map[string]any{\n\t\t\"type\": \"string\",\n\t\t\"description\": \"Provider type\",\n\t\t\"enum\": knownProviders,\n\t}\n\n\tschema[\"properties\"].(map[string]any)[\"providers\"] = providerSchema\n\n\t// Add agents\n\tagentSchema := map[string]any{\n\t\t\"type\": \"object\",\n\t\t\"description\": \"Agent configurations\",\n\t\t\"additionalProperties\": map[string]any{\n\t\t\t\"type\": \"object\",\n\t\t\t\"description\": \"Agent configuration\",\n\t\t\t\"properties\": map[string]any{\n\t\t\t\t\"model\": map[string]any{\n\t\t\t\t\t\"type\": \"string\",\n\t\t\t\t\t\"description\": \"Model ID for the agent\",\n\t\t\t\t},\n\t\t\t\t\"maxTokens\": map[string]any{\n\t\t\t\t\t\"type\": \"integer\",\n\t\t\t\t\t\"description\": \"Maximum tokens for the agent\",\n\t\t\t\t\t\"minimum\": 1,\n\t\t\t\t},\n\t\t\t\t\"reasoningEffort\": map[string]any{\n\t\t\t\t\t\"type\": \"string\",\n\t\t\t\t\t\"description\": \"Reasoning effort for models that support it (OpenAI, Anthropic)\",\n\t\t\t\t\t\"enum\": []string{\"low\", \"medium\", \"high\"},\n\t\t\t\t},\n\t\t\t},\n\t\t\t\"required\": []string{\"model\"},\n\t\t},\n\t}\n\n\t// Add model enum\n\tmodelEnum := []string{}\n\tfor modelID := range models.SupportedModels {\n\t\tmodelEnum = append(modelEnum, string(modelID))\n\t}\n\tagentSchema[\"additionalProperties\"].(map[string]any)[\"properties\"].(map[string]any)[\"model\"].(map[string]any)[\"enum\"] = modelEnum\n\n\t// Add specific agent properties\n\tagentProperties := map[string]any{}\n\tknownAgents := []string{\n\t\tstring(config.AgentCoder),\n\t\tstring(config.AgentTask),\n\t\tstring(config.AgentTitle),\n\t}\n\n\tfor _, agentName := range knownAgents {\n\t\tagentProperties[agentName] = map[string]any{\n\t\t\t\"$ref\": \"#/definitions/agent\",\n\t\t}\n\t}\n\n\t// Create a combined schema that allows both specific agents and additional ones\n\tcombinedAgentSchema := map[string]any{\n\t\t\"type\": \"object\",\n\t\t\"description\": \"Agent configurations\",\n\t\t\"properties\": agentProperties,\n\t\t\"additionalProperties\": agentSchema[\"additionalProperties\"],\n\t}\n\n\tschema[\"properties\"].(map[string]any)[\"agents\"] = combinedAgentSchema\n\tschema[\"definitions\"] = map[string]any{\n\t\t\"agent\": agentSchema[\"additionalProperties\"],\n\t}\n\n\t// Add LSP configuration\n\tschema[\"properties\"].(map[string]any)[\"lsp\"] = map[string]any{\n\t\t\"type\": \"object\",\n\t\t\"description\": \"Language Server Protocol configurations\",\n\t\t\"additionalProperties\": map[string]any{\n\t\t\t\"type\": \"object\",\n\t\t\t\"description\": \"LSP configuration for a language\",\n\t\t\t\"properties\": map[string]any{\n\t\t\t\t\"disabled\": map[string]any{\n\t\t\t\t\t\"type\": \"boolean\",\n\t\t\t\t\t\"description\": \"Whether the LSP is disabled\",\n\t\t\t\t\t\"default\": false,\n\t\t\t\t},\n\t\t\t\t\"command\": map[string]any{\n\t\t\t\t\t\"type\": \"string\",\n\t\t\t\t\t\"description\": \"Command to execute for the LSP server\",\n\t\t\t\t},\n\t\t\t\t\"args\": map[string]any{\n\t\t\t\t\t\"type\": \"array\",\n\t\t\t\t\t\"description\": \"Command arguments for the LSP server\",\n\t\t\t\t\t\"items\": map[string]any{\n\t\t\t\t\t\t\"type\": \"string\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t\"options\": map[string]any{\n\t\t\t\t\t\"type\": \"object\",\n\t\t\t\t\t\"description\": \"Additional options for the LSP server\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t\"required\": []string{\"command\"},\n\t\t},\n\t}\n\n\treturn schema\n}\n"], ["/opencode/internal/db/files.sql.go", "// Code generated by sqlc. DO NOT EDIT.\n// versions:\n// sqlc v1.29.0\n// source: files.sql\n\npackage db\n\nimport (\n\t\"context\"\n)\n\nconst createFile = `-- name: CreateFile :one\nINSERT INTO files (\n id,\n session_id,\n path,\n content,\n version,\n created_at,\n updated_at\n) VALUES (\n ?, ?, ?, ?, ?, strftime('%s', 'now'), strftime('%s', 'now')\n)\nRETURNING id, session_id, path, content, version, created_at, updated_at\n`\n\ntype CreateFileParams struct {\n\tID string `json:\"id\"`\n\tSessionID string `json:\"session_id\"`\n\tPath string `json:\"path\"`\n\tContent string `json:\"content\"`\n\tVersion string `json:\"version\"`\n}\n\nfunc (q *Queries) CreateFile(ctx context.Context, arg CreateFileParams) (File, error) {\n\trow := q.queryRow(ctx, q.createFileStmt, createFile,\n\t\targ.ID,\n\t\targ.SessionID,\n\t\targ.Path,\n\t\targ.Content,\n\t\targ.Version,\n\t)\n\tvar i File\n\terr := row.Scan(\n\t\t&i.ID,\n\t\t&i.SessionID,\n\t\t&i.Path,\n\t\t&i.Content,\n\t\t&i.Version,\n\t\t&i.CreatedAt,\n\t\t&i.UpdatedAt,\n\t)\n\treturn i, err\n}\n\nconst deleteFile = `-- name: DeleteFile :exec\nDELETE FROM files\nWHERE id = ?\n`\n\nfunc (q *Queries) DeleteFile(ctx context.Context, id string) error {\n\t_, err := q.exec(ctx, q.deleteFileStmt, deleteFile, id)\n\treturn err\n}\n\nconst deleteSessionFiles = `-- name: DeleteSessionFiles :exec\nDELETE FROM files\nWHERE session_id = ?\n`\n\nfunc (q *Queries) DeleteSessionFiles(ctx context.Context, sessionID string) error {\n\t_, err := q.exec(ctx, q.deleteSessionFilesStmt, deleteSessionFiles, sessionID)\n\treturn err\n}\n\nconst getFile = `-- name: GetFile :one\nSELECT id, session_id, path, content, version, created_at, updated_at\nFROM files\nWHERE id = ? LIMIT 1\n`\n\nfunc (q *Queries) GetFile(ctx context.Context, id string) (File, error) {\n\trow := q.queryRow(ctx, q.getFileStmt, getFile, id)\n\tvar i File\n\terr := row.Scan(\n\t\t&i.ID,\n\t\t&i.SessionID,\n\t\t&i.Path,\n\t\t&i.Content,\n\t\t&i.Version,\n\t\t&i.CreatedAt,\n\t\t&i.UpdatedAt,\n\t)\n\treturn i, err\n}\n\nconst getFileByPathAndSession = `-- name: GetFileByPathAndSession :one\nSELECT id, session_id, path, content, version, created_at, updated_at\nFROM files\nWHERE path = ? AND session_id = ?\nORDER BY created_at DESC\nLIMIT 1\n`\n\ntype GetFileByPathAndSessionParams struct {\n\tPath string `json:\"path\"`\n\tSessionID string `json:\"session_id\"`\n}\n\nfunc (q *Queries) GetFileByPathAndSession(ctx context.Context, arg GetFileByPathAndSessionParams) (File, error) {\n\trow := q.queryRow(ctx, q.getFileByPathAndSessionStmt, getFileByPathAndSession, arg.Path, arg.SessionID)\n\tvar i File\n\terr := row.Scan(\n\t\t&i.ID,\n\t\t&i.SessionID,\n\t\t&i.Path,\n\t\t&i.Content,\n\t\t&i.Version,\n\t\t&i.CreatedAt,\n\t\t&i.UpdatedAt,\n\t)\n\treturn i, err\n}\n\nconst listFilesByPath = `-- name: ListFilesByPath :many\nSELECT id, session_id, path, content, version, created_at, updated_at\nFROM files\nWHERE path = ?\nORDER BY created_at DESC\n`\n\nfunc (q *Queries) ListFilesByPath(ctx context.Context, path string) ([]File, error) {\n\trows, err := q.query(ctx, q.listFilesByPathStmt, listFilesByPath, path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer rows.Close()\n\titems := []File{}\n\tfor rows.Next() {\n\t\tvar i File\n\t\tif err := rows.Scan(\n\t\t\t&i.ID,\n\t\t\t&i.SessionID,\n\t\t\t&i.Path,\n\t\t\t&i.Content,\n\t\t\t&i.Version,\n\t\t\t&i.CreatedAt,\n\t\t\t&i.UpdatedAt,\n\t\t); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\titems = append(items, i)\n\t}\n\tif err := rows.Close(); err != nil {\n\t\treturn nil, err\n\t}\n\tif err := rows.Err(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn items, nil\n}\n\nconst listFilesBySession = `-- name: ListFilesBySession :many\nSELECT id, session_id, path, content, version, created_at, updated_at\nFROM files\nWHERE session_id = ?\nORDER BY created_at ASC\n`\n\nfunc (q *Queries) ListFilesBySession(ctx context.Context, sessionID string) ([]File, error) {\n\trows, err := q.query(ctx, q.listFilesBySessionStmt, listFilesBySession, sessionID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer rows.Close()\n\titems := []File{}\n\tfor rows.Next() {\n\t\tvar i File\n\t\tif err := rows.Scan(\n\t\t\t&i.ID,\n\t\t\t&i.SessionID,\n\t\t\t&i.Path,\n\t\t\t&i.Content,\n\t\t\t&i.Version,\n\t\t\t&i.CreatedAt,\n\t\t\t&i.UpdatedAt,\n\t\t); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\titems = append(items, i)\n\t}\n\tif err := rows.Close(); err != nil {\n\t\treturn nil, err\n\t}\n\tif err := rows.Err(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn items, nil\n}\n\nconst listLatestSessionFiles = `-- name: ListLatestSessionFiles :many\nSELECT f.id, f.session_id, f.path, f.content, f.version, f.created_at, f.updated_at\nFROM files f\nINNER JOIN (\n SELECT path, MAX(created_at) as max_created_at\n FROM files\n GROUP BY path\n) latest ON f.path = latest.path AND f.created_at = latest.max_created_at\nWHERE f.session_id = ?\nORDER BY f.path\n`\n\nfunc (q *Queries) ListLatestSessionFiles(ctx context.Context, sessionID string) ([]File, error) {\n\trows, err := q.query(ctx, q.listLatestSessionFilesStmt, listLatestSessionFiles, sessionID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer rows.Close()\n\titems := []File{}\n\tfor rows.Next() {\n\t\tvar i File\n\t\tif err := rows.Scan(\n\t\t\t&i.ID,\n\t\t\t&i.SessionID,\n\t\t\t&i.Path,\n\t\t\t&i.Content,\n\t\t\t&i.Version,\n\t\t\t&i.CreatedAt,\n\t\t\t&i.UpdatedAt,\n\t\t); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\titems = append(items, i)\n\t}\n\tif err := rows.Close(); err != nil {\n\t\treturn nil, err\n\t}\n\tif err := rows.Err(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn items, nil\n}\n\nconst listNewFiles = `-- name: ListNewFiles :many\nSELECT id, session_id, path, content, version, created_at, updated_at\nFROM files\nWHERE is_new = 1\nORDER BY created_at DESC\n`\n\nfunc (q *Queries) ListNewFiles(ctx context.Context) ([]File, error) {\n\trows, err := q.query(ctx, q.listNewFilesStmt, listNewFiles)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer rows.Close()\n\titems := []File{}\n\tfor rows.Next() {\n\t\tvar i File\n\t\tif err := rows.Scan(\n\t\t\t&i.ID,\n\t\t\t&i.SessionID,\n\t\t\t&i.Path,\n\t\t\t&i.Content,\n\t\t\t&i.Version,\n\t\t\t&i.CreatedAt,\n\t\t\t&i.UpdatedAt,\n\t\t); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\titems = append(items, i)\n\t}\n\tif err := rows.Close(); err != nil {\n\t\treturn nil, err\n\t}\n\tif err := rows.Err(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn items, nil\n}\n\nconst updateFile = `-- name: UpdateFile :one\nUPDATE files\nSET\n content = ?,\n version = ?,\n updated_at = strftime('%s', 'now')\nWHERE id = ?\nRETURNING id, session_id, path, content, version, created_at, updated_at\n`\n\ntype UpdateFileParams struct {\n\tContent string `json:\"content\"`\n\tVersion string `json:\"version\"`\n\tID string `json:\"id\"`\n}\n\nfunc (q *Queries) UpdateFile(ctx context.Context, arg UpdateFileParams) (File, error) {\n\trow := q.queryRow(ctx, q.updateFileStmt, updateFile, arg.Content, arg.Version, arg.ID)\n\tvar i File\n\terr := row.Scan(\n\t\t&i.ID,\n\t\t&i.SessionID,\n\t\t&i.Path,\n\t\t&i.Content,\n\t\t&i.Version,\n\t\t&i.CreatedAt,\n\t\t&i.UpdatedAt,\n\t)\n\treturn i, err\n}\n"], ["/opencode/internal/db/sessions.sql.go", "// Code generated by sqlc. DO NOT EDIT.\n// versions:\n// sqlc v1.29.0\n// source: sessions.sql\n\npackage db\n\nimport (\n\t\"context\"\n\t\"database/sql\"\n)\n\nconst createSession = `-- name: CreateSession :one\nINSERT INTO sessions (\n id,\n parent_session_id,\n title,\n message_count,\n prompt_tokens,\n completion_tokens,\n cost,\n summary_message_id,\n updated_at,\n created_at\n) VALUES (\n ?,\n ?,\n ?,\n ?,\n ?,\n ?,\n ?,\n null,\n strftime('%s', 'now'),\n strftime('%s', 'now')\n) RETURNING id, parent_session_id, title, message_count, prompt_tokens, completion_tokens, cost, updated_at, created_at, summary_message_id\n`\n\ntype CreateSessionParams struct {\n\tID string `json:\"id\"`\n\tParentSessionID sql.NullString `json:\"parent_session_id\"`\n\tTitle string `json:\"title\"`\n\tMessageCount int64 `json:\"message_count\"`\n\tPromptTokens int64 `json:\"prompt_tokens\"`\n\tCompletionTokens int64 `json:\"completion_tokens\"`\n\tCost float64 `json:\"cost\"`\n}\n\nfunc (q *Queries) CreateSession(ctx context.Context, arg CreateSessionParams) (Session, error) {\n\trow := q.queryRow(ctx, q.createSessionStmt, createSession,\n\t\targ.ID,\n\t\targ.ParentSessionID,\n\t\targ.Title,\n\t\targ.MessageCount,\n\t\targ.PromptTokens,\n\t\targ.CompletionTokens,\n\t\targ.Cost,\n\t)\n\tvar i Session\n\terr := row.Scan(\n\t\t&i.ID,\n\t\t&i.ParentSessionID,\n\t\t&i.Title,\n\t\t&i.MessageCount,\n\t\t&i.PromptTokens,\n\t\t&i.CompletionTokens,\n\t\t&i.Cost,\n\t\t&i.UpdatedAt,\n\t\t&i.CreatedAt,\n\t\t&i.SummaryMessageID,\n\t)\n\treturn i, err\n}\n\nconst deleteSession = `-- name: DeleteSession :exec\nDELETE FROM sessions\nWHERE id = ?\n`\n\nfunc (q *Queries) DeleteSession(ctx context.Context, id string) error {\n\t_, err := q.exec(ctx, q.deleteSessionStmt, deleteSession, id)\n\treturn err\n}\n\nconst getSessionByID = `-- name: GetSessionByID :one\nSELECT id, parent_session_id, title, message_count, prompt_tokens, completion_tokens, cost, updated_at, created_at, summary_message_id\nFROM sessions\nWHERE id = ? LIMIT 1\n`\n\nfunc (q *Queries) GetSessionByID(ctx context.Context, id string) (Session, error) {\n\trow := q.queryRow(ctx, q.getSessionByIDStmt, getSessionByID, id)\n\tvar i Session\n\terr := row.Scan(\n\t\t&i.ID,\n\t\t&i.ParentSessionID,\n\t\t&i.Title,\n\t\t&i.MessageCount,\n\t\t&i.PromptTokens,\n\t\t&i.CompletionTokens,\n\t\t&i.Cost,\n\t\t&i.UpdatedAt,\n\t\t&i.CreatedAt,\n\t\t&i.SummaryMessageID,\n\t)\n\treturn i, err\n}\n\nconst listSessions = `-- name: ListSessions :many\nSELECT id, parent_session_id, title, message_count, prompt_tokens, completion_tokens, cost, updated_at, created_at, summary_message_id\nFROM sessions\nWHERE parent_session_id is NULL\nORDER BY created_at DESC\n`\n\nfunc (q *Queries) ListSessions(ctx context.Context) ([]Session, error) {\n\trows, err := q.query(ctx, q.listSessionsStmt, listSessions)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer rows.Close()\n\titems := []Session{}\n\tfor rows.Next() {\n\t\tvar i Session\n\t\tif err := rows.Scan(\n\t\t\t&i.ID,\n\t\t\t&i.ParentSessionID,\n\t\t\t&i.Title,\n\t\t\t&i.MessageCount,\n\t\t\t&i.PromptTokens,\n\t\t\t&i.CompletionTokens,\n\t\t\t&i.Cost,\n\t\t\t&i.UpdatedAt,\n\t\t\t&i.CreatedAt,\n\t\t\t&i.SummaryMessageID,\n\t\t); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\titems = append(items, i)\n\t}\n\tif err := rows.Close(); err != nil {\n\t\treturn nil, err\n\t}\n\tif err := rows.Err(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn items, nil\n}\n\nconst updateSession = `-- name: UpdateSession :one\nUPDATE sessions\nSET\n title = ?,\n prompt_tokens = ?,\n completion_tokens = ?,\n summary_message_id = ?,\n cost = ?\nWHERE id = ?\nRETURNING id, parent_session_id, title, message_count, prompt_tokens, completion_tokens, cost, updated_at, created_at, summary_message_id\n`\n\ntype UpdateSessionParams struct {\n\tTitle string `json:\"title\"`\n\tPromptTokens int64 `json:\"prompt_tokens\"`\n\tCompletionTokens int64 `json:\"completion_tokens\"`\n\tSummaryMessageID sql.NullString `json:\"summary_message_id\"`\n\tCost float64 `json:\"cost\"`\n\tID string `json:\"id\"`\n}\n\nfunc (q *Queries) UpdateSession(ctx context.Context, arg UpdateSessionParams) (Session, error) {\n\trow := q.queryRow(ctx, q.updateSessionStmt, updateSession,\n\t\targ.Title,\n\t\targ.PromptTokens,\n\t\targ.CompletionTokens,\n\t\targ.SummaryMessageID,\n\t\targ.Cost,\n\t\targ.ID,\n\t)\n\tvar i Session\n\terr := row.Scan(\n\t\t&i.ID,\n\t\t&i.ParentSessionID,\n\t\t&i.Title,\n\t\t&i.MessageCount,\n\t\t&i.PromptTokens,\n\t\t&i.CompletionTokens,\n\t\t&i.Cost,\n\t\t&i.UpdatedAt,\n\t\t&i.CreatedAt,\n\t\t&i.SummaryMessageID,\n\t)\n\treturn i, err\n}\n"], ["/opencode/internal/pubsub/broker.go", "package pubsub\n\nimport (\n\t\"context\"\n\t\"sync\"\n)\n\nconst bufferSize = 64\n\ntype Broker[T any] struct {\n\tsubs map[chan Event[T]]struct{}\n\tmu sync.RWMutex\n\tdone chan struct{}\n\tsubCount int\n\tmaxEvents int\n}\n\nfunc NewBroker[T any]() *Broker[T] {\n\treturn NewBrokerWithOptions[T](bufferSize, 1000)\n}\n\nfunc NewBrokerWithOptions[T any](channelBufferSize, maxEvents int) *Broker[T] {\n\tb := &Broker[T]{\n\t\tsubs: make(map[chan Event[T]]struct{}),\n\t\tdone: make(chan struct{}),\n\t\tsubCount: 0,\n\t\tmaxEvents: maxEvents,\n\t}\n\treturn b\n}\n\nfunc (b *Broker[T]) Shutdown() {\n\tselect {\n\tcase <-b.done: // Already closed\n\t\treturn\n\tdefault:\n\t\tclose(b.done)\n\t}\n\n\tb.mu.Lock()\n\tdefer b.mu.Unlock()\n\n\tfor ch := range b.subs {\n\t\tdelete(b.subs, ch)\n\t\tclose(ch)\n\t}\n\n\tb.subCount = 0\n}\n\nfunc (b *Broker[T]) Subscribe(ctx context.Context) <-chan Event[T] {\n\tb.mu.Lock()\n\tdefer b.mu.Unlock()\n\n\tselect {\n\tcase <-b.done:\n\t\tch := make(chan Event[T])\n\t\tclose(ch)\n\t\treturn ch\n\tdefault:\n\t}\n\n\tsub := make(chan Event[T], bufferSize)\n\tb.subs[sub] = struct{}{}\n\tb.subCount++\n\n\tgo func() {\n\t\t<-ctx.Done()\n\n\t\tb.mu.Lock()\n\t\tdefer b.mu.Unlock()\n\n\t\tselect {\n\t\tcase <-b.done:\n\t\t\treturn\n\t\tdefault:\n\t\t}\n\n\t\tdelete(b.subs, sub)\n\t\tclose(sub)\n\t\tb.subCount--\n\t}()\n\n\treturn sub\n}\n\nfunc (b *Broker[T]) GetSubscriberCount() int {\n\tb.mu.RLock()\n\tdefer b.mu.RUnlock()\n\treturn b.subCount\n}\n\nfunc (b *Broker[T]) Publish(t EventType, payload T) {\n\tb.mu.RLock()\n\tselect {\n\tcase <-b.done:\n\t\tb.mu.RUnlock()\n\t\treturn\n\tdefault:\n\t}\n\n\tsubscribers := make([]chan Event[T], 0, len(b.subs))\n\tfor sub := range b.subs {\n\t\tsubscribers = append(subscribers, sub)\n\t}\n\tb.mu.RUnlock()\n\n\tevent := Event[T]{Type: t, Payload: payload}\n\n\tfor _, sub := range subscribers {\n\t\tselect {\n\t\tcase sub <- event:\n\t\tdefault:\n\t\t}\n\t}\n}\n"], ["/opencode/internal/tui/styles/styles.go", "package styles\n\nimport (\n\t\"github.com/charmbracelet/lipgloss\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n)\n\nvar (\n\tImageBakcground = \"#212121\"\n)\n\n// Style generation functions that use the current theme\n\n// BaseStyle returns the base style with background and foreground colors\nfunc BaseStyle() lipgloss.Style {\n\tt := theme.CurrentTheme()\n\treturn lipgloss.NewStyle().\n\t\tBackground(t.Background()).\n\t\tForeground(t.Text())\n}\n\n// Regular returns a basic unstyled lipgloss.Style\nfunc Regular() lipgloss.Style {\n\treturn lipgloss.NewStyle()\n}\n\n// Bold returns a bold style\nfunc Bold() lipgloss.Style {\n\treturn Regular().Bold(true)\n}\n\n// Padded returns a style with horizontal padding\nfunc Padded() lipgloss.Style {\n\treturn Regular().Padding(0, 1)\n}\n\n// Border returns a style with a normal border\nfunc Border() lipgloss.Style {\n\tt := theme.CurrentTheme()\n\treturn Regular().\n\t\tBorder(lipgloss.NormalBorder()).\n\t\tBorderForeground(t.BorderNormal())\n}\n\n// ThickBorder returns a style with a thick border\nfunc ThickBorder() lipgloss.Style {\n\tt := theme.CurrentTheme()\n\treturn Regular().\n\t\tBorder(lipgloss.ThickBorder()).\n\t\tBorderForeground(t.BorderNormal())\n}\n\n// DoubleBorder returns a style with a double border\nfunc DoubleBorder() lipgloss.Style {\n\tt := theme.CurrentTheme()\n\treturn Regular().\n\t\tBorder(lipgloss.DoubleBorder()).\n\t\tBorderForeground(t.BorderNormal())\n}\n\n// FocusedBorder returns a style with a border using the focused border color\nfunc FocusedBorder() lipgloss.Style {\n\tt := theme.CurrentTheme()\n\treturn Regular().\n\t\tBorder(lipgloss.NormalBorder()).\n\t\tBorderForeground(t.BorderFocused())\n}\n\n// DimBorder returns a style with a border using the dim border color\nfunc DimBorder() lipgloss.Style {\n\tt := theme.CurrentTheme()\n\treturn Regular().\n\t\tBorder(lipgloss.NormalBorder()).\n\t\tBorderForeground(t.BorderDim())\n}\n\n// PrimaryColor returns the primary color from the current theme\nfunc PrimaryColor() lipgloss.AdaptiveColor {\n\treturn theme.CurrentTheme().Primary()\n}\n\n// SecondaryColor returns the secondary color from the current theme\nfunc SecondaryColor() lipgloss.AdaptiveColor {\n\treturn theme.CurrentTheme().Secondary()\n}\n\n// AccentColor returns the accent color from the current theme\nfunc AccentColor() lipgloss.AdaptiveColor {\n\treturn theme.CurrentTheme().Accent()\n}\n\n// ErrorColor returns the error color from the current theme\nfunc ErrorColor() lipgloss.AdaptiveColor {\n\treturn theme.CurrentTheme().Error()\n}\n\n// WarningColor returns the warning color from the current theme\nfunc WarningColor() lipgloss.AdaptiveColor {\n\treturn theme.CurrentTheme().Warning()\n}\n\n// SuccessColor returns the success color from the current theme\nfunc SuccessColor() lipgloss.AdaptiveColor {\n\treturn theme.CurrentTheme().Success()\n}\n\n// InfoColor returns the info color from the current theme\nfunc InfoColor() lipgloss.AdaptiveColor {\n\treturn theme.CurrentTheme().Info()\n}\n\n// TextColor returns the text color from the current theme\nfunc TextColor() lipgloss.AdaptiveColor {\n\treturn theme.CurrentTheme().Text()\n}\n\n// TextMutedColor returns the muted text color from the current theme\nfunc TextMutedColor() lipgloss.AdaptiveColor {\n\treturn theme.CurrentTheme().TextMuted()\n}\n\n// TextEmphasizedColor returns the emphasized text color from the current theme\nfunc TextEmphasizedColor() lipgloss.AdaptiveColor {\n\treturn theme.CurrentTheme().TextEmphasized()\n}\n\n// BackgroundColor returns the background color from the current theme\nfunc BackgroundColor() lipgloss.AdaptiveColor {\n\treturn theme.CurrentTheme().Background()\n}\n\n// BackgroundSecondaryColor returns the secondary background color from the current theme\nfunc BackgroundSecondaryColor() lipgloss.AdaptiveColor {\n\treturn theme.CurrentTheme().BackgroundSecondary()\n}\n\n// BackgroundDarkerColor returns the darker background color from the current theme\nfunc BackgroundDarkerColor() lipgloss.AdaptiveColor {\n\treturn theme.CurrentTheme().BackgroundDarker()\n}\n\n// BorderNormalColor returns the normal border color from the current theme\nfunc BorderNormalColor() lipgloss.AdaptiveColor {\n\treturn theme.CurrentTheme().BorderNormal()\n}\n\n// BorderFocusedColor returns the focused border color from the current theme\nfunc BorderFocusedColor() lipgloss.AdaptiveColor {\n\treturn theme.CurrentTheme().BorderFocused()\n}\n\n// BorderDimColor returns the dim border color from the current theme\nfunc BorderDimColor() lipgloss.AdaptiveColor {\n\treturn theme.CurrentTheme().BorderDim()\n}\n"], ["/opencode/internal/lsp/protocol/tsdocument-changes.go", "// Copyright 2022 The Go Authors. All rights reserved.\n// Use of this source code is governed by a BSD-style\n// license that can be found in the LICENSE file.\n\npackage protocol\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n)\n\n// DocumentChange is a union of various file edit operations.\n//\n// Exactly one field of this struct is non-nil; see [DocumentChange.Valid].\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#resourceChanges\ntype DocumentChange struct {\n\tTextDocumentEdit *TextDocumentEdit\n\tCreateFile *CreateFile\n\tRenameFile *RenameFile\n\tDeleteFile *DeleteFile\n}\n\n// Valid reports whether the DocumentChange sum-type value is valid,\n// that is, exactly one of create, delete, edit, or rename.\nfunc (ch DocumentChange) Valid() bool {\n\tn := 0\n\tif ch.TextDocumentEdit != nil {\n\t\tn++\n\t}\n\tif ch.CreateFile != nil {\n\t\tn++\n\t}\n\tif ch.RenameFile != nil {\n\t\tn++\n\t}\n\tif ch.DeleteFile != nil {\n\t\tn++\n\t}\n\treturn n == 1\n}\n\nfunc (d *DocumentChange) UnmarshalJSON(data []byte) error {\n\tvar m map[string]any\n\tif err := json.Unmarshal(data, &m); err != nil {\n\t\treturn err\n\t}\n\n\tif _, ok := m[\"textDocument\"]; ok {\n\t\td.TextDocumentEdit = new(TextDocumentEdit)\n\t\treturn json.Unmarshal(data, d.TextDocumentEdit)\n\t}\n\n\t// The {Create,Rename,Delete}File types all share a 'kind' field.\n\tkind := m[\"kind\"]\n\tswitch kind {\n\tcase \"create\":\n\t\td.CreateFile = new(CreateFile)\n\t\treturn json.Unmarshal(data, d.CreateFile)\n\tcase \"rename\":\n\t\td.RenameFile = new(RenameFile)\n\t\treturn json.Unmarshal(data, d.RenameFile)\n\tcase \"delete\":\n\t\td.DeleteFile = new(DeleteFile)\n\t\treturn json.Unmarshal(data, d.DeleteFile)\n\t}\n\treturn fmt.Errorf(\"DocumentChanges: unexpected kind: %q\", kind)\n}\n\nfunc (d *DocumentChange) MarshalJSON() ([]byte, error) {\n\tif d.TextDocumentEdit != nil {\n\t\treturn json.Marshal(d.TextDocumentEdit)\n\t} else if d.CreateFile != nil {\n\t\treturn json.Marshal(d.CreateFile)\n\t} else if d.RenameFile != nil {\n\t\treturn json.Marshal(d.RenameFile)\n\t} else if d.DeleteFile != nil {\n\t\treturn json.Marshal(d.DeleteFile)\n\t}\n\treturn nil, fmt.Errorf(\"empty DocumentChanges union value\")\n}\n"], ["/opencode/internal/app/lsp.go", "package app\n\nimport (\n\t\"context\"\n\t\"time\"\n\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n\t\"github.com/opencode-ai/opencode/internal/lsp\"\n\t\"github.com/opencode-ai/opencode/internal/lsp/watcher\"\n)\n\nfunc (app *App) initLSPClients(ctx context.Context) {\n\tcfg := config.Get()\n\n\t// Initialize LSP clients\n\tfor name, clientConfig := range cfg.LSP {\n\t\t// Start each client initialization in its own goroutine\n\t\tgo app.createAndStartLSPClient(ctx, name, clientConfig.Command, clientConfig.Args...)\n\t}\n\tlogging.Info(\"LSP clients initialization started in background\")\n}\n\n// createAndStartLSPClient creates a new LSP client, initializes it, and starts its workspace watcher\nfunc (app *App) createAndStartLSPClient(ctx context.Context, name string, command string, args ...string) {\n\t// Create a specific context for initialization with a timeout\n\tlogging.Info(\"Creating LSP client\", \"name\", name, \"command\", command, \"args\", args)\n\t\n\t// Create the LSP client\n\tlspClient, err := lsp.NewClient(ctx, command, args...)\n\tif err != nil {\n\t\tlogging.Error(\"Failed to create LSP client for\", name, err)\n\t\treturn\n\t}\n\n\t// Create a longer timeout for initialization (some servers take time to start)\n\tinitCtx, cancel := context.WithTimeout(ctx, 30*time.Second)\n\tdefer cancel()\n\t\n\t// Initialize with the initialization context\n\t_, err = lspClient.InitializeLSPClient(initCtx, config.WorkingDirectory())\n\tif err != nil {\n\t\tlogging.Error(\"Initialize failed\", \"name\", name, \"error\", err)\n\t\t// Clean up the client to prevent resource leaks\n\t\tlspClient.Close()\n\t\treturn\n\t}\n\n\t// Wait for the server to be ready\n\tif err := lspClient.WaitForServerReady(initCtx); err != nil {\n\t\tlogging.Error(\"Server failed to become ready\", \"name\", name, \"error\", err)\n\t\t// We'll continue anyway, as some functionality might still work\n\t\tlspClient.SetServerState(lsp.StateError)\n\t} else {\n\t\tlogging.Info(\"LSP server is ready\", \"name\", name)\n\t\tlspClient.SetServerState(lsp.StateReady)\n\t}\n\n\tlogging.Info(\"LSP client initialized\", \"name\", name)\n\t\n\t// Create a child context that can be canceled when the app is shutting down\n\twatchCtx, cancelFunc := context.WithCancel(ctx)\n\t\n\t// Create a context with the server name for better identification\n\twatchCtx = context.WithValue(watchCtx, \"serverName\", name)\n\t\n\t// Create the workspace watcher\n\tworkspaceWatcher := watcher.NewWorkspaceWatcher(lspClient)\n\n\t// Store the cancel function to be called during cleanup\n\tapp.cancelFuncsMutex.Lock()\n\tapp.watcherCancelFuncs = append(app.watcherCancelFuncs, cancelFunc)\n\tapp.cancelFuncsMutex.Unlock()\n\n\t// Add the watcher to a WaitGroup to track active goroutines\n\tapp.watcherWG.Add(1)\n\n\t// Add to map with mutex protection before starting goroutine\n\tapp.clientsMutex.Lock()\n\tapp.LSPClients[name] = lspClient\n\tapp.clientsMutex.Unlock()\n\n\tgo app.runWorkspaceWatcher(watchCtx, name, workspaceWatcher)\n}\n\n// runWorkspaceWatcher executes the workspace watcher for an LSP client\nfunc (app *App) runWorkspaceWatcher(ctx context.Context, name string, workspaceWatcher *watcher.WorkspaceWatcher) {\n\tdefer app.watcherWG.Done()\n\tdefer logging.RecoverPanic(\"LSP-\"+name, func() {\n\t\t// Try to restart the client\n\t\tapp.restartLSPClient(ctx, name)\n\t})\n\n\tworkspaceWatcher.WatchWorkspace(ctx, config.WorkingDirectory())\n\tlogging.Info(\"Workspace watcher stopped\", \"client\", name)\n}\n\n// restartLSPClient attempts to restart a crashed or failed LSP client\nfunc (app *App) restartLSPClient(ctx context.Context, name string) {\n\t// Get the original configuration\n\tcfg := config.Get()\n\tclientConfig, exists := cfg.LSP[name]\n\tif !exists {\n\t\tlogging.Error(\"Cannot restart client, configuration not found\", \"client\", name)\n\t\treturn\n\t}\n\n\t// Clean up the old client if it exists\n\tapp.clientsMutex.Lock()\n\toldClient, exists := app.LSPClients[name]\n\tif exists {\n\t\tdelete(app.LSPClients, name) // Remove from map before potentially slow shutdown\n\t}\n\tapp.clientsMutex.Unlock()\n\n\tif exists && oldClient != nil {\n\t\t// Try to shut it down gracefully, but don't block on errors\n\t\tshutdownCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)\n\t\t_ = oldClient.Shutdown(shutdownCtx)\n\t\tcancel()\n\t}\n\n\t// Create a new client using the shared function\n\tapp.createAndStartLSPClient(ctx, name, clientConfig.Command, clientConfig.Args...)\n\tlogging.Info(\"Successfully restarted LSP client\", \"client\", name)\n}\n"], ["/opencode/internal/lsp/protocol/interface.go", "package protocol\n\nimport \"fmt\"\n\n// TextEditResult is an interface for types that represent workspace symbols\ntype WorkspaceSymbolResult interface {\n\tGetName() string\n\tGetLocation() Location\n\tisWorkspaceSymbol() // marker method\n}\n\nfunc (ws *WorkspaceSymbol) GetName() string { return ws.Name }\nfunc (ws *WorkspaceSymbol) GetLocation() Location {\n\tswitch v := ws.Location.Value.(type) {\n\tcase Location:\n\t\treturn v\n\tcase LocationUriOnly:\n\t\treturn Location{URI: v.URI}\n\t}\n\treturn Location{}\n}\nfunc (ws *WorkspaceSymbol) isWorkspaceSymbol() {}\n\nfunc (si *SymbolInformation) GetName() string { return si.Name }\nfunc (si *SymbolInformation) GetLocation() Location { return si.Location }\nfunc (si *SymbolInformation) isWorkspaceSymbol() {}\n\n// Results converts the Value to a slice of WorkspaceSymbolResult\nfunc (r Or_Result_workspace_symbol) Results() ([]WorkspaceSymbolResult, error) {\n\tif r.Value == nil {\n\t\treturn make([]WorkspaceSymbolResult, 0), nil\n\t}\n\tswitch v := r.Value.(type) {\n\tcase []WorkspaceSymbol:\n\t\tresults := make([]WorkspaceSymbolResult, len(v))\n\t\tfor i := range v {\n\t\t\tresults[i] = &v[i]\n\t\t}\n\t\treturn results, nil\n\tcase []SymbolInformation:\n\t\tresults := make([]WorkspaceSymbolResult, len(v))\n\t\tfor i := range v {\n\t\t\tresults[i] = &v[i]\n\t\t}\n\t\treturn results, nil\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"unknown symbol type: %T\", r.Value)\n\t}\n}\n\n// TextEditResult is an interface for types that represent document symbols\ntype DocumentSymbolResult interface {\n\tGetRange() Range\n\tGetName() string\n\tisDocumentSymbol() // marker method\n}\n\nfunc (ds *DocumentSymbol) GetRange() Range { return ds.Range }\nfunc (ds *DocumentSymbol) GetName() string { return ds.Name }\nfunc (ds *DocumentSymbol) isDocumentSymbol() {}\n\nfunc (si *SymbolInformation) GetRange() Range { return si.Location.Range }\n\n// Note: SymbolInformation already has GetName() implemented above\nfunc (si *SymbolInformation) isDocumentSymbol() {}\n\n// Results converts the Value to a slice of DocumentSymbolResult\nfunc (r Or_Result_textDocument_documentSymbol) Results() ([]DocumentSymbolResult, error) {\n\tif r.Value == nil {\n\t\treturn make([]DocumentSymbolResult, 0), nil\n\t}\n\tswitch v := r.Value.(type) {\n\tcase []DocumentSymbol:\n\t\tresults := make([]DocumentSymbolResult, len(v))\n\t\tfor i := range v {\n\t\t\tresults[i] = &v[i]\n\t\t}\n\t\treturn results, nil\n\tcase []SymbolInformation:\n\t\tresults := make([]DocumentSymbolResult, len(v))\n\t\tfor i := range v {\n\t\t\tresults[i] = &v[i]\n\t\t}\n\t\treturn results, nil\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"unknown document symbol type: %T\", v)\n\t}\n}\n\n// TextEditResult is an interface for types that can be used as text edits\ntype TextEditResult interface {\n\tGetRange() Range\n\tGetNewText() string\n\tisTextEdit() // marker method\n}\n\nfunc (te *TextEdit) GetRange() Range { return te.Range }\nfunc (te *TextEdit) GetNewText() string { return te.NewText }\nfunc (te *TextEdit) isTextEdit() {}\n\n// Convert Or_TextDocumentEdit_edits_Elem to TextEdit\nfunc (e Or_TextDocumentEdit_edits_Elem) AsTextEdit() (TextEdit, error) {\n\tif e.Value == nil {\n\t\treturn TextEdit{}, fmt.Errorf(\"nil text edit\")\n\t}\n\tswitch v := e.Value.(type) {\n\tcase TextEdit:\n\t\treturn v, nil\n\tcase AnnotatedTextEdit:\n\t\treturn TextEdit{\n\t\t\tRange: v.Range,\n\t\t\tNewText: v.NewText,\n\t\t}, nil\n\tdefault:\n\t\treturn TextEdit{}, fmt.Errorf(\"unknown text edit type: %T\", e.Value)\n\t}\n}\n"], ["/opencode/internal/db/db.go", "// Code generated by sqlc. DO NOT EDIT.\n// versions:\n// sqlc v1.29.0\n\npackage db\n\nimport (\n\t\"context\"\n\t\"database/sql\"\n\t\"fmt\"\n)\n\ntype DBTX interface {\n\tExecContext(context.Context, string, ...interface{}) (sql.Result, error)\n\tPrepareContext(context.Context, string) (*sql.Stmt, error)\n\tQueryContext(context.Context, string, ...interface{}) (*sql.Rows, error)\n\tQueryRowContext(context.Context, string, ...interface{}) *sql.Row\n}\n\nfunc New(db DBTX) *Queries {\n\treturn &Queries{db: db}\n}\n\nfunc Prepare(ctx context.Context, db DBTX) (*Queries, error) {\n\tq := Queries{db: db}\n\tvar err error\n\tif q.createFileStmt, err = db.PrepareContext(ctx, createFile); err != nil {\n\t\treturn nil, fmt.Errorf(\"error preparing query CreateFile: %w\", err)\n\t}\n\tif q.createMessageStmt, err = db.PrepareContext(ctx, createMessage); err != nil {\n\t\treturn nil, fmt.Errorf(\"error preparing query CreateMessage: %w\", err)\n\t}\n\tif q.createSessionStmt, err = db.PrepareContext(ctx, createSession); err != nil {\n\t\treturn nil, fmt.Errorf(\"error preparing query CreateSession: %w\", err)\n\t}\n\tif q.deleteFileStmt, err = db.PrepareContext(ctx, deleteFile); err != nil {\n\t\treturn nil, fmt.Errorf(\"error preparing query DeleteFile: %w\", err)\n\t}\n\tif q.deleteMessageStmt, err = db.PrepareContext(ctx, deleteMessage); err != nil {\n\t\treturn nil, fmt.Errorf(\"error preparing query DeleteMessage: %w\", err)\n\t}\n\tif q.deleteSessionStmt, err = db.PrepareContext(ctx, deleteSession); err != nil {\n\t\treturn nil, fmt.Errorf(\"error preparing query DeleteSession: %w\", err)\n\t}\n\tif q.deleteSessionFilesStmt, err = db.PrepareContext(ctx, deleteSessionFiles); err != nil {\n\t\treturn nil, fmt.Errorf(\"error preparing query DeleteSessionFiles: %w\", err)\n\t}\n\tif q.deleteSessionMessagesStmt, err = db.PrepareContext(ctx, deleteSessionMessages); err != nil {\n\t\treturn nil, fmt.Errorf(\"error preparing query DeleteSessionMessages: %w\", err)\n\t}\n\tif q.getFileStmt, err = db.PrepareContext(ctx, getFile); err != nil {\n\t\treturn nil, fmt.Errorf(\"error preparing query GetFile: %w\", err)\n\t}\n\tif q.getFileByPathAndSessionStmt, err = db.PrepareContext(ctx, getFileByPathAndSession); err != nil {\n\t\treturn nil, fmt.Errorf(\"error preparing query GetFileByPathAndSession: %w\", err)\n\t}\n\tif q.getMessageStmt, err = db.PrepareContext(ctx, getMessage); err != nil {\n\t\treturn nil, fmt.Errorf(\"error preparing query GetMessage: %w\", err)\n\t}\n\tif q.getSessionByIDStmt, err = db.PrepareContext(ctx, getSessionByID); err != nil {\n\t\treturn nil, fmt.Errorf(\"error preparing query GetSessionByID: %w\", err)\n\t}\n\tif q.listFilesByPathStmt, err = db.PrepareContext(ctx, listFilesByPath); err != nil {\n\t\treturn nil, fmt.Errorf(\"error preparing query ListFilesByPath: %w\", err)\n\t}\n\tif q.listFilesBySessionStmt, err = db.PrepareContext(ctx, listFilesBySession); err != nil {\n\t\treturn nil, fmt.Errorf(\"error preparing query ListFilesBySession: %w\", err)\n\t}\n\tif q.listLatestSessionFilesStmt, err = db.PrepareContext(ctx, listLatestSessionFiles); err != nil {\n\t\treturn nil, fmt.Errorf(\"error preparing query ListLatestSessionFiles: %w\", err)\n\t}\n\tif q.listMessagesBySessionStmt, err = db.PrepareContext(ctx, listMessagesBySession); err != nil {\n\t\treturn nil, fmt.Errorf(\"error preparing query ListMessagesBySession: %w\", err)\n\t}\n\tif q.listNewFilesStmt, err = db.PrepareContext(ctx, listNewFiles); err != nil {\n\t\treturn nil, fmt.Errorf(\"error preparing query ListNewFiles: %w\", err)\n\t}\n\tif q.listSessionsStmt, err = db.PrepareContext(ctx, listSessions); err != nil {\n\t\treturn nil, fmt.Errorf(\"error preparing query ListSessions: %w\", err)\n\t}\n\tif q.updateFileStmt, err = db.PrepareContext(ctx, updateFile); err != nil {\n\t\treturn nil, fmt.Errorf(\"error preparing query UpdateFile: %w\", err)\n\t}\n\tif q.updateMessageStmt, err = db.PrepareContext(ctx, updateMessage); err != nil {\n\t\treturn nil, fmt.Errorf(\"error preparing query UpdateMessage: %w\", err)\n\t}\n\tif q.updateSessionStmt, err = db.PrepareContext(ctx, updateSession); err != nil {\n\t\treturn nil, fmt.Errorf(\"error preparing query UpdateSession: %w\", err)\n\t}\n\treturn &q, nil\n}\n\nfunc (q *Queries) Close() error {\n\tvar err error\n\tif q.createFileStmt != nil {\n\t\tif cerr := q.createFileStmt.Close(); cerr != nil {\n\t\t\terr = fmt.Errorf(\"error closing createFileStmt: %w\", cerr)\n\t\t}\n\t}\n\tif q.createMessageStmt != nil {\n\t\tif cerr := q.createMessageStmt.Close(); cerr != nil {\n\t\t\terr = fmt.Errorf(\"error closing createMessageStmt: %w\", cerr)\n\t\t}\n\t}\n\tif q.createSessionStmt != nil {\n\t\tif cerr := q.createSessionStmt.Close(); cerr != nil {\n\t\t\terr = fmt.Errorf(\"error closing createSessionStmt: %w\", cerr)\n\t\t}\n\t}\n\tif q.deleteFileStmt != nil {\n\t\tif cerr := q.deleteFileStmt.Close(); cerr != nil {\n\t\t\terr = fmt.Errorf(\"error closing deleteFileStmt: %w\", cerr)\n\t\t}\n\t}\n\tif q.deleteMessageStmt != nil {\n\t\tif cerr := q.deleteMessageStmt.Close(); cerr != nil {\n\t\t\terr = fmt.Errorf(\"error closing deleteMessageStmt: %w\", cerr)\n\t\t}\n\t}\n\tif q.deleteSessionStmt != nil {\n\t\tif cerr := q.deleteSessionStmt.Close(); cerr != nil {\n\t\t\terr = fmt.Errorf(\"error closing deleteSessionStmt: %w\", cerr)\n\t\t}\n\t}\n\tif q.deleteSessionFilesStmt != nil {\n\t\tif cerr := q.deleteSessionFilesStmt.Close(); cerr != nil {\n\t\t\terr = fmt.Errorf(\"error closing deleteSessionFilesStmt: %w\", cerr)\n\t\t}\n\t}\n\tif q.deleteSessionMessagesStmt != nil {\n\t\tif cerr := q.deleteSessionMessagesStmt.Close(); cerr != nil {\n\t\t\terr = fmt.Errorf(\"error closing deleteSessionMessagesStmt: %w\", cerr)\n\t\t}\n\t}\n\tif q.getFileStmt != nil {\n\t\tif cerr := q.getFileStmt.Close(); cerr != nil {\n\t\t\terr = fmt.Errorf(\"error closing getFileStmt: %w\", cerr)\n\t\t}\n\t}\n\tif q.getFileByPathAndSessionStmt != nil {\n\t\tif cerr := q.getFileByPathAndSessionStmt.Close(); cerr != nil {\n\t\t\terr = fmt.Errorf(\"error closing getFileByPathAndSessionStmt: %w\", cerr)\n\t\t}\n\t}\n\tif q.getMessageStmt != nil {\n\t\tif cerr := q.getMessageStmt.Close(); cerr != nil {\n\t\t\terr = fmt.Errorf(\"error closing getMessageStmt: %w\", cerr)\n\t\t}\n\t}\n\tif q.getSessionByIDStmt != nil {\n\t\tif cerr := q.getSessionByIDStmt.Close(); cerr != nil {\n\t\t\terr = fmt.Errorf(\"error closing getSessionByIDStmt: %w\", cerr)\n\t\t}\n\t}\n\tif q.listFilesByPathStmt != nil {\n\t\tif cerr := q.listFilesByPathStmt.Close(); cerr != nil {\n\t\t\terr = fmt.Errorf(\"error closing listFilesByPathStmt: %w\", cerr)\n\t\t}\n\t}\n\tif q.listFilesBySessionStmt != nil {\n\t\tif cerr := q.listFilesBySessionStmt.Close(); cerr != nil {\n\t\t\terr = fmt.Errorf(\"error closing listFilesBySessionStmt: %w\", cerr)\n\t\t}\n\t}\n\tif q.listLatestSessionFilesStmt != nil {\n\t\tif cerr := q.listLatestSessionFilesStmt.Close(); cerr != nil {\n\t\t\terr = fmt.Errorf(\"error closing listLatestSessionFilesStmt: %w\", cerr)\n\t\t}\n\t}\n\tif q.listMessagesBySessionStmt != nil {\n\t\tif cerr := q.listMessagesBySessionStmt.Close(); cerr != nil {\n\t\t\terr = fmt.Errorf(\"error closing listMessagesBySessionStmt: %w\", cerr)\n\t\t}\n\t}\n\tif q.listNewFilesStmt != nil {\n\t\tif cerr := q.listNewFilesStmt.Close(); cerr != nil {\n\t\t\terr = fmt.Errorf(\"error closing listNewFilesStmt: %w\", cerr)\n\t\t}\n\t}\n\tif q.listSessionsStmt != nil {\n\t\tif cerr := q.listSessionsStmt.Close(); cerr != nil {\n\t\t\terr = fmt.Errorf(\"error closing listSessionsStmt: %w\", cerr)\n\t\t}\n\t}\n\tif q.updateFileStmt != nil {\n\t\tif cerr := q.updateFileStmt.Close(); cerr != nil {\n\t\t\terr = fmt.Errorf(\"error closing updateFileStmt: %w\", cerr)\n\t\t}\n\t}\n\tif q.updateMessageStmt != nil {\n\t\tif cerr := q.updateMessageStmt.Close(); cerr != nil {\n\t\t\terr = fmt.Errorf(\"error closing updateMessageStmt: %w\", cerr)\n\t\t}\n\t}\n\tif q.updateSessionStmt != nil {\n\t\tif cerr := q.updateSessionStmt.Close(); cerr != nil {\n\t\t\terr = fmt.Errorf(\"error closing updateSessionStmt: %w\", cerr)\n\t\t}\n\t}\n\treturn err\n}\n\nfunc (q *Queries) exec(ctx context.Context, stmt *sql.Stmt, query string, args ...interface{}) (sql.Result, error) {\n\tswitch {\n\tcase stmt != nil && q.tx != nil:\n\t\treturn q.tx.StmtContext(ctx, stmt).ExecContext(ctx, args...)\n\tcase stmt != nil:\n\t\treturn stmt.ExecContext(ctx, args...)\n\tdefault:\n\t\treturn q.db.ExecContext(ctx, query, args...)\n\t}\n}\n\nfunc (q *Queries) query(ctx context.Context, stmt *sql.Stmt, query string, args ...interface{}) (*sql.Rows, error) {\n\tswitch {\n\tcase stmt != nil && q.tx != nil:\n\t\treturn q.tx.StmtContext(ctx, stmt).QueryContext(ctx, args...)\n\tcase stmt != nil:\n\t\treturn stmt.QueryContext(ctx, args...)\n\tdefault:\n\t\treturn q.db.QueryContext(ctx, query, args...)\n\t}\n}\n\nfunc (q *Queries) queryRow(ctx context.Context, stmt *sql.Stmt, query string, args ...interface{}) *sql.Row {\n\tswitch {\n\tcase stmt != nil && q.tx != nil:\n\t\treturn q.tx.StmtContext(ctx, stmt).QueryRowContext(ctx, args...)\n\tcase stmt != nil:\n\t\treturn stmt.QueryRowContext(ctx, args...)\n\tdefault:\n\t\treturn q.db.QueryRowContext(ctx, query, args...)\n\t}\n}\n\ntype Queries struct {\n\tdb DBTX\n\ttx *sql.Tx\n\tcreateFileStmt *sql.Stmt\n\tcreateMessageStmt *sql.Stmt\n\tcreateSessionStmt *sql.Stmt\n\tdeleteFileStmt *sql.Stmt\n\tdeleteMessageStmt *sql.Stmt\n\tdeleteSessionStmt *sql.Stmt\n\tdeleteSessionFilesStmt *sql.Stmt\n\tdeleteSessionMessagesStmt *sql.Stmt\n\tgetFileStmt *sql.Stmt\n\tgetFileByPathAndSessionStmt *sql.Stmt\n\tgetMessageStmt *sql.Stmt\n\tgetSessionByIDStmt *sql.Stmt\n\tlistFilesByPathStmt *sql.Stmt\n\tlistFilesBySessionStmt *sql.Stmt\n\tlistLatestSessionFilesStmt *sql.Stmt\n\tlistMessagesBySessionStmt *sql.Stmt\n\tlistNewFilesStmt *sql.Stmt\n\tlistSessionsStmt *sql.Stmt\n\tupdateFileStmt *sql.Stmt\n\tupdateMessageStmt *sql.Stmt\n\tupdateSessionStmt *sql.Stmt\n}\n\nfunc (q *Queries) WithTx(tx *sql.Tx) *Queries {\n\treturn &Queries{\n\t\tdb: tx,\n\t\ttx: tx,\n\t\tcreateFileStmt: q.createFileStmt,\n\t\tcreateMessageStmt: q.createMessageStmt,\n\t\tcreateSessionStmt: q.createSessionStmt,\n\t\tdeleteFileStmt: q.deleteFileStmt,\n\t\tdeleteMessageStmt: q.deleteMessageStmt,\n\t\tdeleteSessionStmt: q.deleteSessionStmt,\n\t\tdeleteSessionFilesStmt: q.deleteSessionFilesStmt,\n\t\tdeleteSessionMessagesStmt: q.deleteSessionMessagesStmt,\n\t\tgetFileStmt: q.getFileStmt,\n\t\tgetFileByPathAndSessionStmt: q.getFileByPathAndSessionStmt,\n\t\tgetMessageStmt: q.getMessageStmt,\n\t\tgetSessionByIDStmt: q.getSessionByIDStmt,\n\t\tlistFilesByPathStmt: q.listFilesByPathStmt,\n\t\tlistFilesBySessionStmt: q.listFilesBySessionStmt,\n\t\tlistLatestSessionFilesStmt: q.listLatestSessionFilesStmt,\n\t\tlistMessagesBySessionStmt: q.listMessagesBySessionStmt,\n\t\tlistNewFilesStmt: q.listNewFilesStmt,\n\t\tlistSessionsStmt: q.listSessionsStmt,\n\t\tupdateFileStmt: q.updateFileStmt,\n\t\tupdateMessageStmt: q.updateMessageStmt,\n\t\tupdateSessionStmt: q.updateSessionStmt,\n\t}\n}\n"], ["/opencode/internal/db/connect.go", "package db\n\nimport (\n\t\"database/sql\"\n\t\"fmt\"\n\t\"os\"\n\t\"path/filepath\"\n\n\t_ \"github.com/ncruces/go-sqlite3/driver\"\n\t_ \"github.com/ncruces/go-sqlite3/embed\"\n\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n\n\t\"github.com/pressly/goose/v3\"\n)\n\nfunc Connect() (*sql.DB, error) {\n\tdataDir := config.Get().Data.Directory\n\tif dataDir == \"\" {\n\t\treturn nil, fmt.Errorf(\"data.dir is not set\")\n\t}\n\tif err := os.MkdirAll(dataDir, 0o700); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to create data directory: %w\", err)\n\t}\n\tdbPath := filepath.Join(dataDir, \"opencode.db\")\n\t// Open the SQLite database\n\tdb, err := sql.Open(\"sqlite3\", dbPath)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to open database: %w\", err)\n\t}\n\n\t// Verify connection\n\tif err = db.Ping(); err != nil {\n\t\tdb.Close()\n\t\treturn nil, fmt.Errorf(\"failed to connect to database: %w\", err)\n\t}\n\n\t// Set pragmas for better performance\n\tpragmas := []string{\n\t\t\"PRAGMA foreign_keys = ON;\",\n\t\t\"PRAGMA journal_mode = WAL;\",\n\t\t\"PRAGMA page_size = 4096;\",\n\t\t\"PRAGMA cache_size = -8000;\",\n\t\t\"PRAGMA synchronous = NORMAL;\",\n\t}\n\n\tfor _, pragma := range pragmas {\n\t\tif _, err = db.Exec(pragma); err != nil {\n\t\t\tlogging.Error(\"Failed to set pragma\", pragma, err)\n\t\t} else {\n\t\t\tlogging.Debug(\"Set pragma\", \"pragma\", pragma)\n\t\t}\n\t}\n\n\tgoose.SetBaseFS(FS)\n\n\tif err := goose.SetDialect(\"sqlite3\"); err != nil {\n\t\tlogging.Error(\"Failed to set dialect\", \"error\", err)\n\t\treturn nil, fmt.Errorf(\"failed to set dialect: %w\", err)\n\t}\n\n\tif err := goose.Up(db, \"migrations\"); err != nil {\n\t\tlogging.Error(\"Failed to apply migrations\", \"error\", err)\n\t\treturn nil, fmt.Errorf(\"failed to apply migrations: %w\", err)\n\t}\n\treturn db, nil\n}\n"], ["/opencode/internal/tui/layout/layout.go", "package layout\n\nimport (\n\t\"reflect\"\n\n\t\"github.com/charmbracelet/bubbles/key\"\n\ttea \"github.com/charmbracelet/bubbletea\"\n)\n\ntype Focusable interface {\n\tFocus() tea.Cmd\n\tBlur() tea.Cmd\n\tIsFocused() bool\n}\n\ntype Sizeable interface {\n\tSetSize(width, height int) tea.Cmd\n\tGetSize() (int, int)\n}\n\ntype Bindings interface {\n\tBindingKeys() []key.Binding\n}\n\nfunc KeyMapToSlice(t any) (bindings []key.Binding) {\n\ttyp := reflect.TypeOf(t)\n\tif typ.Kind() != reflect.Struct {\n\t\treturn nil\n\t}\n\tfor i := range typ.NumField() {\n\t\tv := reflect.ValueOf(t).Field(i)\n\t\tbindings = append(bindings, v.Interface().(key.Binding))\n\t}\n\treturn\n}\n"], ["/opencode/internal/lsp/protocol/tsprotocol.go", "// Copyright 2023 The Go Authors. All rights reserved.\n// Use of this source code is governed by a BSD-style\n// license that can be found in the LICENSE file.\n\n// Code generated for LSP. DO NOT EDIT.\n\npackage protocol\n\n// Code generated from protocol/metaModel.json at ref release/protocol/3.17.6-next.9 (hash c94395b5da53729e6dff931293b051009ccaaaa4).\n// https://github.com/microsoft/vscode-languageserver-node/blob/release/protocol/3.17.6-next.9/protocol/metaModel.json\n// LSP metaData.version = 3.17.0.\n\nimport \"encoding/json\"\n\n// created for And\ntype And_RegOpt_textDocument_colorPresentation struct {\n\tWorkDoneProgressOptions\n\tTextDocumentRegistrationOptions\n}\n\n// A special text edit with an additional change annotation.\n//\n// @since 3.16.0.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#annotatedTextEdit\ntype AnnotatedTextEdit struct {\n\t// The actual identifier of the change annotation\n\tAnnotationID *ChangeAnnotationIdentifier `json:\"annotationId,omitempty\"`\n\tTextEdit\n}\n\n// The parameters passed via an apply workspace edit request.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#applyWorkspaceEditParams\ntype ApplyWorkspaceEditParams struct {\n\t// An optional label of the workspace edit. This label is\n\t// presented in the user interface for example on an undo\n\t// stack to undo the workspace edit.\n\tLabel string `json:\"label,omitempty\"`\n\t// The edits to apply.\n\tEdit WorkspaceEdit `json:\"edit\"`\n\t// Additional data about the edit.\n\t//\n\t// @since 3.18.0\n\t// @proposed\n\tMetadata *WorkspaceEditMetadata `json:\"metadata,omitempty\"`\n}\n\n// The result returned from the apply workspace edit request.\n//\n// @since 3.17 renamed from ApplyWorkspaceEditResponse\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#applyWorkspaceEditResult\ntype ApplyWorkspaceEditResult struct {\n\t// Indicates whether the edit was applied or not.\n\tApplied bool `json:\"applied\"`\n\t// An optional textual description for why the edit was not applied.\n\t// This may be used by the server for diagnostic logging or to provide\n\t// a suitable error for a request that triggered the edit.\n\tFailureReason string `json:\"failureReason,omitempty\"`\n\t// Depending on the client's failure handling strategy `failedChange` might\n\t// contain the index of the change that failed. This property is only available\n\t// if the client signals a `failureHandlingStrategy` in its client capabilities.\n\tFailedChange uint32 `json:\"failedChange,omitempty\"`\n}\n\n// A base for all symbol information.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#baseSymbolInformation\ntype BaseSymbolInformation struct {\n\t// The name of this symbol.\n\tName string `json:\"name\"`\n\t// The kind of this symbol.\n\tKind SymbolKind `json:\"kind\"`\n\t// Tags for this symbol.\n\t//\n\t// @since 3.16.0\n\tTags []SymbolTag `json:\"tags,omitempty\"`\n\t// The name of the symbol containing this symbol. This information is for\n\t// user interface purposes (e.g. to render a qualifier in the user interface\n\t// if necessary). It can't be used to re-infer a hierarchy for the document\n\t// symbols.\n\tContainerName string `json:\"containerName,omitempty\"`\n}\n\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#callHierarchyClientCapabilities\ntype CallHierarchyClientCapabilities struct {\n\t// Whether implementation supports dynamic registration. If this is set to `true`\n\t// the client supports the new `(TextDocumentRegistrationOptions & StaticRegistrationOptions)`\n\t// return value for the corresponding server capability as well.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n}\n\n// Represents an incoming call, e.g. a caller of a method or constructor.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#callHierarchyIncomingCall\ntype CallHierarchyIncomingCall struct {\n\t// The item that makes the call.\n\tFrom CallHierarchyItem `json:\"from\"`\n\t// The ranges at which the calls appear. This is relative to the caller\n\t// denoted by {@link CallHierarchyIncomingCall.from `this.from`}.\n\tFromRanges []Range `json:\"fromRanges\"`\n}\n\n// The parameter of a `callHierarchy/incomingCalls` request.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#callHierarchyIncomingCallsParams\ntype CallHierarchyIncomingCallsParams struct {\n\tItem CallHierarchyItem `json:\"item\"`\n\tWorkDoneProgressParams\n\tPartialResultParams\n}\n\n// Represents programming constructs like functions or constructors in the context\n// of call hierarchy.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#callHierarchyItem\ntype CallHierarchyItem struct {\n\t// The name of this item.\n\tName string `json:\"name\"`\n\t// The kind of this item.\n\tKind SymbolKind `json:\"kind\"`\n\t// Tags for this item.\n\tTags []SymbolTag `json:\"tags,omitempty\"`\n\t// More detail for this item, e.g. the signature of a function.\n\tDetail string `json:\"detail,omitempty\"`\n\t// The resource identifier of this item.\n\tURI DocumentUri `json:\"uri\"`\n\t// The range enclosing this symbol not including leading/trailing whitespace but everything else, e.g. comments and code.\n\tRange Range `json:\"range\"`\n\t// The range that should be selected and revealed when this symbol is being picked, e.g. the name of a function.\n\t// Must be contained by the {@link CallHierarchyItem.range `range`}.\n\tSelectionRange Range `json:\"selectionRange\"`\n\t// A data entry field that is preserved between a call hierarchy prepare and\n\t// incoming calls or outgoing calls requests.\n\tData interface{} `json:\"data,omitempty\"`\n}\n\n// Call hierarchy options used during static registration.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#callHierarchyOptions\ntype CallHierarchyOptions struct {\n\tWorkDoneProgressOptions\n}\n\n// Represents an outgoing call, e.g. calling a getter from a method or a method from a constructor etc.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#callHierarchyOutgoingCall\ntype CallHierarchyOutgoingCall struct {\n\t// The item that is called.\n\tTo CallHierarchyItem `json:\"to\"`\n\t// The range at which this item is called. This is the range relative to the caller, e.g the item\n\t// passed to {@link CallHierarchyItemProvider.provideCallHierarchyOutgoingCalls `provideCallHierarchyOutgoingCalls`}\n\t// and not {@link CallHierarchyOutgoingCall.to `this.to`}.\n\tFromRanges []Range `json:\"fromRanges\"`\n}\n\n// The parameter of a `callHierarchy/outgoingCalls` request.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#callHierarchyOutgoingCallsParams\ntype CallHierarchyOutgoingCallsParams struct {\n\tItem CallHierarchyItem `json:\"item\"`\n\tWorkDoneProgressParams\n\tPartialResultParams\n}\n\n// The parameter of a `textDocument/prepareCallHierarchy` request.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#callHierarchyPrepareParams\ntype CallHierarchyPrepareParams struct {\n\tTextDocumentPositionParams\n\tWorkDoneProgressParams\n}\n\n// Call hierarchy options used during static or dynamic registration.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#callHierarchyRegistrationOptions\ntype CallHierarchyRegistrationOptions struct {\n\tTextDocumentRegistrationOptions\n\tCallHierarchyOptions\n\tStaticRegistrationOptions\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#cancelParams\ntype CancelParams struct {\n\t// The request id to cancel.\n\tID interface{} `json:\"id\"`\n}\n\n// Additional information that describes document changes.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#changeAnnotation\ntype ChangeAnnotation struct {\n\t// A human-readable string describing the actual change. The string\n\t// is rendered prominent in the user interface.\n\tLabel string `json:\"label\"`\n\t// A flag which indicates that user confirmation is needed\n\t// before applying the change.\n\tNeedsConfirmation bool `json:\"needsConfirmation,omitempty\"`\n\t// A human-readable string which is rendered less prominent in\n\t// the user interface.\n\tDescription string `json:\"description,omitempty\"`\n}\n\n// An identifier to refer to a change annotation stored with a workspace edit.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#changeAnnotationIdentifier\ntype ChangeAnnotationIdentifier = string // (alias)\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#changeAnnotationsSupportOptions\ntype ChangeAnnotationsSupportOptions struct {\n\t// Whether the client groups edits with equal labels into tree nodes,\n\t// for instance all edits labelled with \"Changes in Strings\" would\n\t// be a tree node.\n\tGroupsOnLabel bool `json:\"groupsOnLabel,omitempty\"`\n}\n\n// Defines the capabilities provided by the client.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#clientCapabilities\ntype ClientCapabilities struct {\n\t// Workspace specific client capabilities.\n\tWorkspace WorkspaceClientCapabilities `json:\"workspace,omitempty\"`\n\t// Text document specific client capabilities.\n\tTextDocument TextDocumentClientCapabilities `json:\"textDocument,omitempty\"`\n\t// Capabilities specific to the notebook document support.\n\t//\n\t// @since 3.17.0\n\tNotebookDocument *NotebookDocumentClientCapabilities `json:\"notebookDocument,omitempty\"`\n\t// Window specific client capabilities.\n\tWindow WindowClientCapabilities `json:\"window,omitempty\"`\n\t// General client capabilities.\n\t//\n\t// @since 3.16.0\n\tGeneral *GeneralClientCapabilities `json:\"general,omitempty\"`\n\t// Experimental client capabilities.\n\tExperimental interface{} `json:\"experimental,omitempty\"`\n}\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#clientCodeActionKindOptions\ntype ClientCodeActionKindOptions struct {\n\t// The code action kind values the client supports. When this\n\t// property exists the client also guarantees that it will\n\t// handle values outside its set gracefully and falls back\n\t// to a default value when unknown.\n\tValueSet []CodeActionKind `json:\"valueSet\"`\n}\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#clientCodeActionLiteralOptions\ntype ClientCodeActionLiteralOptions struct {\n\t// The code action kind is support with the following value\n\t// set.\n\tCodeActionKind ClientCodeActionKindOptions `json:\"codeActionKind\"`\n}\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#clientCodeActionResolveOptions\ntype ClientCodeActionResolveOptions struct {\n\t// The properties that a client can resolve lazily.\n\tProperties []string `json:\"properties\"`\n}\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#clientCodeLensResolveOptions\ntype ClientCodeLensResolveOptions struct {\n\t// The properties that a client can resolve lazily.\n\tProperties []string `json:\"properties\"`\n}\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#clientCompletionItemInsertTextModeOptions\ntype ClientCompletionItemInsertTextModeOptions struct {\n\tValueSet []InsertTextMode `json:\"valueSet\"`\n}\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#clientCompletionItemOptions\ntype ClientCompletionItemOptions struct {\n\t// Client supports snippets as insert text.\n\t//\n\t// A snippet can define tab stops and placeholders with `$1`, `$2`\n\t// and `${3:foo}`. `$0` defines the final tab stop, it defaults to\n\t// the end of the snippet. Placeholders with equal identifiers are linked,\n\t// that is typing in one will update others too.\n\tSnippetSupport bool `json:\"snippetSupport,omitempty\"`\n\t// Client supports commit characters on a completion item.\n\tCommitCharactersSupport bool `json:\"commitCharactersSupport,omitempty\"`\n\t// Client supports the following content formats for the documentation\n\t// property. The order describes the preferred format of the client.\n\tDocumentationFormat []MarkupKind `json:\"documentationFormat,omitempty\"`\n\t// Client supports the deprecated property on a completion item.\n\tDeprecatedSupport bool `json:\"deprecatedSupport,omitempty\"`\n\t// Client supports the preselect property on a completion item.\n\tPreselectSupport bool `json:\"preselectSupport,omitempty\"`\n\t// Client supports the tag property on a completion item. Clients supporting\n\t// tags have to handle unknown tags gracefully. Clients especially need to\n\t// preserve unknown tags when sending a completion item back to the server in\n\t// a resolve call.\n\t//\n\t// @since 3.15.0\n\tTagSupport *CompletionItemTagOptions `json:\"tagSupport,omitempty\"`\n\t// Client support insert replace edit to control different behavior if a\n\t// completion item is inserted in the text or should replace text.\n\t//\n\t// @since 3.16.0\n\tInsertReplaceSupport bool `json:\"insertReplaceSupport,omitempty\"`\n\t// Indicates which properties a client can resolve lazily on a completion\n\t// item. Before version 3.16.0 only the predefined properties `documentation`\n\t// and `details` could be resolved lazily.\n\t//\n\t// @since 3.16.0\n\tResolveSupport *ClientCompletionItemResolveOptions `json:\"resolveSupport,omitempty\"`\n\t// The client supports the `insertTextMode` property on\n\t// a completion item to override the whitespace handling mode\n\t// as defined by the client (see `insertTextMode`).\n\t//\n\t// @since 3.16.0\n\tInsertTextModeSupport *ClientCompletionItemInsertTextModeOptions `json:\"insertTextModeSupport,omitempty\"`\n\t// The client has support for completion item label\n\t// details (see also `CompletionItemLabelDetails`).\n\t//\n\t// @since 3.17.0\n\tLabelDetailsSupport bool `json:\"labelDetailsSupport,omitempty\"`\n}\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#clientCompletionItemOptionsKind\ntype ClientCompletionItemOptionsKind struct {\n\t// The completion item kind values the client supports. When this\n\t// property exists the client also guarantees that it will\n\t// handle values outside its set gracefully and falls back\n\t// to a default value when unknown.\n\t//\n\t// If this property is not present the client only supports\n\t// the completion items kinds from `Text` to `Reference` as defined in\n\t// the initial version of the protocol.\n\tValueSet []CompletionItemKind `json:\"valueSet,omitempty\"`\n}\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#clientCompletionItemResolveOptions\ntype ClientCompletionItemResolveOptions struct {\n\t// The properties that a client can resolve lazily.\n\tProperties []string `json:\"properties\"`\n}\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#clientDiagnosticsTagOptions\ntype ClientDiagnosticsTagOptions struct {\n\t// The tags supported by the client.\n\tValueSet []DiagnosticTag `json:\"valueSet\"`\n}\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#clientFoldingRangeKindOptions\ntype ClientFoldingRangeKindOptions struct {\n\t// The folding range kind values the client supports. When this\n\t// property exists the client also guarantees that it will\n\t// handle values outside its set gracefully and falls back\n\t// to a default value when unknown.\n\tValueSet []FoldingRangeKind `json:\"valueSet,omitempty\"`\n}\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#clientFoldingRangeOptions\ntype ClientFoldingRangeOptions struct {\n\t// If set, the client signals that it supports setting collapsedText on\n\t// folding ranges to display custom labels instead of the default text.\n\t//\n\t// @since 3.17.0\n\tCollapsedText bool `json:\"collapsedText,omitempty\"`\n}\n\n// Information about the client\n//\n// @since 3.15.0\n// @since 3.18.0 ClientInfo type name added.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#clientInfo\ntype ClientInfo struct {\n\t// The name of the client as defined by the client.\n\tName string `json:\"name\"`\n\t// The client's version as defined by the client.\n\tVersion string `json:\"version,omitempty\"`\n}\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#clientInlayHintResolveOptions\ntype ClientInlayHintResolveOptions struct {\n\t// The properties that a client can resolve lazily.\n\tProperties []string `json:\"properties\"`\n}\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#clientSemanticTokensRequestFullDelta\ntype ClientSemanticTokensRequestFullDelta struct {\n\t// The client will send the `textDocument/semanticTokens/full/delta` request if\n\t// the server provides a corresponding handler.\n\tDelta bool `json:\"delta,omitempty\"`\n}\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#clientSemanticTokensRequestOptions\ntype ClientSemanticTokensRequestOptions struct {\n\t// The client will send the `textDocument/semanticTokens/range` request if\n\t// the server provides a corresponding handler.\n\tRange *Or_ClientSemanticTokensRequestOptions_range `json:\"range,omitempty\"`\n\t// The client will send the `textDocument/semanticTokens/full` request if\n\t// the server provides a corresponding handler.\n\tFull *Or_ClientSemanticTokensRequestOptions_full `json:\"full,omitempty\"`\n}\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#clientShowMessageActionItemOptions\ntype ClientShowMessageActionItemOptions struct {\n\t// Whether the client supports additional attributes which\n\t// are preserved and send back to the server in the\n\t// request's response.\n\tAdditionalPropertiesSupport bool `json:\"additionalPropertiesSupport,omitempty\"`\n}\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#clientSignatureInformationOptions\ntype ClientSignatureInformationOptions struct {\n\t// Client supports the following content formats for the documentation\n\t// property. The order describes the preferred format of the client.\n\tDocumentationFormat []MarkupKind `json:\"documentationFormat,omitempty\"`\n\t// Client capabilities specific to parameter information.\n\tParameterInformation *ClientSignatureParameterInformationOptions `json:\"parameterInformation,omitempty\"`\n\t// The client supports the `activeParameter` property on `SignatureInformation`\n\t// literal.\n\t//\n\t// @since 3.16.0\n\tActiveParameterSupport bool `json:\"activeParameterSupport,omitempty\"`\n\t// The client supports the `activeParameter` property on\n\t// `SignatureHelp`/`SignatureInformation` being set to `null` to\n\t// indicate that no parameter should be active.\n\t//\n\t// @since 3.18.0\n\t// @proposed\n\tNoActiveParameterSupport bool `json:\"noActiveParameterSupport,omitempty\"`\n}\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#clientSignatureParameterInformationOptions\ntype ClientSignatureParameterInformationOptions struct {\n\t// The client supports processing label offsets instead of a\n\t// simple label string.\n\t//\n\t// @since 3.14.0\n\tLabelOffsetSupport bool `json:\"labelOffsetSupport,omitempty\"`\n}\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#clientSymbolKindOptions\ntype ClientSymbolKindOptions struct {\n\t// The symbol kind values the client supports. When this\n\t// property exists the client also guarantees that it will\n\t// handle values outside its set gracefully and falls back\n\t// to a default value when unknown.\n\t//\n\t// If this property is not present the client only supports\n\t// the symbol kinds from `File` to `Array` as defined in\n\t// the initial version of the protocol.\n\tValueSet []SymbolKind `json:\"valueSet,omitempty\"`\n}\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#clientSymbolResolveOptions\ntype ClientSymbolResolveOptions struct {\n\t// The properties that a client can resolve lazily. Usually\n\t// `location.range`\n\tProperties []string `json:\"properties\"`\n}\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#clientSymbolTagOptions\ntype ClientSymbolTagOptions struct {\n\t// The tags supported by the client.\n\tValueSet []SymbolTag `json:\"valueSet\"`\n}\n\n// A code action represents a change that can be performed in code, e.g. to fix a problem or\n// to refactor code.\n//\n// A CodeAction must set either `edit` and/or a `command`. If both are supplied, the `edit` is applied first, then the `command` is executed.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#codeAction\ntype CodeAction struct {\n\t// A short, human-readable, title for this code action.\n\tTitle string `json:\"title\"`\n\t// The kind of the code action.\n\t//\n\t// Used to filter code actions.\n\tKind CodeActionKind `json:\"kind,omitempty\"`\n\t// The diagnostics that this code action resolves.\n\tDiagnostics []Diagnostic `json:\"diagnostics,omitempty\"`\n\t// Marks this as a preferred action. Preferred actions are used by the `auto fix` command and can be targeted\n\t// by keybindings.\n\t//\n\t// A quick fix should be marked preferred if it properly addresses the underlying error.\n\t// A refactoring should be marked preferred if it is the most reasonable choice of actions to take.\n\t//\n\t// @since 3.15.0\n\tIsPreferred bool `json:\"isPreferred,omitempty\"`\n\t// Marks that the code action cannot currently be applied.\n\t//\n\t// Clients should follow the following guidelines regarding disabled code actions:\n\t//\n\t// - Disabled code actions are not shown in automatic [lightbulbs](https://code.visualstudio.com/docs/editor/editingevolved#_code-action)\n\t// code action menus.\n\t//\n\t// - Disabled actions are shown as faded out in the code action menu when the user requests a more specific type\n\t// of code action, such as refactorings.\n\t//\n\t// - If the user has a [keybinding](https://code.visualstudio.com/docs/editor/refactoring#_keybindings-for-code-actions)\n\t// that auto applies a code action and only disabled code actions are returned, the client should show the user an\n\t// error message with `reason` in the editor.\n\t//\n\t// @since 3.16.0\n\tDisabled *CodeActionDisabled `json:\"disabled,omitempty\"`\n\t// The workspace edit this code action performs.\n\tEdit *WorkspaceEdit `json:\"edit,omitempty\"`\n\t// A command this code action executes. If a code action\n\t// provides an edit and a command, first the edit is\n\t// executed and then the command.\n\tCommand *Command `json:\"command,omitempty\"`\n\t// A data entry field that is preserved on a code action between\n\t// a `textDocument/codeAction` and a `codeAction/resolve` request.\n\t//\n\t// @since 3.16.0\n\tData *json.RawMessage `json:\"data,omitempty\"`\n}\n\n// The Client Capabilities of a {@link CodeActionRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#codeActionClientCapabilities\ntype CodeActionClientCapabilities struct {\n\t// Whether code action supports dynamic registration.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n\t// The client support code action literals of type `CodeAction` as a valid\n\t// response of the `textDocument/codeAction` request. If the property is not\n\t// set the request can only return `Command` literals.\n\t//\n\t// @since 3.8.0\n\tCodeActionLiteralSupport ClientCodeActionLiteralOptions `json:\"codeActionLiteralSupport,omitempty\"`\n\t// Whether code action supports the `isPreferred` property.\n\t//\n\t// @since 3.15.0\n\tIsPreferredSupport bool `json:\"isPreferredSupport,omitempty\"`\n\t// Whether code action supports the `disabled` property.\n\t//\n\t// @since 3.16.0\n\tDisabledSupport bool `json:\"disabledSupport,omitempty\"`\n\t// Whether code action supports the `data` property which is\n\t// preserved between a `textDocument/codeAction` and a\n\t// `codeAction/resolve` request.\n\t//\n\t// @since 3.16.0\n\tDataSupport bool `json:\"dataSupport,omitempty\"`\n\t// Whether the client supports resolving additional code action\n\t// properties via a separate `codeAction/resolve` request.\n\t//\n\t// @since 3.16.0\n\tResolveSupport *ClientCodeActionResolveOptions `json:\"resolveSupport,omitempty\"`\n\t// Whether the client honors the change annotations in\n\t// text edits and resource operations returned via the\n\t// `CodeAction#edit` property by for example presenting\n\t// the workspace edit in the user interface and asking\n\t// for confirmation.\n\t//\n\t// @since 3.16.0\n\tHonorsChangeAnnotations bool `json:\"honorsChangeAnnotations,omitempty\"`\n\t// Whether the client supports documentation for a class of\n\t// code actions.\n\t//\n\t// @since 3.18.0\n\t// @proposed\n\tDocumentationSupport bool `json:\"documentationSupport,omitempty\"`\n}\n\n// Contains additional diagnostic information about the context in which\n// a {@link CodeActionProvider.provideCodeActions code action} is run.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#codeActionContext\ntype CodeActionContext struct {\n\t// An array of diagnostics known on the client side overlapping the range provided to the\n\t// `textDocument/codeAction` request. They are provided so that the server knows which\n\t// errors are currently presented to the user for the given range. There is no guarantee\n\t// that these accurately reflect the error state of the resource. The primary parameter\n\t// to compute code actions is the provided range.\n\tDiagnostics []Diagnostic `json:\"diagnostics\"`\n\t// Requested kind of actions to return.\n\t//\n\t// Actions not of this kind are filtered out by the client before being shown. So servers\n\t// can omit computing them.\n\tOnly []CodeActionKind `json:\"only,omitempty\"`\n\t// The reason why code actions were requested.\n\t//\n\t// @since 3.17.0\n\tTriggerKind *CodeActionTriggerKind `json:\"triggerKind,omitempty\"`\n}\n\n// Captures why the code action is currently disabled.\n//\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#codeActionDisabled\ntype CodeActionDisabled struct {\n\t// Human readable description of why the code action is currently disabled.\n\t//\n\t// This is displayed in the code actions UI.\n\tReason string `json:\"reason\"`\n}\n\n// A set of predefined code action kinds\ntype CodeActionKind string\n\n// Documentation for a class of code actions.\n//\n// @since 3.18.0\n// @proposed\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#codeActionKindDocumentation\ntype CodeActionKindDocumentation struct {\n\t// The kind of the code action being documented.\n\t//\n\t// If the kind is generic, such as `CodeActionKind.Refactor`, the documentation will be shown whenever any\n\t// refactorings are returned. If the kind if more specific, such as `CodeActionKind.RefactorExtract`, the\n\t// documentation will only be shown when extract refactoring code actions are returned.\n\tKind CodeActionKind `json:\"kind\"`\n\t// Command that is ued to display the documentation to the user.\n\t//\n\t// The title of this documentation code action is taken from {@linkcode Command.title}\n\tCommand Command `json:\"command\"`\n}\n\n// Provider options for a {@link CodeActionRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#codeActionOptions\ntype CodeActionOptions struct {\n\t// CodeActionKinds that this server may return.\n\t//\n\t// The list of kinds may be generic, such as `CodeActionKind.Refactor`, or the server\n\t// may list out every specific kind they provide.\n\tCodeActionKinds []CodeActionKind `json:\"codeActionKinds,omitempty\"`\n\t// Static documentation for a class of code actions.\n\t//\n\t// Documentation from the provider should be shown in the code actions menu if either:\n\t//\n\t//\n\t// - Code actions of `kind` are requested by the editor. In this case, the editor will show the documentation that\n\t// most closely matches the requested code action kind. For example, if a provider has documentation for\n\t// both `Refactor` and `RefactorExtract`, when the user requests code actions for `RefactorExtract`,\n\t// the editor will use the documentation for `RefactorExtract` instead of the documentation for `Refactor`.\n\t//\n\t//\n\t// - Any code actions of `kind` are returned by the provider.\n\t//\n\t// At most one documentation entry should be shown per provider.\n\t//\n\t// @since 3.18.0\n\t// @proposed\n\tDocumentation []CodeActionKindDocumentation `json:\"documentation,omitempty\"`\n\t// The server provides support to resolve additional\n\t// information for a code action.\n\t//\n\t// @since 3.16.0\n\tResolveProvider bool `json:\"resolveProvider,omitempty\"`\n\tWorkDoneProgressOptions\n}\n\n// The parameters of a {@link CodeActionRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#codeActionParams\ntype CodeActionParams struct {\n\t// The document in which the command was invoked.\n\tTextDocument TextDocumentIdentifier `json:\"textDocument\"`\n\t// The range for which the command was invoked.\n\tRange Range `json:\"range\"`\n\t// Context carrying additional information.\n\tContext CodeActionContext `json:\"context\"`\n\tWorkDoneProgressParams\n\tPartialResultParams\n}\n\n// Registration options for a {@link CodeActionRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#codeActionRegistrationOptions\ntype CodeActionRegistrationOptions struct {\n\tTextDocumentRegistrationOptions\n\tCodeActionOptions\n}\n\n// The reason why code actions were requested.\n//\n// @since 3.17.0\ntype CodeActionTriggerKind uint32\n\n// Structure to capture a description for an error code.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#codeDescription\ntype CodeDescription struct {\n\t// An URI to open with more information about the diagnostic error.\n\tHref URI `json:\"href\"`\n}\n\n// A code lens represents a {@link Command command} that should be shown along with\n// source text, like the number of references, a way to run tests, etc.\n//\n// A code lens is _unresolved_ when no command is associated to it. For performance\n// reasons the creation of a code lens and resolving should be done in two stages.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#codeLens\ntype CodeLens struct {\n\t// The range in which this code lens is valid. Should only span a single line.\n\tRange Range `json:\"range\"`\n\t// The command this code lens represents.\n\tCommand *Command `json:\"command,omitempty\"`\n\t// A data entry field that is preserved on a code lens item between\n\t// a {@link CodeLensRequest} and a {@link CodeLensResolveRequest}\n\tData interface{} `json:\"data,omitempty\"`\n}\n\n// The client capabilities of a {@link CodeLensRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#codeLensClientCapabilities\ntype CodeLensClientCapabilities struct {\n\t// Whether code lens supports dynamic registration.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n\t// Whether the client supports resolving additional code lens\n\t// properties via a separate `codeLens/resolve` request.\n\t//\n\t// @since 3.18.0\n\tResolveSupport *ClientCodeLensResolveOptions `json:\"resolveSupport,omitempty\"`\n}\n\n// Code Lens provider options of a {@link CodeLensRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#codeLensOptions\ntype CodeLensOptions struct {\n\t// Code lens has a resolve provider as well.\n\tResolveProvider bool `json:\"resolveProvider,omitempty\"`\n\tWorkDoneProgressOptions\n}\n\n// The parameters of a {@link CodeLensRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#codeLensParams\ntype CodeLensParams struct {\n\t// The document to request code lens for.\n\tTextDocument TextDocumentIdentifier `json:\"textDocument\"`\n\tWorkDoneProgressParams\n\tPartialResultParams\n}\n\n// Registration options for a {@link CodeLensRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#codeLensRegistrationOptions\ntype CodeLensRegistrationOptions struct {\n\tTextDocumentRegistrationOptions\n\tCodeLensOptions\n}\n\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#codeLensWorkspaceClientCapabilities\ntype CodeLensWorkspaceClientCapabilities struct {\n\t// Whether the client implementation supports a refresh request sent from the\n\t// server to the client.\n\t//\n\t// Note that this event is global and will force the client to refresh all\n\t// code lenses currently shown. It should be used with absolute care and is\n\t// useful for situation where a server for example detect a project wide\n\t// change that requires such a calculation.\n\tRefreshSupport bool `json:\"refreshSupport,omitempty\"`\n}\n\n// Represents a color in RGBA space.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#color\ntype Color struct {\n\t// The red component of this color in the range [0-1].\n\tRed float64 `json:\"red\"`\n\t// The green component of this color in the range [0-1].\n\tGreen float64 `json:\"green\"`\n\t// The blue component of this color in the range [0-1].\n\tBlue float64 `json:\"blue\"`\n\t// The alpha component of this color in the range [0-1].\n\tAlpha float64 `json:\"alpha\"`\n}\n\n// Represents a color range from a document.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#colorInformation\ntype ColorInformation struct {\n\t// The range in the document where this color appears.\n\tRange Range `json:\"range\"`\n\t// The actual color value for this color range.\n\tColor Color `json:\"color\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#colorPresentation\ntype ColorPresentation struct {\n\t// The label of this color presentation. It will be shown on the color\n\t// picker header. By default this is also the text that is inserted when selecting\n\t// this color presentation.\n\tLabel string `json:\"label\"`\n\t// An {@link TextEdit edit} which is applied to a document when selecting\n\t// this presentation for the color. When `falsy` the {@link ColorPresentation.label label}\n\t// is used.\n\tTextEdit *TextEdit `json:\"textEdit,omitempty\"`\n\t// An optional array of additional {@link TextEdit text edits} that are applied when\n\t// selecting this color presentation. Edits must not overlap with the main {@link ColorPresentation.textEdit edit} nor with themselves.\n\tAdditionalTextEdits []TextEdit `json:\"additionalTextEdits,omitempty\"`\n}\n\n// Parameters for a {@link ColorPresentationRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#colorPresentationParams\ntype ColorPresentationParams struct {\n\t// The text document.\n\tTextDocument TextDocumentIdentifier `json:\"textDocument\"`\n\t// The color to request presentations for.\n\tColor Color `json:\"color\"`\n\t// The range where the color would be inserted. Serves as a context.\n\tRange Range `json:\"range\"`\n\tWorkDoneProgressParams\n\tPartialResultParams\n}\n\n// Represents a reference to a command. Provides a title which\n// will be used to represent a command in the UI and, optionally,\n// an array of arguments which will be passed to the command handler\n// function when invoked.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#command\ntype Command struct {\n\t// Title of the command, like `save`.\n\tTitle string `json:\"title\"`\n\t// An optional tooltip.\n\t//\n\t// @since 3.18.0\n\t// @proposed\n\tTooltip string `json:\"tooltip,omitempty\"`\n\t// The identifier of the actual command handler.\n\tCommand string `json:\"command\"`\n\t// Arguments that the command handler should be\n\t// invoked with.\n\tArguments []json.RawMessage `json:\"arguments,omitempty\"`\n}\n\n// Completion client capabilities\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#completionClientCapabilities\ntype CompletionClientCapabilities struct {\n\t// Whether completion supports dynamic registration.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n\t// The client supports the following `CompletionItem` specific\n\t// capabilities.\n\tCompletionItem ClientCompletionItemOptions `json:\"completionItem,omitempty\"`\n\tCompletionItemKind *ClientCompletionItemOptionsKind `json:\"completionItemKind,omitempty\"`\n\t// Defines how the client handles whitespace and indentation\n\t// when accepting a completion item that uses multi line\n\t// text in either `insertText` or `textEdit`.\n\t//\n\t// @since 3.17.0\n\tInsertTextMode InsertTextMode `json:\"insertTextMode,omitempty\"`\n\t// The client supports to send additional context information for a\n\t// `textDocument/completion` request.\n\tContextSupport bool `json:\"contextSupport,omitempty\"`\n\t// The client supports the following `CompletionList` specific\n\t// capabilities.\n\t//\n\t// @since 3.17.0\n\tCompletionList *CompletionListCapabilities `json:\"completionList,omitempty\"`\n}\n\n// Contains additional information about the context in which a completion request is triggered.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#completionContext\ntype CompletionContext struct {\n\t// How the completion was triggered.\n\tTriggerKind CompletionTriggerKind `json:\"triggerKind\"`\n\t// The trigger character (a single character) that has trigger code complete.\n\t// Is undefined if `triggerKind !== CompletionTriggerKind.TriggerCharacter`\n\tTriggerCharacter string `json:\"triggerCharacter,omitempty\"`\n}\n\n// A completion item represents a text snippet that is\n// proposed to complete text that is being typed.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#completionItem\ntype CompletionItem struct {\n\t// The label of this completion item.\n\t//\n\t// The label property is also by default the text that\n\t// is inserted when selecting this completion.\n\t//\n\t// If label details are provided the label itself should\n\t// be an unqualified name of the completion item.\n\tLabel string `json:\"label\"`\n\t// Additional details for the label\n\t//\n\t// @since 3.17.0\n\tLabelDetails *CompletionItemLabelDetails `json:\"labelDetails,omitempty\"`\n\t// The kind of this completion item. Based of the kind\n\t// an icon is chosen by the editor.\n\tKind CompletionItemKind `json:\"kind,omitempty\"`\n\t// Tags for this completion item.\n\t//\n\t// @since 3.15.0\n\tTags []CompletionItemTag `json:\"tags,omitempty\"`\n\t// A human-readable string with additional information\n\t// about this item, like type or symbol information.\n\tDetail string `json:\"detail,omitempty\"`\n\t// A human-readable string that represents a doc-comment.\n\tDocumentation *Or_CompletionItem_documentation `json:\"documentation,omitempty\"`\n\t// Indicates if this item is deprecated.\n\t// @deprecated Use `tags` instead.\n\tDeprecated bool `json:\"deprecated,omitempty\"`\n\t// Select this item when showing.\n\t//\n\t// *Note* that only one completion item can be selected and that the\n\t// tool / client decides which item that is. The rule is that the *first*\n\t// item of those that match best is selected.\n\tPreselect bool `json:\"preselect,omitempty\"`\n\t// A string that should be used when comparing this item\n\t// with other items. When `falsy` the {@link CompletionItem.label label}\n\t// is used.\n\tSortText string `json:\"sortText,omitempty\"`\n\t// A string that should be used when filtering a set of\n\t// completion items. When `falsy` the {@link CompletionItem.label label}\n\t// is used.\n\tFilterText string `json:\"filterText,omitempty\"`\n\t// A string that should be inserted into a document when selecting\n\t// this completion. When `falsy` the {@link CompletionItem.label label}\n\t// is used.\n\t//\n\t// The `insertText` is subject to interpretation by the client side.\n\t// Some tools might not take the string literally. For example\n\t// VS Code when code complete is requested in this example\n\t// `con` and a completion item with an `insertText` of\n\t// `console` is provided it will only insert `sole`. Therefore it is\n\t// recommended to use `textEdit` instead since it avoids additional client\n\t// side interpretation.\n\tInsertText string `json:\"insertText,omitempty\"`\n\t// The format of the insert text. The format applies to both the\n\t// `insertText` property and the `newText` property of a provided\n\t// `textEdit`. If omitted defaults to `InsertTextFormat.PlainText`.\n\t//\n\t// Please note that the insertTextFormat doesn't apply to\n\t// `additionalTextEdits`.\n\tInsertTextFormat *InsertTextFormat `json:\"insertTextFormat,omitempty\"`\n\t// How whitespace and indentation is handled during completion\n\t// item insertion. If not provided the clients default value depends on\n\t// the `textDocument.completion.insertTextMode` client capability.\n\t//\n\t// @since 3.16.0\n\tInsertTextMode *InsertTextMode `json:\"insertTextMode,omitempty\"`\n\t// An {@link TextEdit edit} which is applied to a document when selecting\n\t// this completion. When an edit is provided the value of\n\t// {@link CompletionItem.insertText insertText} is ignored.\n\t//\n\t// Most editors support two different operations when accepting a completion\n\t// item. One is to insert a completion text and the other is to replace an\n\t// existing text with a completion text. Since this can usually not be\n\t// predetermined by a server it can report both ranges. Clients need to\n\t// signal support for `InsertReplaceEdits` via the\n\t// `textDocument.completion.insertReplaceSupport` client capability\n\t// property.\n\t//\n\t// *Note 1:* The text edit's range as well as both ranges from an insert\n\t// replace edit must be a [single line] and they must contain the position\n\t// at which completion has been requested.\n\t// *Note 2:* If an `InsertReplaceEdit` is returned the edit's insert range\n\t// must be a prefix of the edit's replace range, that means it must be\n\t// contained and starting at the same position.\n\t//\n\t// @since 3.16.0 additional type `InsertReplaceEdit`\n\tTextEdit *Or_CompletionItem_textEdit `json:\"textEdit,omitempty\"`\n\t// The edit text used if the completion item is part of a CompletionList and\n\t// CompletionList defines an item default for the text edit range.\n\t//\n\t// Clients will only honor this property if they opt into completion list\n\t// item defaults using the capability `completionList.itemDefaults`.\n\t//\n\t// If not provided and a list's default range is provided the label\n\t// property is used as a text.\n\t//\n\t// @since 3.17.0\n\tTextEditText string `json:\"textEditText,omitempty\"`\n\t// An optional array of additional {@link TextEdit text edits} that are applied when\n\t// selecting this completion. Edits must not overlap (including the same insert position)\n\t// with the main {@link CompletionItem.textEdit edit} nor with themselves.\n\t//\n\t// Additional text edits should be used to change text unrelated to the current cursor position\n\t// (for example adding an import statement at the top of the file if the completion item will\n\t// insert an unqualified type).\n\tAdditionalTextEdits []TextEdit `json:\"additionalTextEdits,omitempty\"`\n\t// An optional set of characters that when pressed while this completion is active will accept it first and\n\t// then type that character. *Note* that all commit characters should have `length=1` and that superfluous\n\t// characters will be ignored.\n\tCommitCharacters []string `json:\"commitCharacters,omitempty\"`\n\t// An optional {@link Command command} that is executed *after* inserting this completion. *Note* that\n\t// additional modifications to the current document should be described with the\n\t// {@link CompletionItem.additionalTextEdits additionalTextEdits}-property.\n\tCommand *Command `json:\"command,omitempty\"`\n\t// A data entry field that is preserved on a completion item between a\n\t// {@link CompletionRequest} and a {@link CompletionResolveRequest}.\n\tData interface{} `json:\"data,omitempty\"`\n}\n\n// In many cases the items of an actual completion result share the same\n// value for properties like `commitCharacters` or the range of a text\n// edit. A completion list can therefore define item defaults which will\n// be used if a completion item itself doesn't specify the value.\n//\n// If a completion list specifies a default value and a completion item\n// also specifies a corresponding value the one from the item is used.\n//\n// Servers are only allowed to return default values if the client\n// signals support for this via the `completionList.itemDefaults`\n// capability.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#completionItemDefaults\ntype CompletionItemDefaults struct {\n\t// A default commit character set.\n\t//\n\t// @since 3.17.0\n\tCommitCharacters []string `json:\"commitCharacters,omitempty\"`\n\t// A default edit range.\n\t//\n\t// @since 3.17.0\n\tEditRange *Or_CompletionItemDefaults_editRange `json:\"editRange,omitempty\"`\n\t// A default insert text format.\n\t//\n\t// @since 3.17.0\n\tInsertTextFormat *InsertTextFormat `json:\"insertTextFormat,omitempty\"`\n\t// A default insert text mode.\n\t//\n\t// @since 3.17.0\n\tInsertTextMode *InsertTextMode `json:\"insertTextMode,omitempty\"`\n\t// A default data value.\n\t//\n\t// @since 3.17.0\n\tData interface{} `json:\"data,omitempty\"`\n}\n\n// The kind of a completion entry.\ntype CompletionItemKind uint32\n\n// Additional details for a completion item label.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#completionItemLabelDetails\ntype CompletionItemLabelDetails struct {\n\t// An optional string which is rendered less prominently directly after {@link CompletionItem.label label},\n\t// without any spacing. Should be used for function signatures and type annotations.\n\tDetail string `json:\"detail,omitempty\"`\n\t// An optional string which is rendered less prominently after {@link CompletionItem.detail}. Should be used\n\t// for fully qualified names and file paths.\n\tDescription string `json:\"description,omitempty\"`\n}\n\n// Completion item tags are extra annotations that tweak the rendering of a completion\n// item.\n//\n// @since 3.15.0\ntype CompletionItemTag uint32\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#completionItemTagOptions\ntype CompletionItemTagOptions struct {\n\t// The tags supported by the client.\n\tValueSet []CompletionItemTag `json:\"valueSet\"`\n}\n\n// Represents a collection of {@link CompletionItem completion items} to be presented\n// in the editor.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#completionList\ntype CompletionList struct {\n\t// This list it not complete. Further typing results in recomputing this list.\n\t//\n\t// Recomputed lists have all their items replaced (not appended) in the\n\t// incomplete completion sessions.\n\tIsIncomplete bool `json:\"isIncomplete\"`\n\t// In many cases the items of an actual completion result share the same\n\t// value for properties like `commitCharacters` or the range of a text\n\t// edit. A completion list can therefore define item defaults which will\n\t// be used if a completion item itself doesn't specify the value.\n\t//\n\t// If a completion list specifies a default value and a completion item\n\t// also specifies a corresponding value the one from the item is used.\n\t//\n\t// Servers are only allowed to return default values if the client\n\t// signals support for this via the `completionList.itemDefaults`\n\t// capability.\n\t//\n\t// @since 3.17.0\n\tItemDefaults *CompletionItemDefaults `json:\"itemDefaults,omitempty\"`\n\t// The completion items.\n\tItems []CompletionItem `json:\"items\"`\n}\n\n// The client supports the following `CompletionList` specific\n// capabilities.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#completionListCapabilities\ntype CompletionListCapabilities struct {\n\t// The client supports the following itemDefaults on\n\t// a completion list.\n\t//\n\t// The value lists the supported property names of the\n\t// `CompletionList.itemDefaults` object. If omitted\n\t// no properties are supported.\n\t//\n\t// @since 3.17.0\n\tItemDefaults []string `json:\"itemDefaults,omitempty\"`\n}\n\n// Completion options.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#completionOptions\ntype CompletionOptions struct {\n\t// Most tools trigger completion request automatically without explicitly requesting\n\t// it using a keyboard shortcut (e.g. Ctrl+Space). Typically they do so when the user\n\t// starts to type an identifier. For example if the user types `c` in a JavaScript file\n\t// code complete will automatically pop up present `console` besides others as a\n\t// completion item. Characters that make up identifiers don't need to be listed here.\n\t//\n\t// If code complete should automatically be trigger on characters not being valid inside\n\t// an identifier (for example `.` in JavaScript) list them in `triggerCharacters`.\n\tTriggerCharacters []string `json:\"triggerCharacters,omitempty\"`\n\t// The list of all possible characters that commit a completion. This field can be used\n\t// if clients don't support individual commit characters per completion item. See\n\t// `ClientCapabilities.textDocument.completion.completionItem.commitCharactersSupport`\n\t//\n\t// If a server provides both `allCommitCharacters` and commit characters on an individual\n\t// completion item the ones on the completion item win.\n\t//\n\t// @since 3.2.0\n\tAllCommitCharacters []string `json:\"allCommitCharacters,omitempty\"`\n\t// The server provides support to resolve additional\n\t// information for a completion item.\n\tResolveProvider bool `json:\"resolveProvider,omitempty\"`\n\t// The server supports the following `CompletionItem` specific\n\t// capabilities.\n\t//\n\t// @since 3.17.0\n\tCompletionItem *ServerCompletionItemOptions `json:\"completionItem,omitempty\"`\n\tWorkDoneProgressOptions\n}\n\n// Completion parameters\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#completionParams\ntype CompletionParams struct {\n\t// The completion context. This is only available it the client specifies\n\t// to send this using the client capability `textDocument.completion.contextSupport === true`\n\tContext CompletionContext `json:\"context,omitempty\"`\n\tTextDocumentPositionParams\n\tWorkDoneProgressParams\n\tPartialResultParams\n}\n\n// Registration options for a {@link CompletionRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#completionRegistrationOptions\ntype CompletionRegistrationOptions struct {\n\tTextDocumentRegistrationOptions\n\tCompletionOptions\n}\n\n// How a completion was triggered\ntype CompletionTriggerKind uint32\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#configurationItem\ntype ConfigurationItem struct {\n\t// The scope to get the configuration section for.\n\tScopeURI *URI `json:\"scopeUri,omitempty\"`\n\t// The configuration section asked for.\n\tSection string `json:\"section,omitempty\"`\n}\n\n// The parameters of a configuration request.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#configurationParams\ntype ConfigurationParams struct {\n\tItems []ConfigurationItem `json:\"items\"`\n}\n\n// Create file operation.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#createFile\ntype CreateFile struct {\n\t// A create\n\tKind string `json:\"kind\"`\n\t// The resource to create.\n\tURI DocumentUri `json:\"uri\"`\n\t// Additional options\n\tOptions *CreateFileOptions `json:\"options,omitempty\"`\n\tResourceOperation\n}\n\n// Options to create a file.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#createFileOptions\ntype CreateFileOptions struct {\n\t// Overwrite existing file. Overwrite wins over `ignoreIfExists`\n\tOverwrite bool `json:\"overwrite,omitempty\"`\n\t// Ignore if exists.\n\tIgnoreIfExists bool `json:\"ignoreIfExists,omitempty\"`\n}\n\n// The parameters sent in notifications/requests for user-initiated creation of\n// files.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#createFilesParams\ntype CreateFilesParams struct {\n\t// An array of all files/folders created in this operation.\n\tFiles []FileCreate `json:\"files\"`\n}\n\n// The declaration of a symbol representation as one or many {@link Location locations}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#declaration\ntype Declaration = Or_Declaration // (alias)\n// @since 3.14.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#declarationClientCapabilities\ntype DeclarationClientCapabilities struct {\n\t// Whether declaration supports dynamic registration. If this is set to `true`\n\t// the client supports the new `DeclarationRegistrationOptions` return value\n\t// for the corresponding server capability as well.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n\t// The client supports additional metadata in the form of declaration links.\n\tLinkSupport bool `json:\"linkSupport,omitempty\"`\n}\n\n// Information about where a symbol is declared.\n//\n// Provides additional metadata over normal {@link Location location} declarations, including the range of\n// the declaring symbol.\n//\n// Servers should prefer returning `DeclarationLink` over `Declaration` if supported\n// by the client.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#declarationLink\ntype DeclarationLink = LocationLink // (alias)\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#declarationOptions\ntype DeclarationOptions struct {\n\tWorkDoneProgressOptions\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#declarationParams\ntype DeclarationParams struct {\n\tTextDocumentPositionParams\n\tWorkDoneProgressParams\n\tPartialResultParams\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#declarationRegistrationOptions\ntype DeclarationRegistrationOptions struct {\n\tDeclarationOptions\n\tTextDocumentRegistrationOptions\n\tStaticRegistrationOptions\n}\n\n// The definition of a symbol represented as one or many {@link Location locations}.\n// For most programming languages there is only one location at which a symbol is\n// defined.\n//\n// Servers should prefer returning `DefinitionLink` over `Definition` if supported\n// by the client.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#definition\ntype Definition = Or_Definition // (alias)\n// Client Capabilities for a {@link DefinitionRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#definitionClientCapabilities\ntype DefinitionClientCapabilities struct {\n\t// Whether definition supports dynamic registration.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n\t// The client supports additional metadata in the form of definition links.\n\t//\n\t// @since 3.14.0\n\tLinkSupport bool `json:\"linkSupport,omitempty\"`\n}\n\n// Information about where a symbol is defined.\n//\n// Provides additional metadata over normal {@link Location location} definitions, including the range of\n// the defining symbol\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#definitionLink\ntype DefinitionLink = LocationLink // (alias)\n// Server Capabilities for a {@link DefinitionRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#definitionOptions\ntype DefinitionOptions struct {\n\tWorkDoneProgressOptions\n}\n\n// Parameters for a {@link DefinitionRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#definitionParams\ntype DefinitionParams struct {\n\tTextDocumentPositionParams\n\tWorkDoneProgressParams\n\tPartialResultParams\n}\n\n// Registration options for a {@link DefinitionRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#definitionRegistrationOptions\ntype DefinitionRegistrationOptions struct {\n\tTextDocumentRegistrationOptions\n\tDefinitionOptions\n}\n\n// Delete file operation\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#deleteFile\ntype DeleteFile struct {\n\t// A delete\n\tKind string `json:\"kind\"`\n\t// The file to delete.\n\tURI DocumentUri `json:\"uri\"`\n\t// Delete options.\n\tOptions *DeleteFileOptions `json:\"options,omitempty\"`\n\tResourceOperation\n}\n\n// Delete file options\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#deleteFileOptions\ntype DeleteFileOptions struct {\n\t// Delete the content recursively if a folder is denoted.\n\tRecursive bool `json:\"recursive,omitempty\"`\n\t// Ignore the operation if the file doesn't exist.\n\tIgnoreIfNotExists bool `json:\"ignoreIfNotExists,omitempty\"`\n}\n\n// The parameters sent in notifications/requests for user-initiated deletes of\n// files.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#deleteFilesParams\ntype DeleteFilesParams struct {\n\t// An array of all files/folders deleted in this operation.\n\tFiles []FileDelete `json:\"files\"`\n}\n\n// Represents a diagnostic, such as a compiler error or warning. Diagnostic objects\n// are only valid in the scope of a resource.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#diagnostic\ntype Diagnostic struct {\n\t// The range at which the message applies\n\tRange Range `json:\"range\"`\n\t// The diagnostic's severity. To avoid interpretation mismatches when a\n\t// server is used with different clients it is highly recommended that servers\n\t// always provide a severity value.\n\tSeverity DiagnosticSeverity `json:\"severity,omitempty\"`\n\t// The diagnostic's code, which usually appear in the user interface.\n\tCode interface{} `json:\"code,omitempty\"`\n\t// An optional property to describe the error code.\n\t// Requires the code field (above) to be present/not null.\n\t//\n\t// @since 3.16.0\n\tCodeDescription *CodeDescription `json:\"codeDescription,omitempty\"`\n\t// A human-readable string describing the source of this\n\t// diagnostic, e.g. 'typescript' or 'super lint'. It usually\n\t// appears in the user interface.\n\tSource string `json:\"source,omitempty\"`\n\t// The diagnostic's message. It usually appears in the user interface\n\tMessage string `json:\"message\"`\n\t// Additional metadata about the diagnostic.\n\t//\n\t// @since 3.15.0\n\tTags []DiagnosticTag `json:\"tags,omitempty\"`\n\t// An array of related diagnostic information, e.g. when symbol-names within\n\t// a scope collide all definitions can be marked via this property.\n\tRelatedInformation []DiagnosticRelatedInformation `json:\"relatedInformation,omitempty\"`\n\t// A data entry field that is preserved between a `textDocument/publishDiagnostics`\n\t// notification and `textDocument/codeAction` request.\n\t//\n\t// @since 3.16.0\n\tData *json.RawMessage `json:\"data,omitempty\"`\n}\n\n// Client capabilities specific to diagnostic pull requests.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#diagnosticClientCapabilities\ntype DiagnosticClientCapabilities struct {\n\t// Whether implementation supports dynamic registration. If this is set to `true`\n\t// the client supports the new `(TextDocumentRegistrationOptions & StaticRegistrationOptions)`\n\t// return value for the corresponding server capability as well.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n\t// Whether the clients supports related documents for document diagnostic pulls.\n\tRelatedDocumentSupport bool `json:\"relatedDocumentSupport,omitempty\"`\n\tDiagnosticsCapabilities\n}\n\n// Diagnostic options.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#diagnosticOptions\ntype DiagnosticOptions struct {\n\t// An optional identifier under which the diagnostics are\n\t// managed by the client.\n\tIdentifier string `json:\"identifier,omitempty\"`\n\t// Whether the language has inter file dependencies meaning that\n\t// editing code in one file can result in a different diagnostic\n\t// set in another file. Inter file dependencies are common for\n\t// most programming languages and typically uncommon for linters.\n\tInterFileDependencies bool `json:\"interFileDependencies\"`\n\t// The server provides support for workspace diagnostics as well.\n\tWorkspaceDiagnostics bool `json:\"workspaceDiagnostics\"`\n\tWorkDoneProgressOptions\n}\n\n// Diagnostic registration options.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#diagnosticRegistrationOptions\ntype DiagnosticRegistrationOptions struct {\n\tTextDocumentRegistrationOptions\n\tDiagnosticOptions\n\tStaticRegistrationOptions\n}\n\n// Represents a related message and source code location for a diagnostic. This should be\n// used to point to code locations that cause or related to a diagnostics, e.g when duplicating\n// a symbol in a scope.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#diagnosticRelatedInformation\ntype DiagnosticRelatedInformation struct {\n\t// The location of this related diagnostic information.\n\tLocation Location `json:\"location\"`\n\t// The message of this related diagnostic information.\n\tMessage string `json:\"message\"`\n}\n\n// Cancellation data returned from a diagnostic request.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#diagnosticServerCancellationData\ntype DiagnosticServerCancellationData struct {\n\tRetriggerRequest bool `json:\"retriggerRequest\"`\n}\n\n// The diagnostic's severity.\ntype DiagnosticSeverity uint32\n\n// The diagnostic tags.\n//\n// @since 3.15.0\ntype DiagnosticTag uint32\n\n// Workspace client capabilities specific to diagnostic pull requests.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#diagnosticWorkspaceClientCapabilities\ntype DiagnosticWorkspaceClientCapabilities struct {\n\t// Whether the client implementation supports a refresh request sent from\n\t// the server to the client.\n\t//\n\t// Note that this event is global and will force the client to refresh all\n\t// pulled diagnostics currently shown. It should be used with absolute care and\n\t// is useful for situation where a server for example detects a project wide\n\t// change that requires such a calculation.\n\tRefreshSupport bool `json:\"refreshSupport,omitempty\"`\n}\n\n// General diagnostics capabilities for pull and push model.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#diagnosticsCapabilities\ntype DiagnosticsCapabilities struct {\n\t// Whether the clients accepts diagnostics with related information.\n\tRelatedInformation bool `json:\"relatedInformation,omitempty\"`\n\t// Client supports the tag property to provide meta data about a diagnostic.\n\t// Clients supporting tags have to handle unknown tags gracefully.\n\t//\n\t// @since 3.15.0\n\tTagSupport *ClientDiagnosticsTagOptions `json:\"tagSupport,omitempty\"`\n\t// Client supports a codeDescription property\n\t//\n\t// @since 3.16.0\n\tCodeDescriptionSupport bool `json:\"codeDescriptionSupport,omitempty\"`\n\t// Whether code action supports the `data` property which is\n\t// preserved between a `textDocument/publishDiagnostics` and\n\t// `textDocument/codeAction` request.\n\t//\n\t// @since 3.16.0\n\tDataSupport bool `json:\"dataSupport,omitempty\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#didChangeConfigurationClientCapabilities\ntype DidChangeConfigurationClientCapabilities struct {\n\t// Did change configuration notification supports dynamic registration.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n}\n\n// The parameters of a change configuration notification.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#didChangeConfigurationParams\ntype DidChangeConfigurationParams struct {\n\t// The actual changed settings\n\tSettings interface{} `json:\"settings\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#didChangeConfigurationRegistrationOptions\ntype DidChangeConfigurationRegistrationOptions struct {\n\tSection *Or_DidChangeConfigurationRegistrationOptions_section `json:\"section,omitempty\"`\n}\n\n// The params sent in a change notebook document notification.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#didChangeNotebookDocumentParams\ntype DidChangeNotebookDocumentParams struct {\n\t// The notebook document that did change. The version number points\n\t// to the version after all provided changes have been applied. If\n\t// only the text document content of a cell changes the notebook version\n\t// doesn't necessarily have to change.\n\tNotebookDocument VersionedNotebookDocumentIdentifier `json:\"notebookDocument\"`\n\t// The actual changes to the notebook document.\n\t//\n\t// The changes describe single state changes to the notebook document.\n\t// So if there are two changes c1 (at array index 0) and c2 (at array\n\t// index 1) for a notebook in state S then c1 moves the notebook from\n\t// S to S' and c2 from S' to S''. So c1 is computed on the state S and\n\t// c2 is computed on the state S'.\n\t//\n\t// To mirror the content of a notebook using change events use the following approach:\n\t//\n\t// - start with the same initial content\n\t// - apply the 'notebookDocument/didChange' notifications in the order you receive them.\n\t// - apply the `NotebookChangeEvent`s in a single notification in the order\n\t// you receive them.\n\tChange NotebookDocumentChangeEvent `json:\"change\"`\n}\n\n// The change text document notification's parameters.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#didChangeTextDocumentParams\ntype DidChangeTextDocumentParams struct {\n\t// The document that did change. The version number points\n\t// to the version after all provided content changes have\n\t// been applied.\n\tTextDocument VersionedTextDocumentIdentifier `json:\"textDocument\"`\n\t// The actual content changes. The content changes describe single state changes\n\t// to the document. So if there are two content changes c1 (at array index 0) and\n\t// c2 (at array index 1) for a document in state S then c1 moves the document from\n\t// S to S' and c2 from S' to S''. So c1 is computed on the state S and c2 is computed\n\t// on the state S'.\n\t//\n\t// To mirror the content of a document using change events use the following approach:\n\t//\n\t// - start with the same initial content\n\t// - apply the 'textDocument/didChange' notifications in the order you receive them.\n\t// - apply the `TextDocumentContentChangeEvent`s in a single notification in the order\n\t// you receive them.\n\tContentChanges []TextDocumentContentChangeEvent `json:\"contentChanges\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#didChangeWatchedFilesClientCapabilities\ntype DidChangeWatchedFilesClientCapabilities struct {\n\t// Did change watched files notification supports dynamic registration. Please note\n\t// that the current protocol doesn't support static configuration for file changes\n\t// from the server side.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n\t// Whether the client has support for {@link RelativePattern relative pattern}\n\t// or not.\n\t//\n\t// @since 3.17.0\n\tRelativePatternSupport bool `json:\"relativePatternSupport,omitempty\"`\n}\n\n// The watched files change notification's parameters.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#didChangeWatchedFilesParams\ntype DidChangeWatchedFilesParams struct {\n\t// The actual file events.\n\tChanges []FileEvent `json:\"changes\"`\n}\n\n// Describe options to be used when registered for text document change events.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#didChangeWatchedFilesRegistrationOptions\ntype DidChangeWatchedFilesRegistrationOptions struct {\n\t// The watchers to register.\n\tWatchers []FileSystemWatcher `json:\"watchers\"`\n}\n\n// The parameters of a `workspace/didChangeWorkspaceFolders` notification.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#didChangeWorkspaceFoldersParams\ntype DidChangeWorkspaceFoldersParams struct {\n\t// The actual workspace folder change event.\n\tEvent WorkspaceFoldersChangeEvent `json:\"event\"`\n}\n\n// The params sent in a close notebook document notification.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#didCloseNotebookDocumentParams\ntype DidCloseNotebookDocumentParams struct {\n\t// The notebook document that got closed.\n\tNotebookDocument NotebookDocumentIdentifier `json:\"notebookDocument\"`\n\t// The text documents that represent the content\n\t// of a notebook cell that got closed.\n\tCellTextDocuments []TextDocumentIdentifier `json:\"cellTextDocuments\"`\n}\n\n// The parameters sent in a close text document notification\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#didCloseTextDocumentParams\ntype DidCloseTextDocumentParams struct {\n\t// The document that was closed.\n\tTextDocument TextDocumentIdentifier `json:\"textDocument\"`\n}\n\n// The params sent in an open notebook document notification.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#didOpenNotebookDocumentParams\ntype DidOpenNotebookDocumentParams struct {\n\t// The notebook document that got opened.\n\tNotebookDocument NotebookDocument `json:\"notebookDocument\"`\n\t// The text documents that represent the content\n\t// of a notebook cell.\n\tCellTextDocuments []TextDocumentItem `json:\"cellTextDocuments\"`\n}\n\n// The parameters sent in an open text document notification\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#didOpenTextDocumentParams\ntype DidOpenTextDocumentParams struct {\n\t// The document that was opened.\n\tTextDocument TextDocumentItem `json:\"textDocument\"`\n}\n\n// The params sent in a save notebook document notification.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#didSaveNotebookDocumentParams\ntype DidSaveNotebookDocumentParams struct {\n\t// The notebook document that got saved.\n\tNotebookDocument NotebookDocumentIdentifier `json:\"notebookDocument\"`\n}\n\n// The parameters sent in a save text document notification\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#didSaveTextDocumentParams\ntype DidSaveTextDocumentParams struct {\n\t// The document that was saved.\n\tTextDocument TextDocumentIdentifier `json:\"textDocument\"`\n\t// Optional the content when saved. Depends on the includeText value\n\t// when the save notification was requested.\n\tText *string `json:\"text,omitempty\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentColorClientCapabilities\ntype DocumentColorClientCapabilities struct {\n\t// Whether implementation supports dynamic registration. If this is set to `true`\n\t// the client supports the new `DocumentColorRegistrationOptions` return value\n\t// for the corresponding server capability as well.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentColorOptions\ntype DocumentColorOptions struct {\n\tWorkDoneProgressOptions\n}\n\n// Parameters for a {@link DocumentColorRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentColorParams\ntype DocumentColorParams struct {\n\t// The text document.\n\tTextDocument TextDocumentIdentifier `json:\"textDocument\"`\n\tWorkDoneProgressParams\n\tPartialResultParams\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentColorRegistrationOptions\ntype DocumentColorRegistrationOptions struct {\n\tTextDocumentRegistrationOptions\n\tDocumentColorOptions\n\tStaticRegistrationOptions\n}\n\n// Parameters of the document diagnostic request.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentDiagnosticParams\ntype DocumentDiagnosticParams struct {\n\t// The text document.\n\tTextDocument TextDocumentIdentifier `json:\"textDocument\"`\n\t// The additional identifier provided during registration.\n\tIdentifier string `json:\"identifier,omitempty\"`\n\t// The result id of a previous response if provided.\n\tPreviousResultID string `json:\"previousResultId,omitempty\"`\n\tWorkDoneProgressParams\n\tPartialResultParams\n}\n\n// The result of a document diagnostic pull request. A report can\n// either be a full report containing all diagnostics for the\n// requested document or an unchanged report indicating that nothing\n// has changed in terms of diagnostics in comparison to the last\n// pull request.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentDiagnosticReport\ntype DocumentDiagnosticReport = Or_DocumentDiagnosticReport // (alias)\n// The document diagnostic report kinds.\n//\n// @since 3.17.0\ntype DocumentDiagnosticReportKind string\n\n// A partial result for a document diagnostic report.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentDiagnosticReportPartialResult\ntype DocumentDiagnosticReportPartialResult struct {\n\tRelatedDocuments map[DocumentUri]interface{} `json:\"relatedDocuments\"`\n}\n\n// A document filter describes a top level text document or\n// a notebook cell document.\n//\n// @since 3.17.0 - proposed support for NotebookCellTextDocumentFilter.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentFilter\ntype DocumentFilter = Or_DocumentFilter // (alias)\n// Client capabilities of a {@link DocumentFormattingRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentFormattingClientCapabilities\ntype DocumentFormattingClientCapabilities struct {\n\t// Whether formatting supports dynamic registration.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n}\n\n// Provider options for a {@link DocumentFormattingRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentFormattingOptions\ntype DocumentFormattingOptions struct {\n\tWorkDoneProgressOptions\n}\n\n// The parameters of a {@link DocumentFormattingRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentFormattingParams\ntype DocumentFormattingParams struct {\n\t// The document to format.\n\tTextDocument TextDocumentIdentifier `json:\"textDocument\"`\n\t// The format options.\n\tOptions FormattingOptions `json:\"options\"`\n\tWorkDoneProgressParams\n}\n\n// Registration options for a {@link DocumentFormattingRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentFormattingRegistrationOptions\ntype DocumentFormattingRegistrationOptions struct {\n\tTextDocumentRegistrationOptions\n\tDocumentFormattingOptions\n}\n\n// A document highlight is a range inside a text document which deserves\n// special attention. Usually a document highlight is visualized by changing\n// the background color of its range.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentHighlight\ntype DocumentHighlight struct {\n\t// The range this highlight applies to.\n\tRange Range `json:\"range\"`\n\t// The highlight kind, default is {@link DocumentHighlightKind.Text text}.\n\tKind DocumentHighlightKind `json:\"kind,omitempty\"`\n}\n\n// Client Capabilities for a {@link DocumentHighlightRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentHighlightClientCapabilities\ntype DocumentHighlightClientCapabilities struct {\n\t// Whether document highlight supports dynamic registration.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n}\n\n// A document highlight kind.\ntype DocumentHighlightKind uint32\n\n// Provider options for a {@link DocumentHighlightRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentHighlightOptions\ntype DocumentHighlightOptions struct {\n\tWorkDoneProgressOptions\n}\n\n// Parameters for a {@link DocumentHighlightRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentHighlightParams\ntype DocumentHighlightParams struct {\n\tTextDocumentPositionParams\n\tWorkDoneProgressParams\n\tPartialResultParams\n}\n\n// Registration options for a {@link DocumentHighlightRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentHighlightRegistrationOptions\ntype DocumentHighlightRegistrationOptions struct {\n\tTextDocumentRegistrationOptions\n\tDocumentHighlightOptions\n}\n\n// A document link is a range in a text document that links to an internal or external resource, like another\n// text document or a web site.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentLink\ntype DocumentLink struct {\n\t// The range this link applies to.\n\tRange Range `json:\"range\"`\n\t// The uri this link points to. If missing a resolve request is sent later.\n\tTarget *URI `json:\"target,omitempty\"`\n\t// The tooltip text when you hover over this link.\n\t//\n\t// If a tooltip is provided, is will be displayed in a string that includes instructions on how to\n\t// trigger the link, such as `{0} (ctrl + click)`. The specific instructions vary depending on OS,\n\t// user settings, and localization.\n\t//\n\t// @since 3.15.0\n\tTooltip string `json:\"tooltip,omitempty\"`\n\t// A data entry field that is preserved on a document link between a\n\t// DocumentLinkRequest and a DocumentLinkResolveRequest.\n\tData interface{} `json:\"data,omitempty\"`\n}\n\n// The client capabilities of a {@link DocumentLinkRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentLinkClientCapabilities\ntype DocumentLinkClientCapabilities struct {\n\t// Whether document link supports dynamic registration.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n\t// Whether the client supports the `tooltip` property on `DocumentLink`.\n\t//\n\t// @since 3.15.0\n\tTooltipSupport bool `json:\"tooltipSupport,omitempty\"`\n}\n\n// Provider options for a {@link DocumentLinkRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentLinkOptions\ntype DocumentLinkOptions struct {\n\t// Document links have a resolve provider as well.\n\tResolveProvider bool `json:\"resolveProvider,omitempty\"`\n\tWorkDoneProgressOptions\n}\n\n// The parameters of a {@link DocumentLinkRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentLinkParams\ntype DocumentLinkParams struct {\n\t// The document to provide document links for.\n\tTextDocument TextDocumentIdentifier `json:\"textDocument\"`\n\tWorkDoneProgressParams\n\tPartialResultParams\n}\n\n// Registration options for a {@link DocumentLinkRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentLinkRegistrationOptions\ntype DocumentLinkRegistrationOptions struct {\n\tTextDocumentRegistrationOptions\n\tDocumentLinkOptions\n}\n\n// Client capabilities of a {@link DocumentOnTypeFormattingRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentOnTypeFormattingClientCapabilities\ntype DocumentOnTypeFormattingClientCapabilities struct {\n\t// Whether on type formatting supports dynamic registration.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n}\n\n// Provider options for a {@link DocumentOnTypeFormattingRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentOnTypeFormattingOptions\ntype DocumentOnTypeFormattingOptions struct {\n\t// A character on which formatting should be triggered, like `{`.\n\tFirstTriggerCharacter string `json:\"firstTriggerCharacter\"`\n\t// More trigger characters.\n\tMoreTriggerCharacter []string `json:\"moreTriggerCharacter,omitempty\"`\n}\n\n// The parameters of a {@link DocumentOnTypeFormattingRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentOnTypeFormattingParams\ntype DocumentOnTypeFormattingParams struct {\n\t// The document to format.\n\tTextDocument TextDocumentIdentifier `json:\"textDocument\"`\n\t// The position around which the on type formatting should happen.\n\t// This is not necessarily the exact position where the character denoted\n\t// by the property `ch` got typed.\n\tPosition Position `json:\"position\"`\n\t// The character that has been typed that triggered the formatting\n\t// on type request. That is not necessarily the last character that\n\t// got inserted into the document since the client could auto insert\n\t// characters as well (e.g. like automatic brace completion).\n\tCh string `json:\"ch\"`\n\t// The formatting options.\n\tOptions FormattingOptions `json:\"options\"`\n}\n\n// Registration options for a {@link DocumentOnTypeFormattingRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentOnTypeFormattingRegistrationOptions\ntype DocumentOnTypeFormattingRegistrationOptions struct {\n\tTextDocumentRegistrationOptions\n\tDocumentOnTypeFormattingOptions\n}\n\n// Client capabilities of a {@link DocumentRangeFormattingRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentRangeFormattingClientCapabilities\ntype DocumentRangeFormattingClientCapabilities struct {\n\t// Whether range formatting supports dynamic registration.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n\t// Whether the client supports formatting multiple ranges at once.\n\t//\n\t// @since 3.18.0\n\t// @proposed\n\tRangesSupport bool `json:\"rangesSupport,omitempty\"`\n}\n\n// Provider options for a {@link DocumentRangeFormattingRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentRangeFormattingOptions\ntype DocumentRangeFormattingOptions struct {\n\t// Whether the server supports formatting multiple ranges at once.\n\t//\n\t// @since 3.18.0\n\t// @proposed\n\tRangesSupport bool `json:\"rangesSupport,omitempty\"`\n\tWorkDoneProgressOptions\n}\n\n// The parameters of a {@link DocumentRangeFormattingRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentRangeFormattingParams\ntype DocumentRangeFormattingParams struct {\n\t// The document to format.\n\tTextDocument TextDocumentIdentifier `json:\"textDocument\"`\n\t// The range to format\n\tRange Range `json:\"range\"`\n\t// The format options\n\tOptions FormattingOptions `json:\"options\"`\n\tWorkDoneProgressParams\n}\n\n// Registration options for a {@link DocumentRangeFormattingRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentRangeFormattingRegistrationOptions\ntype DocumentRangeFormattingRegistrationOptions struct {\n\tTextDocumentRegistrationOptions\n\tDocumentRangeFormattingOptions\n}\n\n// The parameters of a {@link DocumentRangesFormattingRequest}.\n//\n// @since 3.18.0\n// @proposed\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentRangesFormattingParams\ntype DocumentRangesFormattingParams struct {\n\t// The document to format.\n\tTextDocument TextDocumentIdentifier `json:\"textDocument\"`\n\t// The ranges to format\n\tRanges []Range `json:\"ranges\"`\n\t// The format options\n\tOptions FormattingOptions `json:\"options\"`\n\tWorkDoneProgressParams\n}\n\n// A document selector is the combination of one or many document filters.\n//\n// @sample `let sel:DocumentSelector = [{ language: 'typescript' }, { language: 'json', pattern: '**∕tsconfig.json' }]`;\n//\n// The use of a string as a document filter is deprecated @since 3.16.0.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentSelector\ntype DocumentSelector = []DocumentFilter // (alias)\n// Represents programming constructs like variables, classes, interfaces etc.\n// that appear in a document. Document symbols can be hierarchical and they\n// have two ranges: one that encloses its definition and one that points to\n// its most interesting range, e.g. the range of an identifier.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentSymbol\ntype DocumentSymbol struct {\n\t// The name of this symbol. Will be displayed in the user interface and therefore must not be\n\t// an empty string or a string only consisting of white spaces.\n\tName string `json:\"name\"`\n\t// More detail for this symbol, e.g the signature of a function.\n\tDetail string `json:\"detail,omitempty\"`\n\t// The kind of this symbol.\n\tKind SymbolKind `json:\"kind\"`\n\t// Tags for this document symbol.\n\t//\n\t// @since 3.16.0\n\tTags []SymbolTag `json:\"tags,omitempty\"`\n\t// Indicates if this symbol is deprecated.\n\t//\n\t// @deprecated Use tags instead\n\tDeprecated bool `json:\"deprecated,omitempty\"`\n\t// The range enclosing this symbol not including leading/trailing whitespace but everything else\n\t// like comments. This information is typically used to determine if the clients cursor is\n\t// inside the symbol to reveal in the symbol in the UI.\n\tRange Range `json:\"range\"`\n\t// The range that should be selected and revealed when this symbol is being picked, e.g the name of a function.\n\t// Must be contained by the `range`.\n\tSelectionRange Range `json:\"selectionRange\"`\n\t// Children of this symbol, e.g. properties of a class.\n\tChildren []DocumentSymbol `json:\"children,omitempty\"`\n}\n\n// Client Capabilities for a {@link DocumentSymbolRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentSymbolClientCapabilities\ntype DocumentSymbolClientCapabilities struct {\n\t// Whether document symbol supports dynamic registration.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n\t// Specific capabilities for the `SymbolKind` in the\n\t// `textDocument/documentSymbol` request.\n\tSymbolKind *ClientSymbolKindOptions `json:\"symbolKind,omitempty\"`\n\t// The client supports hierarchical document symbols.\n\tHierarchicalDocumentSymbolSupport bool `json:\"hierarchicalDocumentSymbolSupport,omitempty\"`\n\t// The client supports tags on `SymbolInformation`. Tags are supported on\n\t// `DocumentSymbol` if `hierarchicalDocumentSymbolSupport` is set to true.\n\t// Clients supporting tags have to handle unknown tags gracefully.\n\t//\n\t// @since 3.16.0\n\tTagSupport *ClientSymbolTagOptions `json:\"tagSupport,omitempty\"`\n\t// The client supports an additional label presented in the UI when\n\t// registering a document symbol provider.\n\t//\n\t// @since 3.16.0\n\tLabelSupport bool `json:\"labelSupport,omitempty\"`\n}\n\n// Provider options for a {@link DocumentSymbolRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentSymbolOptions\ntype DocumentSymbolOptions struct {\n\t// A human-readable string that is shown when multiple outlines trees\n\t// are shown for the same document.\n\t//\n\t// @since 3.16.0\n\tLabel string `json:\"label,omitempty\"`\n\tWorkDoneProgressOptions\n}\n\n// Parameters for a {@link DocumentSymbolRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentSymbolParams\ntype DocumentSymbolParams struct {\n\t// The text document.\n\tTextDocument TextDocumentIdentifier `json:\"textDocument\"`\n\tWorkDoneProgressParams\n\tPartialResultParams\n}\n\n// Registration options for a {@link DocumentSymbolRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentSymbolRegistrationOptions\ntype DocumentSymbolRegistrationOptions struct {\n\tTextDocumentRegistrationOptions\n\tDocumentSymbolOptions\n}\n\n// Edit range variant that includes ranges for insert and replace operations.\n//\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#editRangeWithInsertReplace\ntype EditRangeWithInsertReplace struct {\n\tInsert Range `json:\"insert\"`\n\tReplace Range `json:\"replace\"`\n}\n\n// Predefined error codes.\ntype ErrorCodes int32\n\n// The client capabilities of a {@link ExecuteCommandRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#executeCommandClientCapabilities\ntype ExecuteCommandClientCapabilities struct {\n\t// Execute command supports dynamic registration.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n}\n\n// The server capabilities of a {@link ExecuteCommandRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#executeCommandOptions\ntype ExecuteCommandOptions struct {\n\t// The commands to be executed on the server\n\tCommands []string `json:\"commands\"`\n\tWorkDoneProgressOptions\n}\n\n// The parameters of a {@link ExecuteCommandRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#executeCommandParams\ntype ExecuteCommandParams struct {\n\t// The identifier of the actual command handler.\n\tCommand string `json:\"command\"`\n\t// Arguments that the command should be invoked with.\n\tArguments []json.RawMessage `json:\"arguments,omitempty\"`\n\tWorkDoneProgressParams\n}\n\n// Registration options for a {@link ExecuteCommandRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#executeCommandRegistrationOptions\ntype ExecuteCommandRegistrationOptions struct {\n\tExecuteCommandOptions\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#executionSummary\ntype ExecutionSummary struct {\n\t// A strict monotonically increasing value\n\t// indicating the execution order of a cell\n\t// inside a notebook.\n\tExecutionOrder uint32 `json:\"executionOrder\"`\n\t// Whether the execution was successful or\n\t// not if known by the client.\n\tSuccess bool `json:\"success,omitempty\"`\n}\ntype FailureHandlingKind string\n\n// The file event type\ntype FileChangeType uint32\n\n// Represents information on a file/folder create.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#fileCreate\ntype FileCreate struct {\n\t// A file:// URI for the location of the file/folder being created.\n\tURI string `json:\"uri\"`\n}\n\n// Represents information on a file/folder delete.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#fileDelete\ntype FileDelete struct {\n\t// A file:// URI for the location of the file/folder being deleted.\n\tURI string `json:\"uri\"`\n}\n\n// An event describing a file change.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#fileEvent\ntype FileEvent struct {\n\t// The file's uri.\n\tURI DocumentUri `json:\"uri\"`\n\t// The change type.\n\tType FileChangeType `json:\"type\"`\n}\n\n// Capabilities relating to events from file operations by the user in the client.\n//\n// These events do not come from the file system, they come from user operations\n// like renaming a file in the UI.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#fileOperationClientCapabilities\ntype FileOperationClientCapabilities struct {\n\t// Whether the client supports dynamic registration for file requests/notifications.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n\t// The client has support for sending didCreateFiles notifications.\n\tDidCreate bool `json:\"didCreate,omitempty\"`\n\t// The client has support for sending willCreateFiles requests.\n\tWillCreate bool `json:\"willCreate,omitempty\"`\n\t// The client has support for sending didRenameFiles notifications.\n\tDidRename bool `json:\"didRename,omitempty\"`\n\t// The client has support for sending willRenameFiles requests.\n\tWillRename bool `json:\"willRename,omitempty\"`\n\t// The client has support for sending didDeleteFiles notifications.\n\tDidDelete bool `json:\"didDelete,omitempty\"`\n\t// The client has support for sending willDeleteFiles requests.\n\tWillDelete bool `json:\"willDelete,omitempty\"`\n}\n\n// A filter to describe in which file operation requests or notifications\n// the server is interested in receiving.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#fileOperationFilter\ntype FileOperationFilter struct {\n\t// A Uri scheme like `file` or `untitled`.\n\tScheme string `json:\"scheme,omitempty\"`\n\t// The actual file operation pattern.\n\tPattern FileOperationPattern `json:\"pattern\"`\n}\n\n// Options for notifications/requests for user operations on files.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#fileOperationOptions\ntype FileOperationOptions struct {\n\t// The server is interested in receiving didCreateFiles notifications.\n\tDidCreate *FileOperationRegistrationOptions `json:\"didCreate,omitempty\"`\n\t// The server is interested in receiving willCreateFiles requests.\n\tWillCreate *FileOperationRegistrationOptions `json:\"willCreate,omitempty\"`\n\t// The server is interested in receiving didRenameFiles notifications.\n\tDidRename *FileOperationRegistrationOptions `json:\"didRename,omitempty\"`\n\t// The server is interested in receiving willRenameFiles requests.\n\tWillRename *FileOperationRegistrationOptions `json:\"willRename,omitempty\"`\n\t// The server is interested in receiving didDeleteFiles file notifications.\n\tDidDelete *FileOperationRegistrationOptions `json:\"didDelete,omitempty\"`\n\t// The server is interested in receiving willDeleteFiles file requests.\n\tWillDelete *FileOperationRegistrationOptions `json:\"willDelete,omitempty\"`\n}\n\n// A pattern to describe in which file operation requests or notifications\n// the server is interested in receiving.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#fileOperationPattern\ntype FileOperationPattern struct {\n\t// The glob pattern to match. Glob patterns can have the following syntax:\n\t//\n\t// - `*` to match one or more characters in a path segment\n\t// - `?` to match on one character in a path segment\n\t// - `**` to match any number of path segments, including none\n\t// - `{}` to group sub patterns into an OR expression. (e.g. `**/*.{ts,js}` matches all TypeScript and JavaScript files)\n\t// - `[]` to declare a range of characters to match in a path segment (e.g., `example.[0-9]` to match on `example.0`, `example.1`, …)\n\t// - `[!...]` to negate a range of characters to match in a path segment (e.g., `example.[!0-9]` to match on `example.a`, `example.b`, but not `example.0`)\n\tGlob string `json:\"glob\"`\n\t// Whether to match files or folders with this pattern.\n\t//\n\t// Matches both if undefined.\n\tMatches *FileOperationPatternKind `json:\"matches,omitempty\"`\n\t// Additional options used during matching.\n\tOptions *FileOperationPatternOptions `json:\"options,omitempty\"`\n}\n\n// A pattern kind describing if a glob pattern matches a file a folder or\n// both.\n//\n// @since 3.16.0\ntype FileOperationPatternKind string\n\n// Matching options for the file operation pattern.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#fileOperationPatternOptions\ntype FileOperationPatternOptions struct {\n\t// The pattern should be matched ignoring casing.\n\tIgnoreCase bool `json:\"ignoreCase,omitempty\"`\n}\n\n// The options to register for file operations.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#fileOperationRegistrationOptions\ntype FileOperationRegistrationOptions struct {\n\t// The actual filters.\n\tFilters []FileOperationFilter `json:\"filters\"`\n}\n\n// Represents information on a file/folder rename.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#fileRename\ntype FileRename struct {\n\t// A file:// URI for the original location of the file/folder being renamed.\n\tOldURI string `json:\"oldUri\"`\n\t// A file:// URI for the new location of the file/folder being renamed.\n\tNewURI string `json:\"newUri\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#fileSystemWatcher\ntype FileSystemWatcher struct {\n\t// The glob pattern to watch. See {@link GlobPattern glob pattern} for more detail.\n\t//\n\t// @since 3.17.0 support for relative patterns.\n\tGlobPattern GlobPattern `json:\"globPattern\"`\n\t// The kind of events of interest. If omitted it defaults\n\t// to WatchKind.Create | WatchKind.Change | WatchKind.Delete\n\t// which is 7.\n\tKind *WatchKind `json:\"kind,omitempty\"`\n}\n\n// Represents a folding range. To be valid, start and end line must be bigger than zero and smaller\n// than the number of lines in the document. Clients are free to ignore invalid ranges.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#foldingRange\ntype FoldingRange struct {\n\t// The zero-based start line of the range to fold. The folded area starts after the line's last character.\n\t// To be valid, the end must be zero or larger and smaller than the number of lines in the document.\n\tStartLine uint32 `json:\"startLine\"`\n\t// The zero-based character offset from where the folded range starts. If not defined, defaults to the length of the start line.\n\tStartCharacter uint32 `json:\"startCharacter,omitempty\"`\n\t// The zero-based end line of the range to fold. The folded area ends with the line's last character.\n\t// To be valid, the end must be zero or larger and smaller than the number of lines in the document.\n\tEndLine uint32 `json:\"endLine\"`\n\t// The zero-based character offset before the folded range ends. If not defined, defaults to the length of the end line.\n\tEndCharacter uint32 `json:\"endCharacter,omitempty\"`\n\t// Describes the kind of the folding range such as 'comment' or 'region'. The kind\n\t// is used to categorize folding ranges and used by commands like 'Fold all comments'.\n\t// See {@link FoldingRangeKind} for an enumeration of standardized kinds.\n\tKind string `json:\"kind,omitempty\"`\n\t// The text that the client should show when the specified range is\n\t// collapsed. If not defined or not supported by the client, a default\n\t// will be chosen by the client.\n\t//\n\t// @since 3.17.0\n\tCollapsedText string `json:\"collapsedText,omitempty\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#foldingRangeClientCapabilities\ntype FoldingRangeClientCapabilities struct {\n\t// Whether implementation supports dynamic registration for folding range\n\t// providers. If this is set to `true` the client supports the new\n\t// `FoldingRangeRegistrationOptions` return value for the corresponding\n\t// server capability as well.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n\t// The maximum number of folding ranges that the client prefers to receive\n\t// per document. The value serves as a hint, servers are free to follow the\n\t// limit.\n\tRangeLimit uint32 `json:\"rangeLimit,omitempty\"`\n\t// If set, the client signals that it only supports folding complete lines.\n\t// If set, client will ignore specified `startCharacter` and `endCharacter`\n\t// properties in a FoldingRange.\n\tLineFoldingOnly bool `json:\"lineFoldingOnly,omitempty\"`\n\t// Specific options for the folding range kind.\n\t//\n\t// @since 3.17.0\n\tFoldingRangeKind *ClientFoldingRangeKindOptions `json:\"foldingRangeKind,omitempty\"`\n\t// Specific options for the folding range.\n\t//\n\t// @since 3.17.0\n\tFoldingRange *ClientFoldingRangeOptions `json:\"foldingRange,omitempty\"`\n}\n\n// A set of predefined range kinds.\ntype FoldingRangeKind string\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#foldingRangeOptions\ntype FoldingRangeOptions struct {\n\tWorkDoneProgressOptions\n}\n\n// Parameters for a {@link FoldingRangeRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#foldingRangeParams\ntype FoldingRangeParams struct {\n\t// The text document.\n\tTextDocument TextDocumentIdentifier `json:\"textDocument\"`\n\tWorkDoneProgressParams\n\tPartialResultParams\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#foldingRangeRegistrationOptions\ntype FoldingRangeRegistrationOptions struct {\n\tTextDocumentRegistrationOptions\n\tFoldingRangeOptions\n\tStaticRegistrationOptions\n}\n\n// Client workspace capabilities specific to folding ranges\n//\n// @since 3.18.0\n// @proposed\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#foldingRangeWorkspaceClientCapabilities\ntype FoldingRangeWorkspaceClientCapabilities struct {\n\t// Whether the client implementation supports a refresh request sent from the\n\t// server to the client.\n\t//\n\t// Note that this event is global and will force the client to refresh all\n\t// folding ranges currently shown. It should be used with absolute care and is\n\t// useful for situation where a server for example detects a project wide\n\t// change that requires such a calculation.\n\t//\n\t// @since 3.18.0\n\t// @proposed\n\tRefreshSupport bool `json:\"refreshSupport,omitempty\"`\n}\n\n// Value-object describing what options formatting should use.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#formattingOptions\ntype FormattingOptions struct {\n\t// Size of a tab in spaces.\n\tTabSize uint32 `json:\"tabSize\"`\n\t// Prefer spaces over tabs.\n\tInsertSpaces bool `json:\"insertSpaces\"`\n\t// Trim trailing whitespace on a line.\n\t//\n\t// @since 3.15.0\n\tTrimTrailingWhitespace bool `json:\"trimTrailingWhitespace,omitempty\"`\n\t// Insert a newline character at the end of the file if one does not exist.\n\t//\n\t// @since 3.15.0\n\tInsertFinalNewline bool `json:\"insertFinalNewline,omitempty\"`\n\t// Trim all newlines after the final newline at the end of the file.\n\t//\n\t// @since 3.15.0\n\tTrimFinalNewlines bool `json:\"trimFinalNewlines,omitempty\"`\n}\n\n// A diagnostic report with a full set of problems.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#fullDocumentDiagnosticReport\ntype FullDocumentDiagnosticReport struct {\n\t// A full document diagnostic report.\n\tKind string `json:\"kind\"`\n\t// An optional result id. If provided it will\n\t// be sent on the next diagnostic request for the\n\t// same document.\n\tResultID string `json:\"resultId,omitempty\"`\n\t// The actual items.\n\tItems []Diagnostic `json:\"items\"`\n}\n\n// General client capabilities.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#generalClientCapabilities\ntype GeneralClientCapabilities struct {\n\t// Client capability that signals how the client\n\t// handles stale requests (e.g. a request\n\t// for which the client will not process the response\n\t// anymore since the information is outdated).\n\t//\n\t// @since 3.17.0\n\tStaleRequestSupport *StaleRequestSupportOptions `json:\"staleRequestSupport,omitempty\"`\n\t// Client capabilities specific to regular expressions.\n\t//\n\t// @since 3.16.0\n\tRegularExpressions *RegularExpressionsClientCapabilities `json:\"regularExpressions,omitempty\"`\n\t// Client capabilities specific to the client's markdown parser.\n\t//\n\t// @since 3.16.0\n\tMarkdown *MarkdownClientCapabilities `json:\"markdown,omitempty\"`\n\t// The position encodings supported by the client. Client and server\n\t// have to agree on the same position encoding to ensure that offsets\n\t// (e.g. character position in a line) are interpreted the same on both\n\t// sides.\n\t//\n\t// To keep the protocol backwards compatible the following applies: if\n\t// the value 'utf-16' is missing from the array of position encodings\n\t// servers can assume that the client supports UTF-16. UTF-16 is\n\t// therefore a mandatory encoding.\n\t//\n\t// If omitted it defaults to ['utf-16'].\n\t//\n\t// Implementation considerations: since the conversion from one encoding\n\t// into another requires the content of the file / line the conversion\n\t// is best done where the file is read which is usually on the server\n\t// side.\n\t//\n\t// @since 3.17.0\n\tPositionEncodings []PositionEncodingKind `json:\"positionEncodings,omitempty\"`\n}\n\n// The glob pattern. Either a string pattern or a relative pattern.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#globPattern\ntype GlobPattern = Or_GlobPattern // (alias)\n// The result of a hover request.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#hover\ntype Hover struct {\n\t// The hover's content\n\tContents MarkupContent `json:\"contents\"`\n\t// An optional range inside the text document that is used to\n\t// visualize the hover, e.g. by changing the background color.\n\tRange Range `json:\"range,omitempty\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#hoverClientCapabilities\ntype HoverClientCapabilities struct {\n\t// Whether hover supports dynamic registration.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n\t// Client supports the following content formats for the content\n\t// property. The order describes the preferred format of the client.\n\tContentFormat []MarkupKind `json:\"contentFormat,omitempty\"`\n}\n\n// Hover options.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#hoverOptions\ntype HoverOptions struct {\n\tWorkDoneProgressOptions\n}\n\n// Parameters for a {@link HoverRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#hoverParams\ntype HoverParams struct {\n\tTextDocumentPositionParams\n\tWorkDoneProgressParams\n}\n\n// Registration options for a {@link HoverRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#hoverRegistrationOptions\ntype HoverRegistrationOptions struct {\n\tTextDocumentRegistrationOptions\n\tHoverOptions\n}\n\n// @since 3.6.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#implementationClientCapabilities\ntype ImplementationClientCapabilities struct {\n\t// Whether implementation supports dynamic registration. If this is set to `true`\n\t// the client supports the new `ImplementationRegistrationOptions` return value\n\t// for the corresponding server capability as well.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n\t// The client supports additional metadata in the form of definition links.\n\t//\n\t// @since 3.14.0\n\tLinkSupport bool `json:\"linkSupport,omitempty\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#implementationOptions\ntype ImplementationOptions struct {\n\tWorkDoneProgressOptions\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#implementationParams\ntype ImplementationParams struct {\n\tTextDocumentPositionParams\n\tWorkDoneProgressParams\n\tPartialResultParams\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#implementationRegistrationOptions\ntype ImplementationRegistrationOptions struct {\n\tTextDocumentRegistrationOptions\n\tImplementationOptions\n\tStaticRegistrationOptions\n}\n\n// The data type of the ResponseError if the\n// initialize request fails.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#initializeError\ntype InitializeError struct {\n\t// Indicates whether the client execute the following retry logic:\n\t// (1) show the message provided by the ResponseError to the user\n\t// (2) user selects retry or cancel\n\t// (3) if user selected retry the initialize method is sent again.\n\tRetry bool `json:\"retry\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#initializeParams\ntype InitializeParams struct {\n\tXInitializeParams\n\tWorkspaceFoldersInitializeParams\n}\n\n// The result returned from an initialize request.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#initializeResult\ntype InitializeResult struct {\n\t// The capabilities the language server provides.\n\tCapabilities ServerCapabilities `json:\"capabilities\"`\n\t// Information about the server.\n\t//\n\t// @since 3.15.0\n\tServerInfo *ServerInfo `json:\"serverInfo,omitempty\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#initializedParams\ntype InitializedParams struct {\n}\n\n// Inlay hint information.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#inlayHint\ntype InlayHint struct {\n\t// The position of this hint.\n\t//\n\t// If multiple hints have the same position, they will be shown in the order\n\t// they appear in the response.\n\tPosition Position `json:\"position\"`\n\t// The label of this hint. A human readable string or an array of\n\t// InlayHintLabelPart label parts.\n\t//\n\t// *Note* that neither the string nor the label part can be empty.\n\tLabel []InlayHintLabelPart `json:\"label\"`\n\t// The kind of this hint. Can be omitted in which case the client\n\t// should fall back to a reasonable default.\n\tKind InlayHintKind `json:\"kind,omitempty\"`\n\t// Optional text edits that are performed when accepting this inlay hint.\n\t//\n\t// *Note* that edits are expected to change the document so that the inlay\n\t// hint (or its nearest variant) is now part of the document and the inlay\n\t// hint itself is now obsolete.\n\tTextEdits []TextEdit `json:\"textEdits,omitempty\"`\n\t// The tooltip text when you hover over this item.\n\tTooltip *Or_InlayHint_tooltip `json:\"tooltip,omitempty\"`\n\t// Render padding before the hint.\n\t//\n\t// Note: Padding should use the editor's background color, not the\n\t// background color of the hint itself. That means padding can be used\n\t// to visually align/separate an inlay hint.\n\tPaddingLeft bool `json:\"paddingLeft,omitempty\"`\n\t// Render padding after the hint.\n\t//\n\t// Note: Padding should use the editor's background color, not the\n\t// background color of the hint itself. That means padding can be used\n\t// to visually align/separate an inlay hint.\n\tPaddingRight bool `json:\"paddingRight,omitempty\"`\n\t// A data entry field that is preserved on an inlay hint between\n\t// a `textDocument/inlayHint` and a `inlayHint/resolve` request.\n\tData interface{} `json:\"data,omitempty\"`\n}\n\n// Inlay hint client capabilities.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#inlayHintClientCapabilities\ntype InlayHintClientCapabilities struct {\n\t// Whether inlay hints support dynamic registration.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n\t// Indicates which properties a client can resolve lazily on an inlay\n\t// hint.\n\tResolveSupport *ClientInlayHintResolveOptions `json:\"resolveSupport,omitempty\"`\n}\n\n// Inlay hint kinds.\n//\n// @since 3.17.0\ntype InlayHintKind uint32\n\n// An inlay hint label part allows for interactive and composite labels\n// of inlay hints.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#inlayHintLabelPart\ntype InlayHintLabelPart struct {\n\t// The value of this label part.\n\tValue string `json:\"value\"`\n\t// The tooltip text when you hover over this label part. Depending on\n\t// the client capability `inlayHint.resolveSupport` clients might resolve\n\t// this property late using the resolve request.\n\tTooltip *Or_InlayHintLabelPart_tooltip `json:\"tooltip,omitempty\"`\n\t// An optional source code location that represents this\n\t// label part.\n\t//\n\t// The editor will use this location for the hover and for code navigation\n\t// features: This part will become a clickable link that resolves to the\n\t// definition of the symbol at the given location (not necessarily the\n\t// location itself), it shows the hover that shows at the given location,\n\t// and it shows a context menu with further code navigation commands.\n\t//\n\t// Depending on the client capability `inlayHint.resolveSupport` clients\n\t// might resolve this property late using the resolve request.\n\tLocation *Location `json:\"location,omitempty\"`\n\t// An optional command for this label part.\n\t//\n\t// Depending on the client capability `inlayHint.resolveSupport` clients\n\t// might resolve this property late using the resolve request.\n\tCommand *Command `json:\"command,omitempty\"`\n}\n\n// Inlay hint options used during static registration.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#inlayHintOptions\ntype InlayHintOptions struct {\n\t// The server provides support to resolve additional\n\t// information for an inlay hint item.\n\tResolveProvider bool `json:\"resolveProvider,omitempty\"`\n\tWorkDoneProgressOptions\n}\n\n// A parameter literal used in inlay hint requests.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#inlayHintParams\ntype InlayHintParams struct {\n\t// The text document.\n\tTextDocument TextDocumentIdentifier `json:\"textDocument\"`\n\t// The document range for which inlay hints should be computed.\n\tRange Range `json:\"range\"`\n\tWorkDoneProgressParams\n}\n\n// Inlay hint options used during static or dynamic registration.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#inlayHintRegistrationOptions\ntype InlayHintRegistrationOptions struct {\n\tInlayHintOptions\n\tTextDocumentRegistrationOptions\n\tStaticRegistrationOptions\n}\n\n// Client workspace capabilities specific to inlay hints.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#inlayHintWorkspaceClientCapabilities\ntype InlayHintWorkspaceClientCapabilities struct {\n\t// Whether the client implementation supports a refresh request sent from\n\t// the server to the client.\n\t//\n\t// Note that this event is global and will force the client to refresh all\n\t// inlay hints currently shown. It should be used with absolute care and\n\t// is useful for situation where a server for example detects a project wide\n\t// change that requires such a calculation.\n\tRefreshSupport bool `json:\"refreshSupport,omitempty\"`\n}\n\n// Client capabilities specific to inline completions.\n//\n// @since 3.18.0\n// @proposed\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#inlineCompletionClientCapabilities\ntype InlineCompletionClientCapabilities struct {\n\t// Whether implementation supports dynamic registration for inline completion providers.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n}\n\n// Provides information about the context in which an inline completion was requested.\n//\n// @since 3.18.0\n// @proposed\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#inlineCompletionContext\ntype InlineCompletionContext struct {\n\t// Describes how the inline completion was triggered.\n\tTriggerKind InlineCompletionTriggerKind `json:\"triggerKind\"`\n\t// Provides information about the currently selected item in the autocomplete widget if it is visible.\n\tSelectedCompletionInfo *SelectedCompletionInfo `json:\"selectedCompletionInfo,omitempty\"`\n}\n\n// An inline completion item represents a text snippet that is proposed inline to complete text that is being typed.\n//\n// @since 3.18.0\n// @proposed\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#inlineCompletionItem\ntype InlineCompletionItem struct {\n\t// The text to replace the range with. Must be set.\n\tInsertText Or_InlineCompletionItem_insertText `json:\"insertText\"`\n\t// A text that is used to decide if this inline completion should be shown. When `falsy` the {@link InlineCompletionItem.insertText} is used.\n\tFilterText string `json:\"filterText,omitempty\"`\n\t// The range to replace. Must begin and end on the same line.\n\tRange *Range `json:\"range,omitempty\"`\n\t// An optional {@link Command} that is executed *after* inserting this completion.\n\tCommand *Command `json:\"command,omitempty\"`\n}\n\n// Represents a collection of {@link InlineCompletionItem inline completion items} to be presented in the editor.\n//\n// @since 3.18.0\n// @proposed\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#inlineCompletionList\ntype InlineCompletionList struct {\n\t// The inline completion items\n\tItems []InlineCompletionItem `json:\"items\"`\n}\n\n// Inline completion options used during static registration.\n//\n// @since 3.18.0\n// @proposed\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#inlineCompletionOptions\ntype InlineCompletionOptions struct {\n\tWorkDoneProgressOptions\n}\n\n// A parameter literal used in inline completion requests.\n//\n// @since 3.18.0\n// @proposed\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#inlineCompletionParams\ntype InlineCompletionParams struct {\n\t// Additional information about the context in which inline completions were\n\t// requested.\n\tContext InlineCompletionContext `json:\"context\"`\n\tTextDocumentPositionParams\n\tWorkDoneProgressParams\n}\n\n// Inline completion options used during static or dynamic registration.\n//\n// @since 3.18.0\n// @proposed\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#inlineCompletionRegistrationOptions\ntype InlineCompletionRegistrationOptions struct {\n\tInlineCompletionOptions\n\tTextDocumentRegistrationOptions\n\tStaticRegistrationOptions\n}\n\n// Describes how an {@link InlineCompletionItemProvider inline completion provider} was triggered.\n//\n// @since 3.18.0\n// @proposed\ntype InlineCompletionTriggerKind uint32\n\n// Inline value information can be provided by different means:\n//\n// - directly as a text value (class InlineValueText).\n// - as a name to use for a variable lookup (class InlineValueVariableLookup)\n// - as an evaluatable expression (class InlineValueEvaluatableExpression)\n//\n// The InlineValue types combines all inline value types into one type.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#inlineValue\ntype InlineValue = Or_InlineValue // (alias)\n// Client capabilities specific to inline values.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#inlineValueClientCapabilities\ntype InlineValueClientCapabilities struct {\n\t// Whether implementation supports dynamic registration for inline value providers.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n}\n\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#inlineValueContext\ntype InlineValueContext struct {\n\t// The stack frame (as a DAP Id) where the execution has stopped.\n\tFrameID int32 `json:\"frameId\"`\n\t// The document range where execution has stopped.\n\t// Typically the end position of the range denotes the line where the inline values are shown.\n\tStoppedLocation Range `json:\"stoppedLocation\"`\n}\n\n// Provide an inline value through an expression evaluation.\n// If only a range is specified, the expression will be extracted from the underlying document.\n// An optional expression can be used to override the extracted expression.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#inlineValueEvaluatableExpression\ntype InlineValueEvaluatableExpression struct {\n\t// The document range for which the inline value applies.\n\t// The range is used to extract the evaluatable expression from the underlying document.\n\tRange Range `json:\"range\"`\n\t// If specified the expression overrides the extracted expression.\n\tExpression string `json:\"expression,omitempty\"`\n}\n\n// Inline value options used during static registration.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#inlineValueOptions\ntype InlineValueOptions struct {\n\tWorkDoneProgressOptions\n}\n\n// A parameter literal used in inline value requests.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#inlineValueParams\ntype InlineValueParams struct {\n\t// The text document.\n\tTextDocument TextDocumentIdentifier `json:\"textDocument\"`\n\t// The document range for which inline values should be computed.\n\tRange Range `json:\"range\"`\n\t// Additional information about the context in which inline values were\n\t// requested.\n\tContext InlineValueContext `json:\"context\"`\n\tWorkDoneProgressParams\n}\n\n// Inline value options used during static or dynamic registration.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#inlineValueRegistrationOptions\ntype InlineValueRegistrationOptions struct {\n\tInlineValueOptions\n\tTextDocumentRegistrationOptions\n\tStaticRegistrationOptions\n}\n\n// Provide inline value as text.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#inlineValueText\ntype InlineValueText struct {\n\t// The document range for which the inline value applies.\n\tRange Range `json:\"range\"`\n\t// The text of the inline value.\n\tText string `json:\"text\"`\n}\n\n// Provide inline value through a variable lookup.\n// If only a range is specified, the variable name will be extracted from the underlying document.\n// An optional variable name can be used to override the extracted name.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#inlineValueVariableLookup\ntype InlineValueVariableLookup struct {\n\t// The document range for which the inline value applies.\n\t// The range is used to extract the variable name from the underlying document.\n\tRange Range `json:\"range\"`\n\t// If specified the name of the variable to look up.\n\tVariableName string `json:\"variableName,omitempty\"`\n\t// How to perform the lookup.\n\tCaseSensitiveLookup bool `json:\"caseSensitiveLookup\"`\n}\n\n// Client workspace capabilities specific to inline values.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#inlineValueWorkspaceClientCapabilities\ntype InlineValueWorkspaceClientCapabilities struct {\n\t// Whether the client implementation supports a refresh request sent from the\n\t// server to the client.\n\t//\n\t// Note that this event is global and will force the client to refresh all\n\t// inline values currently shown. It should be used with absolute care and is\n\t// useful for situation where a server for example detects a project wide\n\t// change that requires such a calculation.\n\tRefreshSupport bool `json:\"refreshSupport,omitempty\"`\n}\n\n// A special text edit to provide an insert and a replace operation.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#insertReplaceEdit\ntype InsertReplaceEdit struct {\n\t// The string to be inserted.\n\tNewText string `json:\"newText\"`\n\t// The range if the insert is requested\n\tInsert Range `json:\"insert\"`\n\t// The range if the replace is requested.\n\tReplace Range `json:\"replace\"`\n}\n\n// Defines whether the insert text in a completion item should be interpreted as\n// plain text or a snippet.\ntype InsertTextFormat uint32\n\n// How whitespace and indentation is handled during completion\n// item insertion.\n//\n// @since 3.16.0\ntype InsertTextMode uint32\ntype LSPAny = interface{}\n\n// LSP arrays.\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#lSPArray\ntype LSPArray = []interface{} // (alias)\ntype LSPErrorCodes int32\n\n// LSP object definition.\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#lSPObject\ntype LSPObject = map[string]LSPAny // (alias)\n// Predefined Language kinds\n// @since 3.18.0\n// @proposed\ntype LanguageKind string\n\n// Client capabilities for the linked editing range request.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#linkedEditingRangeClientCapabilities\ntype LinkedEditingRangeClientCapabilities struct {\n\t// Whether implementation supports dynamic registration. If this is set to `true`\n\t// the client supports the new `(TextDocumentRegistrationOptions & StaticRegistrationOptions)`\n\t// return value for the corresponding server capability as well.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#linkedEditingRangeOptions\ntype LinkedEditingRangeOptions struct {\n\tWorkDoneProgressOptions\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#linkedEditingRangeParams\ntype LinkedEditingRangeParams struct {\n\tTextDocumentPositionParams\n\tWorkDoneProgressParams\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#linkedEditingRangeRegistrationOptions\ntype LinkedEditingRangeRegistrationOptions struct {\n\tTextDocumentRegistrationOptions\n\tLinkedEditingRangeOptions\n\tStaticRegistrationOptions\n}\n\n// The result of a linked editing range request.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#linkedEditingRanges\ntype LinkedEditingRanges struct {\n\t// A list of ranges that can be edited together. The ranges must have\n\t// identical length and contain identical text content. The ranges cannot overlap.\n\tRanges []Range `json:\"ranges\"`\n\t// An optional word pattern (regular expression) that describes valid contents for\n\t// the given ranges. If no pattern is provided, the client configuration's word\n\t// pattern will be used.\n\tWordPattern string `json:\"wordPattern,omitempty\"`\n}\n\n// created for Literal (Lit_ClientSemanticTokensRequestOptions_range_Item1)\ntype Lit_ClientSemanticTokensRequestOptions_range_Item1 struct {\n}\n\n// created for Literal (Lit_SemanticTokensOptions_range_Item1)\ntype Lit_SemanticTokensOptions_range_Item1 struct {\n}\n\n// Represents a location inside a resource, such as a line\n// inside a text file.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#location\ntype Location struct {\n\tURI DocumentUri `json:\"uri\"`\n\tRange Range `json:\"range\"`\n}\n\n// Represents the connection of two locations. Provides additional metadata over normal {@link Location locations},\n// including an origin range.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#locationLink\ntype LocationLink struct {\n\t// Span of the origin of this link.\n\t//\n\t// Used as the underlined span for mouse interaction. Defaults to the word range at\n\t// the definition position.\n\tOriginSelectionRange *Range `json:\"originSelectionRange,omitempty\"`\n\t// The target resource identifier of this link.\n\tTargetURI DocumentUri `json:\"targetUri\"`\n\t// The full target range of this link. If the target for example is a symbol then target range is the\n\t// range enclosing this symbol not including leading/trailing whitespace but everything else\n\t// like comments. This information is typically used to highlight the range in the editor.\n\tTargetRange Range `json:\"targetRange\"`\n\t// The range that should be selected and revealed when this link is being followed, e.g the name of a function.\n\t// Must be contained by the `targetRange`. See also `DocumentSymbol#range`\n\tTargetSelectionRange Range `json:\"targetSelectionRange\"`\n}\n\n// Location with only uri and does not include range.\n//\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#locationUriOnly\ntype LocationUriOnly struct {\n\tURI DocumentUri `json:\"uri\"`\n}\n\n// The log message parameters.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#logMessageParams\ntype LogMessageParams struct {\n\t// The message type. See {@link MessageType}\n\tType MessageType `json:\"type\"`\n\t// The actual message.\n\tMessage string `json:\"message\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#logTraceParams\ntype LogTraceParams struct {\n\tMessage string `json:\"message\"`\n\tVerbose string `json:\"verbose,omitempty\"`\n}\n\n// Client capabilities specific to the used markdown parser.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#markdownClientCapabilities\ntype MarkdownClientCapabilities struct {\n\t// The name of the parser.\n\tParser string `json:\"parser\"`\n\t// The version of the parser.\n\tVersion string `json:\"version,omitempty\"`\n\t// A list of HTML tags that the client allows / supports in\n\t// Markdown.\n\t//\n\t// @since 3.17.0\n\tAllowedTags []string `json:\"allowedTags,omitempty\"`\n}\n\n// MarkedString can be used to render human readable text. It is either a markdown string\n// or a code-block that provides a language and a code snippet. The language identifier\n// is semantically equal to the optional language identifier in fenced code blocks in GitHub\n// issues. See https://help.github.com/articles/creating-and-highlighting-code-blocks/#syntax-highlighting\n//\n// The pair of a language and a value is an equivalent to markdown:\n// ```${language}\n// ${value}\n// ```\n//\n// Note that markdown strings will be sanitized - that means html will be escaped.\n// @deprecated use MarkupContent instead.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#markedString\ntype MarkedString = Or_MarkedString // (alias)\n// @since 3.18.0\n// @deprecated use MarkupContent instead.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#markedStringWithLanguage\ntype MarkedStringWithLanguage struct {\n\tLanguage string `json:\"language\"`\n\tValue string `json:\"value\"`\n}\n\n// A `MarkupContent` literal represents a string value which content is interpreted base on its\n// kind flag. Currently the protocol supports `plaintext` and `markdown` as markup kinds.\n//\n// If the kind is `markdown` then the value can contain fenced code blocks like in GitHub issues.\n// See https://help.github.com/articles/creating-and-highlighting-code-blocks/#syntax-highlighting\n//\n// Here is an example how such a string can be constructed using JavaScript / TypeScript:\n// ```ts\n//\n//\tlet markdown: MarkdownContent = {\n//\t kind: MarkupKind.Markdown,\n//\t value: [\n//\t '# Header',\n//\t 'Some text',\n//\t '```typescript',\n//\t 'someCode();',\n//\t '```'\n//\t ].join('\\n')\n//\t};\n//\n// ```\n//\n// *Please Note* that clients might sanitize the return markdown. A client could decide to\n// remove HTML from the markdown to avoid script execution.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#markupContent\ntype MarkupContent struct {\n\t// The type of the Markup\n\tKind MarkupKind `json:\"kind\"`\n\t// The content itself\n\tValue string `json:\"value\"`\n}\n\n// Describes the content type that a client supports in various\n// result literals like `Hover`, `ParameterInfo` or `CompletionItem`.\n//\n// Please note that `MarkupKinds` must not start with a `$`. This kinds\n// are reserved for internal usage.\ntype MarkupKind string\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#messageActionItem\ntype MessageActionItem struct {\n\t// A short title like 'Retry', 'Open Log' etc.\n\tTitle string `json:\"title\"`\n}\n\n// The message type\ntype MessageType uint32\n\n// Moniker definition to match LSIF 0.5 moniker definition.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#moniker\ntype Moniker struct {\n\t// The scheme of the moniker. For example tsc or .Net\n\tScheme string `json:\"scheme\"`\n\t// The identifier of the moniker. The value is opaque in LSIF however\n\t// schema owners are allowed to define the structure if they want.\n\tIdentifier string `json:\"identifier\"`\n\t// The scope in which the moniker is unique\n\tUnique UniquenessLevel `json:\"unique\"`\n\t// The moniker kind if known.\n\tKind *MonikerKind `json:\"kind,omitempty\"`\n}\n\n// Client capabilities specific to the moniker request.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#monikerClientCapabilities\ntype MonikerClientCapabilities struct {\n\t// Whether moniker supports dynamic registration. If this is set to `true`\n\t// the client supports the new `MonikerRegistrationOptions` return value\n\t// for the corresponding server capability as well.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n}\n\n// The moniker kind.\n//\n// @since 3.16.0\ntype MonikerKind string\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#monikerOptions\ntype MonikerOptions struct {\n\tWorkDoneProgressOptions\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#monikerParams\ntype MonikerParams struct {\n\tTextDocumentPositionParams\n\tWorkDoneProgressParams\n\tPartialResultParams\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#monikerRegistrationOptions\ntype MonikerRegistrationOptions struct {\n\tTextDocumentRegistrationOptions\n\tMonikerOptions\n}\n\n// A notebook cell.\n//\n// A cell's document URI must be unique across ALL notebook\n// cells and can therefore be used to uniquely identify a\n// notebook cell or the cell's text document.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#notebookCell\ntype NotebookCell struct {\n\t// The cell's kind\n\tKind NotebookCellKind `json:\"kind\"`\n\t// The URI of the cell's text document\n\t// content.\n\tDocument DocumentUri `json:\"document\"`\n\t// Additional metadata stored with the cell.\n\t//\n\t// Note: should always be an object literal (e.g. LSPObject)\n\tMetadata *LSPObject `json:\"metadata,omitempty\"`\n\t// Additional execution summary information\n\t// if supported by the client.\n\tExecutionSummary *ExecutionSummary `json:\"executionSummary,omitempty\"`\n}\n\n// A change describing how to move a `NotebookCell`\n// array from state S to S'.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#notebookCellArrayChange\ntype NotebookCellArrayChange struct {\n\t// The start oftest of the cell that changed.\n\tStart uint32 `json:\"start\"`\n\t// The deleted cells\n\tDeleteCount uint32 `json:\"deleteCount\"`\n\t// The new cells, if any\n\tCells []NotebookCell `json:\"cells,omitempty\"`\n}\n\n// A notebook cell kind.\n//\n// @since 3.17.0\ntype NotebookCellKind uint32\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#notebookCellLanguage\ntype NotebookCellLanguage struct {\n\tLanguage string `json:\"language\"`\n}\n\n// A notebook cell text document filter denotes a cell text\n// document by different properties.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#notebookCellTextDocumentFilter\ntype NotebookCellTextDocumentFilter struct {\n\t// A filter that matches against the notebook\n\t// containing the notebook cell. If a string\n\t// value is provided it matches against the\n\t// notebook type. '*' matches every notebook.\n\tNotebook Or_NotebookCellTextDocumentFilter_notebook `json:\"notebook\"`\n\t// A language id like `python`.\n\t//\n\t// Will be matched against the language id of the\n\t// notebook cell document. '*' matches every language.\n\tLanguage string `json:\"language,omitempty\"`\n}\n\n// A notebook document.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#notebookDocument\ntype NotebookDocument struct {\n\t// The notebook document's uri.\n\tURI URI `json:\"uri\"`\n\t// The type of the notebook.\n\tNotebookType string `json:\"notebookType\"`\n\t// The version number of this document (it will increase after each\n\t// change, including undo/redo).\n\tVersion int32 `json:\"version\"`\n\t// Additional metadata stored with the notebook\n\t// document.\n\t//\n\t// Note: should always be an object literal (e.g. LSPObject)\n\tMetadata *LSPObject `json:\"metadata,omitempty\"`\n\t// The cells of a notebook.\n\tCells []NotebookCell `json:\"cells\"`\n}\n\n// Structural changes to cells in a notebook document.\n//\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#notebookDocumentCellChangeStructure\ntype NotebookDocumentCellChangeStructure struct {\n\t// The change to the cell array.\n\tArray NotebookCellArrayChange `json:\"array\"`\n\t// Additional opened cell text documents.\n\tDidOpen []TextDocumentItem `json:\"didOpen,omitempty\"`\n\t// Additional closed cell text documents.\n\tDidClose []TextDocumentIdentifier `json:\"didClose,omitempty\"`\n}\n\n// Cell changes to a notebook document.\n//\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#notebookDocumentCellChanges\ntype NotebookDocumentCellChanges struct {\n\t// Changes to the cell structure to add or\n\t// remove cells.\n\tStructure *NotebookDocumentCellChangeStructure `json:\"structure,omitempty\"`\n\t// Changes to notebook cells properties like its\n\t// kind, execution summary or metadata.\n\tData []NotebookCell `json:\"data,omitempty\"`\n\t// Changes to the text content of notebook cells.\n\tTextContent []NotebookDocumentCellContentChanges `json:\"textContent,omitempty\"`\n}\n\n// Content changes to a cell in a notebook document.\n//\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#notebookDocumentCellContentChanges\ntype NotebookDocumentCellContentChanges struct {\n\tDocument VersionedTextDocumentIdentifier `json:\"document\"`\n\tChanges []TextDocumentContentChangeEvent `json:\"changes\"`\n}\n\n// A change event for a notebook document.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#notebookDocumentChangeEvent\ntype NotebookDocumentChangeEvent struct {\n\t// The changed meta data if any.\n\t//\n\t// Note: should always be an object literal (e.g. LSPObject)\n\tMetadata *LSPObject `json:\"metadata,omitempty\"`\n\t// Changes to cells\n\tCells *NotebookDocumentCellChanges `json:\"cells,omitempty\"`\n}\n\n// Capabilities specific to the notebook document support.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#notebookDocumentClientCapabilities\ntype NotebookDocumentClientCapabilities struct {\n\t// Capabilities specific to notebook document synchronization\n\t//\n\t// @since 3.17.0\n\tSynchronization NotebookDocumentSyncClientCapabilities `json:\"synchronization\"`\n}\n\n// A notebook document filter denotes a notebook document by\n// different properties. The properties will be match\n// against the notebook's URI (same as with documents)\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#notebookDocumentFilter\ntype NotebookDocumentFilter = Or_NotebookDocumentFilter // (alias)\n// A notebook document filter where `notebookType` is required field.\n//\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#notebookDocumentFilterNotebookType\ntype NotebookDocumentFilterNotebookType struct {\n\t// The type of the enclosing notebook.\n\tNotebookType string `json:\"notebookType\"`\n\t// A Uri {@link Uri.scheme scheme}, like `file` or `untitled`.\n\tScheme string `json:\"scheme,omitempty\"`\n\t// A glob pattern.\n\tPattern *GlobPattern `json:\"pattern,omitempty\"`\n}\n\n// A notebook document filter where `pattern` is required field.\n//\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#notebookDocumentFilterPattern\ntype NotebookDocumentFilterPattern struct {\n\t// The type of the enclosing notebook.\n\tNotebookType string `json:\"notebookType,omitempty\"`\n\t// A Uri {@link Uri.scheme scheme}, like `file` or `untitled`.\n\tScheme string `json:\"scheme,omitempty\"`\n\t// A glob pattern.\n\tPattern GlobPattern `json:\"pattern\"`\n}\n\n// A notebook document filter where `scheme` is required field.\n//\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#notebookDocumentFilterScheme\ntype NotebookDocumentFilterScheme struct {\n\t// The type of the enclosing notebook.\n\tNotebookType string `json:\"notebookType,omitempty\"`\n\t// A Uri {@link Uri.scheme scheme}, like `file` or `untitled`.\n\tScheme string `json:\"scheme\"`\n\t// A glob pattern.\n\tPattern *GlobPattern `json:\"pattern,omitempty\"`\n}\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#notebookDocumentFilterWithCells\ntype NotebookDocumentFilterWithCells struct {\n\t// The notebook to be synced If a string\n\t// value is provided it matches against the\n\t// notebook type. '*' matches every notebook.\n\tNotebook *Or_NotebookDocumentFilterWithCells_notebook `json:\"notebook,omitempty\"`\n\t// The cells of the matching notebook to be synced.\n\tCells []NotebookCellLanguage `json:\"cells\"`\n}\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#notebookDocumentFilterWithNotebook\ntype NotebookDocumentFilterWithNotebook struct {\n\t// The notebook to be synced If a string\n\t// value is provided it matches against the\n\t// notebook type. '*' matches every notebook.\n\tNotebook Or_NotebookDocumentFilterWithNotebook_notebook `json:\"notebook\"`\n\t// The cells of the matching notebook to be synced.\n\tCells []NotebookCellLanguage `json:\"cells,omitempty\"`\n}\n\n// A literal to identify a notebook document in the client.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#notebookDocumentIdentifier\ntype NotebookDocumentIdentifier struct {\n\t// The notebook document's uri.\n\tURI URI `json:\"uri\"`\n}\n\n// Notebook specific client capabilities.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#notebookDocumentSyncClientCapabilities\ntype NotebookDocumentSyncClientCapabilities struct {\n\t// Whether implementation supports dynamic registration. If this is\n\t// set to `true` the client supports the new\n\t// `(TextDocumentRegistrationOptions & StaticRegistrationOptions)`\n\t// return value for the corresponding server capability as well.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n\t// The client supports sending execution summary data per cell.\n\tExecutionSummarySupport bool `json:\"executionSummarySupport,omitempty\"`\n}\n\n// Options specific to a notebook plus its cells\n// to be synced to the server.\n//\n// If a selector provides a notebook document\n// filter but no cell selector all cells of a\n// matching notebook document will be synced.\n//\n// If a selector provides no notebook document\n// filter but only a cell selector all notebook\n// document that contain at least one matching\n// cell will be synced.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#notebookDocumentSyncOptions\ntype NotebookDocumentSyncOptions struct {\n\t// The notebooks to be synced\n\tNotebookSelector []Or_NotebookDocumentSyncOptions_notebookSelector_Elem `json:\"notebookSelector\"`\n\t// Whether save notification should be forwarded to\n\t// the server. Will only be honored if mode === `notebook`.\n\tSave bool `json:\"save,omitempty\"`\n}\n\n// Registration options specific to a notebook.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#notebookDocumentSyncRegistrationOptions\ntype NotebookDocumentSyncRegistrationOptions struct {\n\tNotebookDocumentSyncOptions\n\tStaticRegistrationOptions\n}\n\n// A text document identifier to optionally denote a specific version of a text document.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#optionalVersionedTextDocumentIdentifier\ntype OptionalVersionedTextDocumentIdentifier struct {\n\t// The version number of this document. If a versioned text document identifier\n\t// is sent from the server to the client and the file is not open in the editor\n\t// (the server has not received an open notification before) the server can send\n\t// `null` to indicate that the version is unknown and the content on disk is the\n\t// truth (as specified with document content ownership).\n\tVersion int32 `json:\"version\"`\n\tTextDocumentIdentifier\n}\n\n// created for Or [int32 string]\ntype Or_CancelParams_id struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [ClientSemanticTokensRequestFullDelta bool]\ntype Or_ClientSemanticTokensRequestOptions_full struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [Lit_ClientSemanticTokensRequestOptions_range_Item1 bool]\ntype Or_ClientSemanticTokensRequestOptions_range struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [EditRangeWithInsertReplace Range]\ntype Or_CompletionItemDefaults_editRange struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [MarkupContent string]\ntype Or_CompletionItem_documentation struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [InsertReplaceEdit TextEdit]\ntype Or_CompletionItem_textEdit struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [Location []Location]\ntype Or_Declaration struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [Location []Location]\ntype Or_Definition struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [int32 string]\ntype Or_Diagnostic_code struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [[]string string]\ntype Or_DidChangeConfigurationRegistrationOptions_section struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [RelatedFullDocumentDiagnosticReport RelatedUnchangedDocumentDiagnosticReport]\ntype Or_DocumentDiagnosticReport struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [FullDocumentDiagnosticReport UnchangedDocumentDiagnosticReport]\ntype Or_DocumentDiagnosticReportPartialResult_relatedDocuments_Value struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [NotebookCellTextDocumentFilter TextDocumentFilter]\ntype Or_DocumentFilter struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [Pattern RelativePattern]\ntype Or_GlobPattern struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [MarkedString MarkupContent []MarkedString]\ntype Or_Hover_contents struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [MarkupContent string]\ntype Or_InlayHintLabelPart_tooltip struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [[]InlayHintLabelPart string]\ntype Or_InlayHint_label struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [MarkupContent string]\ntype Or_InlayHint_tooltip struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [StringValue string]\ntype Or_InlineCompletionItem_insertText struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [InlineValueEvaluatableExpression InlineValueText InlineValueVariableLookup]\ntype Or_InlineValue struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [LSPArray LSPObject bool float64 int32 string uint32]\ntype Or_LSPAny struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [MarkedStringWithLanguage string]\ntype Or_MarkedString struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [NotebookDocumentFilter string]\ntype Or_NotebookCellTextDocumentFilter_notebook struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [NotebookDocumentFilterNotebookType NotebookDocumentFilterPattern NotebookDocumentFilterScheme]\ntype Or_NotebookDocumentFilter struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [NotebookDocumentFilter string]\ntype Or_NotebookDocumentFilterWithCells_notebook struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [NotebookDocumentFilter string]\ntype Or_NotebookDocumentFilterWithNotebook_notebook struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [NotebookDocumentFilterWithCells NotebookDocumentFilterWithNotebook]\ntype Or_NotebookDocumentSyncOptions_notebookSelector_Elem struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [MarkupContent string]\ntype Or_ParameterInformation_documentation struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [Tuple_ParameterInformation_label_Item1 string]\ntype Or_ParameterInformation_label struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [PrepareRenameDefaultBehavior PrepareRenamePlaceholder Range]\ntype Or_PrepareRenameResult struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [int32 string]\ntype Or_ProgressToken struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [FullDocumentDiagnosticReport UnchangedDocumentDiagnosticReport]\ntype Or_RelatedFullDocumentDiagnosticReport_relatedDocuments_Value struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [FullDocumentDiagnosticReport UnchangedDocumentDiagnosticReport]\ntype Or_RelatedUnchangedDocumentDiagnosticReport_relatedDocuments_Value struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [URI WorkspaceFolder]\ntype Or_RelativePattern_baseUri struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [CodeAction Command]\ntype Or_Result_textDocument_codeAction_Item0_Elem struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [CompletionList []CompletionItem]\ntype Or_Result_textDocument_completion struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [Declaration []DeclarationLink]\ntype Or_Result_textDocument_declaration struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [Definition []DefinitionLink]\ntype Or_Result_textDocument_definition struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [[]DocumentSymbol []SymbolInformation]\ntype Or_Result_textDocument_documentSymbol struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [Definition []DefinitionLink]\ntype Or_Result_textDocument_implementation struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [InlineCompletionList []InlineCompletionItem]\ntype Or_Result_textDocument_inlineCompletion struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [SemanticTokens SemanticTokensDelta]\ntype Or_Result_textDocument_semanticTokens_full_delta struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [Definition []DefinitionLink]\ntype Or_Result_textDocument_typeDefinition struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [[]SymbolInformation []WorkspaceSymbol]\ntype Or_Result_workspace_symbol struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [SemanticTokensFullDelta bool]\ntype Or_SemanticTokensOptions_full struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [Lit_SemanticTokensOptions_range_Item1 bool]\ntype Or_SemanticTokensOptions_range struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [CallHierarchyOptions CallHierarchyRegistrationOptions bool]\ntype Or_ServerCapabilities_callHierarchyProvider struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [CodeActionOptions bool]\ntype Or_ServerCapabilities_codeActionProvider struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [DocumentColorOptions DocumentColorRegistrationOptions bool]\ntype Or_ServerCapabilities_colorProvider struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [DeclarationOptions DeclarationRegistrationOptions bool]\ntype Or_ServerCapabilities_declarationProvider struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [DefinitionOptions bool]\ntype Or_ServerCapabilities_definitionProvider struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [DiagnosticOptions DiagnosticRegistrationOptions]\ntype Or_ServerCapabilities_diagnosticProvider struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [DocumentFormattingOptions bool]\ntype Or_ServerCapabilities_documentFormattingProvider struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [DocumentHighlightOptions bool]\ntype Or_ServerCapabilities_documentHighlightProvider struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [DocumentRangeFormattingOptions bool]\ntype Or_ServerCapabilities_documentRangeFormattingProvider struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [DocumentSymbolOptions bool]\ntype Or_ServerCapabilities_documentSymbolProvider struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [FoldingRangeOptions FoldingRangeRegistrationOptions bool]\ntype Or_ServerCapabilities_foldingRangeProvider struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [HoverOptions bool]\ntype Or_ServerCapabilities_hoverProvider struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [ImplementationOptions ImplementationRegistrationOptions bool]\ntype Or_ServerCapabilities_implementationProvider struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [InlayHintOptions InlayHintRegistrationOptions bool]\ntype Or_ServerCapabilities_inlayHintProvider struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [InlineCompletionOptions bool]\ntype Or_ServerCapabilities_inlineCompletionProvider struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [InlineValueOptions InlineValueRegistrationOptions bool]\ntype Or_ServerCapabilities_inlineValueProvider struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [LinkedEditingRangeOptions LinkedEditingRangeRegistrationOptions bool]\ntype Or_ServerCapabilities_linkedEditingRangeProvider struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [MonikerOptions MonikerRegistrationOptions bool]\ntype Or_ServerCapabilities_monikerProvider struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [NotebookDocumentSyncOptions NotebookDocumentSyncRegistrationOptions]\ntype Or_ServerCapabilities_notebookDocumentSync struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [ReferenceOptions bool]\ntype Or_ServerCapabilities_referencesProvider struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [RenameOptions bool]\ntype Or_ServerCapabilities_renameProvider struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [SelectionRangeOptions SelectionRangeRegistrationOptions bool]\ntype Or_ServerCapabilities_selectionRangeProvider struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [SemanticTokensOptions SemanticTokensRegistrationOptions]\ntype Or_ServerCapabilities_semanticTokensProvider struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [TextDocumentSyncKind TextDocumentSyncOptions]\ntype Or_ServerCapabilities_textDocumentSync struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [TypeDefinitionOptions TypeDefinitionRegistrationOptions bool]\ntype Or_ServerCapabilities_typeDefinitionProvider struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [TypeHierarchyOptions TypeHierarchyRegistrationOptions bool]\ntype Or_ServerCapabilities_typeHierarchyProvider struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [WorkspaceSymbolOptions bool]\ntype Or_ServerCapabilities_workspaceSymbolProvider struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [MarkupContent string]\ntype Or_SignatureInformation_documentation struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [TextDocumentContentChangePartial TextDocumentContentChangeWholeDocument]\ntype Or_TextDocumentContentChangeEvent struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [AnnotatedTextEdit SnippetTextEdit TextEdit]\ntype Or_TextDocumentEdit_edits_Elem struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [TextDocumentFilterLanguage TextDocumentFilterPattern TextDocumentFilterScheme]\ntype Or_TextDocumentFilter struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [SaveOptions bool]\ntype Or_TextDocumentSyncOptions_save struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [WorkspaceFullDocumentDiagnosticReport WorkspaceUnchangedDocumentDiagnosticReport]\ntype Or_WorkspaceDocumentDiagnosticReport struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [CreateFile DeleteFile RenameFile TextDocumentEdit]\ntype Or_WorkspaceEdit_documentChanges_Elem struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [bool string]\ntype Or_WorkspaceFoldersServerCapabilities_changeNotifications struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [TextDocumentContentOptions TextDocumentContentRegistrationOptions]\ntype Or_WorkspaceOptions_textDocumentContent struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [Location LocationUriOnly]\ntype Or_WorkspaceSymbol_location struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// The parameters of a configuration request.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#configurationParams\ntype ParamConfiguration struct {\n\tItems []ConfigurationItem `json:\"items\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#initializeParams\ntype ParamInitialize struct {\n\tXInitializeParams\n\tWorkspaceFoldersInitializeParams\n}\n\n// Represents a parameter of a callable-signature. A parameter can\n// have a label and a doc-comment.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#parameterInformation\ntype ParameterInformation struct {\n\t// The label of this parameter information.\n\t//\n\t// Either a string or an inclusive start and exclusive end offsets within its containing\n\t// signature label. (see SignatureInformation.label). The offsets are based on a UTF-16\n\t// string representation as `Position` and `Range` does.\n\t//\n\t// To avoid ambiguities a server should use the [start, end] offset value instead of using\n\t// a substring. Whether a client support this is controlled via `labelOffsetSupport` client\n\t// capability.\n\t//\n\t// *Note*: a label of type string should be a substring of its containing signature label.\n\t// Its intended use case is to highlight the parameter label part in the `SignatureInformation.label`.\n\tLabel Or_ParameterInformation_label `json:\"label\"`\n\t// The human-readable doc-comment of this parameter. Will be shown\n\t// in the UI but can be omitted.\n\tDocumentation *Or_ParameterInformation_documentation `json:\"documentation,omitempty\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#partialResultParams\ntype PartialResultParams struct {\n\t// An optional token that a server can use to report partial results (e.g. streaming) to\n\t// the client.\n\tPartialResultToken *ProgressToken `json:\"partialResultToken,omitempty\"`\n}\n\n// The glob pattern to watch relative to the base path. Glob patterns can have the following syntax:\n//\n// - `*` to match one or more characters in a path segment\n// - `?` to match on one character in a path segment\n// - `**` to match any number of path segments, including none\n// - `{}` to group conditions (e.g. `**/*.{ts,js}` matches all TypeScript and JavaScript files)\n// - `[]` to declare a range of characters to match in a path segment (e.g., `example.[0-9]` to match on `example.0`, `example.1`, …)\n// - `[!...]` to negate a range of characters to match in a path segment (e.g., `example.[!0-9]` to match on `example.a`, `example.b`, but not `example.0`)\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#pattern\ntype Pattern = string // (alias)\n// Position in a text document expressed as zero-based line and character\n// offset. Prior to 3.17 the offsets were always based on a UTF-16 string\n// representation. So a string of the form `a𐐀b` the character offset of the\n// character `a` is 0, the character offset of `𐐀` is 1 and the character\n// offset of b is 3 since `𐐀` is represented using two code units in UTF-16.\n// Since 3.17 clients and servers can agree on a different string encoding\n// representation (e.g. UTF-8). The client announces it's supported encoding\n// via the client capability [`general.positionEncodings`](https://microsoft.github.io/language-server-protocol/specifications/specification-current/#clientCapabilities).\n// The value is an array of position encodings the client supports, with\n// decreasing preference (e.g. the encoding at index `0` is the most preferred\n// one). To stay backwards compatible the only mandatory encoding is UTF-16\n// represented via the string `utf-16`. The server can pick one of the\n// encodings offered by the client and signals that encoding back to the\n// client via the initialize result's property\n// [`capabilities.positionEncoding`](https://microsoft.github.io/language-server-protocol/specifications/specification-current/#serverCapabilities). If the string value\n// `utf-16` is missing from the client's capability `general.positionEncodings`\n// servers can safely assume that the client supports UTF-16. If the server\n// omits the position encoding in its initialize result the encoding defaults\n// to the string value `utf-16`. Implementation considerations: since the\n// conversion from one encoding into another requires the content of the\n// file / line the conversion is best done where the file is read which is\n// usually on the server side.\n//\n// Positions are line end character agnostic. So you can not specify a position\n// that denotes `\\r|\\n` or `\\n|` where `|` represents the character offset.\n//\n// @since 3.17.0 - support for negotiated position encoding.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#position\ntype Position struct {\n\t// Line position in a document (zero-based).\n\t//\n\t// If a line number is greater than the number of lines in a document, it defaults back to the number of lines in the document.\n\t// If a line number is negative, it defaults to 0.\n\tLine uint32 `json:\"line\"`\n\t// Character offset on a line in a document (zero-based).\n\t//\n\t// The meaning of this offset is determined by the negotiated\n\t// `PositionEncodingKind`.\n\t//\n\t// If the character value is greater than the line length it defaults back to the\n\t// line length.\n\tCharacter uint32 `json:\"character\"`\n}\n\n// A set of predefined position encoding kinds.\n//\n// @since 3.17.0\ntype PositionEncodingKind string\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#prepareRenameDefaultBehavior\ntype PrepareRenameDefaultBehavior struct {\n\tDefaultBehavior bool `json:\"defaultBehavior\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#prepareRenameParams\ntype PrepareRenameParams struct {\n\tTextDocumentPositionParams\n\tWorkDoneProgressParams\n}\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#prepareRenamePlaceholder\ntype PrepareRenamePlaceholder struct {\n\tRange Range `json:\"range\"`\n\tPlaceholder string `json:\"placeholder\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#prepareRenameResult\ntype PrepareRenameResult = Or_PrepareRenameResult // (alias)\ntype PrepareSupportDefaultBehavior uint32\n\n// A previous result id in a workspace pull request.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#previousResultId\ntype PreviousResultID struct {\n\t// The URI for which the client knowns a\n\t// result id.\n\tURI DocumentUri `json:\"uri\"`\n\t// The value of the previous result id.\n\tValue string `json:\"value\"`\n}\n\n// A previous result id in a workspace pull request.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#previousResultId\ntype PreviousResultId struct {\n\t// The URI for which the client knowns a\n\t// result id.\n\tURI DocumentUri `json:\"uri\"`\n\t// The value of the previous result id.\n\tValue string `json:\"value\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#progressParams\ntype ProgressParams struct {\n\t// The progress token provided by the client or server.\n\tToken ProgressToken `json:\"token\"`\n\t// The progress data.\n\tValue interface{} `json:\"value\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#progressToken\ntype ProgressToken = Or_ProgressToken // (alias)\n// The publish diagnostic client capabilities.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#publishDiagnosticsClientCapabilities\ntype PublishDiagnosticsClientCapabilities struct {\n\t// Whether the client interprets the version property of the\n\t// `textDocument/publishDiagnostics` notification's parameter.\n\t//\n\t// @since 3.15.0\n\tVersionSupport bool `json:\"versionSupport,omitempty\"`\n\tDiagnosticsCapabilities\n}\n\n// The publish diagnostic notification's parameters.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#publishDiagnosticsParams\ntype PublishDiagnosticsParams struct {\n\t// The URI for which diagnostic information is reported.\n\tURI DocumentUri `json:\"uri\"`\n\t// Optional the version number of the document the diagnostics are published for.\n\t//\n\t// @since 3.15.0\n\tVersion int32 `json:\"version,omitempty\"`\n\t// An array of diagnostic information items.\n\tDiagnostics []Diagnostic `json:\"diagnostics\"`\n}\n\n// A range in a text document expressed as (zero-based) start and end positions.\n//\n// If you want to specify a range that contains a line including the line ending\n// character(s) then use an end position denoting the start of the next line.\n// For example:\n// ```ts\n//\n//\t{\n//\t start: { line: 5, character: 23 }\n//\t end : { line 6, character : 0 }\n//\t}\n//\n// ```\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#range\ntype Range struct {\n\t// The range's start position.\n\tStart Position `json:\"start\"`\n\t// The range's end position.\n\tEnd Position `json:\"end\"`\n}\n\n// Client Capabilities for a {@link ReferencesRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#referenceClientCapabilities\ntype ReferenceClientCapabilities struct {\n\t// Whether references supports dynamic registration.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n}\n\n// Value-object that contains additional information when\n// requesting references.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#referenceContext\ntype ReferenceContext struct {\n\t// Include the declaration of the current symbol.\n\tIncludeDeclaration bool `json:\"includeDeclaration\"`\n}\n\n// Reference options.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#referenceOptions\ntype ReferenceOptions struct {\n\tWorkDoneProgressOptions\n}\n\n// Parameters for a {@link ReferencesRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#referenceParams\ntype ReferenceParams struct {\n\tContext ReferenceContext `json:\"context\"`\n\tTextDocumentPositionParams\n\tWorkDoneProgressParams\n\tPartialResultParams\n}\n\n// Registration options for a {@link ReferencesRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#referenceRegistrationOptions\ntype ReferenceRegistrationOptions struct {\n\tTextDocumentRegistrationOptions\n\tReferenceOptions\n}\n\n// General parameters to register for a notification or to register a provider.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#registration\ntype Registration struct {\n\t// The id used to register the request. The id can be used to deregister\n\t// the request again.\n\tID string `json:\"id\"`\n\t// The method / capability to register for.\n\tMethod string `json:\"method\"`\n\t// Options necessary for the registration.\n\tRegisterOptions interface{} `json:\"registerOptions,omitempty\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#registrationParams\ntype RegistrationParams struct {\n\tRegistrations []Registration `json:\"registrations\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#regularExpressionEngineKind\ntype RegularExpressionEngineKind = string // (alias)\n// Client capabilities specific to regular expressions.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#regularExpressionsClientCapabilities\ntype RegularExpressionsClientCapabilities struct {\n\t// The engine's name.\n\tEngine RegularExpressionEngineKind `json:\"engine\"`\n\t// The engine's version.\n\tVersion string `json:\"version,omitempty\"`\n}\n\n// A full diagnostic report with a set of related documents.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#relatedFullDocumentDiagnosticReport\ntype RelatedFullDocumentDiagnosticReport struct {\n\t// Diagnostics of related documents. This information is useful\n\t// in programming languages where code in a file A can generate\n\t// diagnostics in a file B which A depends on. An example of\n\t// such a language is C/C++ where marco definitions in a file\n\t// a.cpp and result in errors in a header file b.hpp.\n\t//\n\t// @since 3.17.0\n\tRelatedDocuments map[DocumentUri]interface{} `json:\"relatedDocuments,omitempty\"`\n\tFullDocumentDiagnosticReport\n}\n\n// An unchanged diagnostic report with a set of related documents.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#relatedUnchangedDocumentDiagnosticReport\ntype RelatedUnchangedDocumentDiagnosticReport struct {\n\t// Diagnostics of related documents. This information is useful\n\t// in programming languages where code in a file A can generate\n\t// diagnostics in a file B which A depends on. An example of\n\t// such a language is C/C++ where marco definitions in a file\n\t// a.cpp and result in errors in a header file b.hpp.\n\t//\n\t// @since 3.17.0\n\tRelatedDocuments map[DocumentUri]interface{} `json:\"relatedDocuments,omitempty\"`\n\tUnchangedDocumentDiagnosticReport\n}\n\n// A relative pattern is a helper to construct glob patterns that are matched\n// relatively to a base URI. The common value for a `baseUri` is a workspace\n// folder root, but it can be another absolute URI as well.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#relativePattern\ntype RelativePattern struct {\n\t// A workspace folder or a base URI to which this pattern will be matched\n\t// against relatively.\n\tBaseURI Or_RelativePattern_baseUri `json:\"baseUri\"`\n\t// The actual glob pattern;\n\tPattern Pattern `json:\"pattern\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#renameClientCapabilities\ntype RenameClientCapabilities struct {\n\t// Whether rename supports dynamic registration.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n\t// Client supports testing for validity of rename operations\n\t// before execution.\n\t//\n\t// @since 3.12.0\n\tPrepareSupport bool `json:\"prepareSupport,omitempty\"`\n\t// Client supports the default behavior result.\n\t//\n\t// The value indicates the default behavior used by the\n\t// client.\n\t//\n\t// @since 3.16.0\n\tPrepareSupportDefaultBehavior *PrepareSupportDefaultBehavior `json:\"prepareSupportDefaultBehavior,omitempty\"`\n\t// Whether the client honors the change annotations in\n\t// text edits and resource operations returned via the\n\t// rename request's workspace edit by for example presenting\n\t// the workspace edit in the user interface and asking\n\t// for confirmation.\n\t//\n\t// @since 3.16.0\n\tHonorsChangeAnnotations bool `json:\"honorsChangeAnnotations,omitempty\"`\n}\n\n// Rename file operation\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#renameFile\ntype RenameFile struct {\n\t// A rename\n\tKind string `json:\"kind\"`\n\t// The old (existing) location.\n\tOldURI DocumentUri `json:\"oldUri\"`\n\t// The new location.\n\tNewURI DocumentUri `json:\"newUri\"`\n\t// Rename options.\n\tOptions *RenameFileOptions `json:\"options,omitempty\"`\n\tResourceOperation\n}\n\n// Rename file options\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#renameFileOptions\ntype RenameFileOptions struct {\n\t// Overwrite target if existing. Overwrite wins over `ignoreIfExists`\n\tOverwrite bool `json:\"overwrite,omitempty\"`\n\t// Ignores if target exists.\n\tIgnoreIfExists bool `json:\"ignoreIfExists,omitempty\"`\n}\n\n// The parameters sent in notifications/requests for user-initiated renames of\n// files.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#renameFilesParams\ntype RenameFilesParams struct {\n\t// An array of all files/folders renamed in this operation. When a folder is renamed, only\n\t// the folder will be included, and not its children.\n\tFiles []FileRename `json:\"files\"`\n}\n\n// Provider options for a {@link RenameRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#renameOptions\ntype RenameOptions struct {\n\t// Renames should be checked and tested before being executed.\n\t//\n\t// @since version 3.12.0\n\tPrepareProvider bool `json:\"prepareProvider,omitempty\"`\n\tWorkDoneProgressOptions\n}\n\n// The parameters of a {@link RenameRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#renameParams\ntype RenameParams struct {\n\t// The document to rename.\n\tTextDocument TextDocumentIdentifier `json:\"textDocument\"`\n\t// The position at which this request was sent.\n\tPosition Position `json:\"position\"`\n\t// The new name of the symbol. If the given name is not valid the\n\t// request must return a {@link ResponseError} with an\n\t// appropriate message set.\n\tNewName string `json:\"newName\"`\n\tWorkDoneProgressParams\n}\n\n// Registration options for a {@link RenameRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#renameRegistrationOptions\ntype RenameRegistrationOptions struct {\n\tTextDocumentRegistrationOptions\n\tRenameOptions\n}\n\n// A generic resource operation.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#resourceOperation\ntype ResourceOperation struct {\n\t// The resource operation kind.\n\tKind string `json:\"kind\"`\n\t// An optional annotation identifier describing the operation.\n\t//\n\t// @since 3.16.0\n\tAnnotationID *ChangeAnnotationIdentifier `json:\"annotationId,omitempty\"`\n}\ntype ResourceOperationKind string\n\n// Save options.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#saveOptions\ntype SaveOptions struct {\n\t// The client is supposed to include the content on save.\n\tIncludeText bool `json:\"includeText,omitempty\"`\n}\n\n// Describes the currently selected completion item.\n//\n// @since 3.18.0\n// @proposed\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#selectedCompletionInfo\ntype SelectedCompletionInfo struct {\n\t// The range that will be replaced if this completion item is accepted.\n\tRange Range `json:\"range\"`\n\t// The text the range will be replaced with if this completion is accepted.\n\tText string `json:\"text\"`\n}\n\n// A selection range represents a part of a selection hierarchy. A selection range\n// may have a parent selection range that contains it.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#selectionRange\ntype SelectionRange struct {\n\t// The {@link Range range} of this selection range.\n\tRange Range `json:\"range\"`\n\t// The parent selection range containing this range. Therefore `parent.range` must contain `this.range`.\n\tParent *SelectionRange `json:\"parent,omitempty\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#selectionRangeClientCapabilities\ntype SelectionRangeClientCapabilities struct {\n\t// Whether implementation supports dynamic registration for selection range providers. If this is set to `true`\n\t// the client supports the new `SelectionRangeRegistrationOptions` return value for the corresponding server\n\t// capability as well.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#selectionRangeOptions\ntype SelectionRangeOptions struct {\n\tWorkDoneProgressOptions\n}\n\n// A parameter literal used in selection range requests.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#selectionRangeParams\ntype SelectionRangeParams struct {\n\t// The text document.\n\tTextDocument TextDocumentIdentifier `json:\"textDocument\"`\n\t// The positions inside the text document.\n\tPositions []Position `json:\"positions\"`\n\tWorkDoneProgressParams\n\tPartialResultParams\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#selectionRangeRegistrationOptions\ntype SelectionRangeRegistrationOptions struct {\n\tSelectionRangeOptions\n\tTextDocumentRegistrationOptions\n\tStaticRegistrationOptions\n}\n\n// A set of predefined token modifiers. This set is not fixed\n// an clients can specify additional token types via the\n// corresponding client capabilities.\n//\n// @since 3.16.0\ntype SemanticTokenModifiers string\n\n// A set of predefined token types. This set is not fixed\n// an clients can specify additional token types via the\n// corresponding client capabilities.\n//\n// @since 3.16.0\ntype SemanticTokenTypes string\n\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#semanticTokens\ntype SemanticTokens struct {\n\t// An optional result id. If provided and clients support delta updating\n\t// the client will include the result id in the next semantic token request.\n\t// A server can then instead of computing all semantic tokens again simply\n\t// send a delta.\n\tResultID string `json:\"resultId,omitempty\"`\n\t// The actual tokens.\n\tData []uint32 `json:\"data\"`\n}\n\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#semanticTokensClientCapabilities\ntype SemanticTokensClientCapabilities struct {\n\t// Whether implementation supports dynamic registration. If this is set to `true`\n\t// the client supports the new `(TextDocumentRegistrationOptions & StaticRegistrationOptions)`\n\t// return value for the corresponding server capability as well.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n\t// Which requests the client supports and might send to the server\n\t// depending on the server's capability. Please note that clients might not\n\t// show semantic tokens or degrade some of the user experience if a range\n\t// or full request is advertised by the client but not provided by the\n\t// server. If for example the client capability `requests.full` and\n\t// `request.range` are both set to true but the server only provides a\n\t// range provider the client might not render a minimap correctly or might\n\t// even decide to not show any semantic tokens at all.\n\tRequests ClientSemanticTokensRequestOptions `json:\"requests\"`\n\t// The token types that the client supports.\n\tTokenTypes []string `json:\"tokenTypes\"`\n\t// The token modifiers that the client supports.\n\tTokenModifiers []string `json:\"tokenModifiers\"`\n\t// The token formats the clients supports.\n\tFormats []TokenFormat `json:\"formats\"`\n\t// Whether the client supports tokens that can overlap each other.\n\tOverlappingTokenSupport bool `json:\"overlappingTokenSupport,omitempty\"`\n\t// Whether the client supports tokens that can span multiple lines.\n\tMultilineTokenSupport bool `json:\"multilineTokenSupport,omitempty\"`\n\t// Whether the client allows the server to actively cancel a\n\t// semantic token request, e.g. supports returning\n\t// LSPErrorCodes.ServerCancelled. If a server does the client\n\t// needs to retrigger the request.\n\t//\n\t// @since 3.17.0\n\tServerCancelSupport bool `json:\"serverCancelSupport,omitempty\"`\n\t// Whether the client uses semantic tokens to augment existing\n\t// syntax tokens. If set to `true` client side created syntax\n\t// tokens and semantic tokens are both used for colorization. If\n\t// set to `false` the client only uses the returned semantic tokens\n\t// for colorization.\n\t//\n\t// If the value is `undefined` then the client behavior is not\n\t// specified.\n\t//\n\t// @since 3.17.0\n\tAugmentsSyntaxTokens bool `json:\"augmentsSyntaxTokens,omitempty\"`\n}\n\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#semanticTokensDelta\ntype SemanticTokensDelta struct {\n\tResultID string `json:\"resultId,omitempty\"`\n\t// The semantic token edits to transform a previous result into a new result.\n\tEdits []SemanticTokensEdit `json:\"edits\"`\n}\n\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#semanticTokensDeltaParams\ntype SemanticTokensDeltaParams struct {\n\t// The text document.\n\tTextDocument TextDocumentIdentifier `json:\"textDocument\"`\n\t// The result id of a previous response. The result Id can either point to a full response\n\t// or a delta response depending on what was received last.\n\tPreviousResultID string `json:\"previousResultId\"`\n\tWorkDoneProgressParams\n\tPartialResultParams\n}\n\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#semanticTokensDeltaPartialResult\ntype SemanticTokensDeltaPartialResult struct {\n\tEdits []SemanticTokensEdit `json:\"edits\"`\n}\n\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#semanticTokensEdit\ntype SemanticTokensEdit struct {\n\t// The start offset of the edit.\n\tStart uint32 `json:\"start\"`\n\t// The count of elements to remove.\n\tDeleteCount uint32 `json:\"deleteCount\"`\n\t// The elements to insert.\n\tData []uint32 `json:\"data,omitempty\"`\n}\n\n// Semantic tokens options to support deltas for full documents\n//\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#semanticTokensFullDelta\ntype SemanticTokensFullDelta struct {\n\t// The server supports deltas for full documents.\n\tDelta bool `json:\"delta,omitempty\"`\n}\n\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#semanticTokensLegend\ntype SemanticTokensLegend struct {\n\t// The token types a server uses.\n\tTokenTypes []string `json:\"tokenTypes\"`\n\t// The token modifiers a server uses.\n\tTokenModifiers []string `json:\"tokenModifiers\"`\n}\n\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#semanticTokensOptions\ntype SemanticTokensOptions struct {\n\t// The legend used by the server\n\tLegend SemanticTokensLegend `json:\"legend\"`\n\t// Server supports providing semantic tokens for a specific range\n\t// of a document.\n\tRange *Or_SemanticTokensOptions_range `json:\"range,omitempty\"`\n\t// Server supports providing semantic tokens for a full document.\n\tFull *Or_SemanticTokensOptions_full `json:\"full,omitempty\"`\n\tWorkDoneProgressOptions\n}\n\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#semanticTokensParams\ntype SemanticTokensParams struct {\n\t// The text document.\n\tTextDocument TextDocumentIdentifier `json:\"textDocument\"`\n\tWorkDoneProgressParams\n\tPartialResultParams\n}\n\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#semanticTokensPartialResult\ntype SemanticTokensPartialResult struct {\n\tData []uint32 `json:\"data\"`\n}\n\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#semanticTokensRangeParams\ntype SemanticTokensRangeParams struct {\n\t// The text document.\n\tTextDocument TextDocumentIdentifier `json:\"textDocument\"`\n\t// The range the semantic tokens are requested for.\n\tRange Range `json:\"range\"`\n\tWorkDoneProgressParams\n\tPartialResultParams\n}\n\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#semanticTokensRegistrationOptions\ntype SemanticTokensRegistrationOptions struct {\n\tTextDocumentRegistrationOptions\n\tSemanticTokensOptions\n\tStaticRegistrationOptions\n}\n\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#semanticTokensWorkspaceClientCapabilities\ntype SemanticTokensWorkspaceClientCapabilities struct {\n\t// Whether the client implementation supports a refresh request sent from\n\t// the server to the client.\n\t//\n\t// Note that this event is global and will force the client to refresh all\n\t// semantic tokens currently shown. It should be used with absolute care\n\t// and is useful for situation where a server for example detects a project\n\t// wide change that requires such a calculation.\n\tRefreshSupport bool `json:\"refreshSupport,omitempty\"`\n}\n\n// Defines the capabilities provided by a language\n// server.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#serverCapabilities\ntype ServerCapabilities struct {\n\t// The position encoding the server picked from the encodings offered\n\t// by the client via the client capability `general.positionEncodings`.\n\t//\n\t// If the client didn't provide any position encodings the only valid\n\t// value that a server can return is 'utf-16'.\n\t//\n\t// If omitted it defaults to 'utf-16'.\n\t//\n\t// @since 3.17.0\n\tPositionEncoding *PositionEncodingKind `json:\"positionEncoding,omitempty\"`\n\t// Defines how text documents are synced. Is either a detailed structure\n\t// defining each notification or for backwards compatibility the\n\t// TextDocumentSyncKind number.\n\tTextDocumentSync interface{} `json:\"textDocumentSync,omitempty\"`\n\t// Defines how notebook documents are synced.\n\t//\n\t// @since 3.17.0\n\tNotebookDocumentSync *Or_ServerCapabilities_notebookDocumentSync `json:\"notebookDocumentSync,omitempty\"`\n\t// The server provides completion support.\n\tCompletionProvider *CompletionOptions `json:\"completionProvider,omitempty\"`\n\t// The server provides hover support.\n\tHoverProvider *Or_ServerCapabilities_hoverProvider `json:\"hoverProvider,omitempty\"`\n\t// The server provides signature help support.\n\tSignatureHelpProvider *SignatureHelpOptions `json:\"signatureHelpProvider,omitempty\"`\n\t// The server provides Goto Declaration support.\n\tDeclarationProvider *Or_ServerCapabilities_declarationProvider `json:\"declarationProvider,omitempty\"`\n\t// The server provides goto definition support.\n\tDefinitionProvider *Or_ServerCapabilities_definitionProvider `json:\"definitionProvider,omitempty\"`\n\t// The server provides Goto Type Definition support.\n\tTypeDefinitionProvider *Or_ServerCapabilities_typeDefinitionProvider `json:\"typeDefinitionProvider,omitempty\"`\n\t// The server provides Goto Implementation support.\n\tImplementationProvider *Or_ServerCapabilities_implementationProvider `json:\"implementationProvider,omitempty\"`\n\t// The server provides find references support.\n\tReferencesProvider *Or_ServerCapabilities_referencesProvider `json:\"referencesProvider,omitempty\"`\n\t// The server provides document highlight support.\n\tDocumentHighlightProvider *Or_ServerCapabilities_documentHighlightProvider `json:\"documentHighlightProvider,omitempty\"`\n\t// The server provides document symbol support.\n\tDocumentSymbolProvider *Or_ServerCapabilities_documentSymbolProvider `json:\"documentSymbolProvider,omitempty\"`\n\t// The server provides code actions. CodeActionOptions may only be\n\t// specified if the client states that it supports\n\t// `codeActionLiteralSupport` in its initial `initialize` request.\n\tCodeActionProvider interface{} `json:\"codeActionProvider,omitempty\"`\n\t// The server provides code lens.\n\tCodeLensProvider *CodeLensOptions `json:\"codeLensProvider,omitempty\"`\n\t// The server provides document link support.\n\tDocumentLinkProvider *DocumentLinkOptions `json:\"documentLinkProvider,omitempty\"`\n\t// The server provides color provider support.\n\tColorProvider *Or_ServerCapabilities_colorProvider `json:\"colorProvider,omitempty\"`\n\t// The server provides workspace symbol support.\n\tWorkspaceSymbolProvider *Or_ServerCapabilities_workspaceSymbolProvider `json:\"workspaceSymbolProvider,omitempty\"`\n\t// The server provides document formatting.\n\tDocumentFormattingProvider *Or_ServerCapabilities_documentFormattingProvider `json:\"documentFormattingProvider,omitempty\"`\n\t// The server provides document range formatting.\n\tDocumentRangeFormattingProvider *Or_ServerCapabilities_documentRangeFormattingProvider `json:\"documentRangeFormattingProvider,omitempty\"`\n\t// The server provides document formatting on typing.\n\tDocumentOnTypeFormattingProvider *DocumentOnTypeFormattingOptions `json:\"documentOnTypeFormattingProvider,omitempty\"`\n\t// The server provides rename support. RenameOptions may only be\n\t// specified if the client states that it supports\n\t// `prepareSupport` in its initial `initialize` request.\n\tRenameProvider interface{} `json:\"renameProvider,omitempty\"`\n\t// The server provides folding provider support.\n\tFoldingRangeProvider *Or_ServerCapabilities_foldingRangeProvider `json:\"foldingRangeProvider,omitempty\"`\n\t// The server provides selection range support.\n\tSelectionRangeProvider *Or_ServerCapabilities_selectionRangeProvider `json:\"selectionRangeProvider,omitempty\"`\n\t// The server provides execute command support.\n\tExecuteCommandProvider *ExecuteCommandOptions `json:\"executeCommandProvider,omitempty\"`\n\t// The server provides call hierarchy support.\n\t//\n\t// @since 3.16.0\n\tCallHierarchyProvider *Or_ServerCapabilities_callHierarchyProvider `json:\"callHierarchyProvider,omitempty\"`\n\t// The server provides linked editing range support.\n\t//\n\t// @since 3.16.0\n\tLinkedEditingRangeProvider *Or_ServerCapabilities_linkedEditingRangeProvider `json:\"linkedEditingRangeProvider,omitempty\"`\n\t// The server provides semantic tokens support.\n\t//\n\t// @since 3.16.0\n\tSemanticTokensProvider interface{} `json:\"semanticTokensProvider,omitempty\"`\n\t// The server provides moniker support.\n\t//\n\t// @since 3.16.0\n\tMonikerProvider *Or_ServerCapabilities_monikerProvider `json:\"monikerProvider,omitempty\"`\n\t// The server provides type hierarchy support.\n\t//\n\t// @since 3.17.0\n\tTypeHierarchyProvider *Or_ServerCapabilities_typeHierarchyProvider `json:\"typeHierarchyProvider,omitempty\"`\n\t// The server provides inline values.\n\t//\n\t// @since 3.17.0\n\tInlineValueProvider *Or_ServerCapabilities_inlineValueProvider `json:\"inlineValueProvider,omitempty\"`\n\t// The server provides inlay hints.\n\t//\n\t// @since 3.17.0\n\tInlayHintProvider interface{} `json:\"inlayHintProvider,omitempty\"`\n\t// The server has support for pull model diagnostics.\n\t//\n\t// @since 3.17.0\n\tDiagnosticProvider *Or_ServerCapabilities_diagnosticProvider `json:\"diagnosticProvider,omitempty\"`\n\t// Inline completion options used during static registration.\n\t//\n\t// @since 3.18.0\n\t// @proposed\n\tInlineCompletionProvider *Or_ServerCapabilities_inlineCompletionProvider `json:\"inlineCompletionProvider,omitempty\"`\n\t// Workspace specific server capabilities.\n\tWorkspace *WorkspaceOptions `json:\"workspace,omitempty\"`\n\t// Experimental server capabilities.\n\tExperimental interface{} `json:\"experimental,omitempty\"`\n}\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#serverCompletionItemOptions\ntype ServerCompletionItemOptions struct {\n\t// The server has support for completion item label\n\t// details (see also `CompletionItemLabelDetails`) when\n\t// receiving a completion item in a resolve call.\n\t//\n\t// @since 3.17.0\n\tLabelDetailsSupport bool `json:\"labelDetailsSupport,omitempty\"`\n}\n\n// Information about the server\n//\n// @since 3.15.0\n// @since 3.18.0 ServerInfo type name added.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#serverInfo\ntype ServerInfo struct {\n\t// The name of the server as defined by the server.\n\tName string `json:\"name\"`\n\t// The server's version as defined by the server.\n\tVersion string `json:\"version,omitempty\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#setTraceParams\ntype SetTraceParams struct {\n\tValue TraceValue `json:\"value\"`\n}\n\n// Client capabilities for the showDocument request.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#showDocumentClientCapabilities\ntype ShowDocumentClientCapabilities struct {\n\t// The client has support for the showDocument\n\t// request.\n\tSupport bool `json:\"support\"`\n}\n\n// Params to show a resource in the UI.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#showDocumentParams\ntype ShowDocumentParams struct {\n\t// The uri to show.\n\tURI URI `json:\"uri\"`\n\t// Indicates to show the resource in an external program.\n\t// To show, for example, `https://code.visualstudio.com/`\n\t// in the default WEB browser set `external` to `true`.\n\tExternal bool `json:\"external,omitempty\"`\n\t// An optional property to indicate whether the editor\n\t// showing the document should take focus or not.\n\t// Clients might ignore this property if an external\n\t// program is started.\n\tTakeFocus bool `json:\"takeFocus,omitempty\"`\n\t// An optional selection range if the document is a text\n\t// document. Clients might ignore the property if an\n\t// external program is started or the file is not a text\n\t// file.\n\tSelection *Range `json:\"selection,omitempty\"`\n}\n\n// The result of a showDocument request.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#showDocumentResult\ntype ShowDocumentResult struct {\n\t// A boolean indicating if the show was successful.\n\tSuccess bool `json:\"success\"`\n}\n\n// The parameters of a notification message.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#showMessageParams\ntype ShowMessageParams struct {\n\t// The message type. See {@link MessageType}\n\tType MessageType `json:\"type\"`\n\t// The actual message.\n\tMessage string `json:\"message\"`\n}\n\n// Show message request client capabilities\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#showMessageRequestClientCapabilities\ntype ShowMessageRequestClientCapabilities struct {\n\t// Capabilities specific to the `MessageActionItem` type.\n\tMessageActionItem *ClientShowMessageActionItemOptions `json:\"messageActionItem,omitempty\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#showMessageRequestParams\ntype ShowMessageRequestParams struct {\n\t// The message type. See {@link MessageType}\n\tType MessageType `json:\"type\"`\n\t// The actual message.\n\tMessage string `json:\"message\"`\n\t// The message action items to present.\n\tActions []MessageActionItem `json:\"actions,omitempty\"`\n}\n\n// Signature help represents the signature of something\n// callable. There can be multiple signature but only one\n// active and only one active parameter.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#signatureHelp\ntype SignatureHelp struct {\n\t// One or more signatures.\n\tSignatures []SignatureInformation `json:\"signatures\"`\n\t// The active signature. If omitted or the value lies outside the\n\t// range of `signatures` the value defaults to zero or is ignored if\n\t// the `SignatureHelp` has no signatures.\n\t//\n\t// Whenever possible implementors should make an active decision about\n\t// the active signature and shouldn't rely on a default value.\n\t//\n\t// In future version of the protocol this property might become\n\t// mandatory to better express this.\n\tActiveSignature uint32 `json:\"activeSignature,omitempty\"`\n\t// The active parameter of the active signature.\n\t//\n\t// If `null`, no parameter of the signature is active (for example a named\n\t// argument that does not match any declared parameters). This is only valid\n\t// if the client specifies the client capability\n\t// `textDocument.signatureHelp.noActiveParameterSupport === true`\n\t//\n\t// If omitted or the value lies outside the range of\n\t// `signatures[activeSignature].parameters` defaults to 0 if the active\n\t// signature has parameters.\n\t//\n\t// If the active signature has no parameters it is ignored.\n\t//\n\t// In future version of the protocol this property might become\n\t// mandatory (but still nullable) to better express the active parameter if\n\t// the active signature does have any.\n\tActiveParameter uint32 `json:\"activeParameter,omitempty\"`\n}\n\n// Client Capabilities for a {@link SignatureHelpRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#signatureHelpClientCapabilities\ntype SignatureHelpClientCapabilities struct {\n\t// Whether signature help supports dynamic registration.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n\t// The client supports the following `SignatureInformation`\n\t// specific properties.\n\tSignatureInformation *ClientSignatureInformationOptions `json:\"signatureInformation,omitempty\"`\n\t// The client supports to send additional context information for a\n\t// `textDocument/signatureHelp` request. A client that opts into\n\t// contextSupport will also support the `retriggerCharacters` on\n\t// `SignatureHelpOptions`.\n\t//\n\t// @since 3.15.0\n\tContextSupport bool `json:\"contextSupport,omitempty\"`\n}\n\n// Additional information about the context in which a signature help request was triggered.\n//\n// @since 3.15.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#signatureHelpContext\ntype SignatureHelpContext struct {\n\t// Action that caused signature help to be triggered.\n\tTriggerKind SignatureHelpTriggerKind `json:\"triggerKind\"`\n\t// Character that caused signature help to be triggered.\n\t//\n\t// This is undefined when `triggerKind !== SignatureHelpTriggerKind.TriggerCharacter`\n\tTriggerCharacter string `json:\"triggerCharacter,omitempty\"`\n\t// `true` if signature help was already showing when it was triggered.\n\t//\n\t// Retriggers occurs when the signature help is already active and can be caused by actions such as\n\t// typing a trigger character, a cursor move, or document content changes.\n\tIsRetrigger bool `json:\"isRetrigger\"`\n\t// The currently active `SignatureHelp`.\n\t//\n\t// The `activeSignatureHelp` has its `SignatureHelp.activeSignature` field updated based on\n\t// the user navigating through available signatures.\n\tActiveSignatureHelp *SignatureHelp `json:\"activeSignatureHelp,omitempty\"`\n}\n\n// Server Capabilities for a {@link SignatureHelpRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#signatureHelpOptions\ntype SignatureHelpOptions struct {\n\t// List of characters that trigger signature help automatically.\n\tTriggerCharacters []string `json:\"triggerCharacters,omitempty\"`\n\t// List of characters that re-trigger signature help.\n\t//\n\t// These trigger characters are only active when signature help is already showing. All trigger characters\n\t// are also counted as re-trigger characters.\n\t//\n\t// @since 3.15.0\n\tRetriggerCharacters []string `json:\"retriggerCharacters,omitempty\"`\n\tWorkDoneProgressOptions\n}\n\n// Parameters for a {@link SignatureHelpRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#signatureHelpParams\ntype SignatureHelpParams struct {\n\t// The signature help context. This is only available if the client specifies\n\t// to send this using the client capability `textDocument.signatureHelp.contextSupport === true`\n\t//\n\t// @since 3.15.0\n\tContext *SignatureHelpContext `json:\"context,omitempty\"`\n\tTextDocumentPositionParams\n\tWorkDoneProgressParams\n}\n\n// Registration options for a {@link SignatureHelpRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#signatureHelpRegistrationOptions\ntype SignatureHelpRegistrationOptions struct {\n\tTextDocumentRegistrationOptions\n\tSignatureHelpOptions\n}\n\n// How a signature help was triggered.\n//\n// @since 3.15.0\ntype SignatureHelpTriggerKind uint32\n\n// Represents the signature of something callable. A signature\n// can have a label, like a function-name, a doc-comment, and\n// a set of parameters.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#signatureInformation\ntype SignatureInformation struct {\n\t// The label of this signature. Will be shown in\n\t// the UI.\n\tLabel string `json:\"label\"`\n\t// The human-readable doc-comment of this signature. Will be shown\n\t// in the UI but can be omitted.\n\tDocumentation *Or_SignatureInformation_documentation `json:\"documentation,omitempty\"`\n\t// The parameters of this signature.\n\tParameters []ParameterInformation `json:\"parameters,omitempty\"`\n\t// The index of the active parameter.\n\t//\n\t// If `null`, no parameter of the signature is active (for example a named\n\t// argument that does not match any declared parameters). This is only valid\n\t// if the client specifies the client capability\n\t// `textDocument.signatureHelp.noActiveParameterSupport === true`\n\t//\n\t// If provided (or `null`), this is used in place of\n\t// `SignatureHelp.activeParameter`.\n\t//\n\t// @since 3.16.0\n\tActiveParameter uint32 `json:\"activeParameter,omitempty\"`\n}\n\n// An interactive text edit.\n//\n// @since 3.18.0\n// @proposed\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#snippetTextEdit\ntype SnippetTextEdit struct {\n\t// The range of the text document to be manipulated.\n\tRange Range `json:\"range\"`\n\t// The snippet to be inserted.\n\tSnippet StringValue `json:\"snippet\"`\n\t// The actual identifier of the snippet edit.\n\tAnnotationID *ChangeAnnotationIdentifier `json:\"annotationId,omitempty\"`\n}\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#staleRequestSupportOptions\ntype StaleRequestSupportOptions struct {\n\t// The client will actively cancel the request.\n\tCancel bool `json:\"cancel\"`\n\t// The list of requests for which the client\n\t// will retry the request if it receives a\n\t// response with error code `ContentModified`\n\tRetryOnContentModified []string `json:\"retryOnContentModified\"`\n}\n\n// Static registration options to be returned in the initialize\n// request.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#staticRegistrationOptions\ntype StaticRegistrationOptions struct {\n\t// The id used to register the request. The id can be used to deregister\n\t// the request again. See also Registration#id.\n\tID string `json:\"id,omitempty\"`\n}\n\n// A string value used as a snippet is a template which allows to insert text\n// and to control the editor cursor when insertion happens.\n//\n// A snippet can define tab stops and placeholders with `$1`, `$2`\n// and `${3:foo}`. `$0` defines the final tab stop, it defaults to\n// the end of the snippet. Variables are defined with `$name` and\n// `${name:default value}`.\n//\n// @since 3.18.0\n// @proposed\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#stringValue\ntype StringValue struct {\n\t// The kind of string value.\n\tKind string `json:\"kind\"`\n\t// The snippet string.\n\tValue string `json:\"value\"`\n}\n\n// Represents information about programming constructs like variables, classes,\n// interfaces etc.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#symbolInformation\ntype SymbolInformation struct {\n\t// extends BaseSymbolInformation\n\t// Indicates if this symbol is deprecated.\n\t//\n\t// @deprecated Use tags instead\n\tDeprecated bool `json:\"deprecated,omitempty\"`\n\t// The location of this symbol. The location's range is used by a tool\n\t// to reveal the location in the editor. If the symbol is selected in the\n\t// tool the range's start information is used to position the cursor. So\n\t// the range usually spans more than the actual symbol's name and does\n\t// normally include things like visibility modifiers.\n\t//\n\t// The range doesn't have to denote a node range in the sense of an abstract\n\t// syntax tree. It can therefore not be used to re-construct a hierarchy of\n\t// the symbols.\n\tLocation Location `json:\"location\"`\n\t// The name of this symbol.\n\tName string `json:\"name\"`\n\t// The kind of this symbol.\n\tKind SymbolKind `json:\"kind\"`\n\t// Tags for this symbol.\n\t//\n\t// @since 3.16.0\n\tTags []SymbolTag `json:\"tags,omitempty\"`\n\t// The name of the symbol containing this symbol. This information is for\n\t// user interface purposes (e.g. to render a qualifier in the user interface\n\t// if necessary). It can't be used to re-infer a hierarchy for the document\n\t// symbols.\n\tContainerName string `json:\"containerName,omitempty\"`\n}\n\n// A symbol kind.\ntype SymbolKind uint32\n\n// Symbol tags are extra annotations that tweak the rendering of a symbol.\n//\n// @since 3.16\ntype SymbolTag uint32\n\n// Describe options to be used when registered for text document change events.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#textDocumentChangeRegistrationOptions\ntype TextDocumentChangeRegistrationOptions struct {\n\t// How documents are synced to the server.\n\tSyncKind TextDocumentSyncKind `json:\"syncKind\"`\n\tTextDocumentRegistrationOptions\n}\n\n// Text document specific client capabilities.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#textDocumentClientCapabilities\ntype TextDocumentClientCapabilities struct {\n\t// Defines which synchronization capabilities the client supports.\n\tSynchronization *TextDocumentSyncClientCapabilities `json:\"synchronization,omitempty\"`\n\t// Capabilities specific to the `textDocument/completion` request.\n\tCompletion CompletionClientCapabilities `json:\"completion,omitempty\"`\n\t// Capabilities specific to the `textDocument/hover` request.\n\tHover *HoverClientCapabilities `json:\"hover,omitempty\"`\n\t// Capabilities specific to the `textDocument/signatureHelp` request.\n\tSignatureHelp *SignatureHelpClientCapabilities `json:\"signatureHelp,omitempty\"`\n\t// Capabilities specific to the `textDocument/declaration` request.\n\t//\n\t// @since 3.14.0\n\tDeclaration *DeclarationClientCapabilities `json:\"declaration,omitempty\"`\n\t// Capabilities specific to the `textDocument/definition` request.\n\tDefinition *DefinitionClientCapabilities `json:\"definition,omitempty\"`\n\t// Capabilities specific to the `textDocument/typeDefinition` request.\n\t//\n\t// @since 3.6.0\n\tTypeDefinition *TypeDefinitionClientCapabilities `json:\"typeDefinition,omitempty\"`\n\t// Capabilities specific to the `textDocument/implementation` request.\n\t//\n\t// @since 3.6.0\n\tImplementation *ImplementationClientCapabilities `json:\"implementation,omitempty\"`\n\t// Capabilities specific to the `textDocument/references` request.\n\tReferences *ReferenceClientCapabilities `json:\"references,omitempty\"`\n\t// Capabilities specific to the `textDocument/documentHighlight` request.\n\tDocumentHighlight *DocumentHighlightClientCapabilities `json:\"documentHighlight,omitempty\"`\n\t// Capabilities specific to the `textDocument/documentSymbol` request.\n\tDocumentSymbol DocumentSymbolClientCapabilities `json:\"documentSymbol,omitempty\"`\n\t// Capabilities specific to the `textDocument/codeAction` request.\n\tCodeAction CodeActionClientCapabilities `json:\"codeAction,omitempty\"`\n\t// Capabilities specific to the `textDocument/codeLens` request.\n\tCodeLens *CodeLensClientCapabilities `json:\"codeLens,omitempty\"`\n\t// Capabilities specific to the `textDocument/documentLink` request.\n\tDocumentLink *DocumentLinkClientCapabilities `json:\"documentLink,omitempty\"`\n\t// Capabilities specific to the `textDocument/documentColor` and the\n\t// `textDocument/colorPresentation` request.\n\t//\n\t// @since 3.6.0\n\tColorProvider *DocumentColorClientCapabilities `json:\"colorProvider,omitempty\"`\n\t// Capabilities specific to the `textDocument/formatting` request.\n\tFormatting *DocumentFormattingClientCapabilities `json:\"formatting,omitempty\"`\n\t// Capabilities specific to the `textDocument/rangeFormatting` request.\n\tRangeFormatting *DocumentRangeFormattingClientCapabilities `json:\"rangeFormatting,omitempty\"`\n\t// Capabilities specific to the `textDocument/onTypeFormatting` request.\n\tOnTypeFormatting *DocumentOnTypeFormattingClientCapabilities `json:\"onTypeFormatting,omitempty\"`\n\t// Capabilities specific to the `textDocument/rename` request.\n\tRename *RenameClientCapabilities `json:\"rename,omitempty\"`\n\t// Capabilities specific to the `textDocument/foldingRange` request.\n\t//\n\t// @since 3.10.0\n\tFoldingRange *FoldingRangeClientCapabilities `json:\"foldingRange,omitempty\"`\n\t// Capabilities specific to the `textDocument/selectionRange` request.\n\t//\n\t// @since 3.15.0\n\tSelectionRange *SelectionRangeClientCapabilities `json:\"selectionRange,omitempty\"`\n\t// Capabilities specific to the `textDocument/publishDiagnostics` notification.\n\tPublishDiagnostics PublishDiagnosticsClientCapabilities `json:\"publishDiagnostics,omitempty\"`\n\t// Capabilities specific to the various call hierarchy requests.\n\t//\n\t// @since 3.16.0\n\tCallHierarchy *CallHierarchyClientCapabilities `json:\"callHierarchy,omitempty\"`\n\t// Capabilities specific to the various semantic token request.\n\t//\n\t// @since 3.16.0\n\tSemanticTokens SemanticTokensClientCapabilities `json:\"semanticTokens,omitempty\"`\n\t// Capabilities specific to the `textDocument/linkedEditingRange` request.\n\t//\n\t// @since 3.16.0\n\tLinkedEditingRange *LinkedEditingRangeClientCapabilities `json:\"linkedEditingRange,omitempty\"`\n\t// Client capabilities specific to the `textDocument/moniker` request.\n\t//\n\t// @since 3.16.0\n\tMoniker *MonikerClientCapabilities `json:\"moniker,omitempty\"`\n\t// Capabilities specific to the various type hierarchy requests.\n\t//\n\t// @since 3.17.0\n\tTypeHierarchy *TypeHierarchyClientCapabilities `json:\"typeHierarchy,omitempty\"`\n\t// Capabilities specific to the `textDocument/inlineValue` request.\n\t//\n\t// @since 3.17.0\n\tInlineValue *InlineValueClientCapabilities `json:\"inlineValue,omitempty\"`\n\t// Capabilities specific to the `textDocument/inlayHint` request.\n\t//\n\t// @since 3.17.0\n\tInlayHint *InlayHintClientCapabilities `json:\"inlayHint,omitempty\"`\n\t// Capabilities specific to the diagnostic pull model.\n\t//\n\t// @since 3.17.0\n\tDiagnostic *DiagnosticClientCapabilities `json:\"diagnostic,omitempty\"`\n\t// Client capabilities specific to inline completions.\n\t//\n\t// @since 3.18.0\n\t// @proposed\n\tInlineCompletion *InlineCompletionClientCapabilities `json:\"inlineCompletion,omitempty\"`\n}\n\n// An event describing a change to a text document. If only a text is provided\n// it is considered to be the full content of the document.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#textDocumentContentChangeEvent\ntype TextDocumentContentChangeEvent = Or_TextDocumentContentChangeEvent // (alias)\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#textDocumentContentChangePartial\ntype TextDocumentContentChangePartial struct {\n\t// The range of the document that changed.\n\tRange *Range `json:\"range,omitempty\"`\n\t// The optional length of the range that got replaced.\n\t//\n\t// @deprecated use range instead.\n\tRangeLength uint32 `json:\"rangeLength,omitempty\"`\n\t// The new text for the provided range.\n\tText string `json:\"text\"`\n}\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#textDocumentContentChangeWholeDocument\ntype TextDocumentContentChangeWholeDocument struct {\n\t// The new text of the whole document.\n\tText string `json:\"text\"`\n}\n\n// Client capabilities for a text document content provider.\n//\n// @since 3.18.0\n// @proposed\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#textDocumentContentClientCapabilities\ntype TextDocumentContentClientCapabilities struct {\n\t// Text document content provider supports dynamic registration.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n}\n\n// Text document content provider options.\n//\n// @since 3.18.0\n// @proposed\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#textDocumentContentOptions\ntype TextDocumentContentOptions struct {\n\t// The scheme for which the server provides content.\n\tScheme string `json:\"scheme\"`\n}\n\n// Parameters for the `workspace/textDocumentContent` request.\n//\n// @since 3.18.0\n// @proposed\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#textDocumentContentParams\ntype TextDocumentContentParams struct {\n\t// The uri of the text document.\n\tURI DocumentUri `json:\"uri\"`\n}\n\n// Parameters for the `workspace/textDocumentContent/refresh` request.\n//\n// @since 3.18.0\n// @proposed\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#textDocumentContentRefreshParams\ntype TextDocumentContentRefreshParams struct {\n\t// The uri of the text document to refresh.\n\tURI DocumentUri `json:\"uri\"`\n}\n\n// Text document content provider registration options.\n//\n// @since 3.18.0\n// @proposed\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#textDocumentContentRegistrationOptions\ntype TextDocumentContentRegistrationOptions struct {\n\tTextDocumentContentOptions\n\tStaticRegistrationOptions\n}\n\n// Describes textual changes on a text document. A TextDocumentEdit describes all changes\n// on a document version Si and after they are applied move the document to version Si+1.\n// So the creator of a TextDocumentEdit doesn't need to sort the array of edits or do any\n// kind of ordering. However the edits must be non overlapping.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#textDocumentEdit\ntype TextDocumentEdit struct {\n\t// The text document to change.\n\tTextDocument OptionalVersionedTextDocumentIdentifier `json:\"textDocument\"`\n\t// The edits to be applied.\n\t//\n\t// @since 3.16.0 - support for AnnotatedTextEdit. This is guarded using a\n\t// client capability.\n\t//\n\t// @since 3.18.0 - support for SnippetTextEdit. This is guarded using a\n\t// client capability.\n\tEdits []Or_TextDocumentEdit_edits_Elem `json:\"edits\"`\n}\n\n// A document filter denotes a document by different properties like\n// the {@link TextDocument.languageId language}, the {@link Uri.scheme scheme} of\n// its resource, or a glob-pattern that is applied to the {@link TextDocument.fileName path}.\n//\n// Glob patterns can have the following syntax:\n//\n// - `*` to match one or more characters in a path segment\n// - `?` to match on one character in a path segment\n// - `**` to match any number of path segments, including none\n// - `{}` to group sub patterns into an OR expression. (e.g. `**/*.{ts,js}` matches all TypeScript and JavaScript files)\n// - `[]` to declare a range of characters to match in a path segment (e.g., `example.[0-9]` to match on `example.0`, `example.1`, …)\n// - `[!...]` to negate a range of characters to match in a path segment (e.g., `example.[!0-9]` to match on `example.a`, `example.b`, but not `example.0`)\n//\n// @sample A language filter that applies to typescript files on disk: `{ language: 'typescript', scheme: 'file' }`\n// @sample A language filter that applies to all package.json paths: `{ language: 'json', pattern: '**package.json' }`\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#textDocumentFilter\ntype TextDocumentFilter = Or_TextDocumentFilter // (alias)\n// A document filter where `language` is required field.\n//\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#textDocumentFilterLanguage\ntype TextDocumentFilterLanguage struct {\n\t// A language id, like `typescript`.\n\tLanguage string `json:\"language\"`\n\t// A Uri {@link Uri.scheme scheme}, like `file` or `untitled`.\n\tScheme string `json:\"scheme,omitempty\"`\n\t// A glob pattern, like **/*.{ts,js}. See TextDocumentFilter for examples.\n\t//\n\t// @since 3.18.0 - support for relative patterns.\n\tPattern *GlobPattern `json:\"pattern,omitempty\"`\n}\n\n// A document filter where `pattern` is required field.\n//\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#textDocumentFilterPattern\ntype TextDocumentFilterPattern struct {\n\t// A language id, like `typescript`.\n\tLanguage string `json:\"language,omitempty\"`\n\t// A Uri {@link Uri.scheme scheme}, like `file` or `untitled`.\n\tScheme string `json:\"scheme,omitempty\"`\n\t// A glob pattern, like **/*.{ts,js}. See TextDocumentFilter for examples.\n\t//\n\t// @since 3.18.0 - support for relative patterns.\n\tPattern GlobPattern `json:\"pattern\"`\n}\n\n// A document filter where `scheme` is required field.\n//\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#textDocumentFilterScheme\ntype TextDocumentFilterScheme struct {\n\t// A language id, like `typescript`.\n\tLanguage string `json:\"language,omitempty\"`\n\t// A Uri {@link Uri.scheme scheme}, like `file` or `untitled`.\n\tScheme string `json:\"scheme\"`\n\t// A glob pattern, like **/*.{ts,js}. See TextDocumentFilter for examples.\n\t//\n\t// @since 3.18.0 - support for relative patterns.\n\tPattern *GlobPattern `json:\"pattern,omitempty\"`\n}\n\n// A literal to identify a text document in the client.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#textDocumentIdentifier\ntype TextDocumentIdentifier struct {\n\t// The text document's uri.\n\tURI DocumentUri `json:\"uri\"`\n}\n\n// An item to transfer a text document from the client to the\n// server.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#textDocumentItem\ntype TextDocumentItem struct {\n\t// The text document's uri.\n\tURI DocumentUri `json:\"uri\"`\n\t// The text document's language identifier.\n\tLanguageID LanguageKind `json:\"languageId\"`\n\t// The version number of this document (it will increase after each\n\t// change, including undo/redo).\n\tVersion int32 `json:\"version\"`\n\t// The content of the opened text document.\n\tText string `json:\"text\"`\n}\n\n// A parameter literal used in requests to pass a text document and a position inside that\n// document.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#textDocumentPositionParams\ntype TextDocumentPositionParams struct {\n\t// The text document.\n\tTextDocument TextDocumentIdentifier `json:\"textDocument\"`\n\t// The position inside the text document.\n\tPosition Position `json:\"position\"`\n}\n\n// General text document registration options.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#textDocumentRegistrationOptions\ntype TextDocumentRegistrationOptions struct {\n\t// A document selector to identify the scope of the registration. If set to null\n\t// the document selector provided on the client side will be used.\n\tDocumentSelector DocumentSelector `json:\"documentSelector\"`\n}\n\n// Represents reasons why a text document is saved.\ntype TextDocumentSaveReason uint32\n\n// Save registration options.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#textDocumentSaveRegistrationOptions\ntype TextDocumentSaveRegistrationOptions struct {\n\tTextDocumentRegistrationOptions\n\tSaveOptions\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#textDocumentSyncClientCapabilities\ntype TextDocumentSyncClientCapabilities struct {\n\t// Whether text document synchronization supports dynamic registration.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n\t// The client supports sending will save notifications.\n\tWillSave bool `json:\"willSave,omitempty\"`\n\t// The client supports sending a will save request and\n\t// waits for a response providing text edits which will\n\t// be applied to the document before it is saved.\n\tWillSaveWaitUntil bool `json:\"willSaveWaitUntil,omitempty\"`\n\t// The client supports did save notifications.\n\tDidSave bool `json:\"didSave,omitempty\"`\n}\n\n// Defines how the host (editor) should sync\n// document changes to the language server.\ntype TextDocumentSyncKind uint32\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#textDocumentSyncOptions\ntype TextDocumentSyncOptions struct {\n\t// Open and close notifications are sent to the server. If omitted open close notification should not\n\t// be sent.\n\tOpenClose bool `json:\"openClose,omitempty\"`\n\t// Change notifications are sent to the server. See TextDocumentSyncKind.None, TextDocumentSyncKind.Full\n\t// and TextDocumentSyncKind.Incremental. If omitted it defaults to TextDocumentSyncKind.None.\n\tChange TextDocumentSyncKind `json:\"change,omitempty\"`\n\t// If present will save notifications are sent to the server. If omitted the notification should not be\n\t// sent.\n\tWillSave bool `json:\"willSave,omitempty\"`\n\t// If present will save wait until requests are sent to the server. If omitted the request should not be\n\t// sent.\n\tWillSaveWaitUntil bool `json:\"willSaveWaitUntil,omitempty\"`\n\t// If present save notifications are sent to the server. If omitted the notification should not be\n\t// sent.\n\tSave *SaveOptions `json:\"save,omitempty\"`\n}\n\n// A text edit applicable to a text document.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#textEdit\ntype TextEdit struct {\n\t// The range of the text document to be manipulated. To insert\n\t// text into a document create a range where start === end.\n\tRange Range `json:\"range\"`\n\t// The string to be inserted. For delete operations use an\n\t// empty string.\n\tNewText string `json:\"newText\"`\n}\ntype TokenFormat string\ntype TraceValue string\n\n// created for Tuple\ntype Tuple_ParameterInformation_label_Item1 struct {\n\tFld0 uint32 `json:\"fld0\"`\n\tFld1 uint32 `json:\"fld1\"`\n}\n\n// Since 3.6.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#typeDefinitionClientCapabilities\ntype TypeDefinitionClientCapabilities struct {\n\t// Whether implementation supports dynamic registration. If this is set to `true`\n\t// the client supports the new `TypeDefinitionRegistrationOptions` return value\n\t// for the corresponding server capability as well.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n\t// The client supports additional metadata in the form of definition links.\n\t//\n\t// Since 3.14.0\n\tLinkSupport bool `json:\"linkSupport,omitempty\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#typeDefinitionOptions\ntype TypeDefinitionOptions struct {\n\tWorkDoneProgressOptions\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#typeDefinitionParams\ntype TypeDefinitionParams struct {\n\tTextDocumentPositionParams\n\tWorkDoneProgressParams\n\tPartialResultParams\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#typeDefinitionRegistrationOptions\ntype TypeDefinitionRegistrationOptions struct {\n\tTextDocumentRegistrationOptions\n\tTypeDefinitionOptions\n\tStaticRegistrationOptions\n}\n\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#typeHierarchyClientCapabilities\ntype TypeHierarchyClientCapabilities struct {\n\t// Whether implementation supports dynamic registration. If this is set to `true`\n\t// the client supports the new `(TextDocumentRegistrationOptions & StaticRegistrationOptions)`\n\t// return value for the corresponding server capability as well.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n}\n\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#typeHierarchyItem\ntype TypeHierarchyItem struct {\n\t// The name of this item.\n\tName string `json:\"name\"`\n\t// The kind of this item.\n\tKind SymbolKind `json:\"kind\"`\n\t// Tags for this item.\n\tTags []SymbolTag `json:\"tags,omitempty\"`\n\t// More detail for this item, e.g. the signature of a function.\n\tDetail string `json:\"detail,omitempty\"`\n\t// The resource identifier of this item.\n\tURI DocumentUri `json:\"uri\"`\n\t// The range enclosing this symbol not including leading/trailing whitespace\n\t// but everything else, e.g. comments and code.\n\tRange Range `json:\"range\"`\n\t// The range that should be selected and revealed when this symbol is being\n\t// picked, e.g. the name of a function. Must be contained by the\n\t// {@link TypeHierarchyItem.range `range`}.\n\tSelectionRange Range `json:\"selectionRange\"`\n\t// A data entry field that is preserved between a type hierarchy prepare and\n\t// supertypes or subtypes requests. It could also be used to identify the\n\t// type hierarchy in the server, helping improve the performance on\n\t// resolving supertypes and subtypes.\n\tData interface{} `json:\"data,omitempty\"`\n}\n\n// Type hierarchy options used during static registration.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#typeHierarchyOptions\ntype TypeHierarchyOptions struct {\n\tWorkDoneProgressOptions\n}\n\n// The parameter of a `textDocument/prepareTypeHierarchy` request.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#typeHierarchyPrepareParams\ntype TypeHierarchyPrepareParams struct {\n\tTextDocumentPositionParams\n\tWorkDoneProgressParams\n}\n\n// Type hierarchy options used during static or dynamic registration.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#typeHierarchyRegistrationOptions\ntype TypeHierarchyRegistrationOptions struct {\n\tTextDocumentRegistrationOptions\n\tTypeHierarchyOptions\n\tStaticRegistrationOptions\n}\n\n// The parameter of a `typeHierarchy/subtypes` request.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#typeHierarchySubtypesParams\ntype TypeHierarchySubtypesParams struct {\n\tItem TypeHierarchyItem `json:\"item\"`\n\tWorkDoneProgressParams\n\tPartialResultParams\n}\n\n// The parameter of a `typeHierarchy/supertypes` request.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#typeHierarchySupertypesParams\ntype TypeHierarchySupertypesParams struct {\n\tItem TypeHierarchyItem `json:\"item\"`\n\tWorkDoneProgressParams\n\tPartialResultParams\n}\n\n// A diagnostic report indicating that the last returned\n// report is still accurate.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#unchangedDocumentDiagnosticReport\ntype UnchangedDocumentDiagnosticReport struct {\n\t// A document diagnostic report indicating\n\t// no changes to the last result. A server can\n\t// only return `unchanged` if result ids are\n\t// provided.\n\tKind string `json:\"kind\"`\n\t// A result id which will be sent on the next\n\t// diagnostic request for the same document.\n\tResultID string `json:\"resultId\"`\n}\n\n// Moniker uniqueness level to define scope of the moniker.\n//\n// @since 3.16.0\ntype UniquenessLevel string\n\n// General parameters to unregister a request or notification.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#unregistration\ntype Unregistration struct {\n\t// The id used to unregister the request or notification. Usually an id\n\t// provided during the register request.\n\tID string `json:\"id\"`\n\t// The method to unregister for.\n\tMethod string `json:\"method\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#unregistrationParams\ntype UnregistrationParams struct {\n\tUnregisterations []Unregistration `json:\"unregisterations\"`\n}\n\n// A versioned notebook document identifier.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#versionedNotebookDocumentIdentifier\ntype VersionedNotebookDocumentIdentifier struct {\n\t// The version number of this notebook document.\n\tVersion int32 `json:\"version\"`\n\t// The notebook document's uri.\n\tURI URI `json:\"uri\"`\n}\n\n// A text document identifier to denote a specific version of a text document.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#versionedTextDocumentIdentifier\ntype VersionedTextDocumentIdentifier struct {\n\t// The version number of this document.\n\tVersion int32 `json:\"version\"`\n\tTextDocumentIdentifier\n}\ntype WatchKind = uint32 // The parameters sent in a will save text document notification.\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#willSaveTextDocumentParams\ntype WillSaveTextDocumentParams struct {\n\t// The document that will be saved.\n\tTextDocument TextDocumentIdentifier `json:\"textDocument\"`\n\t// The 'TextDocumentSaveReason'.\n\tReason TextDocumentSaveReason `json:\"reason\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#windowClientCapabilities\ntype WindowClientCapabilities struct {\n\t// It indicates whether the client supports server initiated\n\t// progress using the `window/workDoneProgress/create` request.\n\t//\n\t// The capability also controls Whether client supports handling\n\t// of progress notifications. If set servers are allowed to report a\n\t// `workDoneProgress` property in the request specific server\n\t// capabilities.\n\t//\n\t// @since 3.15.0\n\tWorkDoneProgress bool `json:\"workDoneProgress,omitempty\"`\n\t// Capabilities specific to the showMessage request.\n\t//\n\t// @since 3.16.0\n\tShowMessage *ShowMessageRequestClientCapabilities `json:\"showMessage,omitempty\"`\n\t// Capabilities specific to the showDocument request.\n\t//\n\t// @since 3.16.0\n\tShowDocument *ShowDocumentClientCapabilities `json:\"showDocument,omitempty\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#workDoneProgressBegin\ntype WorkDoneProgressBegin struct {\n\tKind string `json:\"kind\"`\n\t// Mandatory title of the progress operation. Used to briefly inform about\n\t// the kind of operation being performed.\n\t//\n\t// Examples: \"Indexing\" or \"Linking dependencies\".\n\tTitle string `json:\"title\"`\n\t// Controls if a cancel button should show to allow the user to cancel the\n\t// long running operation. Clients that don't support cancellation are allowed\n\t// to ignore the setting.\n\tCancellable bool `json:\"cancellable,omitempty\"`\n\t// Optional, more detailed associated progress message. Contains\n\t// complementary information to the `title`.\n\t//\n\t// Examples: \"3/25 files\", \"project/src/module2\", \"node_modules/some_dep\".\n\t// If unset, the previous progress message (if any) is still valid.\n\tMessage string `json:\"message,omitempty\"`\n\t// Optional progress percentage to display (value 100 is considered 100%).\n\t// If not provided infinite progress is assumed and clients are allowed\n\t// to ignore the `percentage` value in subsequent in report notifications.\n\t//\n\t// The value should be steadily rising. Clients are free to ignore values\n\t// that are not following this rule. The value range is [0, 100].\n\tPercentage uint32 `json:\"percentage,omitempty\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#workDoneProgressCancelParams\ntype WorkDoneProgressCancelParams struct {\n\t// The token to be used to report progress.\n\tToken ProgressToken `json:\"token\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#workDoneProgressCreateParams\ntype WorkDoneProgressCreateParams struct {\n\t// The token to be used to report progress.\n\tToken ProgressToken `json:\"token\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#workDoneProgressEnd\ntype WorkDoneProgressEnd struct {\n\tKind string `json:\"kind\"`\n\t// Optional, a final message indicating to for example indicate the outcome\n\t// of the operation.\n\tMessage string `json:\"message,omitempty\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#workDoneProgressOptions\ntype WorkDoneProgressOptions struct {\n\tWorkDoneProgress bool `json:\"workDoneProgress,omitempty\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#workDoneProgressParams\ntype WorkDoneProgressParams struct {\n\t// An optional token that a server can use to report work done progress.\n\tWorkDoneToken ProgressToken `json:\"workDoneToken,omitempty\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#workDoneProgressReport\ntype WorkDoneProgressReport struct {\n\tKind string `json:\"kind\"`\n\t// Controls enablement state of a cancel button.\n\t//\n\t// Clients that don't support cancellation or don't support controlling the button's\n\t// enablement state are allowed to ignore the property.\n\tCancellable bool `json:\"cancellable,omitempty\"`\n\t// Optional, more detailed associated progress message. Contains\n\t// complementary information to the `title`.\n\t//\n\t// Examples: \"3/25 files\", \"project/src/module2\", \"node_modules/some_dep\".\n\t// If unset, the previous progress message (if any) is still valid.\n\tMessage string `json:\"message,omitempty\"`\n\t// Optional progress percentage to display (value 100 is considered 100%).\n\t// If not provided infinite progress is assumed and clients are allowed\n\t// to ignore the `percentage` value in subsequent in report notifications.\n\t//\n\t// The value should be steadily rising. Clients are free to ignore values\n\t// that are not following this rule. The value range is [0, 100]\n\tPercentage uint32 `json:\"percentage,omitempty\"`\n}\n\n// Workspace specific client capabilities.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#workspaceClientCapabilities\ntype WorkspaceClientCapabilities struct {\n\t// The client supports applying batch edits\n\t// to the workspace by supporting the request\n\t// 'workspace/applyEdit'\n\tApplyEdit bool `json:\"applyEdit,omitempty\"`\n\t// Capabilities specific to `WorkspaceEdit`s.\n\tWorkspaceEdit *WorkspaceEditClientCapabilities `json:\"workspaceEdit,omitempty\"`\n\t// Capabilities specific to the `workspace/didChangeConfiguration` notification.\n\tDidChangeConfiguration DidChangeConfigurationClientCapabilities `json:\"didChangeConfiguration,omitempty\"`\n\t// Capabilities specific to the `workspace/didChangeWatchedFiles` notification.\n\tDidChangeWatchedFiles DidChangeWatchedFilesClientCapabilities `json:\"didChangeWatchedFiles,omitempty\"`\n\t// Capabilities specific to the `workspace/symbol` request.\n\tSymbol *WorkspaceSymbolClientCapabilities `json:\"symbol,omitempty\"`\n\t// Capabilities specific to the `workspace/executeCommand` request.\n\tExecuteCommand *ExecuteCommandClientCapabilities `json:\"executeCommand,omitempty\"`\n\t// The client has support for workspace folders.\n\t//\n\t// @since 3.6.0\n\tWorkspaceFolders bool `json:\"workspaceFolders,omitempty\"`\n\t// The client supports `workspace/configuration` requests.\n\t//\n\t// @since 3.6.0\n\tConfiguration bool `json:\"configuration,omitempty\"`\n\t// Capabilities specific to the semantic token requests scoped to the\n\t// workspace.\n\t//\n\t// @since 3.16.0.\n\tSemanticTokens *SemanticTokensWorkspaceClientCapabilities `json:\"semanticTokens,omitempty\"`\n\t// Capabilities specific to the code lens requests scoped to the\n\t// workspace.\n\t//\n\t// @since 3.16.0.\n\tCodeLens *CodeLensWorkspaceClientCapabilities `json:\"codeLens,omitempty\"`\n\t// The client has support for file notifications/requests for user operations on files.\n\t//\n\t// Since 3.16.0\n\tFileOperations *FileOperationClientCapabilities `json:\"fileOperations,omitempty\"`\n\t// Capabilities specific to the inline values requests scoped to the\n\t// workspace.\n\t//\n\t// @since 3.17.0.\n\tInlineValue *InlineValueWorkspaceClientCapabilities `json:\"inlineValue,omitempty\"`\n\t// Capabilities specific to the inlay hint requests scoped to the\n\t// workspace.\n\t//\n\t// @since 3.17.0.\n\tInlayHint *InlayHintWorkspaceClientCapabilities `json:\"inlayHint,omitempty\"`\n\t// Capabilities specific to the diagnostic requests scoped to the\n\t// workspace.\n\t//\n\t// @since 3.17.0.\n\tDiagnostics *DiagnosticWorkspaceClientCapabilities `json:\"diagnostics,omitempty\"`\n\t// Capabilities specific to the folding range requests scoped to the workspace.\n\t//\n\t// @since 3.18.0\n\t// @proposed\n\tFoldingRange *FoldingRangeWorkspaceClientCapabilities `json:\"foldingRange,omitempty\"`\n\t// Capabilities specific to the `workspace/textDocumentContent` request.\n\t//\n\t// @since 3.18.0\n\t// @proposed\n\tTextDocumentContent *TextDocumentContentClientCapabilities `json:\"textDocumentContent,omitempty\"`\n}\n\n// Parameters of the workspace diagnostic request.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#workspaceDiagnosticParams\ntype WorkspaceDiagnosticParams struct {\n\t// The additional identifier provided during registration.\n\tIdentifier string `json:\"identifier,omitempty\"`\n\t// The currently known diagnostic reports with their\n\t// previous result ids.\n\tPreviousResultIds []PreviousResultId `json:\"previousResultIds\"`\n\tWorkDoneProgressParams\n\tPartialResultParams\n}\n\n// A workspace diagnostic report.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#workspaceDiagnosticReport\ntype WorkspaceDiagnosticReport struct {\n\tItems []WorkspaceDocumentDiagnosticReport `json:\"items\"`\n}\n\n// A partial result for a workspace diagnostic report.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#workspaceDiagnosticReportPartialResult\ntype WorkspaceDiagnosticReportPartialResult struct {\n\tItems []WorkspaceDocumentDiagnosticReport `json:\"items\"`\n}\n\n// A workspace diagnostic document report.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#workspaceDocumentDiagnosticReport\ntype WorkspaceDocumentDiagnosticReport = Or_WorkspaceDocumentDiagnosticReport // (alias)\n// A workspace edit represents changes to many resources managed in the workspace. The edit\n// should either provide `changes` or `documentChanges`. If documentChanges are present\n// they are preferred over `changes` if the client can handle versioned document edits.\n//\n// Since version 3.13.0 a workspace edit can contain resource operations as well. If resource\n// operations are present clients need to execute the operations in the order in which they\n// are provided. So a workspace edit for example can consist of the following two changes:\n// (1) a create file a.txt and (2) a text document edit which insert text into file a.txt.\n//\n// An invalid sequence (e.g. (1) delete file a.txt and (2) insert text into file a.txt) will\n// cause failure of the operation. How the client recovers from the failure is described by\n// the client capability: `workspace.workspaceEdit.failureHandling`\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#workspaceEdit\ntype WorkspaceEdit struct {\n\t// Holds changes to existing resources.\n\tChanges map[DocumentUri][]TextEdit `json:\"changes,omitempty\"`\n\t// Depending on the client capability `workspace.workspaceEdit.resourceOperations` document changes\n\t// are either an array of `TextDocumentEdit`s to express changes to n different text documents\n\t// where each text document edit addresses a specific version of a text document. Or it can contain\n\t// above `TextDocumentEdit`s mixed with create, rename and delete file / folder operations.\n\t//\n\t// Whether a client supports versioned document edits is expressed via\n\t// `workspace.workspaceEdit.documentChanges` client capability.\n\t//\n\t// If a client neither supports `documentChanges` nor `workspace.workspaceEdit.resourceOperations` then\n\t// only plain `TextEdit`s using the `changes` property are supported.\n\tDocumentChanges []DocumentChange `json:\"documentChanges,omitempty\"`\n\t// A map of change annotations that can be referenced in `AnnotatedTextEdit`s or create, rename and\n\t// delete file / folder operations.\n\t//\n\t// Whether clients honor this property depends on the client capability `workspace.changeAnnotationSupport`.\n\t//\n\t// @since 3.16.0\n\tChangeAnnotations map[ChangeAnnotationIdentifier]ChangeAnnotation `json:\"changeAnnotations,omitempty\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#workspaceEditClientCapabilities\ntype WorkspaceEditClientCapabilities struct {\n\t// The client supports versioned document changes in `WorkspaceEdit`s\n\tDocumentChanges bool `json:\"documentChanges,omitempty\"`\n\t// The resource operations the client supports. Clients should at least\n\t// support 'create', 'rename' and 'delete' files and folders.\n\t//\n\t// @since 3.13.0\n\tResourceOperations []ResourceOperationKind `json:\"resourceOperations,omitempty\"`\n\t// The failure handling strategy of a client if applying the workspace edit\n\t// fails.\n\t//\n\t// @since 3.13.0\n\tFailureHandling *FailureHandlingKind `json:\"failureHandling,omitempty\"`\n\t// Whether the client normalizes line endings to the client specific\n\t// setting.\n\t// If set to `true` the client will normalize line ending characters\n\t// in a workspace edit to the client-specified new line\n\t// character.\n\t//\n\t// @since 3.16.0\n\tNormalizesLineEndings bool `json:\"normalizesLineEndings,omitempty\"`\n\t// Whether the client in general supports change annotations on text edits,\n\t// create file, rename file and delete file changes.\n\t//\n\t// @since 3.16.0\n\tChangeAnnotationSupport *ChangeAnnotationsSupportOptions `json:\"changeAnnotationSupport,omitempty\"`\n\t// Whether the client supports `WorkspaceEditMetadata` in `WorkspaceEdit`s.\n\t//\n\t// @since 3.18.0\n\t// @proposed\n\tMetadataSupport bool `json:\"metadataSupport,omitempty\"`\n\t// Whether the client supports snippets as text edits.\n\t//\n\t// @since 3.18.0\n\t// @proposed\n\tSnippetEditSupport bool `json:\"snippetEditSupport,omitempty\"`\n}\n\n// Additional data about a workspace edit.\n//\n// @since 3.18.0\n// @proposed\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#workspaceEditMetadata\ntype WorkspaceEditMetadata struct {\n\t// Signal to the editor that this edit is a refactoring.\n\tIsRefactoring bool `json:\"isRefactoring,omitempty\"`\n}\n\n// A workspace folder inside a client.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#workspaceFolder\ntype WorkspaceFolder struct {\n\t// The associated URI for this workspace folder.\n\tURI URI `json:\"uri\"`\n\t// The name of the workspace folder. Used to refer to this\n\t// workspace folder in the user interface.\n\tName string `json:\"name\"`\n}\n\n// The workspace folder change event.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#workspaceFoldersChangeEvent\ntype WorkspaceFoldersChangeEvent struct {\n\t// The array of added workspace folders\n\tAdded []WorkspaceFolder `json:\"added\"`\n\t// The array of the removed workspace folders\n\tRemoved []WorkspaceFolder `json:\"removed\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#workspaceFoldersInitializeParams\ntype WorkspaceFoldersInitializeParams struct {\n\t// The workspace folders configured in the client when the server starts.\n\t//\n\t// This property is only available if the client supports workspace folders.\n\t// It can be `null` if the client supports workspace folders but none are\n\t// configured.\n\t//\n\t// @since 3.6.0\n\tWorkspaceFolders []WorkspaceFolder `json:\"workspaceFolders,omitempty\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#workspaceFoldersServerCapabilities\ntype WorkspaceFoldersServerCapabilities struct {\n\t// The server has support for workspace folders\n\tSupported bool `json:\"supported,omitempty\"`\n\t// Whether the server wants to receive workspace folder\n\t// change notifications.\n\t//\n\t// If a string is provided the string is treated as an ID\n\t// under which the notification is registered on the client\n\t// side. The ID can be used to unregister for these events\n\t// using the `client/unregisterCapability` request.\n\tChangeNotifications *Or_WorkspaceFoldersServerCapabilities_changeNotifications `json:\"changeNotifications,omitempty\"`\n}\n\n// A full document diagnostic report for a workspace diagnostic result.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#workspaceFullDocumentDiagnosticReport\ntype WorkspaceFullDocumentDiagnosticReport struct {\n\t// The URI for which diagnostic information is reported.\n\tURI DocumentUri `json:\"uri\"`\n\t// The version number for which the diagnostics are reported.\n\t// If the document is not marked as open `null` can be provided.\n\tVersion int32 `json:\"version\"`\n\tFullDocumentDiagnosticReport\n}\n\n// Defines workspace specific capabilities of the server.\n//\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#workspaceOptions\ntype WorkspaceOptions struct {\n\t// The server supports workspace folder.\n\t//\n\t// @since 3.6.0\n\tWorkspaceFolders *WorkspaceFoldersServerCapabilities `json:\"workspaceFolders,omitempty\"`\n\t// The server is interested in notifications/requests for operations on files.\n\t//\n\t// @since 3.16.0\n\tFileOperations *FileOperationOptions `json:\"fileOperations,omitempty\"`\n\t// The server supports the `workspace/textDocumentContent` request.\n\t//\n\t// @since 3.18.0\n\t// @proposed\n\tTextDocumentContent *Or_WorkspaceOptions_textDocumentContent `json:\"textDocumentContent,omitempty\"`\n}\n\n// A special workspace symbol that supports locations without a range.\n//\n// See also SymbolInformation.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#workspaceSymbol\ntype WorkspaceSymbol struct {\n\t// The location of the symbol. Whether a server is allowed to\n\t// return a location without a range depends on the client\n\t// capability `workspace.symbol.resolveSupport`.\n\t//\n\t// See SymbolInformation#location for more details.\n\tLocation Or_WorkspaceSymbol_location `json:\"location\"`\n\t// A data entry field that is preserved on a workspace symbol between a\n\t// workspace symbol request and a workspace symbol resolve request.\n\tData interface{} `json:\"data,omitempty\"`\n\tBaseSymbolInformation\n}\n\n// Client capabilities for a {@link WorkspaceSymbolRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#workspaceSymbolClientCapabilities\ntype WorkspaceSymbolClientCapabilities struct {\n\t// Symbol request supports dynamic registration.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n\t// Specific capabilities for the `SymbolKind` in the `workspace/symbol` request.\n\tSymbolKind *ClientSymbolKindOptions `json:\"symbolKind,omitempty\"`\n\t// The client supports tags on `SymbolInformation`.\n\t// Clients supporting tags have to handle unknown tags gracefully.\n\t//\n\t// @since 3.16.0\n\tTagSupport *ClientSymbolTagOptions `json:\"tagSupport,omitempty\"`\n\t// The client support partial workspace symbols. The client will send the\n\t// request `workspaceSymbol/resolve` to the server to resolve additional\n\t// properties.\n\t//\n\t// @since 3.17.0\n\tResolveSupport *ClientSymbolResolveOptions `json:\"resolveSupport,omitempty\"`\n}\n\n// Server capabilities for a {@link WorkspaceSymbolRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#workspaceSymbolOptions\ntype WorkspaceSymbolOptions struct {\n\t// The server provides support to resolve additional\n\t// information for a workspace symbol.\n\t//\n\t// @since 3.17.0\n\tResolveProvider bool `json:\"resolveProvider,omitempty\"`\n\tWorkDoneProgressOptions\n}\n\n// The parameters of a {@link WorkspaceSymbolRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#workspaceSymbolParams\ntype WorkspaceSymbolParams struct {\n\t// A query string to filter symbols by. Clients may send an empty\n\t// string here to request all symbols.\n\t//\n\t// The `query`-parameter should be interpreted in a *relaxed way* as editors\n\t// will apply their own highlighting and scoring on the results. A good rule\n\t// of thumb is to match case-insensitive and to simply check that the\n\t// characters of *query* appear in their order in a candidate symbol.\n\t// Servers shouldn't use prefix, substring, or similar strict matching.\n\tQuery string `json:\"query\"`\n\tWorkDoneProgressParams\n\tPartialResultParams\n}\n\n// Registration options for a {@link WorkspaceSymbolRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#workspaceSymbolRegistrationOptions\ntype WorkspaceSymbolRegistrationOptions struct {\n\tWorkspaceSymbolOptions\n}\n\n// An unchanged document diagnostic report for a workspace diagnostic result.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#workspaceUnchangedDocumentDiagnosticReport\ntype WorkspaceUnchangedDocumentDiagnosticReport struct {\n\t// The URI for which diagnostic information is reported.\n\tURI DocumentUri `json:\"uri\"`\n\t// The version number for which the diagnostics are reported.\n\t// If the document is not marked as open `null` can be provided.\n\tVersion int32 `json:\"version\"`\n\tUnchangedDocumentDiagnosticReport\n}\n\n// The initialize parameters\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#_InitializeParams\ntype XInitializeParams struct {\n\t// The process Id of the parent process that started\n\t// the server.\n\t//\n\t// Is `null` if the process has not been started by another process.\n\t// If the parent process is not alive then the server should exit.\n\tProcessID int32 `json:\"processId\"`\n\t// Information about the client\n\t//\n\t// @since 3.15.0\n\tClientInfo *ClientInfo `json:\"clientInfo,omitempty\"`\n\t// The locale the client is currently showing the user interface\n\t// in. This must not necessarily be the locale of the operating\n\t// system.\n\t//\n\t// Uses IETF language tags as the value's syntax\n\t// (See https://en.wikipedia.org/wiki/IETF_language_tag)\n\t//\n\t// @since 3.16.0\n\tLocale string `json:\"locale,omitempty\"`\n\t// The rootPath of the workspace. Is null\n\t// if no folder is open.\n\t//\n\t// @deprecated in favour of rootUri.\n\tRootPath string `json:\"rootPath,omitempty\"`\n\t// The rootUri of the workspace. Is null if no\n\t// folder is open. If both `rootPath` and `rootUri` are set\n\t// `rootUri` wins.\n\t//\n\t// @deprecated in favour of workspaceFolders.\n\tRootURI DocumentUri `json:\"rootUri\"`\n\t// The capabilities provided by the client (editor or tool)\n\tCapabilities ClientCapabilities `json:\"capabilities\"`\n\t// User provided initialization options.\n\tInitializationOptions interface{} `json:\"initializationOptions,omitempty\"`\n\t// The initial trace setting. If omitted trace is disabled ('off').\n\tTrace *TraceValue `json:\"trace,omitempty\"`\n\tWorkDoneProgressParams\n}\n\n// The initialize parameters\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#_InitializeParams\ntype _InitializeParams struct {\n\t// The process Id of the parent process that started\n\t// the server.\n\t//\n\t// Is `null` if the process has not been started by another process.\n\t// If the parent process is not alive then the server should exit.\n\tProcessID int32 `json:\"processId\"`\n\t// Information about the client\n\t//\n\t// @since 3.15.0\n\tClientInfo *ClientInfo `json:\"clientInfo,omitempty\"`\n\t// The locale the client is currently showing the user interface\n\t// in. This must not necessarily be the locale of the operating\n\t// system.\n\t//\n\t// Uses IETF language tags as the value's syntax\n\t// (See https://en.wikipedia.org/wiki/IETF_language_tag)\n\t//\n\t// @since 3.16.0\n\tLocale string `json:\"locale,omitempty\"`\n\t// The rootPath of the workspace. Is null\n\t// if no folder is open.\n\t//\n\t// @deprecated in favour of rootUri.\n\tRootPath string `json:\"rootPath,omitempty\"`\n\t// The rootUri of the workspace. Is null if no\n\t// folder is open. If both `rootPath` and `rootUri` are set\n\t// `rootUri` wins.\n\t//\n\t// @deprecated in favour of workspaceFolders.\n\tRootURI DocumentUri `json:\"rootUri\"`\n\t// The capabilities provided by the client (editor or tool)\n\tCapabilities ClientCapabilities `json:\"capabilities\"`\n\t// User provided initialization options.\n\tInitializationOptions interface{} `json:\"initializationOptions,omitempty\"`\n\t// The initial trace setting. If omitted trace is disabled ('off').\n\tTrace *TraceValue `json:\"trace,omitempty\"`\n\tWorkDoneProgressParams\n}\n\nconst (\n\t// A set of predefined code action kinds\n\t// Empty kind.\n\tEmpty CodeActionKind = \"\"\n\t// Base kind for quickfix actions: 'quickfix'\n\tQuickFix CodeActionKind = \"quickfix\"\n\t// Base kind for refactoring actions: 'refactor'\n\tRefactor CodeActionKind = \"refactor\"\n\t// Base kind for refactoring extraction actions: 'refactor.extract'\n\t//\n\t// Example extract actions:\n\t//\n\t//\n\t// - Extract method\n\t// - Extract function\n\t// - Extract variable\n\t// - Extract interface from class\n\t// - ...\n\tRefactorExtract CodeActionKind = \"refactor.extract\"\n\t// Base kind for refactoring inline actions: 'refactor.inline'\n\t//\n\t// Example inline actions:\n\t//\n\t//\n\t// - Inline function\n\t// - Inline variable\n\t// - Inline constant\n\t// - ...\n\tRefactorInline CodeActionKind = \"refactor.inline\"\n\t// Base kind for refactoring move actions: `refactor.move`\n\t//\n\t// Example move actions:\n\t//\n\t//\n\t// - Move a function to a new file\n\t// - Move a property between classes\n\t// - Move method to base class\n\t// - ...\n\t//\n\t// @since 3.18.0\n\t// @proposed\n\tRefactorMove CodeActionKind = \"refactor.move\"\n\t// Base kind for refactoring rewrite actions: 'refactor.rewrite'\n\t//\n\t// Example rewrite actions:\n\t//\n\t//\n\t// - Convert JavaScript function to class\n\t// - Add or remove parameter\n\t// - Encapsulate field\n\t// - Make method static\n\t// - Move method to base class\n\t// - ...\n\tRefactorRewrite CodeActionKind = \"refactor.rewrite\"\n\t// Base kind for source actions: `source`\n\t//\n\t// Source code actions apply to the entire file.\n\tSource CodeActionKind = \"source\"\n\t// Base kind for an organize imports source action: `source.organizeImports`\n\tSourceOrganizeImports CodeActionKind = \"source.organizeImports\"\n\t// Base kind for auto-fix source actions: `source.fixAll`.\n\t//\n\t// Fix all actions automatically fix errors that have a clear fix that do not require user input.\n\t// They should not suppress errors or perform unsafe fixes such as generating new types or classes.\n\t//\n\t// @since 3.15.0\n\tSourceFixAll CodeActionKind = \"source.fixAll\"\n\t// Base kind for all code actions applying to the entire notebook's scope. CodeActionKinds using\n\t// this should always begin with `notebook.`\n\t//\n\t// @since 3.18.0\n\tNotebook CodeActionKind = \"notebook\"\n\t// The reason why code actions were requested.\n\t//\n\t// @since 3.17.0\n\t// Code actions were explicitly requested by the user or by an extension.\n\tCodeActionInvoked CodeActionTriggerKind = 1\n\t// Code actions were requested automatically.\n\t//\n\t// This typically happens when current selection in a file changes, but can\n\t// also be triggered when file content changes.\n\tCodeActionAutomatic CodeActionTriggerKind = 2\n\t// The kind of a completion entry.\n\tTextCompletion CompletionItemKind = 1\n\tMethodCompletion CompletionItemKind = 2\n\tFunctionCompletion CompletionItemKind = 3\n\tConstructorCompletion CompletionItemKind = 4\n\tFieldCompletion CompletionItemKind = 5\n\tVariableCompletion CompletionItemKind = 6\n\tClassCompletion CompletionItemKind = 7\n\tInterfaceCompletion CompletionItemKind = 8\n\tModuleCompletion CompletionItemKind = 9\n\tPropertyCompletion CompletionItemKind = 10\n\tUnitCompletion CompletionItemKind = 11\n\tValueCompletion CompletionItemKind = 12\n\tEnumCompletion CompletionItemKind = 13\n\tKeywordCompletion CompletionItemKind = 14\n\tSnippetCompletion CompletionItemKind = 15\n\tColorCompletion CompletionItemKind = 16\n\tFileCompletion CompletionItemKind = 17\n\tReferenceCompletion CompletionItemKind = 18\n\tFolderCompletion CompletionItemKind = 19\n\tEnumMemberCompletion CompletionItemKind = 20\n\tConstantCompletion CompletionItemKind = 21\n\tStructCompletion CompletionItemKind = 22\n\tEventCompletion CompletionItemKind = 23\n\tOperatorCompletion CompletionItemKind = 24\n\tTypeParameterCompletion CompletionItemKind = 25\n\t// Completion item tags are extra annotations that tweak the rendering of a completion\n\t// item.\n\t//\n\t// @since 3.15.0\n\t// Render a completion as obsolete, usually using a strike-out.\n\tComplDeprecated CompletionItemTag = 1\n\t// How a completion was triggered\n\t// Completion was triggered by typing an identifier (24x7 code\n\t// complete), manual invocation (e.g Ctrl+Space) or via API.\n\tInvoked CompletionTriggerKind = 1\n\t// Completion was triggered by a trigger character specified by\n\t// the `triggerCharacters` properties of the `CompletionRegistrationOptions`.\n\tTriggerCharacter CompletionTriggerKind = 2\n\t// Completion was re-triggered as current completion list is incomplete\n\tTriggerForIncompleteCompletions CompletionTriggerKind = 3\n\t// The diagnostic's severity.\n\t// Reports an error.\n\tSeverityError DiagnosticSeverity = 1\n\t// Reports a warning.\n\tSeverityWarning DiagnosticSeverity = 2\n\t// Reports an information.\n\tSeverityInformation DiagnosticSeverity = 3\n\t// Reports a hint.\n\tSeverityHint DiagnosticSeverity = 4\n\t// The diagnostic tags.\n\t//\n\t// @since 3.15.0\n\t// Unused or unnecessary code.\n\t//\n\t// Clients are allowed to render diagnostics with this tag faded out instead of having\n\t// an error squiggle.\n\tUnnecessary DiagnosticTag = 1\n\t// Deprecated or obsolete code.\n\t//\n\t// Clients are allowed to rendered diagnostics with this tag strike through.\n\tDeprecated DiagnosticTag = 2\n\t// The document diagnostic report kinds.\n\t//\n\t// @since 3.17.0\n\t// A diagnostic report with a full\n\t// set of problems.\n\tDiagnosticFull DocumentDiagnosticReportKind = \"full\"\n\t// A report indicating that the last\n\t// returned report is still accurate.\n\tDiagnosticUnchanged DocumentDiagnosticReportKind = \"unchanged\"\n\t// A document highlight kind.\n\t// A textual occurrence.\n\tText DocumentHighlightKind = 1\n\t// Read-access of a symbol, like reading a variable.\n\tRead DocumentHighlightKind = 2\n\t// Write-access of a symbol, like writing to a variable.\n\tWrite DocumentHighlightKind = 3\n\t// Predefined error codes.\n\tParseError ErrorCodes = -32700\n\tInvalidRequest ErrorCodes = -32600\n\tMethodNotFound ErrorCodes = -32601\n\tInvalidParams ErrorCodes = -32602\n\tInternalError ErrorCodes = -32603\n\t// Error code indicating that a server received a notification or\n\t// request before the server has received the `initialize` request.\n\tServerNotInitialized ErrorCodes = -32002\n\tUnknownErrorCode ErrorCodes = -32001\n\t// Applying the workspace change is simply aborted if one of the changes provided\n\t// fails. All operations executed before the failing operation stay executed.\n\tAbort FailureHandlingKind = \"abort\"\n\t// All operations are executed transactional. That means they either all\n\t// succeed or no changes at all are applied to the workspace.\n\tTransactional FailureHandlingKind = \"transactional\"\n\t// If the workspace edit contains only textual file changes they are executed transactional.\n\t// If resource changes (create, rename or delete file) are part of the change the failure\n\t// handling strategy is abort.\n\tTextOnlyTransactional FailureHandlingKind = \"textOnlyTransactional\"\n\t// The client tries to undo the operations already executed. But there is no\n\t// guarantee that this is succeeding.\n\tUndo FailureHandlingKind = \"undo\"\n\t// The file event type\n\t// The file got created.\n\tCreated FileChangeType = 1\n\t// The file got changed.\n\tChanged FileChangeType = 2\n\t// The file got deleted.\n\tDeleted FileChangeType = 3\n\t// A pattern kind describing if a glob pattern matches a file a folder or\n\t// both.\n\t//\n\t// @since 3.16.0\n\t// The pattern matches a file only.\n\tFilePattern FileOperationPatternKind = \"file\"\n\t// The pattern matches a folder only.\n\tFolderPattern FileOperationPatternKind = \"folder\"\n\t// A set of predefined range kinds.\n\t// Folding range for a comment\n\tComment FoldingRangeKind = \"comment\"\n\t// Folding range for an import or include\n\tImports FoldingRangeKind = \"imports\"\n\t// Folding range for a region (e.g. `#region`)\n\tRegion FoldingRangeKind = \"region\"\n\t// Inlay hint kinds.\n\t//\n\t// @since 3.17.0\n\t// An inlay hint that for a type annotation.\n\tType InlayHintKind = 1\n\t// An inlay hint that is for a parameter.\n\tParameter InlayHintKind = 2\n\t// Describes how an {@link InlineCompletionItemProvider inline completion provider} was triggered.\n\t//\n\t// @since 3.18.0\n\t// @proposed\n\t// Completion was triggered explicitly by a user gesture.\n\tInlineInvoked InlineCompletionTriggerKind = 1\n\t// Completion was triggered automatically while editing.\n\tInlineAutomatic InlineCompletionTriggerKind = 2\n\t// Defines whether the insert text in a completion item should be interpreted as\n\t// plain text or a snippet.\n\t// The primary text to be inserted is treated as a plain string.\n\tPlainTextTextFormat InsertTextFormat = 1\n\t// The primary text to be inserted is treated as a snippet.\n\t//\n\t// A snippet can define tab stops and placeholders with `$1`, `$2`\n\t// and `${3:foo}`. `$0` defines the final tab stop, it defaults to\n\t// the end of the snippet. Placeholders with equal identifiers are linked,\n\t// that is typing in one will update others too.\n\t//\n\t// See also: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#snippet_syntax\n\tSnippetTextFormat InsertTextFormat = 2\n\t// How whitespace and indentation is handled during completion\n\t// item insertion.\n\t//\n\t// @since 3.16.0\n\t// The insertion or replace strings is taken as it is. If the\n\t// value is multi line the lines below the cursor will be\n\t// inserted using the indentation defined in the string value.\n\t// The client will not apply any kind of adjustments to the\n\t// string.\n\tAsIs InsertTextMode = 1\n\t// The editor adjusts leading whitespace of new lines so that\n\t// they match the indentation up to the cursor of the line for\n\t// which the item is accepted.\n\t//\n\t// Consider a line like this: <2tabs><3tabs>foo. Accepting a\n\t// multi line completion item is indented using 2 tabs and all\n\t// following lines inserted will be indented using 2 tabs as well.\n\tAdjustIndentation InsertTextMode = 2\n\t// A request failed but it was syntactically correct, e.g the\n\t// method name was known and the parameters were valid. The error\n\t// message should contain human readable information about why\n\t// the request failed.\n\t//\n\t// @since 3.17.0\n\tRequestFailed LSPErrorCodes = -32803\n\t// The server cancelled the request. This error code should\n\t// only be used for requests that explicitly support being\n\t// server cancellable.\n\t//\n\t// @since 3.17.0\n\tServerCancelled LSPErrorCodes = -32802\n\t// The server detected that the content of a document got\n\t// modified outside normal conditions. A server should\n\t// NOT send this error code if it detects a content change\n\t// in it unprocessed messages. The result even computed\n\t// on an older state might still be useful for the client.\n\t//\n\t// If a client decides that a result is not of any use anymore\n\t// the client should cancel the request.\n\tContentModified LSPErrorCodes = -32801\n\t// The client has canceled a request and a server has detected\n\t// the cancel.\n\tRequestCancelled LSPErrorCodes = -32800\n\t// Predefined Language kinds\n\t// @since 3.18.0\n\t// @proposed\n\tLangABAP LanguageKind = \"abap\"\n\tLangWindowsBat LanguageKind = \"bat\"\n\tLangBibTeX LanguageKind = \"bibtex\"\n\tLangClojure LanguageKind = \"clojure\"\n\tLangCoffeescript LanguageKind = \"coffeescript\"\n\tLangC LanguageKind = \"c\"\n\tLangCPP LanguageKind = \"cpp\"\n\tLangCSharp LanguageKind = \"csharp\"\n\tLangCSS LanguageKind = \"css\"\n\t// @since 3.18.0\n\t// @proposed\n\tLangD LanguageKind = \"d\"\n\t// @since 3.18.0\n\t// @proposed\n\tLangDelphi LanguageKind = \"pascal\"\n\tLangDiff LanguageKind = \"diff\"\n\tLangDart LanguageKind = \"dart\"\n\tLangDockerfile LanguageKind = \"dockerfile\"\n\tLangElixir LanguageKind = \"elixir\"\n\tLangErlang LanguageKind = \"erlang\"\n\tLangFSharp LanguageKind = \"fsharp\"\n\tLangGitCommit LanguageKind = \"git-commit\"\n\tLangGitRebase LanguageKind = \"rebase\"\n\tLangGo LanguageKind = \"go\"\n\tLangGroovy LanguageKind = \"groovy\"\n\tLangHandlebars LanguageKind = \"handlebars\"\n\tLangHaskell LanguageKind = \"haskell\"\n\tLangHTML LanguageKind = \"html\"\n\tLangIni LanguageKind = \"ini\"\n\tLangJava LanguageKind = \"java\"\n\tLangJavaScript LanguageKind = \"javascript\"\n\tLangJavaScriptReact LanguageKind = \"javascriptreact\"\n\tLangJSON LanguageKind = \"json\"\n\tLangLaTeX LanguageKind = \"latex\"\n\tLangLess LanguageKind = \"less\"\n\tLangLua LanguageKind = \"lua\"\n\tLangMakefile LanguageKind = \"makefile\"\n\tLangMarkdown LanguageKind = \"markdown\"\n\tLangObjectiveC LanguageKind = \"objective-c\"\n\tLangObjectiveCPP LanguageKind = \"objective-cpp\"\n\t// @since 3.18.0\n\t// @proposed\n\tLangPascal LanguageKind = \"pascal\"\n\tLangPerl LanguageKind = \"perl\"\n\tLangPerl6 LanguageKind = \"perl6\"\n\tLangPHP LanguageKind = \"php\"\n\tLangPowershell LanguageKind = \"powershell\"\n\tLangPug LanguageKind = \"jade\"\n\tLangPython LanguageKind = \"python\"\n\tLangR LanguageKind = \"r\"\n\tLangRazor LanguageKind = \"razor\"\n\tLangRuby LanguageKind = \"ruby\"\n\tLangRust LanguageKind = \"rust\"\n\tLangSCSS LanguageKind = \"scss\"\n\tLangSASS LanguageKind = \"sass\"\n\tLangScala LanguageKind = \"scala\"\n\tLangShaderLab LanguageKind = \"shaderlab\"\n\tLangShellScript LanguageKind = \"shellscript\"\n\tLangSQL LanguageKind = \"sql\"\n\tLangSwift LanguageKind = \"swift\"\n\tLangTypeScript LanguageKind = \"typescript\"\n\tLangTypeScriptReact LanguageKind = \"typescriptreact\"\n\tLangTeX LanguageKind = \"tex\"\n\tLangVisualBasic LanguageKind = \"vb\"\n\tLangXML LanguageKind = \"xml\"\n\tLangXSL LanguageKind = \"xsl\"\n\tLangYAML LanguageKind = \"yaml\"\n\t// Describes the content type that a client supports in various\n\t// result literals like `Hover`, `ParameterInfo` or `CompletionItem`.\n\t//\n\t// Please note that `MarkupKinds` must not start with a `$`. This kinds\n\t// are reserved for internal usage.\n\t// Plain text is supported as a content format\n\tPlainText MarkupKind = \"plaintext\"\n\t// Markdown is supported as a content format\n\tMarkdown MarkupKind = \"markdown\"\n\t// The message type\n\t// An error message.\n\tError MessageType = 1\n\t// A warning message.\n\tWarning MessageType = 2\n\t// An information message.\n\tInfo MessageType = 3\n\t// A log message.\n\tLog MessageType = 4\n\t// A debug message.\n\t//\n\t// @since 3.18.0\n\t// @proposed\n\tDebug MessageType = 5\n\t// The moniker kind.\n\t//\n\t// @since 3.16.0\n\t// The moniker represent a symbol that is imported into a project\n\tImport MonikerKind = \"import\"\n\t// The moniker represents a symbol that is exported from a project\n\tExport MonikerKind = \"export\"\n\t// The moniker represents a symbol that is local to a project (e.g. a local\n\t// variable of a function, a class not visible outside the project, ...)\n\tLocal MonikerKind = \"local\"\n\t// A notebook cell kind.\n\t//\n\t// @since 3.17.0\n\t// A markup-cell is formatted source that is used for display.\n\tMarkup NotebookCellKind = 1\n\t// A code-cell is source code.\n\tCode NotebookCellKind = 2\n\t// A set of predefined position encoding kinds.\n\t//\n\t// @since 3.17.0\n\t// Character offsets count UTF-8 code units (e.g. bytes).\n\tUTF8 PositionEncodingKind = \"utf-8\"\n\t// Character offsets count UTF-16 code units.\n\t//\n\t// This is the default and must always be supported\n\t// by servers\n\tUTF16 PositionEncodingKind = \"utf-16\"\n\t// Character offsets count UTF-32 code units.\n\t//\n\t// Implementation note: these are the same as Unicode codepoints,\n\t// so this `PositionEncodingKind` may also be used for an\n\t// encoding-agnostic representation of character offsets.\n\tUTF32 PositionEncodingKind = \"utf-32\"\n\t// The client's default behavior is to select the identifier\n\t// according the to language's syntax rule.\n\tIdentifier PrepareSupportDefaultBehavior = 1\n\t// Supports creating new files and folders.\n\tCreate ResourceOperationKind = \"create\"\n\t// Supports renaming existing files and folders.\n\tRename ResourceOperationKind = \"rename\"\n\t// Supports deleting existing files and folders.\n\tDelete ResourceOperationKind = \"delete\"\n\t// A set of predefined token modifiers. This set is not fixed\n\t// an clients can specify additional token types via the\n\t// corresponding client capabilities.\n\t//\n\t// @since 3.16.0\n\tModDeclaration SemanticTokenModifiers = \"declaration\"\n\tModDefinition SemanticTokenModifiers = \"definition\"\n\tModReadonly SemanticTokenModifiers = \"readonly\"\n\tModStatic SemanticTokenModifiers = \"static\"\n\tModDeprecated SemanticTokenModifiers = \"deprecated\"\n\tModAbstract SemanticTokenModifiers = \"abstract\"\n\tModAsync SemanticTokenModifiers = \"async\"\n\tModModification SemanticTokenModifiers = \"modification\"\n\tModDocumentation SemanticTokenModifiers = \"documentation\"\n\tModDefaultLibrary SemanticTokenModifiers = \"defaultLibrary\"\n\t// A set of predefined token types. This set is not fixed\n\t// an clients can specify additional token types via the\n\t// corresponding client capabilities.\n\t//\n\t// @since 3.16.0\n\tNamespaceType SemanticTokenTypes = \"namespace\"\n\t// Represents a generic type. Acts as a fallback for types which can't be mapped to\n\t// a specific type like class or enum.\n\tTypeType SemanticTokenTypes = \"type\"\n\tClassType SemanticTokenTypes = \"class\"\n\tEnumType SemanticTokenTypes = \"enum\"\n\tInterfaceType SemanticTokenTypes = \"interface\"\n\tStructType SemanticTokenTypes = \"struct\"\n\tTypeParameterType SemanticTokenTypes = \"typeParameter\"\n\tParameterType SemanticTokenTypes = \"parameter\"\n\tVariableType SemanticTokenTypes = \"variable\"\n\tPropertyType SemanticTokenTypes = \"property\"\n\tEnumMemberType SemanticTokenTypes = \"enumMember\"\n\tEventType SemanticTokenTypes = \"event\"\n\tFunctionType SemanticTokenTypes = \"function\"\n\tMethodType SemanticTokenTypes = \"method\"\n\tMacroType SemanticTokenTypes = \"macro\"\n\tKeywordType SemanticTokenTypes = \"keyword\"\n\tModifierType SemanticTokenTypes = \"modifier\"\n\tCommentType SemanticTokenTypes = \"comment\"\n\tStringType SemanticTokenTypes = \"string\"\n\tNumberType SemanticTokenTypes = \"number\"\n\tRegexpType SemanticTokenTypes = \"regexp\"\n\tOperatorType SemanticTokenTypes = \"operator\"\n\t// @since 3.17.0\n\tDecoratorType SemanticTokenTypes = \"decorator\"\n\t// @since 3.18.0\n\tLabelType SemanticTokenTypes = \"label\"\n\t// How a signature help was triggered.\n\t//\n\t// @since 3.15.0\n\t// Signature help was invoked manually by the user or by a command.\n\tSigInvoked SignatureHelpTriggerKind = 1\n\t// Signature help was triggered by a trigger character.\n\tSigTriggerCharacter SignatureHelpTriggerKind = 2\n\t// Signature help was triggered by the cursor moving or by the document content changing.\n\tSigContentChange SignatureHelpTriggerKind = 3\n\t// A symbol kind.\n\tFile SymbolKind = 1\n\tModule SymbolKind = 2\n\tNamespace SymbolKind = 3\n\tPackage SymbolKind = 4\n\tClass SymbolKind = 5\n\tMethod SymbolKind = 6\n\tProperty SymbolKind = 7\n\tField SymbolKind = 8\n\tConstructor SymbolKind = 9\n\tEnum SymbolKind = 10\n\tInterface SymbolKind = 11\n\tFunction SymbolKind = 12\n\tVariable SymbolKind = 13\n\tConstant SymbolKind = 14\n\tString SymbolKind = 15\n\tNumber SymbolKind = 16\n\tBoolean SymbolKind = 17\n\tArray SymbolKind = 18\n\tObject SymbolKind = 19\n\tKey SymbolKind = 20\n\tNull SymbolKind = 21\n\tEnumMember SymbolKind = 22\n\tStruct SymbolKind = 23\n\tEvent SymbolKind = 24\n\tOperator SymbolKind = 25\n\tTypeParameter SymbolKind = 26\n\t// Symbol tags are extra annotations that tweak the rendering of a symbol.\n\t//\n\t// @since 3.16\n\t// Render a symbol as obsolete, usually using a strike-out.\n\tDeprecatedSymbol SymbolTag = 1\n\t// Represents reasons why a text document is saved.\n\t// Manually triggered, e.g. by the user pressing save, by starting debugging,\n\t// or by an API call.\n\tManual TextDocumentSaveReason = 1\n\t// Automatic after a delay.\n\tAfterDelay TextDocumentSaveReason = 2\n\t// When the editor lost focus.\n\tFocusOut TextDocumentSaveReason = 3\n\t// Defines how the host (editor) should sync\n\t// document changes to the language server.\n\t// Documents should not be synced at all.\n\tNone TextDocumentSyncKind = 0\n\t// Documents are synced by always sending the full content\n\t// of the document.\n\tFull TextDocumentSyncKind = 1\n\t// Documents are synced by sending the full content on open.\n\t// After that only incremental updates to the document are\n\t// send.\n\tIncremental TextDocumentSyncKind = 2\n\tRelative TokenFormat = \"relative\"\n\t// Turn tracing off.\n\tOff TraceValue = \"off\"\n\t// Trace messages only.\n\tMessages TraceValue = \"messages\"\n\t// Verbose message tracing.\n\tVerbose TraceValue = \"verbose\"\n\t// Moniker uniqueness level to define scope of the moniker.\n\t//\n\t// @since 3.16.0\n\t// The moniker is only unique inside a document\n\tDocument UniquenessLevel = \"document\"\n\t// The moniker is unique inside a project for which a dump got created\n\tProject UniquenessLevel = \"project\"\n\t// The moniker is unique inside the group to which a project belongs\n\tGroup UniquenessLevel = \"group\"\n\t// The moniker is unique inside the moniker scheme.\n\tScheme UniquenessLevel = \"scheme\"\n\t// The moniker is globally unique\n\tGlobal UniquenessLevel = \"global\"\n\t// Interested in create events.\n\tWatchCreate WatchKind = 1\n\t// Interested in change events\n\tWatchChange WatchKind = 2\n\t// Interested in delete events\n\tWatchDelete WatchKind = 4\n)\n"], ["/opencode/internal/llm/provider/azure.go", "package provider\n\nimport (\n\t\"os\"\n\n\t\"github.com/Azure/azure-sdk-for-go/sdk/azidentity\"\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/azure\"\n\t\"github.com/openai/openai-go/option\"\n)\n\ntype azureClient struct {\n\t*openaiClient\n}\n\ntype AzureClient ProviderClient\n\nfunc newAzureClient(opts providerClientOptions) AzureClient {\n\n\tendpoint := os.Getenv(\"AZURE_OPENAI_ENDPOINT\") // ex: https://foo.openai.azure.com\n\tapiVersion := os.Getenv(\"AZURE_OPENAI_API_VERSION\") // ex: 2025-04-01-preview\n\n\tif endpoint == \"\" || apiVersion == \"\" {\n\t\treturn &azureClient{openaiClient: newOpenAIClient(opts).(*openaiClient)}\n\t}\n\n\treqOpts := []option.RequestOption{\n\t\tazure.WithEndpoint(endpoint, apiVersion),\n\t}\n\n\tif opts.apiKey != \"\" || os.Getenv(\"AZURE_OPENAI_API_KEY\") != \"\" {\n\t\tkey := opts.apiKey\n\t\tif key == \"\" {\n\t\t\tkey = os.Getenv(\"AZURE_OPENAI_API_KEY\")\n\t\t}\n\t\treqOpts = append(reqOpts, azure.WithAPIKey(key))\n\t} else if cred, err := azidentity.NewDefaultAzureCredential(nil); err == nil {\n\t\treqOpts = append(reqOpts, azure.WithTokenCredential(cred))\n\t}\n\n\tbase := &openaiClient{\n\t\tproviderOptions: opts,\n\t\tclient: openai.NewClient(reqOpts...),\n\t}\n\n\treturn &azureClient{openaiClient: base}\n}\n"], ["/opencode/internal/tui/theme/catppuccin.go", "package theme\n\nimport (\n\tcatppuccin \"github.com/catppuccin/go\"\n\t\"github.com/charmbracelet/lipgloss\"\n)\n\n// CatppuccinTheme implements the Theme interface with Catppuccin colors.\n// It provides both dark (Mocha) and light (Latte) variants.\ntype CatppuccinTheme struct {\n\tBaseTheme\n}\n\n// NewCatppuccinTheme creates a new instance of the Catppuccin theme.\nfunc NewCatppuccinTheme() *CatppuccinTheme {\n\t// Get the Catppuccin palettes\n\tmocha := catppuccin.Mocha\n\tlatte := catppuccin.Latte\n\n\ttheme := &CatppuccinTheme{}\n\n\t// Base colors\n\ttheme.PrimaryColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Blue().Hex,\n\t\tLight: latte.Blue().Hex,\n\t}\n\ttheme.SecondaryColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Mauve().Hex,\n\t\tLight: latte.Mauve().Hex,\n\t}\n\ttheme.AccentColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Peach().Hex,\n\t\tLight: latte.Peach().Hex,\n\t}\n\n\t// Status colors\n\ttheme.ErrorColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Red().Hex,\n\t\tLight: latte.Red().Hex,\n\t}\n\ttheme.WarningColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Peach().Hex,\n\t\tLight: latte.Peach().Hex,\n\t}\n\ttheme.SuccessColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Green().Hex,\n\t\tLight: latte.Green().Hex,\n\t}\n\ttheme.InfoColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Blue().Hex,\n\t\tLight: latte.Blue().Hex,\n\t}\n\n\t// Text colors\n\ttheme.TextColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Text().Hex,\n\t\tLight: latte.Text().Hex,\n\t}\n\ttheme.TextMutedColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Subtext0().Hex,\n\t\tLight: latte.Subtext0().Hex,\n\t}\n\ttheme.TextEmphasizedColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Lavender().Hex,\n\t\tLight: latte.Lavender().Hex,\n\t}\n\n\t// Background colors\n\ttheme.BackgroundColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#212121\", // From existing styles\n\t\tLight: \"#EEEEEE\", // Light equivalent\n\t}\n\ttheme.BackgroundSecondaryColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#2c2c2c\", // From existing styles\n\t\tLight: \"#E0E0E0\", // Light equivalent\n\t}\n\ttheme.BackgroundDarkerColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#181818\", // From existing styles\n\t\tLight: \"#F5F5F5\", // Light equivalent\n\t}\n\n\t// Border colors\n\ttheme.BorderNormalColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#4b4c5c\", // From existing styles\n\t\tLight: \"#BDBDBD\", // Light equivalent\n\t}\n\ttheme.BorderFocusedColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Blue().Hex,\n\t\tLight: latte.Blue().Hex,\n\t}\n\ttheme.BorderDimColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Surface0().Hex,\n\t\tLight: latte.Surface0().Hex,\n\t}\n\n\t// Diff view colors\n\ttheme.DiffAddedColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#478247\", // From existing diff.go\n\t\tLight: \"#2E7D32\", // Light equivalent\n\t}\n\ttheme.DiffRemovedColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#7C4444\", // From existing diff.go\n\t\tLight: \"#C62828\", // Light equivalent\n\t}\n\ttheme.DiffContextColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#a0a0a0\", // From existing diff.go\n\t\tLight: \"#757575\", // Light equivalent\n\t}\n\ttheme.DiffHunkHeaderColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#a0a0a0\", // From existing diff.go\n\t\tLight: \"#757575\", // Light equivalent\n\t}\n\ttheme.DiffHighlightAddedColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#DAFADA\", // From existing diff.go\n\t\tLight: \"#A5D6A7\", // Light equivalent\n\t}\n\ttheme.DiffHighlightRemovedColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#FADADD\", // From existing diff.go\n\t\tLight: \"#EF9A9A\", // Light equivalent\n\t}\n\ttheme.DiffAddedBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#303A30\", // From existing diff.go\n\t\tLight: \"#E8F5E9\", // Light equivalent\n\t}\n\ttheme.DiffRemovedBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#3A3030\", // From existing diff.go\n\t\tLight: \"#FFEBEE\", // Light equivalent\n\t}\n\ttheme.DiffContextBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#212121\", // From existing diff.go\n\t\tLight: \"#F5F5F5\", // Light equivalent\n\t}\n\ttheme.DiffLineNumberColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#888888\", // From existing diff.go\n\t\tLight: \"#9E9E9E\", // Light equivalent\n\t}\n\ttheme.DiffAddedLineNumberBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#293229\", // From existing diff.go\n\t\tLight: \"#C8E6C9\", // Light equivalent\n\t}\n\ttheme.DiffRemovedLineNumberBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#332929\", // From existing diff.go\n\t\tLight: \"#FFCDD2\", // Light equivalent\n\t}\n\n\t// Markdown colors\n\ttheme.MarkdownTextColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Text().Hex,\n\t\tLight: latte.Text().Hex,\n\t}\n\ttheme.MarkdownHeadingColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Mauve().Hex,\n\t\tLight: latte.Mauve().Hex,\n\t}\n\ttheme.MarkdownLinkColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Sky().Hex,\n\t\tLight: latte.Sky().Hex,\n\t}\n\ttheme.MarkdownLinkTextColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Pink().Hex,\n\t\tLight: latte.Pink().Hex,\n\t}\n\ttheme.MarkdownCodeColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Green().Hex,\n\t\tLight: latte.Green().Hex,\n\t}\n\ttheme.MarkdownBlockQuoteColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Yellow().Hex,\n\t\tLight: latte.Yellow().Hex,\n\t}\n\ttheme.MarkdownEmphColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Yellow().Hex,\n\t\tLight: latte.Yellow().Hex,\n\t}\n\ttheme.MarkdownStrongColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Peach().Hex,\n\t\tLight: latte.Peach().Hex,\n\t}\n\ttheme.MarkdownHorizontalRuleColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Overlay0().Hex,\n\t\tLight: latte.Overlay0().Hex,\n\t}\n\ttheme.MarkdownListItemColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Blue().Hex,\n\t\tLight: latte.Blue().Hex,\n\t}\n\ttheme.MarkdownListEnumerationColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Sky().Hex,\n\t\tLight: latte.Sky().Hex,\n\t}\n\ttheme.MarkdownImageColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Sapphire().Hex,\n\t\tLight: latte.Sapphire().Hex,\n\t}\n\ttheme.MarkdownImageTextColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Pink().Hex,\n\t\tLight: latte.Pink().Hex,\n\t}\n\ttheme.MarkdownCodeBlockColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Text().Hex,\n\t\tLight: latte.Text().Hex,\n\t}\n\n\t// Syntax highlighting colors\n\ttheme.SyntaxCommentColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Overlay1().Hex,\n\t\tLight: latte.Overlay1().Hex,\n\t}\n\ttheme.SyntaxKeywordColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Pink().Hex,\n\t\tLight: latte.Pink().Hex,\n\t}\n\ttheme.SyntaxFunctionColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Green().Hex,\n\t\tLight: latte.Green().Hex,\n\t}\n\ttheme.SyntaxVariableColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Sky().Hex,\n\t\tLight: latte.Sky().Hex,\n\t}\n\ttheme.SyntaxStringColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Yellow().Hex,\n\t\tLight: latte.Yellow().Hex,\n\t}\n\ttheme.SyntaxNumberColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Teal().Hex,\n\t\tLight: latte.Teal().Hex,\n\t}\n\ttheme.SyntaxTypeColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Sky().Hex,\n\t\tLight: latte.Sky().Hex,\n\t}\n\ttheme.SyntaxOperatorColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Pink().Hex,\n\t\tLight: latte.Pink().Hex,\n\t}\n\ttheme.SyntaxPunctuationColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Text().Hex,\n\t\tLight: latte.Text().Hex,\n\t}\n\n\treturn theme\n}\n\nfunc init() {\n\t// Register the Catppuccin theme with the theme manager\n\tRegisterTheme(\"catppuccin\", NewCatppuccinTheme())\n}"], ["/opencode/internal/lsp/protocol/pattern_interfaces.go", "package protocol\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n)\n\n// PatternInfo is an interface for types that represent glob patterns\ntype PatternInfo interface {\n\tGetPattern() string\n\tGetBasePath() string\n\tisPattern() // marker method\n}\n\n// StringPattern implements PatternInfo for string patterns\ntype StringPattern struct {\n\tPattern string\n}\n\nfunc (p StringPattern) GetPattern() string { return p.Pattern }\nfunc (p StringPattern) GetBasePath() string { return \"\" }\nfunc (p StringPattern) isPattern() {}\n\n// RelativePatternInfo implements PatternInfo for RelativePattern\ntype RelativePatternInfo struct {\n\tRP RelativePattern\n\tBasePath string\n}\n\nfunc (p RelativePatternInfo) GetPattern() string { return string(p.RP.Pattern) }\nfunc (p RelativePatternInfo) GetBasePath() string { return p.BasePath }\nfunc (p RelativePatternInfo) isPattern() {}\n\n// AsPattern converts GlobPattern to a PatternInfo object\nfunc (g *GlobPattern) AsPattern() (PatternInfo, error) {\n\tif g.Value == nil {\n\t\treturn nil, fmt.Errorf(\"nil pattern\")\n\t}\n\n\tswitch v := g.Value.(type) {\n\tcase string:\n\t\treturn StringPattern{Pattern: v}, nil\n\tcase RelativePattern:\n\t\t// Handle BaseURI which could be string or DocumentUri\n\t\tbasePath := \"\"\n\t\tswitch baseURI := v.BaseURI.Value.(type) {\n\t\tcase string:\n\t\t\tbasePath = strings.TrimPrefix(baseURI, \"file://\")\n\t\tcase DocumentUri:\n\t\t\tbasePath = strings.TrimPrefix(string(baseURI), \"file://\")\n\t\tdefault:\n\t\t\treturn nil, fmt.Errorf(\"unknown BaseURI type: %T\", v.BaseURI.Value)\n\t\t}\n\t\treturn RelativePatternInfo{RP: v, BasePath: basePath}, nil\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"unknown pattern type: %T\", g.Value)\n\t}\n}\n"], ["/opencode/internal/llm/models/models.go", "package models\n\nimport \"maps\"\n\ntype (\n\tModelID string\n\tModelProvider string\n)\n\ntype Model struct {\n\tID ModelID `json:\"id\"`\n\tName string `json:\"name\"`\n\tProvider ModelProvider `json:\"provider\"`\n\tAPIModel string `json:\"api_model\"`\n\tCostPer1MIn float64 `json:\"cost_per_1m_in\"`\n\tCostPer1MOut float64 `json:\"cost_per_1m_out\"`\n\tCostPer1MInCached float64 `json:\"cost_per_1m_in_cached\"`\n\tCostPer1MOutCached float64 `json:\"cost_per_1m_out_cached\"`\n\tContextWindow int64 `json:\"context_window\"`\n\tDefaultMaxTokens int64 `json:\"default_max_tokens\"`\n\tCanReason bool `json:\"can_reason\"`\n\tSupportsAttachments bool `json:\"supports_attachments\"`\n}\n\n// Model IDs\nconst ( // GEMINI\n\t// Bedrock\n\tBedrockClaude37Sonnet ModelID = \"bedrock.claude-3.7-sonnet\"\n)\n\nconst (\n\tProviderBedrock ModelProvider = \"bedrock\"\n\t// ForTests\n\tProviderMock ModelProvider = \"__mock\"\n)\n\n// Providers in order of popularity\nvar ProviderPopularity = map[ModelProvider]int{\n\tProviderCopilot: 1,\n\tProviderAnthropic: 2,\n\tProviderOpenAI: 3,\n\tProviderGemini: 4,\n\tProviderGROQ: 5,\n\tProviderOpenRouter: 6,\n\tProviderBedrock: 7,\n\tProviderAzure: 8,\n\tProviderVertexAI: 9,\n}\n\nvar SupportedModels = map[ModelID]Model{\n\t//\n\t// // GEMINI\n\t// GEMINI25: {\n\t// \tID: GEMINI25,\n\t// \tName: \"Gemini 2.5 Pro\",\n\t// \tProvider: ProviderGemini,\n\t// \tAPIModel: \"gemini-2.5-pro-exp-03-25\",\n\t// \tCostPer1MIn: 0,\n\t// \tCostPer1MInCached: 0,\n\t// \tCostPer1MOutCached: 0,\n\t// \tCostPer1MOut: 0,\n\t// },\n\t//\n\t// GRMINI20Flash: {\n\t// \tID: GRMINI20Flash,\n\t// \tName: \"Gemini 2.0 Flash\",\n\t// \tProvider: ProviderGemini,\n\t// \tAPIModel: \"gemini-2.0-flash\",\n\t// \tCostPer1MIn: 0.1,\n\t// \tCostPer1MInCached: 0,\n\t// \tCostPer1MOutCached: 0.025,\n\t// \tCostPer1MOut: 0.4,\n\t// },\n\t//\n\t// // Bedrock\n\tBedrockClaude37Sonnet: {\n\t\tID: BedrockClaude37Sonnet,\n\t\tName: \"Bedrock: Claude 3.7 Sonnet\",\n\t\tProvider: ProviderBedrock,\n\t\tAPIModel: \"anthropic.claude-3-7-sonnet-20250219-v1:0\",\n\t\tCostPer1MIn: 3.0,\n\t\tCostPer1MInCached: 3.75,\n\t\tCostPer1MOutCached: 0.30,\n\t\tCostPer1MOut: 15.0,\n\t},\n}\n\nfunc init() {\n\tmaps.Copy(SupportedModels, AnthropicModels)\n\tmaps.Copy(SupportedModels, OpenAIModels)\n\tmaps.Copy(SupportedModels, GeminiModels)\n\tmaps.Copy(SupportedModels, GroqModels)\n\tmaps.Copy(SupportedModels, AzureModels)\n\tmaps.Copy(SupportedModels, OpenRouterModels)\n\tmaps.Copy(SupportedModels, XAIModels)\n\tmaps.Copy(SupportedModels, VertexAIGeminiModels)\n\tmaps.Copy(SupportedModels, CopilotModels)\n}\n"], ["/opencode/internal/lsp/protocol/tsjson.go", "// Copyright 2023 The Go Authors. All rights reserved.\n// Use of this source code is governed by a BSD-style\n// license that can be found in the LICENSE file.\n\n// Code generated for LSP. DO NOT EDIT.\n\npackage protocol\n\n// Code generated from protocol/metaModel.json at ref release/protocol/3.17.6-next.9 (hash c94395b5da53729e6dff931293b051009ccaaaa4).\n// https://github.com/microsoft/vscode-languageserver-node/blob/release/protocol/3.17.6-next.9/protocol/metaModel.json\n// LSP metaData.version = 3.17.0.\n\nimport \"bytes\"\nimport \"encoding/json\"\n\nimport \"fmt\"\n\n// UnmarshalError indicates that a JSON value did not conform to\n// one of the expected cases of an LSP union type.\ntype UnmarshalError struct {\n\tmsg string\n}\n\nfunc (e UnmarshalError) Error() string {\n\treturn e.msg\n}\nfunc (t Or_CancelParams_id) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase int32:\n\t\treturn json.Marshal(x)\n\tcase string:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [int32 string]\", t)\n}\n\nfunc (t *Or_CancelParams_id) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder41 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder41.DisallowUnknownFields()\n\tvar int32Val int32\n\tif err := decoder41.Decode(&int32Val); err == nil {\n\t\tt.Value = int32Val\n\t\treturn nil\n\t}\n\tdecoder42 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder42.DisallowUnknownFields()\n\tvar stringVal string\n\tif err := decoder42.Decode(&stringVal); err == nil {\n\t\tt.Value = stringVal\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [int32 string]\"}\n}\n\nfunc (t Or_ClientSemanticTokensRequestOptions_full) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase ClientSemanticTokensRequestFullDelta:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [ClientSemanticTokensRequestFullDelta bool]\", t)\n}\n\nfunc (t *Or_ClientSemanticTokensRequestOptions_full) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder220 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder220.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder220.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder221 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder221.DisallowUnknownFields()\n\tvar h221 ClientSemanticTokensRequestFullDelta\n\tif err := decoder221.Decode(&h221); err == nil {\n\t\tt.Value = h221\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [ClientSemanticTokensRequestFullDelta bool]\"}\n}\n\nfunc (t Or_ClientSemanticTokensRequestOptions_range) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase Lit_ClientSemanticTokensRequestOptions_range_Item1:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [Lit_ClientSemanticTokensRequestOptions_range_Item1 bool]\", t)\n}\n\nfunc (t *Or_ClientSemanticTokensRequestOptions_range) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder217 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder217.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder217.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder218 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder218.DisallowUnknownFields()\n\tvar h218 Lit_ClientSemanticTokensRequestOptions_range_Item1\n\tif err := decoder218.Decode(&h218); err == nil {\n\t\tt.Value = h218\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [Lit_ClientSemanticTokensRequestOptions_range_Item1 bool]\"}\n}\n\nfunc (t Or_CompletionItemDefaults_editRange) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase EditRangeWithInsertReplace:\n\t\treturn json.Marshal(x)\n\tcase Range:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [EditRangeWithInsertReplace Range]\", t)\n}\n\nfunc (t *Or_CompletionItemDefaults_editRange) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder183 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder183.DisallowUnknownFields()\n\tvar h183 EditRangeWithInsertReplace\n\tif err := decoder183.Decode(&h183); err == nil {\n\t\tt.Value = h183\n\t\treturn nil\n\t}\n\tdecoder184 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder184.DisallowUnknownFields()\n\tvar h184 Range\n\tif err := decoder184.Decode(&h184); err == nil {\n\t\tt.Value = h184\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [EditRangeWithInsertReplace Range]\"}\n}\n\nfunc (t Or_CompletionItem_documentation) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase MarkupContent:\n\t\treturn json.Marshal(x)\n\tcase string:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [MarkupContent string]\", t)\n}\n\nfunc (t *Or_CompletionItem_documentation) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder25 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder25.DisallowUnknownFields()\n\tvar stringVal string\n\tif err := decoder25.Decode(&stringVal); err == nil {\n\t\tt.Value = stringVal\n\t\treturn nil\n\t}\n\tdecoder26 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder26.DisallowUnknownFields()\n\tvar h26 MarkupContent\n\tif err := decoder26.Decode(&h26); err == nil {\n\t\tt.Value = h26\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [MarkupContent string]\"}\n}\n\nfunc (t Or_CompletionItem_textEdit) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase InsertReplaceEdit:\n\t\treturn json.Marshal(x)\n\tcase TextEdit:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [InsertReplaceEdit TextEdit]\", t)\n}\n\nfunc (t *Or_CompletionItem_textEdit) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder29 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder29.DisallowUnknownFields()\n\tvar h29 InsertReplaceEdit\n\tif err := decoder29.Decode(&h29); err == nil {\n\t\tt.Value = h29\n\t\treturn nil\n\t}\n\tdecoder30 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder30.DisallowUnknownFields()\n\tvar h30 TextEdit\n\tif err := decoder30.Decode(&h30); err == nil {\n\t\tt.Value = h30\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [InsertReplaceEdit TextEdit]\"}\n}\n\nfunc (t Or_Declaration) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase Location:\n\t\treturn json.Marshal(x)\n\tcase []Location:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [Location []Location]\", t)\n}\n\nfunc (t *Or_Declaration) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder237 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder237.DisallowUnknownFields()\n\tvar h237 Location\n\tif err := decoder237.Decode(&h237); err == nil {\n\t\tt.Value = h237\n\t\treturn nil\n\t}\n\tdecoder238 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder238.DisallowUnknownFields()\n\tvar h238 []Location\n\tif err := decoder238.Decode(&h238); err == nil {\n\t\tt.Value = h238\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [Location []Location]\"}\n}\n\nfunc (t Or_Definition) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase Location:\n\t\treturn json.Marshal(x)\n\tcase []Location:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [Location []Location]\", t)\n}\n\nfunc (t *Or_Definition) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder224 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder224.DisallowUnknownFields()\n\tvar h224 Location\n\tif err := decoder224.Decode(&h224); err == nil {\n\t\tt.Value = h224\n\t\treturn nil\n\t}\n\tdecoder225 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder225.DisallowUnknownFields()\n\tvar h225 []Location\n\tif err := decoder225.Decode(&h225); err == nil {\n\t\tt.Value = h225\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [Location []Location]\"}\n}\n\nfunc (t Or_Diagnostic_code) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase int32:\n\t\treturn json.Marshal(x)\n\tcase string:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [int32 string]\", t)\n}\n\nfunc (t *Or_Diagnostic_code) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder179 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder179.DisallowUnknownFields()\n\tvar int32Val int32\n\tif err := decoder179.Decode(&int32Val); err == nil {\n\t\tt.Value = int32Val\n\t\treturn nil\n\t}\n\tdecoder180 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder180.DisallowUnknownFields()\n\tvar stringVal string\n\tif err := decoder180.Decode(&stringVal); err == nil {\n\t\tt.Value = stringVal\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [int32 string]\"}\n}\n\nfunc (t Or_DidChangeConfigurationRegistrationOptions_section) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase []string:\n\t\treturn json.Marshal(x)\n\tcase string:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [[]string string]\", t)\n}\n\nfunc (t *Or_DidChangeConfigurationRegistrationOptions_section) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder22 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder22.DisallowUnknownFields()\n\tvar stringVal string\n\tif err := decoder22.Decode(&stringVal); err == nil {\n\t\tt.Value = stringVal\n\t\treturn nil\n\t}\n\tdecoder23 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder23.DisallowUnknownFields()\n\tvar h23 []string\n\tif err := decoder23.Decode(&h23); err == nil {\n\t\tt.Value = h23\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [[]string string]\"}\n}\n\nfunc (t Or_DocumentDiagnosticReport) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase RelatedFullDocumentDiagnosticReport:\n\t\treturn json.Marshal(x)\n\tcase RelatedUnchangedDocumentDiagnosticReport:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [RelatedFullDocumentDiagnosticReport RelatedUnchangedDocumentDiagnosticReport]\", t)\n}\n\nfunc (t *Or_DocumentDiagnosticReport) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder247 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder247.DisallowUnknownFields()\n\tvar h247 RelatedFullDocumentDiagnosticReport\n\tif err := decoder247.Decode(&h247); err == nil {\n\t\tt.Value = h247\n\t\treturn nil\n\t}\n\tdecoder248 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder248.DisallowUnknownFields()\n\tvar h248 RelatedUnchangedDocumentDiagnosticReport\n\tif err := decoder248.Decode(&h248); err == nil {\n\t\tt.Value = h248\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [RelatedFullDocumentDiagnosticReport RelatedUnchangedDocumentDiagnosticReport]\"}\n}\n\nfunc (t Or_DocumentDiagnosticReportPartialResult_relatedDocuments_Value) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase FullDocumentDiagnosticReport:\n\t\treturn json.Marshal(x)\n\tcase UnchangedDocumentDiagnosticReport:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [FullDocumentDiagnosticReport UnchangedDocumentDiagnosticReport]\", t)\n}\n\nfunc (t *Or_DocumentDiagnosticReportPartialResult_relatedDocuments_Value) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder16 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder16.DisallowUnknownFields()\n\tvar h16 FullDocumentDiagnosticReport\n\tif err := decoder16.Decode(&h16); err == nil {\n\t\tt.Value = h16\n\t\treturn nil\n\t}\n\tdecoder17 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder17.DisallowUnknownFields()\n\tvar h17 UnchangedDocumentDiagnosticReport\n\tif err := decoder17.Decode(&h17); err == nil {\n\t\tt.Value = h17\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [FullDocumentDiagnosticReport UnchangedDocumentDiagnosticReport]\"}\n}\n\nfunc (t Or_DocumentFilter) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase NotebookCellTextDocumentFilter:\n\t\treturn json.Marshal(x)\n\tcase TextDocumentFilter:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [NotebookCellTextDocumentFilter TextDocumentFilter]\", t)\n}\n\nfunc (t *Or_DocumentFilter) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder270 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder270.DisallowUnknownFields()\n\tvar h270 NotebookCellTextDocumentFilter\n\tif err := decoder270.Decode(&h270); err == nil {\n\t\tt.Value = h270\n\t\treturn nil\n\t}\n\tdecoder271 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder271.DisallowUnknownFields()\n\tvar h271 TextDocumentFilter\n\tif err := decoder271.Decode(&h271); err == nil {\n\t\tt.Value = h271\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [NotebookCellTextDocumentFilter TextDocumentFilter]\"}\n}\n\nfunc (t Or_GlobPattern) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase Pattern:\n\t\treturn json.Marshal(x)\n\tcase RelativePattern:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [Pattern RelativePattern]\", t)\n}\n\nfunc (t *Or_GlobPattern) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder274 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder274.DisallowUnknownFields()\n\tvar h274 Pattern\n\tif err := decoder274.Decode(&h274); err == nil {\n\t\tt.Value = h274\n\t\treturn nil\n\t}\n\tdecoder275 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder275.DisallowUnknownFields()\n\tvar h275 RelativePattern\n\tif err := decoder275.Decode(&h275); err == nil {\n\t\tt.Value = h275\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [Pattern RelativePattern]\"}\n}\n\nfunc (t Or_Hover_contents) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase MarkedString:\n\t\treturn json.Marshal(x)\n\tcase MarkupContent:\n\t\treturn json.Marshal(x)\n\tcase []MarkedString:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [MarkedString MarkupContent []MarkedString]\", t)\n}\n\nfunc (t *Or_Hover_contents) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder34 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder34.DisallowUnknownFields()\n\tvar h34 MarkedString\n\tif err := decoder34.Decode(&h34); err == nil {\n\t\tt.Value = h34\n\t\treturn nil\n\t}\n\tdecoder35 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder35.DisallowUnknownFields()\n\tvar h35 MarkupContent\n\tif err := decoder35.Decode(&h35); err == nil {\n\t\tt.Value = h35\n\t\treturn nil\n\t}\n\tdecoder36 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder36.DisallowUnknownFields()\n\tvar h36 []MarkedString\n\tif err := decoder36.Decode(&h36); err == nil {\n\t\tt.Value = h36\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [MarkedString MarkupContent []MarkedString]\"}\n}\n\nfunc (t Or_InlayHintLabelPart_tooltip) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase MarkupContent:\n\t\treturn json.Marshal(x)\n\tcase string:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [MarkupContent string]\", t)\n}\n\nfunc (t *Or_InlayHintLabelPart_tooltip) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder56 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder56.DisallowUnknownFields()\n\tvar stringVal string\n\tif err := decoder56.Decode(&stringVal); err == nil {\n\t\tt.Value = stringVal\n\t\treturn nil\n\t}\n\tdecoder57 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder57.DisallowUnknownFields()\n\tvar h57 MarkupContent\n\tif err := decoder57.Decode(&h57); err == nil {\n\t\tt.Value = h57\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [MarkupContent string]\"}\n}\n\nfunc (t Or_InlayHint_label) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase []InlayHintLabelPart:\n\t\treturn json.Marshal(x)\n\tcase string:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [[]InlayHintLabelPart string]\", t)\n}\n\nfunc (t *Or_InlayHint_label) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder9 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder9.DisallowUnknownFields()\n\tvar stringVal string\n\tif err := decoder9.Decode(&stringVal); err == nil {\n\t\tt.Value = stringVal\n\t\treturn nil\n\t}\n\tdecoder10 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder10.DisallowUnknownFields()\n\tvar h10 []InlayHintLabelPart\n\tif err := decoder10.Decode(&h10); err == nil {\n\t\tt.Value = h10\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [[]InlayHintLabelPart string]\"}\n}\n\nfunc (t Or_InlayHint_tooltip) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase MarkupContent:\n\t\treturn json.Marshal(x)\n\tcase string:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [MarkupContent string]\", t)\n}\n\nfunc (t *Or_InlayHint_tooltip) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder12 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder12.DisallowUnknownFields()\n\tvar stringVal string\n\tif err := decoder12.Decode(&stringVal); err == nil {\n\t\tt.Value = stringVal\n\t\treturn nil\n\t}\n\tdecoder13 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder13.DisallowUnknownFields()\n\tvar h13 MarkupContent\n\tif err := decoder13.Decode(&h13); err == nil {\n\t\tt.Value = h13\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [MarkupContent string]\"}\n}\n\nfunc (t Or_InlineCompletionItem_insertText) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase StringValue:\n\t\treturn json.Marshal(x)\n\tcase string:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [StringValue string]\", t)\n}\n\nfunc (t *Or_InlineCompletionItem_insertText) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder19 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder19.DisallowUnknownFields()\n\tvar stringVal string\n\tif err := decoder19.Decode(&stringVal); err == nil {\n\t\tt.Value = stringVal\n\t\treturn nil\n\t}\n\tdecoder20 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder20.DisallowUnknownFields()\n\tvar h20 StringValue\n\tif err := decoder20.Decode(&h20); err == nil {\n\t\tt.Value = h20\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [StringValue string]\"}\n}\n\nfunc (t Or_InlineValue) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase InlineValueEvaluatableExpression:\n\t\treturn json.Marshal(x)\n\tcase InlineValueText:\n\t\treturn json.Marshal(x)\n\tcase InlineValueVariableLookup:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [InlineValueEvaluatableExpression InlineValueText InlineValueVariableLookup]\", t)\n}\n\nfunc (t *Or_InlineValue) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder242 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder242.DisallowUnknownFields()\n\tvar h242 InlineValueEvaluatableExpression\n\tif err := decoder242.Decode(&h242); err == nil {\n\t\tt.Value = h242\n\t\treturn nil\n\t}\n\tdecoder243 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder243.DisallowUnknownFields()\n\tvar h243 InlineValueText\n\tif err := decoder243.Decode(&h243); err == nil {\n\t\tt.Value = h243\n\t\treturn nil\n\t}\n\tdecoder244 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder244.DisallowUnknownFields()\n\tvar h244 InlineValueVariableLookup\n\tif err := decoder244.Decode(&h244); err == nil {\n\t\tt.Value = h244\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [InlineValueEvaluatableExpression InlineValueText InlineValueVariableLookup]\"}\n}\n\nfunc (t Or_LSPAny) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase LSPArray:\n\t\treturn json.Marshal(x)\n\tcase LSPObject:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase float64:\n\t\treturn json.Marshal(x)\n\tcase int32:\n\t\treturn json.Marshal(x)\n\tcase string:\n\t\treturn json.Marshal(x)\n\tcase uint32:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [LSPArray LSPObject bool float64 int32 string uint32]\", t)\n}\n\nfunc (t *Or_LSPAny) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder228 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder228.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder228.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder229 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder229.DisallowUnknownFields()\n\tvar float64Val float64\n\tif err := decoder229.Decode(&float64Val); err == nil {\n\t\tt.Value = float64Val\n\t\treturn nil\n\t}\n\tdecoder230 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder230.DisallowUnknownFields()\n\tvar int32Val int32\n\tif err := decoder230.Decode(&int32Val); err == nil {\n\t\tt.Value = int32Val\n\t\treturn nil\n\t}\n\tdecoder231 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder231.DisallowUnknownFields()\n\tvar stringVal string\n\tif err := decoder231.Decode(&stringVal); err == nil {\n\t\tt.Value = stringVal\n\t\treturn nil\n\t}\n\tdecoder232 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder232.DisallowUnknownFields()\n\tvar uint32Val uint32\n\tif err := decoder232.Decode(&uint32Val); err == nil {\n\t\tt.Value = uint32Val\n\t\treturn nil\n\t}\n\tdecoder233 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder233.DisallowUnknownFields()\n\tvar h233 LSPArray\n\tif err := decoder233.Decode(&h233); err == nil {\n\t\tt.Value = h233\n\t\treturn nil\n\t}\n\tdecoder234 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder234.DisallowUnknownFields()\n\tvar h234 LSPObject\n\tif err := decoder234.Decode(&h234); err == nil {\n\t\tt.Value = h234\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [LSPArray LSPObject bool float64 int32 string uint32]\"}\n}\n\nfunc (t Or_MarkedString) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase MarkedStringWithLanguage:\n\t\treturn json.Marshal(x)\n\tcase string:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [MarkedStringWithLanguage string]\", t)\n}\n\nfunc (t *Or_MarkedString) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder266 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder266.DisallowUnknownFields()\n\tvar stringVal string\n\tif err := decoder266.Decode(&stringVal); err == nil {\n\t\tt.Value = stringVal\n\t\treturn nil\n\t}\n\tdecoder267 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder267.DisallowUnknownFields()\n\tvar h267 MarkedStringWithLanguage\n\tif err := decoder267.Decode(&h267); err == nil {\n\t\tt.Value = h267\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [MarkedStringWithLanguage string]\"}\n}\n\nfunc (t Or_NotebookCellTextDocumentFilter_notebook) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase NotebookDocumentFilter:\n\t\treturn json.Marshal(x)\n\tcase string:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [NotebookDocumentFilter string]\", t)\n}\n\nfunc (t *Or_NotebookCellTextDocumentFilter_notebook) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder208 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder208.DisallowUnknownFields()\n\tvar stringVal string\n\tif err := decoder208.Decode(&stringVal); err == nil {\n\t\tt.Value = stringVal\n\t\treturn nil\n\t}\n\tdecoder209 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder209.DisallowUnknownFields()\n\tvar h209 NotebookDocumentFilter\n\tif err := decoder209.Decode(&h209); err == nil {\n\t\tt.Value = h209\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [NotebookDocumentFilter string]\"}\n}\n\nfunc (t Or_NotebookDocumentFilter) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase NotebookDocumentFilterNotebookType:\n\t\treturn json.Marshal(x)\n\tcase NotebookDocumentFilterPattern:\n\t\treturn json.Marshal(x)\n\tcase NotebookDocumentFilterScheme:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [NotebookDocumentFilterNotebookType NotebookDocumentFilterPattern NotebookDocumentFilterScheme]\", t)\n}\n\nfunc (t *Or_NotebookDocumentFilter) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder285 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder285.DisallowUnknownFields()\n\tvar h285 NotebookDocumentFilterNotebookType\n\tif err := decoder285.Decode(&h285); err == nil {\n\t\tt.Value = h285\n\t\treturn nil\n\t}\n\tdecoder286 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder286.DisallowUnknownFields()\n\tvar h286 NotebookDocumentFilterPattern\n\tif err := decoder286.Decode(&h286); err == nil {\n\t\tt.Value = h286\n\t\treturn nil\n\t}\n\tdecoder287 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder287.DisallowUnknownFields()\n\tvar h287 NotebookDocumentFilterScheme\n\tif err := decoder287.Decode(&h287); err == nil {\n\t\tt.Value = h287\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [NotebookDocumentFilterNotebookType NotebookDocumentFilterPattern NotebookDocumentFilterScheme]\"}\n}\n\nfunc (t Or_NotebookDocumentFilterWithCells_notebook) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase NotebookDocumentFilter:\n\t\treturn json.Marshal(x)\n\tcase string:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [NotebookDocumentFilter string]\", t)\n}\n\nfunc (t *Or_NotebookDocumentFilterWithCells_notebook) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder192 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder192.DisallowUnknownFields()\n\tvar stringVal string\n\tif err := decoder192.Decode(&stringVal); err == nil {\n\t\tt.Value = stringVal\n\t\treturn nil\n\t}\n\tdecoder193 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder193.DisallowUnknownFields()\n\tvar h193 NotebookDocumentFilter\n\tif err := decoder193.Decode(&h193); err == nil {\n\t\tt.Value = h193\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [NotebookDocumentFilter string]\"}\n}\n\nfunc (t Or_NotebookDocumentFilterWithNotebook_notebook) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase NotebookDocumentFilter:\n\t\treturn json.Marshal(x)\n\tcase string:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [NotebookDocumentFilter string]\", t)\n}\n\nfunc (t *Or_NotebookDocumentFilterWithNotebook_notebook) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder189 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder189.DisallowUnknownFields()\n\tvar stringVal string\n\tif err := decoder189.Decode(&stringVal); err == nil {\n\t\tt.Value = stringVal\n\t\treturn nil\n\t}\n\tdecoder190 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder190.DisallowUnknownFields()\n\tvar h190 NotebookDocumentFilter\n\tif err := decoder190.Decode(&h190); err == nil {\n\t\tt.Value = h190\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [NotebookDocumentFilter string]\"}\n}\n\nfunc (t Or_NotebookDocumentSyncOptions_notebookSelector_Elem) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase NotebookDocumentFilterWithCells:\n\t\treturn json.Marshal(x)\n\tcase NotebookDocumentFilterWithNotebook:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [NotebookDocumentFilterWithCells NotebookDocumentFilterWithNotebook]\", t)\n}\n\nfunc (t *Or_NotebookDocumentSyncOptions_notebookSelector_Elem) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder68 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder68.DisallowUnknownFields()\n\tvar h68 NotebookDocumentFilterWithCells\n\tif err := decoder68.Decode(&h68); err == nil {\n\t\tt.Value = h68\n\t\treturn nil\n\t}\n\tdecoder69 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder69.DisallowUnknownFields()\n\tvar h69 NotebookDocumentFilterWithNotebook\n\tif err := decoder69.Decode(&h69); err == nil {\n\t\tt.Value = h69\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [NotebookDocumentFilterWithCells NotebookDocumentFilterWithNotebook]\"}\n}\n\nfunc (t Or_ParameterInformation_documentation) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase MarkupContent:\n\t\treturn json.Marshal(x)\n\tcase string:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [MarkupContent string]\", t)\n}\n\nfunc (t *Or_ParameterInformation_documentation) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder205 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder205.DisallowUnknownFields()\n\tvar stringVal string\n\tif err := decoder205.Decode(&stringVal); err == nil {\n\t\tt.Value = stringVal\n\t\treturn nil\n\t}\n\tdecoder206 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder206.DisallowUnknownFields()\n\tvar h206 MarkupContent\n\tif err := decoder206.Decode(&h206); err == nil {\n\t\tt.Value = h206\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [MarkupContent string]\"}\n}\n\nfunc (t Or_ParameterInformation_label) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase Tuple_ParameterInformation_label_Item1:\n\t\treturn json.Marshal(x)\n\tcase string:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [Tuple_ParameterInformation_label_Item1 string]\", t)\n}\n\nfunc (t *Or_ParameterInformation_label) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder202 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder202.DisallowUnknownFields()\n\tvar stringVal string\n\tif err := decoder202.Decode(&stringVal); err == nil {\n\t\tt.Value = stringVal\n\t\treturn nil\n\t}\n\tdecoder203 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder203.DisallowUnknownFields()\n\tvar h203 Tuple_ParameterInformation_label_Item1\n\tif err := decoder203.Decode(&h203); err == nil {\n\t\tt.Value = h203\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [Tuple_ParameterInformation_label_Item1 string]\"}\n}\n\nfunc (t Or_PrepareRenameResult) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase PrepareRenameDefaultBehavior:\n\t\treturn json.Marshal(x)\n\tcase PrepareRenamePlaceholder:\n\t\treturn json.Marshal(x)\n\tcase Range:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [PrepareRenameDefaultBehavior PrepareRenamePlaceholder Range]\", t)\n}\n\nfunc (t *Or_PrepareRenameResult) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder252 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder252.DisallowUnknownFields()\n\tvar h252 PrepareRenameDefaultBehavior\n\tif err := decoder252.Decode(&h252); err == nil {\n\t\tt.Value = h252\n\t\treturn nil\n\t}\n\tdecoder253 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder253.DisallowUnknownFields()\n\tvar h253 PrepareRenamePlaceholder\n\tif err := decoder253.Decode(&h253); err == nil {\n\t\tt.Value = h253\n\t\treturn nil\n\t}\n\tdecoder254 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder254.DisallowUnknownFields()\n\tvar h254 Range\n\tif err := decoder254.Decode(&h254); err == nil {\n\t\tt.Value = h254\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [PrepareRenameDefaultBehavior PrepareRenamePlaceholder Range]\"}\n}\n\nfunc (t Or_ProgressToken) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase int32:\n\t\treturn json.Marshal(x)\n\tcase string:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [int32 string]\", t)\n}\n\nfunc (t *Or_ProgressToken) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder255 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder255.DisallowUnknownFields()\n\tvar int32Val int32\n\tif err := decoder255.Decode(&int32Val); err == nil {\n\t\tt.Value = int32Val\n\t\treturn nil\n\t}\n\tdecoder256 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder256.DisallowUnknownFields()\n\tvar stringVal string\n\tif err := decoder256.Decode(&stringVal); err == nil {\n\t\tt.Value = stringVal\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [int32 string]\"}\n}\n\nfunc (t Or_RelatedFullDocumentDiagnosticReport_relatedDocuments_Value) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase FullDocumentDiagnosticReport:\n\t\treturn json.Marshal(x)\n\tcase UnchangedDocumentDiagnosticReport:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [FullDocumentDiagnosticReport UnchangedDocumentDiagnosticReport]\", t)\n}\n\nfunc (t *Or_RelatedFullDocumentDiagnosticReport_relatedDocuments_Value) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder60 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder60.DisallowUnknownFields()\n\tvar h60 FullDocumentDiagnosticReport\n\tif err := decoder60.Decode(&h60); err == nil {\n\t\tt.Value = h60\n\t\treturn nil\n\t}\n\tdecoder61 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder61.DisallowUnknownFields()\n\tvar h61 UnchangedDocumentDiagnosticReport\n\tif err := decoder61.Decode(&h61); err == nil {\n\t\tt.Value = h61\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [FullDocumentDiagnosticReport UnchangedDocumentDiagnosticReport]\"}\n}\n\nfunc (t Or_RelatedUnchangedDocumentDiagnosticReport_relatedDocuments_Value) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase FullDocumentDiagnosticReport:\n\t\treturn json.Marshal(x)\n\tcase UnchangedDocumentDiagnosticReport:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [FullDocumentDiagnosticReport UnchangedDocumentDiagnosticReport]\", t)\n}\n\nfunc (t *Or_RelatedUnchangedDocumentDiagnosticReport_relatedDocuments_Value) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder64 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder64.DisallowUnknownFields()\n\tvar h64 FullDocumentDiagnosticReport\n\tif err := decoder64.Decode(&h64); err == nil {\n\t\tt.Value = h64\n\t\treturn nil\n\t}\n\tdecoder65 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder65.DisallowUnknownFields()\n\tvar h65 UnchangedDocumentDiagnosticReport\n\tif err := decoder65.Decode(&h65); err == nil {\n\t\tt.Value = h65\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [FullDocumentDiagnosticReport UnchangedDocumentDiagnosticReport]\"}\n}\n\nfunc (t Or_RelativePattern_baseUri) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase URI:\n\t\treturn json.Marshal(x)\n\tcase WorkspaceFolder:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [URI WorkspaceFolder]\", t)\n}\n\nfunc (t *Or_RelativePattern_baseUri) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder214 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder214.DisallowUnknownFields()\n\tvar h214 URI\n\tif err := decoder214.Decode(&h214); err == nil {\n\t\tt.Value = h214\n\t\treturn nil\n\t}\n\tdecoder215 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder215.DisallowUnknownFields()\n\tvar h215 WorkspaceFolder\n\tif err := decoder215.Decode(&h215); err == nil {\n\t\tt.Value = h215\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [URI WorkspaceFolder]\"}\n}\n\nfunc (t Or_Result_textDocument_codeAction_Item0_Elem) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase CodeAction:\n\t\treturn json.Marshal(x)\n\tcase Command:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [CodeAction Command]\", t)\n}\n\nfunc (t *Or_Result_textDocument_codeAction_Item0_Elem) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder322 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder322.DisallowUnknownFields()\n\tvar h322 CodeAction\n\tif err := decoder322.Decode(&h322); err == nil {\n\t\tt.Value = h322\n\t\treturn nil\n\t}\n\tdecoder323 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder323.DisallowUnknownFields()\n\tvar h323 Command\n\tif err := decoder323.Decode(&h323); err == nil {\n\t\tt.Value = h323\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [CodeAction Command]\"}\n}\n\nfunc (t Or_Result_textDocument_completion) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase CompletionList:\n\t\treturn json.Marshal(x)\n\tcase []CompletionItem:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [CompletionList []CompletionItem]\", t)\n}\n\nfunc (t *Or_Result_textDocument_completion) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder310 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder310.DisallowUnknownFields()\n\tvar h310 CompletionList\n\tif err := decoder310.Decode(&h310); err == nil {\n\t\tt.Value = h310\n\t\treturn nil\n\t}\n\tdecoder311 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder311.DisallowUnknownFields()\n\tvar h311 []CompletionItem\n\tif err := decoder311.Decode(&h311); err == nil {\n\t\tt.Value = h311\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [CompletionList []CompletionItem]\"}\n}\n\nfunc (t Or_Result_textDocument_declaration) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase Declaration:\n\t\treturn json.Marshal(x)\n\tcase []DeclarationLink:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [Declaration []DeclarationLink]\", t)\n}\n\nfunc (t *Or_Result_textDocument_declaration) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder298 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder298.DisallowUnknownFields()\n\tvar h298 Declaration\n\tif err := decoder298.Decode(&h298); err == nil {\n\t\tt.Value = h298\n\t\treturn nil\n\t}\n\tdecoder299 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder299.DisallowUnknownFields()\n\tvar h299 []DeclarationLink\n\tif err := decoder299.Decode(&h299); err == nil {\n\t\tt.Value = h299\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [Declaration []DeclarationLink]\"}\n}\n\nfunc (t Or_Result_textDocument_definition) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase Definition:\n\t\treturn json.Marshal(x)\n\tcase []DefinitionLink:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [Definition []DefinitionLink]\", t)\n}\n\nfunc (t *Or_Result_textDocument_definition) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder314 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder314.DisallowUnknownFields()\n\tvar h314 Definition\n\tif err := decoder314.Decode(&h314); err == nil {\n\t\tt.Value = h314\n\t\treturn nil\n\t}\n\tdecoder315 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder315.DisallowUnknownFields()\n\tvar h315 []DefinitionLink\n\tif err := decoder315.Decode(&h315); err == nil {\n\t\tt.Value = h315\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [Definition []DefinitionLink]\"}\n}\n\nfunc (t Or_Result_textDocument_documentSymbol) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase []DocumentSymbol:\n\t\treturn json.Marshal(x)\n\tcase []SymbolInformation:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [[]DocumentSymbol []SymbolInformation]\", t)\n}\n\nfunc (t *Or_Result_textDocument_documentSymbol) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder318 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder318.DisallowUnknownFields()\n\tvar h318 []DocumentSymbol\n\tif err := decoder318.Decode(&h318); err == nil {\n\t\tt.Value = h318\n\t\treturn nil\n\t}\n\tdecoder319 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder319.DisallowUnknownFields()\n\tvar h319 []SymbolInformation\n\tif err := decoder319.Decode(&h319); err == nil {\n\t\tt.Value = h319\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [[]DocumentSymbol []SymbolInformation]\"}\n}\n\nfunc (t Or_Result_textDocument_implementation) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase Definition:\n\t\treturn json.Marshal(x)\n\tcase []DefinitionLink:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [Definition []DefinitionLink]\", t)\n}\n\nfunc (t *Or_Result_textDocument_implementation) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder290 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder290.DisallowUnknownFields()\n\tvar h290 Definition\n\tif err := decoder290.Decode(&h290); err == nil {\n\t\tt.Value = h290\n\t\treturn nil\n\t}\n\tdecoder291 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder291.DisallowUnknownFields()\n\tvar h291 []DefinitionLink\n\tif err := decoder291.Decode(&h291); err == nil {\n\t\tt.Value = h291\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [Definition []DefinitionLink]\"}\n}\n\nfunc (t Or_Result_textDocument_inlineCompletion) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase InlineCompletionList:\n\t\treturn json.Marshal(x)\n\tcase []InlineCompletionItem:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [InlineCompletionList []InlineCompletionItem]\", t)\n}\n\nfunc (t *Or_Result_textDocument_inlineCompletion) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder306 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder306.DisallowUnknownFields()\n\tvar h306 InlineCompletionList\n\tif err := decoder306.Decode(&h306); err == nil {\n\t\tt.Value = h306\n\t\treturn nil\n\t}\n\tdecoder307 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder307.DisallowUnknownFields()\n\tvar h307 []InlineCompletionItem\n\tif err := decoder307.Decode(&h307); err == nil {\n\t\tt.Value = h307\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [InlineCompletionList []InlineCompletionItem]\"}\n}\n\nfunc (t Or_Result_textDocument_semanticTokens_full_delta) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase SemanticTokens:\n\t\treturn json.Marshal(x)\n\tcase SemanticTokensDelta:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [SemanticTokens SemanticTokensDelta]\", t)\n}\n\nfunc (t *Or_Result_textDocument_semanticTokens_full_delta) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder302 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder302.DisallowUnknownFields()\n\tvar h302 SemanticTokens\n\tif err := decoder302.Decode(&h302); err == nil {\n\t\tt.Value = h302\n\t\treturn nil\n\t}\n\tdecoder303 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder303.DisallowUnknownFields()\n\tvar h303 SemanticTokensDelta\n\tif err := decoder303.Decode(&h303); err == nil {\n\t\tt.Value = h303\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [SemanticTokens SemanticTokensDelta]\"}\n}\n\nfunc (t Or_Result_textDocument_typeDefinition) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase Definition:\n\t\treturn json.Marshal(x)\n\tcase []DefinitionLink:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [Definition []DefinitionLink]\", t)\n}\n\nfunc (t *Or_Result_textDocument_typeDefinition) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder294 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder294.DisallowUnknownFields()\n\tvar h294 Definition\n\tif err := decoder294.Decode(&h294); err == nil {\n\t\tt.Value = h294\n\t\treturn nil\n\t}\n\tdecoder295 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder295.DisallowUnknownFields()\n\tvar h295 []DefinitionLink\n\tif err := decoder295.Decode(&h295); err == nil {\n\t\tt.Value = h295\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [Definition []DefinitionLink]\"}\n}\n\nfunc (t Or_Result_workspace_symbol) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase []SymbolInformation:\n\t\treturn json.Marshal(x)\n\tcase []WorkspaceSymbol:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [[]SymbolInformation []WorkspaceSymbol]\", t)\n}\n\nfunc (t *Or_Result_workspace_symbol) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder326 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder326.DisallowUnknownFields()\n\tvar h326 []SymbolInformation\n\tif err := decoder326.Decode(&h326); err == nil {\n\t\tt.Value = h326\n\t\treturn nil\n\t}\n\tdecoder327 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder327.DisallowUnknownFields()\n\tvar h327 []WorkspaceSymbol\n\tif err := decoder327.Decode(&h327); err == nil {\n\t\tt.Value = h327\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [[]SymbolInformation []WorkspaceSymbol]\"}\n}\n\nfunc (t Or_SemanticTokensOptions_full) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase SemanticTokensFullDelta:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [SemanticTokensFullDelta bool]\", t)\n}\n\nfunc (t *Or_SemanticTokensOptions_full) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder47 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder47.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder47.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder48 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder48.DisallowUnknownFields()\n\tvar h48 SemanticTokensFullDelta\n\tif err := decoder48.Decode(&h48); err == nil {\n\t\tt.Value = h48\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [SemanticTokensFullDelta bool]\"}\n}\n\nfunc (t Or_SemanticTokensOptions_range) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase Lit_SemanticTokensOptions_range_Item1:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [Lit_SemanticTokensOptions_range_Item1 bool]\", t)\n}\n\nfunc (t *Or_SemanticTokensOptions_range) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder44 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder44.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder44.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder45 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder45.DisallowUnknownFields()\n\tvar h45 Lit_SemanticTokensOptions_range_Item1\n\tif err := decoder45.Decode(&h45); err == nil {\n\t\tt.Value = h45\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [Lit_SemanticTokensOptions_range_Item1 bool]\"}\n}\n\nfunc (t Or_ServerCapabilities_callHierarchyProvider) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase CallHierarchyOptions:\n\t\treturn json.Marshal(x)\n\tcase CallHierarchyRegistrationOptions:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [CallHierarchyOptions CallHierarchyRegistrationOptions bool]\", t)\n}\n\nfunc (t *Or_ServerCapabilities_callHierarchyProvider) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder140 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder140.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder140.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder141 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder141.DisallowUnknownFields()\n\tvar h141 CallHierarchyOptions\n\tif err := decoder141.Decode(&h141); err == nil {\n\t\tt.Value = h141\n\t\treturn nil\n\t}\n\tdecoder142 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder142.DisallowUnknownFields()\n\tvar h142 CallHierarchyRegistrationOptions\n\tif err := decoder142.Decode(&h142); err == nil {\n\t\tt.Value = h142\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [CallHierarchyOptions CallHierarchyRegistrationOptions bool]\"}\n}\n\nfunc (t Or_ServerCapabilities_codeActionProvider) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase CodeActionOptions:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [CodeActionOptions bool]\", t)\n}\n\nfunc (t *Or_ServerCapabilities_codeActionProvider) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder109 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder109.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder109.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder110 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder110.DisallowUnknownFields()\n\tvar h110 CodeActionOptions\n\tif err := decoder110.Decode(&h110); err == nil {\n\t\tt.Value = h110\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [CodeActionOptions bool]\"}\n}\n\nfunc (t Or_ServerCapabilities_colorProvider) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase DocumentColorOptions:\n\t\treturn json.Marshal(x)\n\tcase DocumentColorRegistrationOptions:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [DocumentColorOptions DocumentColorRegistrationOptions bool]\", t)\n}\n\nfunc (t *Or_ServerCapabilities_colorProvider) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder113 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder113.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder113.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder114 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder114.DisallowUnknownFields()\n\tvar h114 DocumentColorOptions\n\tif err := decoder114.Decode(&h114); err == nil {\n\t\tt.Value = h114\n\t\treturn nil\n\t}\n\tdecoder115 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder115.DisallowUnknownFields()\n\tvar h115 DocumentColorRegistrationOptions\n\tif err := decoder115.Decode(&h115); err == nil {\n\t\tt.Value = h115\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [DocumentColorOptions DocumentColorRegistrationOptions bool]\"}\n}\n\nfunc (t Or_ServerCapabilities_declarationProvider) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase DeclarationOptions:\n\t\treturn json.Marshal(x)\n\tcase DeclarationRegistrationOptions:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [DeclarationOptions DeclarationRegistrationOptions bool]\", t)\n}\n\nfunc (t *Or_ServerCapabilities_declarationProvider) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder83 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder83.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder83.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder84 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder84.DisallowUnknownFields()\n\tvar h84 DeclarationOptions\n\tif err := decoder84.Decode(&h84); err == nil {\n\t\tt.Value = h84\n\t\treturn nil\n\t}\n\tdecoder85 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder85.DisallowUnknownFields()\n\tvar h85 DeclarationRegistrationOptions\n\tif err := decoder85.Decode(&h85); err == nil {\n\t\tt.Value = h85\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [DeclarationOptions DeclarationRegistrationOptions bool]\"}\n}\n\nfunc (t Or_ServerCapabilities_definitionProvider) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase DefinitionOptions:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [DefinitionOptions bool]\", t)\n}\n\nfunc (t *Or_ServerCapabilities_definitionProvider) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder87 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder87.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder87.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder88 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder88.DisallowUnknownFields()\n\tvar h88 DefinitionOptions\n\tif err := decoder88.Decode(&h88); err == nil {\n\t\tt.Value = h88\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [DefinitionOptions bool]\"}\n}\n\nfunc (t Or_ServerCapabilities_diagnosticProvider) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase DiagnosticOptions:\n\t\treturn json.Marshal(x)\n\tcase DiagnosticRegistrationOptions:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [DiagnosticOptions DiagnosticRegistrationOptions]\", t)\n}\n\nfunc (t *Or_ServerCapabilities_diagnosticProvider) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder174 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder174.DisallowUnknownFields()\n\tvar h174 DiagnosticOptions\n\tif err := decoder174.Decode(&h174); err == nil {\n\t\tt.Value = h174\n\t\treturn nil\n\t}\n\tdecoder175 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder175.DisallowUnknownFields()\n\tvar h175 DiagnosticRegistrationOptions\n\tif err := decoder175.Decode(&h175); err == nil {\n\t\tt.Value = h175\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [DiagnosticOptions DiagnosticRegistrationOptions]\"}\n}\n\nfunc (t Or_ServerCapabilities_documentFormattingProvider) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase DocumentFormattingOptions:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [DocumentFormattingOptions bool]\", t)\n}\n\nfunc (t *Or_ServerCapabilities_documentFormattingProvider) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder120 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder120.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder120.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder121 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder121.DisallowUnknownFields()\n\tvar h121 DocumentFormattingOptions\n\tif err := decoder121.Decode(&h121); err == nil {\n\t\tt.Value = h121\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [DocumentFormattingOptions bool]\"}\n}\n\nfunc (t Or_ServerCapabilities_documentHighlightProvider) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase DocumentHighlightOptions:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [DocumentHighlightOptions bool]\", t)\n}\n\nfunc (t *Or_ServerCapabilities_documentHighlightProvider) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder103 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder103.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder103.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder104 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder104.DisallowUnknownFields()\n\tvar h104 DocumentHighlightOptions\n\tif err := decoder104.Decode(&h104); err == nil {\n\t\tt.Value = h104\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [DocumentHighlightOptions bool]\"}\n}\n\nfunc (t Or_ServerCapabilities_documentRangeFormattingProvider) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase DocumentRangeFormattingOptions:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [DocumentRangeFormattingOptions bool]\", t)\n}\n\nfunc (t *Or_ServerCapabilities_documentRangeFormattingProvider) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder123 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder123.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder123.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder124 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder124.DisallowUnknownFields()\n\tvar h124 DocumentRangeFormattingOptions\n\tif err := decoder124.Decode(&h124); err == nil {\n\t\tt.Value = h124\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [DocumentRangeFormattingOptions bool]\"}\n}\n\nfunc (t Or_ServerCapabilities_documentSymbolProvider) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase DocumentSymbolOptions:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [DocumentSymbolOptions bool]\", t)\n}\n\nfunc (t *Or_ServerCapabilities_documentSymbolProvider) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder106 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder106.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder106.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder107 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder107.DisallowUnknownFields()\n\tvar h107 DocumentSymbolOptions\n\tif err := decoder107.Decode(&h107); err == nil {\n\t\tt.Value = h107\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [DocumentSymbolOptions bool]\"}\n}\n\nfunc (t Or_ServerCapabilities_foldingRangeProvider) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase FoldingRangeOptions:\n\t\treturn json.Marshal(x)\n\tcase FoldingRangeRegistrationOptions:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [FoldingRangeOptions FoldingRangeRegistrationOptions bool]\", t)\n}\n\nfunc (t *Or_ServerCapabilities_foldingRangeProvider) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder130 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder130.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder130.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder131 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder131.DisallowUnknownFields()\n\tvar h131 FoldingRangeOptions\n\tif err := decoder131.Decode(&h131); err == nil {\n\t\tt.Value = h131\n\t\treturn nil\n\t}\n\tdecoder132 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder132.DisallowUnknownFields()\n\tvar h132 FoldingRangeRegistrationOptions\n\tif err := decoder132.Decode(&h132); err == nil {\n\t\tt.Value = h132\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [FoldingRangeOptions FoldingRangeRegistrationOptions bool]\"}\n}\n\nfunc (t Or_ServerCapabilities_hoverProvider) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase HoverOptions:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [HoverOptions bool]\", t)\n}\n\nfunc (t *Or_ServerCapabilities_hoverProvider) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder79 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder79.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder79.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder80 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder80.DisallowUnknownFields()\n\tvar h80 HoverOptions\n\tif err := decoder80.Decode(&h80); err == nil {\n\t\tt.Value = h80\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [HoverOptions bool]\"}\n}\n\nfunc (t Or_ServerCapabilities_implementationProvider) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase ImplementationOptions:\n\t\treturn json.Marshal(x)\n\tcase ImplementationRegistrationOptions:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [ImplementationOptions ImplementationRegistrationOptions bool]\", t)\n}\n\nfunc (t *Or_ServerCapabilities_implementationProvider) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder96 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder96.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder96.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder97 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder97.DisallowUnknownFields()\n\tvar h97 ImplementationOptions\n\tif err := decoder97.Decode(&h97); err == nil {\n\t\tt.Value = h97\n\t\treturn nil\n\t}\n\tdecoder98 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder98.DisallowUnknownFields()\n\tvar h98 ImplementationRegistrationOptions\n\tif err := decoder98.Decode(&h98); err == nil {\n\t\tt.Value = h98\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [ImplementationOptions ImplementationRegistrationOptions bool]\"}\n}\n\nfunc (t Or_ServerCapabilities_inlayHintProvider) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase InlayHintOptions:\n\t\treturn json.Marshal(x)\n\tcase InlayHintRegistrationOptions:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [InlayHintOptions InlayHintRegistrationOptions bool]\", t)\n}\n\nfunc (t *Or_ServerCapabilities_inlayHintProvider) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder169 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder169.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder169.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder170 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder170.DisallowUnknownFields()\n\tvar h170 InlayHintOptions\n\tif err := decoder170.Decode(&h170); err == nil {\n\t\tt.Value = h170\n\t\treturn nil\n\t}\n\tdecoder171 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder171.DisallowUnknownFields()\n\tvar h171 InlayHintRegistrationOptions\n\tif err := decoder171.Decode(&h171); err == nil {\n\t\tt.Value = h171\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [InlayHintOptions InlayHintRegistrationOptions bool]\"}\n}\n\nfunc (t Or_ServerCapabilities_inlineCompletionProvider) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase InlineCompletionOptions:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [InlineCompletionOptions bool]\", t)\n}\n\nfunc (t *Or_ServerCapabilities_inlineCompletionProvider) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder177 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder177.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder177.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder178 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder178.DisallowUnknownFields()\n\tvar h178 InlineCompletionOptions\n\tif err := decoder178.Decode(&h178); err == nil {\n\t\tt.Value = h178\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [InlineCompletionOptions bool]\"}\n}\n\nfunc (t Or_ServerCapabilities_inlineValueProvider) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase InlineValueOptions:\n\t\treturn json.Marshal(x)\n\tcase InlineValueRegistrationOptions:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [InlineValueOptions InlineValueRegistrationOptions bool]\", t)\n}\n\nfunc (t *Or_ServerCapabilities_inlineValueProvider) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder164 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder164.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder164.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder165 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder165.DisallowUnknownFields()\n\tvar h165 InlineValueOptions\n\tif err := decoder165.Decode(&h165); err == nil {\n\t\tt.Value = h165\n\t\treturn nil\n\t}\n\tdecoder166 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder166.DisallowUnknownFields()\n\tvar h166 InlineValueRegistrationOptions\n\tif err := decoder166.Decode(&h166); err == nil {\n\t\tt.Value = h166\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [InlineValueOptions InlineValueRegistrationOptions bool]\"}\n}\n\nfunc (t Or_ServerCapabilities_linkedEditingRangeProvider) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase LinkedEditingRangeOptions:\n\t\treturn json.Marshal(x)\n\tcase LinkedEditingRangeRegistrationOptions:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [LinkedEditingRangeOptions LinkedEditingRangeRegistrationOptions bool]\", t)\n}\n\nfunc (t *Or_ServerCapabilities_linkedEditingRangeProvider) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder145 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder145.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder145.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder146 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder146.DisallowUnknownFields()\n\tvar h146 LinkedEditingRangeOptions\n\tif err := decoder146.Decode(&h146); err == nil {\n\t\tt.Value = h146\n\t\treturn nil\n\t}\n\tdecoder147 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder147.DisallowUnknownFields()\n\tvar h147 LinkedEditingRangeRegistrationOptions\n\tif err := decoder147.Decode(&h147); err == nil {\n\t\tt.Value = h147\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [LinkedEditingRangeOptions LinkedEditingRangeRegistrationOptions bool]\"}\n}\n\nfunc (t Or_ServerCapabilities_monikerProvider) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase MonikerOptions:\n\t\treturn json.Marshal(x)\n\tcase MonikerRegistrationOptions:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [MonikerOptions MonikerRegistrationOptions bool]\", t)\n}\n\nfunc (t *Or_ServerCapabilities_monikerProvider) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder154 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder154.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder154.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder155 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder155.DisallowUnknownFields()\n\tvar h155 MonikerOptions\n\tif err := decoder155.Decode(&h155); err == nil {\n\t\tt.Value = h155\n\t\treturn nil\n\t}\n\tdecoder156 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder156.DisallowUnknownFields()\n\tvar h156 MonikerRegistrationOptions\n\tif err := decoder156.Decode(&h156); err == nil {\n\t\tt.Value = h156\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [MonikerOptions MonikerRegistrationOptions bool]\"}\n}\n\nfunc (t Or_ServerCapabilities_notebookDocumentSync) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase NotebookDocumentSyncOptions:\n\t\treturn json.Marshal(x)\n\tcase NotebookDocumentSyncRegistrationOptions:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [NotebookDocumentSyncOptions NotebookDocumentSyncRegistrationOptions]\", t)\n}\n\nfunc (t *Or_ServerCapabilities_notebookDocumentSync) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder76 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder76.DisallowUnknownFields()\n\tvar h76 NotebookDocumentSyncOptions\n\tif err := decoder76.Decode(&h76); err == nil {\n\t\tt.Value = h76\n\t\treturn nil\n\t}\n\tdecoder77 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder77.DisallowUnknownFields()\n\tvar h77 NotebookDocumentSyncRegistrationOptions\n\tif err := decoder77.Decode(&h77); err == nil {\n\t\tt.Value = h77\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [NotebookDocumentSyncOptions NotebookDocumentSyncRegistrationOptions]\"}\n}\n\nfunc (t Or_ServerCapabilities_referencesProvider) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase ReferenceOptions:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [ReferenceOptions bool]\", t)\n}\n\nfunc (t *Or_ServerCapabilities_referencesProvider) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder100 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder100.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder100.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder101 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder101.DisallowUnknownFields()\n\tvar h101 ReferenceOptions\n\tif err := decoder101.Decode(&h101); err == nil {\n\t\tt.Value = h101\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [ReferenceOptions bool]\"}\n}\n\nfunc (t Or_ServerCapabilities_renameProvider) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase RenameOptions:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [RenameOptions bool]\", t)\n}\n\nfunc (t *Or_ServerCapabilities_renameProvider) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder126 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder126.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder126.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder127 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder127.DisallowUnknownFields()\n\tvar h127 RenameOptions\n\tif err := decoder127.Decode(&h127); err == nil {\n\t\tt.Value = h127\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [RenameOptions bool]\"}\n}\n\nfunc (t Or_ServerCapabilities_selectionRangeProvider) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase SelectionRangeOptions:\n\t\treturn json.Marshal(x)\n\tcase SelectionRangeRegistrationOptions:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [SelectionRangeOptions SelectionRangeRegistrationOptions bool]\", t)\n}\n\nfunc (t *Or_ServerCapabilities_selectionRangeProvider) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder135 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder135.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder135.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder136 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder136.DisallowUnknownFields()\n\tvar h136 SelectionRangeOptions\n\tif err := decoder136.Decode(&h136); err == nil {\n\t\tt.Value = h136\n\t\treturn nil\n\t}\n\tdecoder137 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder137.DisallowUnknownFields()\n\tvar h137 SelectionRangeRegistrationOptions\n\tif err := decoder137.Decode(&h137); err == nil {\n\t\tt.Value = h137\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [SelectionRangeOptions SelectionRangeRegistrationOptions bool]\"}\n}\n\nfunc (t Or_ServerCapabilities_semanticTokensProvider) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase SemanticTokensOptions:\n\t\treturn json.Marshal(x)\n\tcase SemanticTokensRegistrationOptions:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [SemanticTokensOptions SemanticTokensRegistrationOptions]\", t)\n}\n\nfunc (t *Or_ServerCapabilities_semanticTokensProvider) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder150 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder150.DisallowUnknownFields()\n\tvar h150 SemanticTokensOptions\n\tif err := decoder150.Decode(&h150); err == nil {\n\t\tt.Value = h150\n\t\treturn nil\n\t}\n\tdecoder151 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder151.DisallowUnknownFields()\n\tvar h151 SemanticTokensRegistrationOptions\n\tif err := decoder151.Decode(&h151); err == nil {\n\t\tt.Value = h151\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [SemanticTokensOptions SemanticTokensRegistrationOptions]\"}\n}\n\nfunc (t Or_ServerCapabilities_textDocumentSync) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase TextDocumentSyncKind:\n\t\treturn json.Marshal(x)\n\tcase TextDocumentSyncOptions:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [TextDocumentSyncKind TextDocumentSyncOptions]\", t)\n}\n\nfunc (t *Or_ServerCapabilities_textDocumentSync) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder72 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder72.DisallowUnknownFields()\n\tvar h72 TextDocumentSyncKind\n\tif err := decoder72.Decode(&h72); err == nil {\n\t\tt.Value = h72\n\t\treturn nil\n\t}\n\tdecoder73 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder73.DisallowUnknownFields()\n\tvar h73 TextDocumentSyncOptions\n\tif err := decoder73.Decode(&h73); err == nil {\n\t\tt.Value = h73\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [TextDocumentSyncKind TextDocumentSyncOptions]\"}\n}\n\nfunc (t Or_ServerCapabilities_typeDefinitionProvider) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase TypeDefinitionOptions:\n\t\treturn json.Marshal(x)\n\tcase TypeDefinitionRegistrationOptions:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [TypeDefinitionOptions TypeDefinitionRegistrationOptions bool]\", t)\n}\n\nfunc (t *Or_ServerCapabilities_typeDefinitionProvider) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder91 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder91.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder91.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder92 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder92.DisallowUnknownFields()\n\tvar h92 TypeDefinitionOptions\n\tif err := decoder92.Decode(&h92); err == nil {\n\t\tt.Value = h92\n\t\treturn nil\n\t}\n\tdecoder93 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder93.DisallowUnknownFields()\n\tvar h93 TypeDefinitionRegistrationOptions\n\tif err := decoder93.Decode(&h93); err == nil {\n\t\tt.Value = h93\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [TypeDefinitionOptions TypeDefinitionRegistrationOptions bool]\"}\n}\n\nfunc (t Or_ServerCapabilities_typeHierarchyProvider) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase TypeHierarchyOptions:\n\t\treturn json.Marshal(x)\n\tcase TypeHierarchyRegistrationOptions:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [TypeHierarchyOptions TypeHierarchyRegistrationOptions bool]\", t)\n}\n\nfunc (t *Or_ServerCapabilities_typeHierarchyProvider) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder159 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder159.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder159.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder160 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder160.DisallowUnknownFields()\n\tvar h160 TypeHierarchyOptions\n\tif err := decoder160.Decode(&h160); err == nil {\n\t\tt.Value = h160\n\t\treturn nil\n\t}\n\tdecoder161 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder161.DisallowUnknownFields()\n\tvar h161 TypeHierarchyRegistrationOptions\n\tif err := decoder161.Decode(&h161); err == nil {\n\t\tt.Value = h161\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [TypeHierarchyOptions TypeHierarchyRegistrationOptions bool]\"}\n}\n\nfunc (t Or_ServerCapabilities_workspaceSymbolProvider) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase WorkspaceSymbolOptions:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [WorkspaceSymbolOptions bool]\", t)\n}\n\nfunc (t *Or_ServerCapabilities_workspaceSymbolProvider) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder117 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder117.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder117.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder118 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder118.DisallowUnknownFields()\n\tvar h118 WorkspaceSymbolOptions\n\tif err := decoder118.Decode(&h118); err == nil {\n\t\tt.Value = h118\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [WorkspaceSymbolOptions bool]\"}\n}\n\nfunc (t Or_SignatureInformation_documentation) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase MarkupContent:\n\t\treturn json.Marshal(x)\n\tcase string:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [MarkupContent string]\", t)\n}\n\nfunc (t *Or_SignatureInformation_documentation) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder186 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder186.DisallowUnknownFields()\n\tvar stringVal string\n\tif err := decoder186.Decode(&stringVal); err == nil {\n\t\tt.Value = stringVal\n\t\treturn nil\n\t}\n\tdecoder187 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder187.DisallowUnknownFields()\n\tvar h187 MarkupContent\n\tif err := decoder187.Decode(&h187); err == nil {\n\t\tt.Value = h187\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [MarkupContent string]\"}\n}\n\nfunc (t Or_TextDocumentContentChangeEvent) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase TextDocumentContentChangePartial:\n\t\treturn json.Marshal(x)\n\tcase TextDocumentContentChangeWholeDocument:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [TextDocumentContentChangePartial TextDocumentContentChangeWholeDocument]\", t)\n}\n\nfunc (t *Or_TextDocumentContentChangeEvent) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder263 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder263.DisallowUnknownFields()\n\tvar h263 TextDocumentContentChangePartial\n\tif err := decoder263.Decode(&h263); err == nil {\n\t\tt.Value = h263\n\t\treturn nil\n\t}\n\tdecoder264 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder264.DisallowUnknownFields()\n\tvar h264 TextDocumentContentChangeWholeDocument\n\tif err := decoder264.Decode(&h264); err == nil {\n\t\tt.Value = h264\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [TextDocumentContentChangePartial TextDocumentContentChangeWholeDocument]\"}\n}\n\nfunc (t Or_TextDocumentEdit_edits_Elem) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase AnnotatedTextEdit:\n\t\treturn json.Marshal(x)\n\tcase SnippetTextEdit:\n\t\treturn json.Marshal(x)\n\tcase TextEdit:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [AnnotatedTextEdit SnippetTextEdit TextEdit]\", t)\n}\n\nfunc (t *Or_TextDocumentEdit_edits_Elem) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder52 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder52.DisallowUnknownFields()\n\tvar h52 AnnotatedTextEdit\n\tif err := decoder52.Decode(&h52); err == nil {\n\t\tt.Value = h52\n\t\treturn nil\n\t}\n\tdecoder53 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder53.DisallowUnknownFields()\n\tvar h53 SnippetTextEdit\n\tif err := decoder53.Decode(&h53); err == nil {\n\t\tt.Value = h53\n\t\treturn nil\n\t}\n\tdecoder54 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder54.DisallowUnknownFields()\n\tvar h54 TextEdit\n\tif err := decoder54.Decode(&h54); err == nil {\n\t\tt.Value = h54\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [AnnotatedTextEdit SnippetTextEdit TextEdit]\"}\n}\n\nfunc (t Or_TextDocumentFilter) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase TextDocumentFilterLanguage:\n\t\treturn json.Marshal(x)\n\tcase TextDocumentFilterPattern:\n\t\treturn json.Marshal(x)\n\tcase TextDocumentFilterScheme:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [TextDocumentFilterLanguage TextDocumentFilterPattern TextDocumentFilterScheme]\", t)\n}\n\nfunc (t *Or_TextDocumentFilter) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder279 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder279.DisallowUnknownFields()\n\tvar h279 TextDocumentFilterLanguage\n\tif err := decoder279.Decode(&h279); err == nil {\n\t\tt.Value = h279\n\t\treturn nil\n\t}\n\tdecoder280 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder280.DisallowUnknownFields()\n\tvar h280 TextDocumentFilterPattern\n\tif err := decoder280.Decode(&h280); err == nil {\n\t\tt.Value = h280\n\t\treturn nil\n\t}\n\tdecoder281 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder281.DisallowUnknownFields()\n\tvar h281 TextDocumentFilterScheme\n\tif err := decoder281.Decode(&h281); err == nil {\n\t\tt.Value = h281\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [TextDocumentFilterLanguage TextDocumentFilterPattern TextDocumentFilterScheme]\"}\n}\n\nfunc (t Or_TextDocumentSyncOptions_save) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase SaveOptions:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [SaveOptions bool]\", t)\n}\n\nfunc (t *Or_TextDocumentSyncOptions_save) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder195 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder195.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder195.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder196 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder196.DisallowUnknownFields()\n\tvar h196 SaveOptions\n\tif err := decoder196.Decode(&h196); err == nil {\n\t\tt.Value = h196\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [SaveOptions bool]\"}\n}\n\nfunc (t Or_WorkspaceDocumentDiagnosticReport) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase WorkspaceFullDocumentDiagnosticReport:\n\t\treturn json.Marshal(x)\n\tcase WorkspaceUnchangedDocumentDiagnosticReport:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [WorkspaceFullDocumentDiagnosticReport WorkspaceUnchangedDocumentDiagnosticReport]\", t)\n}\n\nfunc (t *Or_WorkspaceDocumentDiagnosticReport) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder259 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder259.DisallowUnknownFields()\n\tvar h259 WorkspaceFullDocumentDiagnosticReport\n\tif err := decoder259.Decode(&h259); err == nil {\n\t\tt.Value = h259\n\t\treturn nil\n\t}\n\tdecoder260 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder260.DisallowUnknownFields()\n\tvar h260 WorkspaceUnchangedDocumentDiagnosticReport\n\tif err := decoder260.Decode(&h260); err == nil {\n\t\tt.Value = h260\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [WorkspaceFullDocumentDiagnosticReport WorkspaceUnchangedDocumentDiagnosticReport]\"}\n}\n\nfunc (t Or_WorkspaceEdit_documentChanges_Elem) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase CreateFile:\n\t\treturn json.Marshal(x)\n\tcase DeleteFile:\n\t\treturn json.Marshal(x)\n\tcase RenameFile:\n\t\treturn json.Marshal(x)\n\tcase TextDocumentEdit:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [CreateFile DeleteFile RenameFile TextDocumentEdit]\", t)\n}\n\nfunc (t *Or_WorkspaceEdit_documentChanges_Elem) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder4 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder4.DisallowUnknownFields()\n\tvar h4 CreateFile\n\tif err := decoder4.Decode(&h4); err == nil {\n\t\tt.Value = h4\n\t\treturn nil\n\t}\n\tdecoder5 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder5.DisallowUnknownFields()\n\tvar h5 DeleteFile\n\tif err := decoder5.Decode(&h5); err == nil {\n\t\tt.Value = h5\n\t\treturn nil\n\t}\n\tdecoder6 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder6.DisallowUnknownFields()\n\tvar h6 RenameFile\n\tif err := decoder6.Decode(&h6); err == nil {\n\t\tt.Value = h6\n\t\treturn nil\n\t}\n\tdecoder7 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder7.DisallowUnknownFields()\n\tvar h7 TextDocumentEdit\n\tif err := decoder7.Decode(&h7); err == nil {\n\t\tt.Value = h7\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [CreateFile DeleteFile RenameFile TextDocumentEdit]\"}\n}\n\nfunc (t Or_WorkspaceFoldersServerCapabilities_changeNotifications) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase string:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [bool string]\", t)\n}\n\nfunc (t *Or_WorkspaceFoldersServerCapabilities_changeNotifications) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder210 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder210.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder210.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder211 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder211.DisallowUnknownFields()\n\tvar stringVal string\n\tif err := decoder211.Decode(&stringVal); err == nil {\n\t\tt.Value = stringVal\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [bool string]\"}\n}\n\nfunc (t Or_WorkspaceOptions_textDocumentContent) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase TextDocumentContentOptions:\n\t\treturn json.Marshal(x)\n\tcase TextDocumentContentRegistrationOptions:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [TextDocumentContentOptions TextDocumentContentRegistrationOptions]\", t)\n}\n\nfunc (t *Or_WorkspaceOptions_textDocumentContent) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder199 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder199.DisallowUnknownFields()\n\tvar h199 TextDocumentContentOptions\n\tif err := decoder199.Decode(&h199); err == nil {\n\t\tt.Value = h199\n\t\treturn nil\n\t}\n\tdecoder200 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder200.DisallowUnknownFields()\n\tvar h200 TextDocumentContentRegistrationOptions\n\tif err := decoder200.Decode(&h200); err == nil {\n\t\tt.Value = h200\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [TextDocumentContentOptions TextDocumentContentRegistrationOptions]\"}\n}\n\nfunc (t Or_WorkspaceSymbol_location) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase Location:\n\t\treturn json.Marshal(x)\n\tcase LocationUriOnly:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [Location LocationUriOnly]\", t)\n}\n\nfunc (t *Or_WorkspaceSymbol_location) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder39 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder39.DisallowUnknownFields()\n\tvar h39 Location\n\tif err := decoder39.Decode(&h39); err == nil {\n\t\tt.Value = h39\n\t\treturn nil\n\t}\n\tdecoder40 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder40.DisallowUnknownFields()\n\tvar h40 LocationUriOnly\n\tif err := decoder40.Decode(&h40); err == nil {\n\t\tt.Value = h40\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [Location LocationUriOnly]\"}\n}\n"], ["/opencode/internal/tui/util/util.go", "package util\n\nimport (\n\t\"time\"\n\n\ttea \"github.com/charmbracelet/bubbletea\"\n)\n\nfunc CmdHandler(msg tea.Msg) tea.Cmd {\n\treturn func() tea.Msg {\n\t\treturn msg\n\t}\n}\n\nfunc ReportError(err error) tea.Cmd {\n\treturn CmdHandler(InfoMsg{\n\t\tType: InfoTypeError,\n\t\tMsg: err.Error(),\n\t})\n}\n\ntype InfoType int\n\nconst (\n\tInfoTypeInfo InfoType = iota\n\tInfoTypeWarn\n\tInfoTypeError\n)\n\nfunc ReportInfo(info string) tea.Cmd {\n\treturn CmdHandler(InfoMsg{\n\t\tType: InfoTypeInfo,\n\t\tMsg: info,\n\t})\n}\n\nfunc ReportWarn(warn string) tea.Cmd {\n\treturn CmdHandler(InfoMsg{\n\t\tType: InfoTypeWarn,\n\t\tMsg: warn,\n\t})\n}\n\ntype (\n\tInfoMsg struct {\n\t\tType InfoType\n\t\tMsg string\n\t\tTTL time.Duration\n\t}\n\tClearStatusMsg struct{}\n)\n\nfunc Clamp(v, low, high int) int {\n\tif high < low {\n\t\tlow, high = high, low\n\t}\n\treturn min(high, max(low, v))\n}\n"], ["/opencode/internal/lsp/methods.go", "// Generated code. Do not edit\npackage lsp\n\nimport (\n\t\"context\"\n\n\t\"github.com/opencode-ai/opencode/internal/lsp/protocol\"\n)\n\n// Implementation sends a textDocument/implementation request to the LSP server.\n// A request to resolve the implementation locations of a symbol at a given text document position. The request's parameter is of type TextDocumentPositionParams the response is of type Definition or a Thenable that resolves to such.\nfunc (c *Client) Implementation(ctx context.Context, params protocol.ImplementationParams) (protocol.Or_Result_textDocument_implementation, error) {\n\tvar result protocol.Or_Result_textDocument_implementation\n\terr := c.Call(ctx, \"textDocument/implementation\", params, &result)\n\treturn result, err\n}\n\n// TypeDefinition sends a textDocument/typeDefinition request to the LSP server.\n// A request to resolve the type definition locations of a symbol at a given text document position. The request's parameter is of type TextDocumentPositionParams the response is of type Definition or a Thenable that resolves to such.\nfunc (c *Client) TypeDefinition(ctx context.Context, params protocol.TypeDefinitionParams) (protocol.Or_Result_textDocument_typeDefinition, error) {\n\tvar result protocol.Or_Result_textDocument_typeDefinition\n\terr := c.Call(ctx, \"textDocument/typeDefinition\", params, &result)\n\treturn result, err\n}\n\n// DocumentColor sends a textDocument/documentColor request to the LSP server.\n// A request to list all color symbols found in a given text document. The request's parameter is of type DocumentColorParams the response is of type ColorInformation ColorInformation[] or a Thenable that resolves to such.\nfunc (c *Client) DocumentColor(ctx context.Context, params protocol.DocumentColorParams) ([]protocol.ColorInformation, error) {\n\tvar result []protocol.ColorInformation\n\terr := c.Call(ctx, \"textDocument/documentColor\", params, &result)\n\treturn result, err\n}\n\n// ColorPresentation sends a textDocument/colorPresentation request to the LSP server.\n// A request to list all presentation for a color. The request's parameter is of type ColorPresentationParams the response is of type ColorInformation ColorInformation[] or a Thenable that resolves to such.\nfunc (c *Client) ColorPresentation(ctx context.Context, params protocol.ColorPresentationParams) ([]protocol.ColorPresentation, error) {\n\tvar result []protocol.ColorPresentation\n\terr := c.Call(ctx, \"textDocument/colorPresentation\", params, &result)\n\treturn result, err\n}\n\n// FoldingRange sends a textDocument/foldingRange request to the LSP server.\n// A request to provide folding ranges in a document. The request's parameter is of type FoldingRangeParams, the response is of type FoldingRangeList or a Thenable that resolves to such.\nfunc (c *Client) FoldingRange(ctx context.Context, params protocol.FoldingRangeParams) ([]protocol.FoldingRange, error) {\n\tvar result []protocol.FoldingRange\n\terr := c.Call(ctx, \"textDocument/foldingRange\", params, &result)\n\treturn result, err\n}\n\n// Declaration sends a textDocument/declaration request to the LSP server.\n// A request to resolve the type definition locations of a symbol at a given text document position. The request's parameter is of type TextDocumentPositionParams the response is of type Declaration or a typed array of DeclarationLink or a Thenable that resolves to such.\nfunc (c *Client) Declaration(ctx context.Context, params protocol.DeclarationParams) (protocol.Or_Result_textDocument_declaration, error) {\n\tvar result protocol.Or_Result_textDocument_declaration\n\terr := c.Call(ctx, \"textDocument/declaration\", params, &result)\n\treturn result, err\n}\n\n// SelectionRange sends a textDocument/selectionRange request to the LSP server.\n// A request to provide selection ranges in a document. The request's parameter is of type SelectionRangeParams, the response is of type SelectionRange SelectionRange[] or a Thenable that resolves to such.\nfunc (c *Client) SelectionRange(ctx context.Context, params protocol.SelectionRangeParams) ([]protocol.SelectionRange, error) {\n\tvar result []protocol.SelectionRange\n\terr := c.Call(ctx, \"textDocument/selectionRange\", params, &result)\n\treturn result, err\n}\n\n// PrepareCallHierarchy sends a textDocument/prepareCallHierarchy request to the LSP server.\n// A request to result a CallHierarchyItem in a document at a given position. Can be used as an input to an incoming or outgoing call hierarchy. Since 3.16.0\nfunc (c *Client) PrepareCallHierarchy(ctx context.Context, params protocol.CallHierarchyPrepareParams) ([]protocol.CallHierarchyItem, error) {\n\tvar result []protocol.CallHierarchyItem\n\terr := c.Call(ctx, \"textDocument/prepareCallHierarchy\", params, &result)\n\treturn result, err\n}\n\n// IncomingCalls sends a callHierarchy/incomingCalls request to the LSP server.\n// A request to resolve the incoming calls for a given CallHierarchyItem. Since 3.16.0\nfunc (c *Client) IncomingCalls(ctx context.Context, params protocol.CallHierarchyIncomingCallsParams) ([]protocol.CallHierarchyIncomingCall, error) {\n\tvar result []protocol.CallHierarchyIncomingCall\n\terr := c.Call(ctx, \"callHierarchy/incomingCalls\", params, &result)\n\treturn result, err\n}\n\n// OutgoingCalls sends a callHierarchy/outgoingCalls request to the LSP server.\n// A request to resolve the outgoing calls for a given CallHierarchyItem. Since 3.16.0\nfunc (c *Client) OutgoingCalls(ctx context.Context, params protocol.CallHierarchyOutgoingCallsParams) ([]protocol.CallHierarchyOutgoingCall, error) {\n\tvar result []protocol.CallHierarchyOutgoingCall\n\terr := c.Call(ctx, \"callHierarchy/outgoingCalls\", params, &result)\n\treturn result, err\n}\n\n// SemanticTokensFull sends a textDocument/semanticTokens/full request to the LSP server.\n// Since 3.16.0\nfunc (c *Client) SemanticTokensFull(ctx context.Context, params protocol.SemanticTokensParams) (protocol.SemanticTokens, error) {\n\tvar result protocol.SemanticTokens\n\terr := c.Call(ctx, \"textDocument/semanticTokens/full\", params, &result)\n\treturn result, err\n}\n\n// SemanticTokensFullDelta sends a textDocument/semanticTokens/full/delta request to the LSP server.\n// Since 3.16.0\nfunc (c *Client) SemanticTokensFullDelta(ctx context.Context, params protocol.SemanticTokensDeltaParams) (protocol.Or_Result_textDocument_semanticTokens_full_delta, error) {\n\tvar result protocol.Or_Result_textDocument_semanticTokens_full_delta\n\terr := c.Call(ctx, \"textDocument/semanticTokens/full/delta\", params, &result)\n\treturn result, err\n}\n\n// SemanticTokensRange sends a textDocument/semanticTokens/range request to the LSP server.\n// Since 3.16.0\nfunc (c *Client) SemanticTokensRange(ctx context.Context, params protocol.SemanticTokensRangeParams) (protocol.SemanticTokens, error) {\n\tvar result protocol.SemanticTokens\n\terr := c.Call(ctx, \"textDocument/semanticTokens/range\", params, &result)\n\treturn result, err\n}\n\n// LinkedEditingRange sends a textDocument/linkedEditingRange request to the LSP server.\n// A request to provide ranges that can be edited together. Since 3.16.0\nfunc (c *Client) LinkedEditingRange(ctx context.Context, params protocol.LinkedEditingRangeParams) (protocol.LinkedEditingRanges, error) {\n\tvar result protocol.LinkedEditingRanges\n\terr := c.Call(ctx, \"textDocument/linkedEditingRange\", params, &result)\n\treturn result, err\n}\n\n// WillCreateFiles sends a workspace/willCreateFiles request to the LSP server.\n// The will create files request is sent from the client to the server before files are actually created as long as the creation is triggered from within the client. The request can return a WorkspaceEdit which will be applied to workspace before the files are created. Hence the WorkspaceEdit can not manipulate the content of the file to be created. Since 3.16.0\nfunc (c *Client) WillCreateFiles(ctx context.Context, params protocol.CreateFilesParams) (protocol.WorkspaceEdit, error) {\n\tvar result protocol.WorkspaceEdit\n\terr := c.Call(ctx, \"workspace/willCreateFiles\", params, &result)\n\treturn result, err\n}\n\n// WillRenameFiles sends a workspace/willRenameFiles request to the LSP server.\n// The will rename files request is sent from the client to the server before files are actually renamed as long as the rename is triggered from within the client. Since 3.16.0\nfunc (c *Client) WillRenameFiles(ctx context.Context, params protocol.RenameFilesParams) (protocol.WorkspaceEdit, error) {\n\tvar result protocol.WorkspaceEdit\n\terr := c.Call(ctx, \"workspace/willRenameFiles\", params, &result)\n\treturn result, err\n}\n\n// WillDeleteFiles sends a workspace/willDeleteFiles request to the LSP server.\n// The did delete files notification is sent from the client to the server when files were deleted from within the client. Since 3.16.0\nfunc (c *Client) WillDeleteFiles(ctx context.Context, params protocol.DeleteFilesParams) (protocol.WorkspaceEdit, error) {\n\tvar result protocol.WorkspaceEdit\n\terr := c.Call(ctx, \"workspace/willDeleteFiles\", params, &result)\n\treturn result, err\n}\n\n// Moniker sends a textDocument/moniker request to the LSP server.\n// A request to get the moniker of a symbol at a given text document position. The request parameter is of type TextDocumentPositionParams. The response is of type Moniker Moniker[] or null.\nfunc (c *Client) Moniker(ctx context.Context, params protocol.MonikerParams) ([]protocol.Moniker, error) {\n\tvar result []protocol.Moniker\n\terr := c.Call(ctx, \"textDocument/moniker\", params, &result)\n\treturn result, err\n}\n\n// PrepareTypeHierarchy sends a textDocument/prepareTypeHierarchy request to the LSP server.\n// A request to result a TypeHierarchyItem in a document at a given position. Can be used as an input to a subtypes or supertypes type hierarchy. Since 3.17.0\nfunc (c *Client) PrepareTypeHierarchy(ctx context.Context, params protocol.TypeHierarchyPrepareParams) ([]protocol.TypeHierarchyItem, error) {\n\tvar result []protocol.TypeHierarchyItem\n\terr := c.Call(ctx, \"textDocument/prepareTypeHierarchy\", params, &result)\n\treturn result, err\n}\n\n// Supertypes sends a typeHierarchy/supertypes request to the LSP server.\n// A request to resolve the supertypes for a given TypeHierarchyItem. Since 3.17.0\nfunc (c *Client) Supertypes(ctx context.Context, params protocol.TypeHierarchySupertypesParams) ([]protocol.TypeHierarchyItem, error) {\n\tvar result []protocol.TypeHierarchyItem\n\terr := c.Call(ctx, \"typeHierarchy/supertypes\", params, &result)\n\treturn result, err\n}\n\n// Subtypes sends a typeHierarchy/subtypes request to the LSP server.\n// A request to resolve the subtypes for a given TypeHierarchyItem. Since 3.17.0\nfunc (c *Client) Subtypes(ctx context.Context, params protocol.TypeHierarchySubtypesParams) ([]protocol.TypeHierarchyItem, error) {\n\tvar result []protocol.TypeHierarchyItem\n\terr := c.Call(ctx, \"typeHierarchy/subtypes\", params, &result)\n\treturn result, err\n}\n\n// InlineValue sends a textDocument/inlineValue request to the LSP server.\n// A request to provide inline values in a document. The request's parameter is of type InlineValueParams, the response is of type InlineValue InlineValue[] or a Thenable that resolves to such. Since 3.17.0\nfunc (c *Client) InlineValue(ctx context.Context, params protocol.InlineValueParams) ([]protocol.InlineValue, error) {\n\tvar result []protocol.InlineValue\n\terr := c.Call(ctx, \"textDocument/inlineValue\", params, &result)\n\treturn result, err\n}\n\n// InlayHint sends a textDocument/inlayHint request to the LSP server.\n// A request to provide inlay hints in a document. The request's parameter is of type InlayHintsParams, the response is of type InlayHint InlayHint[] or a Thenable that resolves to such. Since 3.17.0\nfunc (c *Client) InlayHint(ctx context.Context, params protocol.InlayHintParams) ([]protocol.InlayHint, error) {\n\tvar result []protocol.InlayHint\n\terr := c.Call(ctx, \"textDocument/inlayHint\", params, &result)\n\treturn result, err\n}\n\n// Resolve sends a inlayHint/resolve request to the LSP server.\n// A request to resolve additional properties for an inlay hint. The request's parameter is of type InlayHint, the response is of type InlayHint or a Thenable that resolves to such. Since 3.17.0\nfunc (c *Client) Resolve(ctx context.Context, params protocol.InlayHint) (protocol.InlayHint, error) {\n\tvar result protocol.InlayHint\n\terr := c.Call(ctx, \"inlayHint/resolve\", params, &result)\n\treturn result, err\n}\n\n// Diagnostic sends a textDocument/diagnostic request to the LSP server.\n// The document diagnostic request definition. Since 3.17.0\nfunc (c *Client) Diagnostic(ctx context.Context, params protocol.DocumentDiagnosticParams) (protocol.DocumentDiagnosticReport, error) {\n\tvar result protocol.DocumentDiagnosticReport\n\terr := c.Call(ctx, \"textDocument/diagnostic\", params, &result)\n\treturn result, err\n}\n\n// DiagnosticWorkspace sends a workspace/diagnostic request to the LSP server.\n// The workspace diagnostic request definition. Since 3.17.0\nfunc (c *Client) DiagnosticWorkspace(ctx context.Context, params protocol.WorkspaceDiagnosticParams) (protocol.WorkspaceDiagnosticReport, error) {\n\tvar result protocol.WorkspaceDiagnosticReport\n\terr := c.Call(ctx, \"workspace/diagnostic\", params, &result)\n\treturn result, err\n}\n\n// InlineCompletion sends a textDocument/inlineCompletion request to the LSP server.\n// A request to provide inline completions in a document. The request's parameter is of type InlineCompletionParams, the response is of type InlineCompletion InlineCompletion[] or a Thenable that resolves to such. Since 3.18.0 PROPOSED\nfunc (c *Client) InlineCompletion(ctx context.Context, params protocol.InlineCompletionParams) (protocol.Or_Result_textDocument_inlineCompletion, error) {\n\tvar result protocol.Or_Result_textDocument_inlineCompletion\n\terr := c.Call(ctx, \"textDocument/inlineCompletion\", params, &result)\n\treturn result, err\n}\n\n// TextDocumentContent sends a workspace/textDocumentContent request to the LSP server.\n// The workspace/textDocumentContent request is sent from the client to the server to request the content of a text document. Since 3.18.0 PROPOSED\nfunc (c *Client) TextDocumentContent(ctx context.Context, params protocol.TextDocumentContentParams) (string, error) {\n\tvar result string\n\terr := c.Call(ctx, \"workspace/textDocumentContent\", params, &result)\n\treturn result, err\n}\n\n// Initialize sends a initialize request to the LSP server.\n// The initialize request is sent from the client to the server. It is sent once as the request after starting up the server. The requests parameter is of type InitializeParams the response if of type InitializeResult of a Thenable that resolves to such.\nfunc (c *Client) Initialize(ctx context.Context, params protocol.ParamInitialize) (protocol.InitializeResult, error) {\n\tvar result protocol.InitializeResult\n\terr := c.Call(ctx, \"initialize\", params, &result)\n\treturn result, err\n}\n\n// Shutdown sends a shutdown request to the LSP server.\n// A shutdown request is sent from the client to the server. It is sent once when the client decides to shutdown the server. The only notification that is sent after a shutdown request is the exit event.\nfunc (c *Client) Shutdown(ctx context.Context) error {\n\treturn c.Call(ctx, \"shutdown\", nil, nil)\n}\n\n// WillSaveWaitUntil sends a textDocument/willSaveWaitUntil request to the LSP server.\n// A document will save request is sent from the client to the server before the document is actually saved. The request can return an array of TextEdits which will be applied to the text document before it is saved. Please note that clients might drop results if computing the text edits took too long or if a server constantly fails on this request. This is done to keep the save fast and reliable.\nfunc (c *Client) WillSaveWaitUntil(ctx context.Context, params protocol.WillSaveTextDocumentParams) ([]protocol.TextEdit, error) {\n\tvar result []protocol.TextEdit\n\terr := c.Call(ctx, \"textDocument/willSaveWaitUntil\", params, &result)\n\treturn result, err\n}\n\n// Completion sends a textDocument/completion request to the LSP server.\n// Request to request completion at a given text document position. The request's parameter is of type TextDocumentPosition the response is of type CompletionItem CompletionItem[] or CompletionList or a Thenable that resolves to such. The request can delay the computation of the CompletionItem.detail detail and CompletionItem.documentation documentation properties to the completionItem/resolve request. However, properties that are needed for the initial sorting and filtering, like sortText, filterText, insertText, and textEdit, must not be changed during resolve.\nfunc (c *Client) Completion(ctx context.Context, params protocol.CompletionParams) (protocol.Or_Result_textDocument_completion, error) {\n\tvar result protocol.Or_Result_textDocument_completion\n\terr := c.Call(ctx, \"textDocument/completion\", params, &result)\n\treturn result, err\n}\n\n// ResolveCompletionItem sends a completionItem/resolve request to the LSP server.\n// Request to resolve additional information for a given completion item.The request's parameter is of type CompletionItem the response is of type CompletionItem or a Thenable that resolves to such.\nfunc (c *Client) ResolveCompletionItem(ctx context.Context, params protocol.CompletionItem) (protocol.CompletionItem, error) {\n\tvar result protocol.CompletionItem\n\terr := c.Call(ctx, \"completionItem/resolve\", params, &result)\n\treturn result, err\n}\n\n// Hover sends a textDocument/hover request to the LSP server.\n// Request to request hover information at a given text document position. The request's parameter is of type TextDocumentPosition the response is of type Hover or a Thenable that resolves to such.\nfunc (c *Client) Hover(ctx context.Context, params protocol.HoverParams) (protocol.Hover, error) {\n\tvar result protocol.Hover\n\terr := c.Call(ctx, \"textDocument/hover\", params, &result)\n\treturn result, err\n}\n\n// SignatureHelp sends a textDocument/signatureHelp request to the LSP server.\nfunc (c *Client) SignatureHelp(ctx context.Context, params protocol.SignatureHelpParams) (protocol.SignatureHelp, error) {\n\tvar result protocol.SignatureHelp\n\terr := c.Call(ctx, \"textDocument/signatureHelp\", params, &result)\n\treturn result, err\n}\n\n// Definition sends a textDocument/definition request to the LSP server.\n// A request to resolve the definition location of a symbol at a given text document position. The request's parameter is of type TextDocumentPosition the response is of either type Definition or a typed array of DefinitionLink or a Thenable that resolves to such.\nfunc (c *Client) Definition(ctx context.Context, params protocol.DefinitionParams) (protocol.Or_Result_textDocument_definition, error) {\n\tvar result protocol.Or_Result_textDocument_definition\n\terr := c.Call(ctx, \"textDocument/definition\", params, &result)\n\treturn result, err\n}\n\n// References sends a textDocument/references request to the LSP server.\n// A request to resolve project-wide references for the symbol denoted by the given text document position. The request's parameter is of type ReferenceParams the response is of type Location Location[] or a Thenable that resolves to such.\nfunc (c *Client) References(ctx context.Context, params protocol.ReferenceParams) ([]protocol.Location, error) {\n\tvar result []protocol.Location\n\terr := c.Call(ctx, \"textDocument/references\", params, &result)\n\treturn result, err\n}\n\n// DocumentHighlight sends a textDocument/documentHighlight request to the LSP server.\n// Request to resolve a DocumentHighlight for a given text document position. The request's parameter is of type TextDocumentPosition the request response is an array of type DocumentHighlight or a Thenable that resolves to such.\nfunc (c *Client) DocumentHighlight(ctx context.Context, params protocol.DocumentHighlightParams) ([]protocol.DocumentHighlight, error) {\n\tvar result []protocol.DocumentHighlight\n\terr := c.Call(ctx, \"textDocument/documentHighlight\", params, &result)\n\treturn result, err\n}\n\n// DocumentSymbol sends a textDocument/documentSymbol request to the LSP server.\n// A request to list all symbols found in a given text document. The request's parameter is of type TextDocumentIdentifier the response is of type SymbolInformation SymbolInformation[] or a Thenable that resolves to such.\nfunc (c *Client) DocumentSymbol(ctx context.Context, params protocol.DocumentSymbolParams) (protocol.Or_Result_textDocument_documentSymbol, error) {\n\tvar result protocol.Or_Result_textDocument_documentSymbol\n\terr := c.Call(ctx, \"textDocument/documentSymbol\", params, &result)\n\treturn result, err\n}\n\n// CodeAction sends a textDocument/codeAction request to the LSP server.\n// A request to provide commands for the given text document and range.\nfunc (c *Client) CodeAction(ctx context.Context, params protocol.CodeActionParams) ([]protocol.Or_Result_textDocument_codeAction_Item0_Elem, error) {\n\tvar result []protocol.Or_Result_textDocument_codeAction_Item0_Elem\n\terr := c.Call(ctx, \"textDocument/codeAction\", params, &result)\n\treturn result, err\n}\n\n// ResolveCodeAction sends a codeAction/resolve request to the LSP server.\n// Request to resolve additional information for a given code action.The request's parameter is of type CodeAction the response is of type CodeAction or a Thenable that resolves to such.\nfunc (c *Client) ResolveCodeAction(ctx context.Context, params protocol.CodeAction) (protocol.CodeAction, error) {\n\tvar result protocol.CodeAction\n\terr := c.Call(ctx, \"codeAction/resolve\", params, &result)\n\treturn result, err\n}\n\n// Symbol sends a workspace/symbol request to the LSP server.\n// A request to list project-wide symbols matching the query string given by the WorkspaceSymbolParams. The response is of type SymbolInformation SymbolInformation[] or a Thenable that resolves to such. Since 3.17.0 - support for WorkspaceSymbol in the returned data. Clients need to advertise support for WorkspaceSymbols via the client capability workspace.symbol.resolveSupport.\nfunc (c *Client) Symbol(ctx context.Context, params protocol.WorkspaceSymbolParams) (protocol.Or_Result_workspace_symbol, error) {\n\tvar result protocol.Or_Result_workspace_symbol\n\terr := c.Call(ctx, \"workspace/symbol\", params, &result)\n\treturn result, err\n}\n\n// ResolveWorkspaceSymbol sends a workspaceSymbol/resolve request to the LSP server.\n// A request to resolve the range inside the workspace symbol's location. Since 3.17.0\nfunc (c *Client) ResolveWorkspaceSymbol(ctx context.Context, params protocol.WorkspaceSymbol) (protocol.WorkspaceSymbol, error) {\n\tvar result protocol.WorkspaceSymbol\n\terr := c.Call(ctx, \"workspaceSymbol/resolve\", params, &result)\n\treturn result, err\n}\n\n// CodeLens sends a textDocument/codeLens request to the LSP server.\n// A request to provide code lens for the given text document.\nfunc (c *Client) CodeLens(ctx context.Context, params protocol.CodeLensParams) ([]protocol.CodeLens, error) {\n\tvar result []protocol.CodeLens\n\terr := c.Call(ctx, \"textDocument/codeLens\", params, &result)\n\treturn result, err\n}\n\n// ResolveCodeLens sends a codeLens/resolve request to the LSP server.\n// A request to resolve a command for a given code lens.\nfunc (c *Client) ResolveCodeLens(ctx context.Context, params protocol.CodeLens) (protocol.CodeLens, error) {\n\tvar result protocol.CodeLens\n\terr := c.Call(ctx, \"codeLens/resolve\", params, &result)\n\treturn result, err\n}\n\n// DocumentLink sends a textDocument/documentLink request to the LSP server.\n// A request to provide document links\nfunc (c *Client) DocumentLink(ctx context.Context, params protocol.DocumentLinkParams) ([]protocol.DocumentLink, error) {\n\tvar result []protocol.DocumentLink\n\terr := c.Call(ctx, \"textDocument/documentLink\", params, &result)\n\treturn result, err\n}\n\n// ResolveDocumentLink sends a documentLink/resolve request to the LSP server.\n// Request to resolve additional information for a given document link. The request's parameter is of type DocumentLink the response is of type DocumentLink or a Thenable that resolves to such.\nfunc (c *Client) ResolveDocumentLink(ctx context.Context, params protocol.DocumentLink) (protocol.DocumentLink, error) {\n\tvar result protocol.DocumentLink\n\terr := c.Call(ctx, \"documentLink/resolve\", params, &result)\n\treturn result, err\n}\n\n// Formatting sends a textDocument/formatting request to the LSP server.\n// A request to format a whole document.\nfunc (c *Client) Formatting(ctx context.Context, params protocol.DocumentFormattingParams) ([]protocol.TextEdit, error) {\n\tvar result []protocol.TextEdit\n\terr := c.Call(ctx, \"textDocument/formatting\", params, &result)\n\treturn result, err\n}\n\n// RangeFormatting sends a textDocument/rangeFormatting request to the LSP server.\n// A request to format a range in a document.\nfunc (c *Client) RangeFormatting(ctx context.Context, params protocol.DocumentRangeFormattingParams) ([]protocol.TextEdit, error) {\n\tvar result []protocol.TextEdit\n\terr := c.Call(ctx, \"textDocument/rangeFormatting\", params, &result)\n\treturn result, err\n}\n\n// RangesFormatting sends a textDocument/rangesFormatting request to the LSP server.\n// A request to format ranges in a document. Since 3.18.0 PROPOSED\nfunc (c *Client) RangesFormatting(ctx context.Context, params protocol.DocumentRangesFormattingParams) ([]protocol.TextEdit, error) {\n\tvar result []protocol.TextEdit\n\terr := c.Call(ctx, \"textDocument/rangesFormatting\", params, &result)\n\treturn result, err\n}\n\n// OnTypeFormatting sends a textDocument/onTypeFormatting request to the LSP server.\n// A request to format a document on type.\nfunc (c *Client) OnTypeFormatting(ctx context.Context, params protocol.DocumentOnTypeFormattingParams) ([]protocol.TextEdit, error) {\n\tvar result []protocol.TextEdit\n\terr := c.Call(ctx, \"textDocument/onTypeFormatting\", params, &result)\n\treturn result, err\n}\n\n// Rename sends a textDocument/rename request to the LSP server.\n// A request to rename a symbol.\nfunc (c *Client) Rename(ctx context.Context, params protocol.RenameParams) (protocol.WorkspaceEdit, error) {\n\tvar result protocol.WorkspaceEdit\n\terr := c.Call(ctx, \"textDocument/rename\", params, &result)\n\treturn result, err\n}\n\n// PrepareRename sends a textDocument/prepareRename request to the LSP server.\n// A request to test and perform the setup necessary for a rename. Since 3.16 - support for default behavior\nfunc (c *Client) PrepareRename(ctx context.Context, params protocol.PrepareRenameParams) (protocol.PrepareRenameResult, error) {\n\tvar result protocol.PrepareRenameResult\n\terr := c.Call(ctx, \"textDocument/prepareRename\", params, &result)\n\treturn result, err\n}\n\n// ExecuteCommand sends a workspace/executeCommand request to the LSP server.\n// A request send from the client to the server to execute a command. The request might return a workspace edit which the client will apply to the workspace.\nfunc (c *Client) ExecuteCommand(ctx context.Context, params protocol.ExecuteCommandParams) (any, error) {\n\tvar result any\n\terr := c.Call(ctx, \"workspace/executeCommand\", params, &result)\n\treturn result, err\n}\n\n// DidChangeWorkspaceFolders sends a workspace/didChangeWorkspaceFolders notification to the LSP server.\n// The workspace/didChangeWorkspaceFolders notification is sent from the client to the server when the workspace folder configuration changes.\nfunc (c *Client) DidChangeWorkspaceFolders(ctx context.Context, params protocol.DidChangeWorkspaceFoldersParams) error {\n\treturn c.Notify(ctx, \"workspace/didChangeWorkspaceFolders\", params)\n}\n\n// WorkDoneProgressCancel sends a window/workDoneProgress/cancel notification to the LSP server.\n// The window/workDoneProgress/cancel notification is sent from the client to the server to cancel a progress initiated on the server side.\nfunc (c *Client) WorkDoneProgressCancel(ctx context.Context, params protocol.WorkDoneProgressCancelParams) error {\n\treturn c.Notify(ctx, \"window/workDoneProgress/cancel\", params)\n}\n\n// DidCreateFiles sends a workspace/didCreateFiles notification to the LSP server.\n// The did create files notification is sent from the client to the server when files were created from within the client. Since 3.16.0\nfunc (c *Client) DidCreateFiles(ctx context.Context, params protocol.CreateFilesParams) error {\n\treturn c.Notify(ctx, \"workspace/didCreateFiles\", params)\n}\n\n// DidRenameFiles sends a workspace/didRenameFiles notification to the LSP server.\n// The did rename files notification is sent from the client to the server when files were renamed from within the client. Since 3.16.0\nfunc (c *Client) DidRenameFiles(ctx context.Context, params protocol.RenameFilesParams) error {\n\treturn c.Notify(ctx, \"workspace/didRenameFiles\", params)\n}\n\n// DidDeleteFiles sends a workspace/didDeleteFiles notification to the LSP server.\n// The will delete files request is sent from the client to the server before files are actually deleted as long as the deletion is triggered from within the client. Since 3.16.0\nfunc (c *Client) DidDeleteFiles(ctx context.Context, params protocol.DeleteFilesParams) error {\n\treturn c.Notify(ctx, \"workspace/didDeleteFiles\", params)\n}\n\n// DidOpenNotebookDocument sends a notebookDocument/didOpen notification to the LSP server.\n// A notification sent when a notebook opens. Since 3.17.0\nfunc (c *Client) DidOpenNotebookDocument(ctx context.Context, params protocol.DidOpenNotebookDocumentParams) error {\n\treturn c.Notify(ctx, \"notebookDocument/didOpen\", params)\n}\n\n// DidChangeNotebookDocument sends a notebookDocument/didChange notification to the LSP server.\nfunc (c *Client) DidChangeNotebookDocument(ctx context.Context, params protocol.DidChangeNotebookDocumentParams) error {\n\treturn c.Notify(ctx, \"notebookDocument/didChange\", params)\n}\n\n// DidSaveNotebookDocument sends a notebookDocument/didSave notification to the LSP server.\n// A notification sent when a notebook document is saved. Since 3.17.0\nfunc (c *Client) DidSaveNotebookDocument(ctx context.Context, params protocol.DidSaveNotebookDocumentParams) error {\n\treturn c.Notify(ctx, \"notebookDocument/didSave\", params)\n}\n\n// DidCloseNotebookDocument sends a notebookDocument/didClose notification to the LSP server.\n// A notification sent when a notebook closes. Since 3.17.0\nfunc (c *Client) DidCloseNotebookDocument(ctx context.Context, params protocol.DidCloseNotebookDocumentParams) error {\n\treturn c.Notify(ctx, \"notebookDocument/didClose\", params)\n}\n\n// Initialized sends a initialized notification to the LSP server.\n// The initialized notification is sent from the client to the server after the client is fully initialized and the server is allowed to send requests from the server to the client.\nfunc (c *Client) Initialized(ctx context.Context, params protocol.InitializedParams) error {\n\treturn c.Notify(ctx, \"initialized\", params)\n}\n\n// Exit sends a exit notification to the LSP server.\n// The exit event is sent from the client to the server to ask the server to exit its process.\nfunc (c *Client) Exit(ctx context.Context) error {\n\treturn c.Notify(ctx, \"exit\", nil)\n}\n\n// DidChangeConfiguration sends a workspace/didChangeConfiguration notification to the LSP server.\n// The configuration change notification is sent from the client to the server when the client's configuration has changed. The notification contains the changed configuration as defined by the language client.\nfunc (c *Client) DidChangeConfiguration(ctx context.Context, params protocol.DidChangeConfigurationParams) error {\n\treturn c.Notify(ctx, \"workspace/didChangeConfiguration\", params)\n}\n\n// DidOpen sends a textDocument/didOpen notification to the LSP server.\n// The document open notification is sent from the client to the server to signal newly opened text documents. The document's truth is now managed by the client and the server must not try to read the document's truth using the document's uri. Open in this sense means it is managed by the client. It doesn't necessarily mean that its content is presented in an editor. An open notification must not be sent more than once without a corresponding close notification send before. This means open and close notification must be balanced and the max open count is one.\nfunc (c *Client) DidOpen(ctx context.Context, params protocol.DidOpenTextDocumentParams) error {\n\treturn c.Notify(ctx, \"textDocument/didOpen\", params)\n}\n\n// DidChange sends a textDocument/didChange notification to the LSP server.\n// The document change notification is sent from the client to the server to signal changes to a text document.\nfunc (c *Client) DidChange(ctx context.Context, params protocol.DidChangeTextDocumentParams) error {\n\treturn c.Notify(ctx, \"textDocument/didChange\", params)\n}\n\n// DidClose sends a textDocument/didClose notification to the LSP server.\n// The document close notification is sent from the client to the server when the document got closed in the client. The document's truth now exists where the document's uri points to (e.g. if the document's uri is a file uri the truth now exists on disk). As with the open notification the close notification is about managing the document's content. Receiving a close notification doesn't mean that the document was open in an editor before. A close notification requires a previous open notification to be sent.\nfunc (c *Client) DidClose(ctx context.Context, params protocol.DidCloseTextDocumentParams) error {\n\treturn c.Notify(ctx, \"textDocument/didClose\", params)\n}\n\n// DidSave sends a textDocument/didSave notification to the LSP server.\n// The document save notification is sent from the client to the server when the document got saved in the client.\nfunc (c *Client) DidSave(ctx context.Context, params protocol.DidSaveTextDocumentParams) error {\n\treturn c.Notify(ctx, \"textDocument/didSave\", params)\n}\n\n// WillSave sends a textDocument/willSave notification to the LSP server.\n// A document will save notification is sent from the client to the server before the document is actually saved.\nfunc (c *Client) WillSave(ctx context.Context, params protocol.WillSaveTextDocumentParams) error {\n\treturn c.Notify(ctx, \"textDocument/willSave\", params)\n}\n\n// DidChangeWatchedFiles sends a workspace/didChangeWatchedFiles notification to the LSP server.\n// The watched files notification is sent from the client to the server when the client detects changes to file watched by the language client.\nfunc (c *Client) DidChangeWatchedFiles(ctx context.Context, params protocol.DidChangeWatchedFilesParams) error {\n\treturn c.Notify(ctx, \"workspace/didChangeWatchedFiles\", params)\n}\n\n// SetTrace sends a $/setTrace notification to the LSP server.\nfunc (c *Client) SetTrace(ctx context.Context, params protocol.SetTraceParams) error {\n\treturn c.Notify(ctx, \"$/setTrace\", params)\n}\n\n// Progress sends a $/progress notification to the LSP server.\nfunc (c *Client) Progress(ctx context.Context, params protocol.ProgressParams) error {\n\treturn c.Notify(ctx, \"$/progress\", params)\n}\n"], ["/opencode/internal/tui/theme/flexoki.go", "package theme\n\nimport (\n\t\"github.com/charmbracelet/lipgloss\"\n)\n\n// Flexoki color palette constants\nconst (\n\t// Base colors\n\tflexokiPaper = \"#FFFCF0\" // Paper (lightest)\n\tflexokiBase50 = \"#F2F0E5\" // bg-2 (light)\n\tflexokiBase100 = \"#E6E4D9\" // ui (light)\n\tflexokiBase150 = \"#DAD8CE\" // ui-2 (light)\n\tflexokiBase200 = \"#CECDC3\" // ui-3 (light)\n\tflexokiBase300 = \"#B7B5AC\" // tx-3 (light)\n\tflexokiBase500 = \"#878580\" // tx-2 (light)\n\tflexokiBase600 = \"#6F6E69\" // tx (light)\n\tflexokiBase700 = \"#575653\" // tx-3 (dark)\n\tflexokiBase800 = \"#403E3C\" // ui-3 (dark)\n\tflexokiBase850 = \"#343331\" // ui-2 (dark)\n\tflexokiBase900 = \"#282726\" // ui (dark)\n\tflexokiBase950 = \"#1C1B1A\" // bg-2 (dark)\n\tflexokiBlack = \"#100F0F\" // bg (darkest)\n\n\t// Accent colors - Light theme (600)\n\tflexokiRed600 = \"#AF3029\"\n\tflexokiOrange600 = \"#BC5215\"\n\tflexokiYellow600 = \"#AD8301\"\n\tflexokiGreen600 = \"#66800B\"\n\tflexokiCyan600 = \"#24837B\"\n\tflexokiBlue600 = \"#205EA6\"\n\tflexokiPurple600 = \"#5E409D\"\n\tflexokiMagenta600 = \"#A02F6F\"\n\n\t// Accent colors - Dark theme (400)\n\tflexokiRed400 = \"#D14D41\"\n\tflexokiOrange400 = \"#DA702C\"\n\tflexokiYellow400 = \"#D0A215\"\n\tflexokiGreen400 = \"#879A39\"\n\tflexokiCyan400 = \"#3AA99F\"\n\tflexokiBlue400 = \"#4385BE\"\n\tflexokiPurple400 = \"#8B7EC8\"\n\tflexokiMagenta400 = \"#CE5D97\"\n)\n\n// FlexokiTheme implements the Theme interface with Flexoki colors.\n// It provides both dark and light variants.\ntype FlexokiTheme struct {\n\tBaseTheme\n}\n\n// NewFlexokiTheme creates a new instance of the Flexoki theme.\nfunc NewFlexokiTheme() *FlexokiTheme {\n\ttheme := &FlexokiTheme{}\n\n\t// Base colors\n\ttheme.PrimaryColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiBlue400,\n\t\tLight: flexokiBlue600,\n\t}\n\ttheme.SecondaryColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiPurple400,\n\t\tLight: flexokiPurple600,\n\t}\n\ttheme.AccentColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiOrange400,\n\t\tLight: flexokiOrange600,\n\t}\n\n\t// Status colors\n\ttheme.ErrorColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiRed400,\n\t\tLight: flexokiRed600,\n\t}\n\ttheme.WarningColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiYellow400,\n\t\tLight: flexokiYellow600,\n\t}\n\ttheme.SuccessColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiGreen400,\n\t\tLight: flexokiGreen600,\n\t}\n\ttheme.InfoColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiCyan400,\n\t\tLight: flexokiCyan600,\n\t}\n\n\t// Text colors\n\ttheme.TextColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiBase300,\n\t\tLight: flexokiBase600,\n\t}\n\ttheme.TextMutedColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiBase700,\n\t\tLight: flexokiBase500,\n\t}\n\ttheme.TextEmphasizedColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiYellow400,\n\t\tLight: flexokiYellow600,\n\t}\n\n\t// Background colors\n\ttheme.BackgroundColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiBlack,\n\t\tLight: flexokiPaper,\n\t}\n\ttheme.BackgroundSecondaryColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiBase950,\n\t\tLight: flexokiBase50,\n\t}\n\ttheme.BackgroundDarkerColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiBase900,\n\t\tLight: flexokiBase100,\n\t}\n\n\t// Border colors\n\ttheme.BorderNormalColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiBase900,\n\t\tLight: flexokiBase100,\n\t}\n\ttheme.BorderFocusedColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiBlue400,\n\t\tLight: flexokiBlue600,\n\t}\n\ttheme.BorderDimColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiBase850,\n\t\tLight: flexokiBase150,\n\t}\n\n\t// Diff view colors\n\ttheme.DiffAddedColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiGreen400,\n\t\tLight: flexokiGreen600,\n\t}\n\ttheme.DiffRemovedColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiRed400,\n\t\tLight: flexokiRed600,\n\t}\n\ttheme.DiffContextColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiBase700,\n\t\tLight: flexokiBase500,\n\t}\n\ttheme.DiffHunkHeaderColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiBase700,\n\t\tLight: flexokiBase500,\n\t}\n\ttheme.DiffHighlightAddedColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiGreen400,\n\t\tLight: flexokiGreen600,\n\t}\n\ttheme.DiffHighlightRemovedColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiRed400,\n\t\tLight: flexokiRed600,\n\t}\n\ttheme.DiffAddedBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#1D2419\", // Darker green background\n\t\tLight: \"#EFF2E2\", // Light green background\n\t}\n\ttheme.DiffRemovedBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#241919\", // Darker red background\n\t\tLight: \"#F2E2E2\", // Light red background\n\t}\n\ttheme.DiffContextBgColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiBlack,\n\t\tLight: flexokiPaper,\n\t}\n\ttheme.DiffLineNumberColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiBase700,\n\t\tLight: flexokiBase500,\n\t}\n\ttheme.DiffAddedLineNumberBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#1A2017\", // Slightly darker green\n\t\tLight: \"#E5EBD9\", // Light green\n\t}\n\ttheme.DiffRemovedLineNumberBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#201717\", // Slightly darker red\n\t\tLight: \"#EBD9D9\", // Light red\n\t}\n\n\t// Markdown colors\n\ttheme.MarkdownTextColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiBase300,\n\t\tLight: flexokiBase600,\n\t}\n\ttheme.MarkdownHeadingColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiYellow400,\n\t\tLight: flexokiYellow600,\n\t}\n\ttheme.MarkdownLinkColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiCyan400,\n\t\tLight: flexokiCyan600,\n\t}\n\ttheme.MarkdownLinkTextColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiMagenta400,\n\t\tLight: flexokiMagenta600,\n\t}\n\ttheme.MarkdownCodeColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiGreen400,\n\t\tLight: flexokiGreen600,\n\t}\n\ttheme.MarkdownBlockQuoteColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiCyan400,\n\t\tLight: flexokiCyan600,\n\t}\n\ttheme.MarkdownEmphColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiYellow400,\n\t\tLight: flexokiYellow600,\n\t}\n\ttheme.MarkdownStrongColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiOrange400,\n\t\tLight: flexokiOrange600,\n\t}\n\ttheme.MarkdownHorizontalRuleColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiBase800,\n\t\tLight: flexokiBase200,\n\t}\n\ttheme.MarkdownListItemColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiBlue400,\n\t\tLight: flexokiBlue600,\n\t}\n\ttheme.MarkdownListEnumerationColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiBlue400,\n\t\tLight: flexokiBlue600,\n\t}\n\ttheme.MarkdownImageColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiPurple400,\n\t\tLight: flexokiPurple600,\n\t}\n\ttheme.MarkdownImageTextColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiMagenta400,\n\t\tLight: flexokiMagenta600,\n\t}\n\ttheme.MarkdownCodeBlockColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiBase300,\n\t\tLight: flexokiBase600,\n\t}\n\n\t// Syntax highlighting colors (based on Flexoki's mappings)\n\ttheme.SyntaxCommentColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiBase700, // tx-3\n\t\tLight: flexokiBase300, // tx-3\n\t}\n\ttheme.SyntaxKeywordColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiGreen400, // gr\n\t\tLight: flexokiGreen600, // gr\n\t}\n\ttheme.SyntaxFunctionColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiOrange400, // or\n\t\tLight: flexokiOrange600, // or\n\t}\n\ttheme.SyntaxVariableColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiBlue400, // bl\n\t\tLight: flexokiBlue600, // bl\n\t}\n\ttheme.SyntaxStringColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiCyan400, // cy\n\t\tLight: flexokiCyan600, // cy\n\t}\n\ttheme.SyntaxNumberColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiPurple400, // pu\n\t\tLight: flexokiPurple600, // pu\n\t}\n\ttheme.SyntaxTypeColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiYellow400, // ye\n\t\tLight: flexokiYellow600, // ye\n\t}\n\ttheme.SyntaxOperatorColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiBase500, // tx-2\n\t\tLight: flexokiBase500, // tx-2\n\t}\n\ttheme.SyntaxPunctuationColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiBase500, // tx-2\n\t\tLight: flexokiBase500, // tx-2\n\t}\n\n\treturn theme\n}\n\nfunc init() {\n\t// Register the Flexoki theme with the theme manager\n\tRegisterTheme(\"flexoki\", NewFlexokiTheme())\n}"], ["/opencode/internal/format/format.go", "package format\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"strings\"\n)\n\n// OutputFormat represents the output format type for non-interactive mode\ntype OutputFormat string\n\nconst (\n\t// Text format outputs the AI response as plain text.\n\tText OutputFormat = \"text\"\n\n\t// JSON format outputs the AI response wrapped in a JSON object.\n\tJSON OutputFormat = \"json\"\n)\n\n// String returns the string representation of the OutputFormat\nfunc (f OutputFormat) String() string {\n\treturn string(f)\n}\n\n// SupportedFormats is a list of all supported output formats as strings\nvar SupportedFormats = []string{\n\tstring(Text),\n\tstring(JSON),\n}\n\n// Parse converts a string to an OutputFormat\nfunc Parse(s string) (OutputFormat, error) {\n\ts = strings.ToLower(strings.TrimSpace(s))\n\n\tswitch s {\n\tcase string(Text):\n\t\treturn Text, nil\n\tcase string(JSON):\n\t\treturn JSON, nil\n\tdefault:\n\t\treturn \"\", fmt.Errorf(\"invalid format: %s\", s)\n\t}\n}\n\n// IsValid checks if the provided format string is supported\nfunc IsValid(s string) bool {\n\t_, err := Parse(s)\n\treturn err == nil\n}\n\n// GetHelpText returns a formatted string describing all supported formats\nfunc GetHelpText() string {\n\treturn fmt.Sprintf(`Supported output formats:\n- %s: Plain text output (default)\n- %s: Output wrapped in a JSON object`,\n\t\tText, JSON)\n}\n\n// FormatOutput formats the AI response according to the specified format\nfunc FormatOutput(content string, formatStr string) string {\n\tformat, err := Parse(formatStr)\n\tif err != nil {\n\t\t// Default to text format on error\n\t\treturn content\n\t}\n\n\tswitch format {\n\tcase JSON:\n\t\treturn formatAsJSON(content)\n\tcase Text:\n\t\tfallthrough\n\tdefault:\n\t\treturn content\n\t}\n}\n\n// formatAsJSON wraps the content in a simple JSON object\nfunc formatAsJSON(content string) string {\n\t// Use the JSON package to properly escape the content\n\tresponse := struct {\n\t\tResponse string `json:\"response\"`\n\t}{\n\t\tResponse: content,\n\t}\n\n\tjsonBytes, err := json.MarshalIndent(response, \"\", \" \")\n\tif err != nil {\n\t\t// In case of an error, return a manually formatted JSON\n\t\tjsonEscaped := strings.Replace(content, \"\\\\\", \"\\\\\\\\\", -1)\n\t\tjsonEscaped = strings.Replace(jsonEscaped, \"\\\"\", \"\\\\\\\"\", -1)\n\t\tjsonEscaped = strings.Replace(jsonEscaped, \"\\n\", \"\\\\n\", -1)\n\t\tjsonEscaped = strings.Replace(jsonEscaped, \"\\r\", \"\\\\r\", -1)\n\t\tjsonEscaped = strings.Replace(jsonEscaped, \"\\t\", \"\\\\t\", -1)\n\n\t\treturn fmt.Sprintf(\"{\\n \\\"response\\\": \\\"%s\\\"\\n}\", jsonEscaped)\n\t}\n\n\treturn string(jsonBytes)\n}\n"], ["/opencode/internal/tui/theme/tokyonight.go", "package theme\n\nimport (\n\t\"github.com/charmbracelet/lipgloss\"\n)\n\n// TokyoNightTheme implements the Theme interface with Tokyo Night colors.\n// It provides both dark and light variants.\ntype TokyoNightTheme struct {\n\tBaseTheme\n}\n\n// NewTokyoNightTheme creates a new instance of the Tokyo Night theme.\nfunc NewTokyoNightTheme() *TokyoNightTheme {\n\t// Tokyo Night color palette\n\t// Dark mode colors\n\tdarkBackground := \"#222436\"\n\tdarkCurrentLine := \"#1e2030\"\n\tdarkSelection := \"#2f334d\"\n\tdarkForeground := \"#c8d3f5\"\n\tdarkComment := \"#636da6\"\n\tdarkRed := \"#ff757f\"\n\tdarkOrange := \"#ff966c\"\n\tdarkYellow := \"#ffc777\"\n\tdarkGreen := \"#c3e88d\"\n\tdarkCyan := \"#86e1fc\"\n\tdarkBlue := \"#82aaff\"\n\tdarkPurple := \"#c099ff\"\n\tdarkBorder := \"#3b4261\"\n\n\t// Light mode colors (Tokyo Night Day)\n\tlightBackground := \"#e1e2e7\"\n\tlightCurrentLine := \"#d5d6db\"\n\tlightSelection := \"#c8c9ce\"\n\tlightForeground := \"#3760bf\"\n\tlightComment := \"#848cb5\"\n\tlightRed := \"#f52a65\"\n\tlightOrange := \"#b15c00\"\n\tlightYellow := \"#8c6c3e\"\n\tlightGreen := \"#587539\"\n\tlightCyan := \"#007197\"\n\tlightBlue := \"#2e7de9\"\n\tlightPurple := \"#9854f1\"\n\tlightBorder := \"#a8aecb\"\n\n\ttheme := &TokyoNightTheme{}\n\n\t// Base colors\n\ttheme.PrimaryColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBlue,\n\t\tLight: lightBlue,\n\t}\n\ttheme.SecondaryColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPurple,\n\t\tLight: lightPurple,\n\t}\n\ttheme.AccentColor = lipgloss.AdaptiveColor{\n\t\tDark: darkOrange,\n\t\tLight: lightOrange,\n\t}\n\n\t// Status colors\n\ttheme.ErrorColor = lipgloss.AdaptiveColor{\n\t\tDark: darkRed,\n\t\tLight: lightRed,\n\t}\n\ttheme.WarningColor = lipgloss.AdaptiveColor{\n\t\tDark: darkOrange,\n\t\tLight: lightOrange,\n\t}\n\ttheme.SuccessColor = lipgloss.AdaptiveColor{\n\t\tDark: darkGreen,\n\t\tLight: lightGreen,\n\t}\n\ttheme.InfoColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBlue,\n\t\tLight: lightBlue,\n\t}\n\n\t// Text colors\n\ttheme.TextColor = lipgloss.AdaptiveColor{\n\t\tDark: darkForeground,\n\t\tLight: lightForeground,\n\t}\n\ttheme.TextMutedColor = lipgloss.AdaptiveColor{\n\t\tDark: darkComment,\n\t\tLight: lightComment,\n\t}\n\ttheme.TextEmphasizedColor = lipgloss.AdaptiveColor{\n\t\tDark: darkYellow,\n\t\tLight: lightYellow,\n\t}\n\n\t// Background colors\n\ttheme.BackgroundColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBackground,\n\t\tLight: lightBackground,\n\t}\n\ttheme.BackgroundSecondaryColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCurrentLine,\n\t\tLight: lightCurrentLine,\n\t}\n\ttheme.BackgroundDarkerColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#191B29\", // Darker background from palette\n\t\tLight: \"#f0f0f5\", // Slightly lighter than background\n\t}\n\n\t// Border colors\n\ttheme.BorderNormalColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBorder,\n\t\tLight: lightBorder,\n\t}\n\ttheme.BorderFocusedColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBlue,\n\t\tLight: lightBlue,\n\t}\n\ttheme.BorderDimColor = lipgloss.AdaptiveColor{\n\t\tDark: darkSelection,\n\t\tLight: lightSelection,\n\t}\n\n\t// Diff view colors\n\ttheme.DiffAddedColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#4fd6be\", // teal from palette\n\t\tLight: \"#1e725c\",\n\t}\n\ttheme.DiffRemovedColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#c53b53\", // red1 from palette\n\t\tLight: \"#c53b53\",\n\t}\n\ttheme.DiffContextColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#828bb8\", // fg_dark from palette\n\t\tLight: \"#7086b5\",\n\t}\n\ttheme.DiffHunkHeaderColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#828bb8\", // fg_dark from palette\n\t\tLight: \"#7086b5\",\n\t}\n\ttheme.DiffHighlightAddedColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#b8db87\", // git.add from palette\n\t\tLight: \"#4db380\",\n\t}\n\ttheme.DiffHighlightRemovedColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#e26a75\", // git.delete from palette\n\t\tLight: \"#f52a65\",\n\t}\n\ttheme.DiffAddedBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#20303b\",\n\t\tLight: \"#d5e5d5\",\n\t}\n\ttheme.DiffRemovedBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#37222c\",\n\t\tLight: \"#f7d8db\",\n\t}\n\ttheme.DiffContextBgColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBackground,\n\t\tLight: lightBackground,\n\t}\n\ttheme.DiffLineNumberColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#545c7e\", // dark3 from palette\n\t\tLight: \"#848cb5\",\n\t}\n\ttheme.DiffAddedLineNumberBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#1b2b34\",\n\t\tLight: \"#c5d5c5\",\n\t}\n\ttheme.DiffRemovedLineNumberBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#2d1f26\",\n\t\tLight: \"#e7c8cb\",\n\t}\n\n\t// Markdown colors\n\ttheme.MarkdownTextColor = lipgloss.AdaptiveColor{\n\t\tDark: darkForeground,\n\t\tLight: lightForeground,\n\t}\n\ttheme.MarkdownHeadingColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPurple,\n\t\tLight: lightPurple,\n\t}\n\ttheme.MarkdownLinkColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBlue,\n\t\tLight: lightBlue,\n\t}\n\ttheme.MarkdownLinkTextColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.MarkdownCodeColor = lipgloss.AdaptiveColor{\n\t\tDark: darkGreen,\n\t\tLight: lightGreen,\n\t}\n\ttheme.MarkdownBlockQuoteColor = lipgloss.AdaptiveColor{\n\t\tDark: darkYellow,\n\t\tLight: lightYellow,\n\t}\n\ttheme.MarkdownEmphColor = lipgloss.AdaptiveColor{\n\t\tDark: darkYellow,\n\t\tLight: lightYellow,\n\t}\n\ttheme.MarkdownStrongColor = lipgloss.AdaptiveColor{\n\t\tDark: darkOrange,\n\t\tLight: lightOrange,\n\t}\n\ttheme.MarkdownHorizontalRuleColor = lipgloss.AdaptiveColor{\n\t\tDark: darkComment,\n\t\tLight: lightComment,\n\t}\n\ttheme.MarkdownListItemColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBlue,\n\t\tLight: lightBlue,\n\t}\n\ttheme.MarkdownListEnumerationColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.MarkdownImageColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBlue,\n\t\tLight: lightBlue,\n\t}\n\ttheme.MarkdownImageTextColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.MarkdownCodeBlockColor = lipgloss.AdaptiveColor{\n\t\tDark: darkForeground,\n\t\tLight: lightForeground,\n\t}\n\n\t// Syntax highlighting colors\n\ttheme.SyntaxCommentColor = lipgloss.AdaptiveColor{\n\t\tDark: darkComment,\n\t\tLight: lightComment,\n\t}\n\ttheme.SyntaxKeywordColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPurple,\n\t\tLight: lightPurple,\n\t}\n\ttheme.SyntaxFunctionColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBlue,\n\t\tLight: lightBlue,\n\t}\n\ttheme.SyntaxVariableColor = lipgloss.AdaptiveColor{\n\t\tDark: darkRed,\n\t\tLight: lightRed,\n\t}\n\ttheme.SyntaxStringColor = lipgloss.AdaptiveColor{\n\t\tDark: darkGreen,\n\t\tLight: lightGreen,\n\t}\n\ttheme.SyntaxNumberColor = lipgloss.AdaptiveColor{\n\t\tDark: darkOrange,\n\t\tLight: lightOrange,\n\t}\n\ttheme.SyntaxTypeColor = lipgloss.AdaptiveColor{\n\t\tDark: darkYellow,\n\t\tLight: lightYellow,\n\t}\n\ttheme.SyntaxOperatorColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.SyntaxPunctuationColor = lipgloss.AdaptiveColor{\n\t\tDark: darkForeground,\n\t\tLight: lightForeground,\n\t}\n\n\treturn theme\n}\n\nfunc init() {\n\t// Register the Tokyo Night theme with the theme manager\n\tRegisterTheme(\"tokyonight\", NewTokyoNightTheme())\n}"], ["/opencode/internal/tui/theme/monokai.go", "package theme\n\nimport (\n\t\"github.com/charmbracelet/lipgloss\"\n)\n\n// MonokaiProTheme implements the Theme interface with Monokai Pro colors.\n// It provides both dark and light variants.\ntype MonokaiProTheme struct {\n\tBaseTheme\n}\n\n// NewMonokaiProTheme creates a new instance of the Monokai Pro theme.\nfunc NewMonokaiProTheme() *MonokaiProTheme {\n\t// Monokai Pro color palette (dark mode)\n\tdarkBackground := \"#2d2a2e\"\n\tdarkCurrentLine := \"#403e41\"\n\tdarkSelection := \"#5b595c\"\n\tdarkForeground := \"#fcfcfa\"\n\tdarkComment := \"#727072\"\n\tdarkRed := \"#ff6188\"\n\tdarkOrange := \"#fc9867\"\n\tdarkYellow := \"#ffd866\"\n\tdarkGreen := \"#a9dc76\"\n\tdarkCyan := \"#78dce8\"\n\tdarkBlue := \"#ab9df2\"\n\tdarkPurple := \"#ab9df2\"\n\tdarkBorder := \"#403e41\"\n\n\t// Light mode colors (adapted from dark)\n\tlightBackground := \"#fafafa\"\n\tlightCurrentLine := \"#f0f0f0\"\n\tlightSelection := \"#e5e5e6\"\n\tlightForeground := \"#2d2a2e\"\n\tlightComment := \"#939293\"\n\tlightRed := \"#f92672\"\n\tlightOrange := \"#fd971f\"\n\tlightYellow := \"#e6db74\"\n\tlightGreen := \"#9bca65\"\n\tlightCyan := \"#66d9ef\"\n\tlightBlue := \"#7e75db\"\n\tlightPurple := \"#ae81ff\"\n\tlightBorder := \"#d3d3d3\"\n\n\ttheme := &MonokaiProTheme{}\n\n\t// Base colors\n\ttheme.PrimaryColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.SecondaryColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPurple,\n\t\tLight: lightPurple,\n\t}\n\ttheme.AccentColor = lipgloss.AdaptiveColor{\n\t\tDark: darkOrange,\n\t\tLight: lightOrange,\n\t}\n\n\t// Status colors\n\ttheme.ErrorColor = lipgloss.AdaptiveColor{\n\t\tDark: darkRed,\n\t\tLight: lightRed,\n\t}\n\ttheme.WarningColor = lipgloss.AdaptiveColor{\n\t\tDark: darkOrange,\n\t\tLight: lightOrange,\n\t}\n\ttheme.SuccessColor = lipgloss.AdaptiveColor{\n\t\tDark: darkGreen,\n\t\tLight: lightGreen,\n\t}\n\ttheme.InfoColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBlue,\n\t\tLight: lightBlue,\n\t}\n\n\t// Text colors\n\ttheme.TextColor = lipgloss.AdaptiveColor{\n\t\tDark: darkForeground,\n\t\tLight: lightForeground,\n\t}\n\ttheme.TextMutedColor = lipgloss.AdaptiveColor{\n\t\tDark: darkComment,\n\t\tLight: lightComment,\n\t}\n\ttheme.TextEmphasizedColor = lipgloss.AdaptiveColor{\n\t\tDark: darkYellow,\n\t\tLight: lightYellow,\n\t}\n\n\t// Background colors\n\ttheme.BackgroundColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBackground,\n\t\tLight: lightBackground,\n\t}\n\ttheme.BackgroundSecondaryColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCurrentLine,\n\t\tLight: lightCurrentLine,\n\t}\n\ttheme.BackgroundDarkerColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#221f22\", // Slightly darker than background\n\t\tLight: \"#ffffff\", // Slightly lighter than background\n\t}\n\n\t// Border colors\n\ttheme.BorderNormalColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBorder,\n\t\tLight: lightBorder,\n\t}\n\ttheme.BorderFocusedColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.BorderDimColor = lipgloss.AdaptiveColor{\n\t\tDark: darkSelection,\n\t\tLight: lightSelection,\n\t}\n\n\t// Diff view colors\n\ttheme.DiffAddedColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#a9dc76\",\n\t\tLight: \"#9bca65\",\n\t}\n\ttheme.DiffRemovedColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#ff6188\",\n\t\tLight: \"#f92672\",\n\t}\n\ttheme.DiffContextColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#a0a0a0\",\n\t\tLight: \"#757575\",\n\t}\n\ttheme.DiffHunkHeaderColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#a0a0a0\",\n\t\tLight: \"#757575\",\n\t}\n\ttheme.DiffHighlightAddedColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#c2e7a9\",\n\t\tLight: \"#c5e0b4\",\n\t}\n\ttheme.DiffHighlightRemovedColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#ff8ca6\",\n\t\tLight: \"#ffb3c8\",\n\t}\n\ttheme.DiffAddedBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#3a4a35\",\n\t\tLight: \"#e8f5e9\",\n\t}\n\ttheme.DiffRemovedBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#4a3439\",\n\t\tLight: \"#ffebee\",\n\t}\n\ttheme.DiffContextBgColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBackground,\n\t\tLight: lightBackground,\n\t}\n\ttheme.DiffLineNumberColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#888888\",\n\t\tLight: \"#9e9e9e\",\n\t}\n\ttheme.DiffAddedLineNumberBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#2d3a28\",\n\t\tLight: \"#c8e6c9\",\n\t}\n\ttheme.DiffRemovedLineNumberBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#3d2a2e\",\n\t\tLight: \"#ffcdd2\",\n\t}\n\n\t// Markdown colors\n\ttheme.MarkdownTextColor = lipgloss.AdaptiveColor{\n\t\tDark: darkForeground,\n\t\tLight: lightForeground,\n\t}\n\ttheme.MarkdownHeadingColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPurple,\n\t\tLight: lightPurple,\n\t}\n\ttheme.MarkdownLinkColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.MarkdownLinkTextColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBlue,\n\t\tLight: lightBlue,\n\t}\n\ttheme.MarkdownCodeColor = lipgloss.AdaptiveColor{\n\t\tDark: darkGreen,\n\t\tLight: lightGreen,\n\t}\n\ttheme.MarkdownBlockQuoteColor = lipgloss.AdaptiveColor{\n\t\tDark: darkYellow,\n\t\tLight: lightYellow,\n\t}\n\ttheme.MarkdownEmphColor = lipgloss.AdaptiveColor{\n\t\tDark: darkYellow,\n\t\tLight: lightYellow,\n\t}\n\ttheme.MarkdownStrongColor = lipgloss.AdaptiveColor{\n\t\tDark: darkOrange,\n\t\tLight: lightOrange,\n\t}\n\ttheme.MarkdownHorizontalRuleColor = lipgloss.AdaptiveColor{\n\t\tDark: darkComment,\n\t\tLight: lightComment,\n\t}\n\ttheme.MarkdownListItemColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.MarkdownListEnumerationColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBlue,\n\t\tLight: lightBlue,\n\t}\n\ttheme.MarkdownImageColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.MarkdownImageTextColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBlue,\n\t\tLight: lightBlue,\n\t}\n\ttheme.MarkdownCodeBlockColor = lipgloss.AdaptiveColor{\n\t\tDark: darkForeground,\n\t\tLight: lightForeground,\n\t}\n\n\t// Syntax highlighting colors\n\ttheme.SyntaxCommentColor = lipgloss.AdaptiveColor{\n\t\tDark: darkComment,\n\t\tLight: lightComment,\n\t}\n\ttheme.SyntaxKeywordColor = lipgloss.AdaptiveColor{\n\t\tDark: darkRed,\n\t\tLight: lightRed,\n\t}\n\ttheme.SyntaxFunctionColor = lipgloss.AdaptiveColor{\n\t\tDark: darkGreen,\n\t\tLight: lightGreen,\n\t}\n\ttheme.SyntaxVariableColor = lipgloss.AdaptiveColor{\n\t\tDark: darkForeground,\n\t\tLight: lightForeground,\n\t}\n\ttheme.SyntaxStringColor = lipgloss.AdaptiveColor{\n\t\tDark: darkYellow,\n\t\tLight: lightYellow,\n\t}\n\ttheme.SyntaxNumberColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPurple,\n\t\tLight: lightPurple,\n\t}\n\ttheme.SyntaxTypeColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBlue,\n\t\tLight: lightBlue,\n\t}\n\ttheme.SyntaxOperatorColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.SyntaxPunctuationColor = lipgloss.AdaptiveColor{\n\t\tDark: darkForeground,\n\t\tLight: lightForeground,\n\t}\n\n\treturn theme\n}\n\nfunc init() {\n\t// Register the Monokai Pro theme with the theme manager\n\tRegisterTheme(\"monokai\", NewMonokaiProTheme())\n}"], ["/opencode/internal/tui/theme/dracula.go", "package theme\n\nimport (\n\t\"github.com/charmbracelet/lipgloss\"\n)\n\n// DraculaTheme implements the Theme interface with Dracula colors.\n// It provides both dark and light variants, though Dracula is primarily a dark theme.\ntype DraculaTheme struct {\n\tBaseTheme\n}\n\n// NewDraculaTheme creates a new instance of the Dracula theme.\nfunc NewDraculaTheme() *DraculaTheme {\n\t// Dracula color palette\n\t// Official colors from https://draculatheme.com/\n\tdarkBackground := \"#282a36\"\n\tdarkCurrentLine := \"#44475a\"\n\tdarkSelection := \"#44475a\"\n\tdarkForeground := \"#f8f8f2\"\n\tdarkComment := \"#6272a4\"\n\tdarkCyan := \"#8be9fd\"\n\tdarkGreen := \"#50fa7b\"\n\tdarkOrange := \"#ffb86c\"\n\tdarkPink := \"#ff79c6\"\n\tdarkPurple := \"#bd93f9\"\n\tdarkRed := \"#ff5555\"\n\tdarkYellow := \"#f1fa8c\"\n\tdarkBorder := \"#44475a\"\n\n\t// Light mode approximation (Dracula is primarily a dark theme)\n\tlightBackground := \"#f8f8f2\"\n\tlightCurrentLine := \"#e6e6e6\"\n\tlightSelection := \"#d8d8d8\"\n\tlightForeground := \"#282a36\"\n\tlightComment := \"#6272a4\"\n\tlightCyan := \"#0097a7\"\n\tlightGreen := \"#388e3c\"\n\tlightOrange := \"#f57c00\"\n\tlightPink := \"#d81b60\"\n\tlightPurple := \"#7e57c2\"\n\tlightRed := \"#e53935\"\n\tlightYellow := \"#fbc02d\"\n\tlightBorder := \"#d8d8d8\"\n\n\ttheme := &DraculaTheme{}\n\n\t// Base colors\n\ttheme.PrimaryColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPurple,\n\t\tLight: lightPurple,\n\t}\n\ttheme.SecondaryColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPink,\n\t\tLight: lightPink,\n\t}\n\ttheme.AccentColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\n\t// Status colors\n\ttheme.ErrorColor = lipgloss.AdaptiveColor{\n\t\tDark: darkRed,\n\t\tLight: lightRed,\n\t}\n\ttheme.WarningColor = lipgloss.AdaptiveColor{\n\t\tDark: darkOrange,\n\t\tLight: lightOrange,\n\t}\n\ttheme.SuccessColor = lipgloss.AdaptiveColor{\n\t\tDark: darkGreen,\n\t\tLight: lightGreen,\n\t}\n\ttheme.InfoColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\n\t// Text colors\n\ttheme.TextColor = lipgloss.AdaptiveColor{\n\t\tDark: darkForeground,\n\t\tLight: lightForeground,\n\t}\n\ttheme.TextMutedColor = lipgloss.AdaptiveColor{\n\t\tDark: darkComment,\n\t\tLight: lightComment,\n\t}\n\ttheme.TextEmphasizedColor = lipgloss.AdaptiveColor{\n\t\tDark: darkYellow,\n\t\tLight: lightYellow,\n\t}\n\n\t// Background colors\n\ttheme.BackgroundColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBackground,\n\t\tLight: lightBackground,\n\t}\n\ttheme.BackgroundSecondaryColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCurrentLine,\n\t\tLight: lightCurrentLine,\n\t}\n\ttheme.BackgroundDarkerColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#21222c\", // Slightly darker than background\n\t\tLight: \"#ffffff\", // Slightly lighter than background\n\t}\n\n\t// Border colors\n\ttheme.BorderNormalColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBorder,\n\t\tLight: lightBorder,\n\t}\n\ttheme.BorderFocusedColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPurple,\n\t\tLight: lightPurple,\n\t}\n\ttheme.BorderDimColor = lipgloss.AdaptiveColor{\n\t\tDark: darkSelection,\n\t\tLight: lightSelection,\n\t}\n\n\t// Diff view colors\n\ttheme.DiffAddedColor = lipgloss.AdaptiveColor{\n\t\tDark: darkGreen,\n\t\tLight: lightGreen,\n\t}\n\ttheme.DiffRemovedColor = lipgloss.AdaptiveColor{\n\t\tDark: darkRed,\n\t\tLight: lightRed,\n\t}\n\ttheme.DiffContextColor = lipgloss.AdaptiveColor{\n\t\tDark: darkComment,\n\t\tLight: lightComment,\n\t}\n\ttheme.DiffHunkHeaderColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPurple,\n\t\tLight: lightPurple,\n\t}\n\ttheme.DiffHighlightAddedColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#50fa7b\",\n\t\tLight: \"#a5d6a7\",\n\t}\n\ttheme.DiffHighlightRemovedColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#ff5555\",\n\t\tLight: \"#ef9a9a\",\n\t}\n\ttheme.DiffAddedBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#2c3b2c\",\n\t\tLight: \"#e8f5e9\",\n\t}\n\ttheme.DiffRemovedBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#3b2c2c\",\n\t\tLight: \"#ffebee\",\n\t}\n\ttheme.DiffContextBgColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBackground,\n\t\tLight: lightBackground,\n\t}\n\ttheme.DiffLineNumberColor = lipgloss.AdaptiveColor{\n\t\tDark: darkComment,\n\t\tLight: lightComment,\n\t}\n\ttheme.DiffAddedLineNumberBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#253025\",\n\t\tLight: \"#c8e6c9\",\n\t}\n\ttheme.DiffRemovedLineNumberBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#302525\",\n\t\tLight: \"#ffcdd2\",\n\t}\n\n\t// Markdown colors\n\ttheme.MarkdownTextColor = lipgloss.AdaptiveColor{\n\t\tDark: darkForeground,\n\t\tLight: lightForeground,\n\t}\n\ttheme.MarkdownHeadingColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPink,\n\t\tLight: lightPink,\n\t}\n\ttheme.MarkdownLinkColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPurple,\n\t\tLight: lightPurple,\n\t}\n\ttheme.MarkdownLinkTextColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.MarkdownCodeColor = lipgloss.AdaptiveColor{\n\t\tDark: darkGreen,\n\t\tLight: lightGreen,\n\t}\n\ttheme.MarkdownBlockQuoteColor = lipgloss.AdaptiveColor{\n\t\tDark: darkYellow,\n\t\tLight: lightYellow,\n\t}\n\ttheme.MarkdownEmphColor = lipgloss.AdaptiveColor{\n\t\tDark: darkYellow,\n\t\tLight: lightYellow,\n\t}\n\ttheme.MarkdownStrongColor = lipgloss.AdaptiveColor{\n\t\tDark: darkOrange,\n\t\tLight: lightOrange,\n\t}\n\ttheme.MarkdownHorizontalRuleColor = lipgloss.AdaptiveColor{\n\t\tDark: darkComment,\n\t\tLight: lightComment,\n\t}\n\ttheme.MarkdownListItemColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPurple,\n\t\tLight: lightPurple,\n\t}\n\ttheme.MarkdownListEnumerationColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.MarkdownImageColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPurple,\n\t\tLight: lightPurple,\n\t}\n\ttheme.MarkdownImageTextColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.MarkdownCodeBlockColor = lipgloss.AdaptiveColor{\n\t\tDark: darkForeground,\n\t\tLight: lightForeground,\n\t}\n\n\t// Syntax highlighting colors\n\ttheme.SyntaxCommentColor = lipgloss.AdaptiveColor{\n\t\tDark: darkComment,\n\t\tLight: lightComment,\n\t}\n\ttheme.SyntaxKeywordColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPink,\n\t\tLight: lightPink,\n\t}\n\ttheme.SyntaxFunctionColor = lipgloss.AdaptiveColor{\n\t\tDark: darkGreen,\n\t\tLight: lightGreen,\n\t}\n\ttheme.SyntaxVariableColor = lipgloss.AdaptiveColor{\n\t\tDark: darkOrange,\n\t\tLight: lightOrange,\n\t}\n\ttheme.SyntaxStringColor = lipgloss.AdaptiveColor{\n\t\tDark: darkYellow,\n\t\tLight: lightYellow,\n\t}\n\ttheme.SyntaxNumberColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPurple,\n\t\tLight: lightPurple,\n\t}\n\ttheme.SyntaxTypeColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.SyntaxOperatorColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPink,\n\t\tLight: lightPink,\n\t}\n\ttheme.SyntaxPunctuationColor = lipgloss.AdaptiveColor{\n\t\tDark: darkForeground,\n\t\tLight: lightForeground,\n\t}\n\n\treturn theme\n}\n\nfunc init() {\n\t// Register the Dracula theme with the theme manager\n\tRegisterTheme(\"dracula\", NewDraculaTheme())\n}"], ["/opencode/internal/tui/theme/opencode.go", "package theme\n\nimport (\n\t\"github.com/charmbracelet/lipgloss\"\n)\n\n// OpenCodeTheme implements the Theme interface with OpenCode brand colors.\n// It provides both dark and light variants.\ntype OpenCodeTheme struct {\n\tBaseTheme\n}\n\n// NewOpenCodeTheme creates a new instance of the OpenCode theme.\nfunc NewOpenCodeTheme() *OpenCodeTheme {\n\t// OpenCode color palette\n\t// Dark mode colors\n\tdarkBackground := \"#212121\"\n\tdarkCurrentLine := \"#252525\"\n\tdarkSelection := \"#303030\"\n\tdarkForeground := \"#e0e0e0\"\n\tdarkComment := \"#6a6a6a\"\n\tdarkPrimary := \"#fab283\" // Primary orange/gold\n\tdarkSecondary := \"#5c9cf5\" // Secondary blue\n\tdarkAccent := \"#9d7cd8\" // Accent purple\n\tdarkRed := \"#e06c75\" // Error red\n\tdarkOrange := \"#f5a742\" // Warning orange\n\tdarkGreen := \"#7fd88f\" // Success green\n\tdarkCyan := \"#56b6c2\" // Info cyan\n\tdarkYellow := \"#e5c07b\" // Emphasized text\n\tdarkBorder := \"#4b4c5c\" // Border color\n\n\t// Light mode colors\n\tlightBackground := \"#f8f8f8\"\n\tlightCurrentLine := \"#f0f0f0\"\n\tlightSelection := \"#e5e5e6\"\n\tlightForeground := \"#2a2a2a\"\n\tlightComment := \"#8a8a8a\"\n\tlightPrimary := \"#3b7dd8\" // Primary blue\n\tlightSecondary := \"#7b5bb6\" // Secondary purple\n\tlightAccent := \"#d68c27\" // Accent orange/gold\n\tlightRed := \"#d1383d\" // Error red\n\tlightOrange := \"#d68c27\" // Warning orange\n\tlightGreen := \"#3d9a57\" // Success green\n\tlightCyan := \"#318795\" // Info cyan\n\tlightYellow := \"#b0851f\" // Emphasized text\n\tlightBorder := \"#d3d3d3\" // Border color\n\n\ttheme := &OpenCodeTheme{}\n\n\t// Base colors\n\ttheme.PrimaryColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPrimary,\n\t\tLight: lightPrimary,\n\t}\n\ttheme.SecondaryColor = lipgloss.AdaptiveColor{\n\t\tDark: darkSecondary,\n\t\tLight: lightSecondary,\n\t}\n\ttheme.AccentColor = lipgloss.AdaptiveColor{\n\t\tDark: darkAccent,\n\t\tLight: lightAccent,\n\t}\n\n\t// Status colors\n\ttheme.ErrorColor = lipgloss.AdaptiveColor{\n\t\tDark: darkRed,\n\t\tLight: lightRed,\n\t}\n\ttheme.WarningColor = lipgloss.AdaptiveColor{\n\t\tDark: darkOrange,\n\t\tLight: lightOrange,\n\t}\n\ttheme.SuccessColor = lipgloss.AdaptiveColor{\n\t\tDark: darkGreen,\n\t\tLight: lightGreen,\n\t}\n\ttheme.InfoColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\n\t// Text colors\n\ttheme.TextColor = lipgloss.AdaptiveColor{\n\t\tDark: darkForeground,\n\t\tLight: lightForeground,\n\t}\n\ttheme.TextMutedColor = lipgloss.AdaptiveColor{\n\t\tDark: darkComment,\n\t\tLight: lightComment,\n\t}\n\ttheme.TextEmphasizedColor = lipgloss.AdaptiveColor{\n\t\tDark: darkYellow,\n\t\tLight: lightYellow,\n\t}\n\n\t// Background colors\n\ttheme.BackgroundColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBackground,\n\t\tLight: lightBackground,\n\t}\n\ttheme.BackgroundSecondaryColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCurrentLine,\n\t\tLight: lightCurrentLine,\n\t}\n\ttheme.BackgroundDarkerColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#121212\", // Slightly darker than background\n\t\tLight: \"#ffffff\", // Slightly lighter than background\n\t}\n\n\t// Border colors\n\ttheme.BorderNormalColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBorder,\n\t\tLight: lightBorder,\n\t}\n\ttheme.BorderFocusedColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPrimary,\n\t\tLight: lightPrimary,\n\t}\n\ttheme.BorderDimColor = lipgloss.AdaptiveColor{\n\t\tDark: darkSelection,\n\t\tLight: lightSelection,\n\t}\n\n\t// Diff view colors\n\ttheme.DiffAddedColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#478247\",\n\t\tLight: \"#2E7D32\",\n\t}\n\ttheme.DiffRemovedColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#7C4444\",\n\t\tLight: \"#C62828\",\n\t}\n\ttheme.DiffContextColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#a0a0a0\",\n\t\tLight: \"#757575\",\n\t}\n\ttheme.DiffHunkHeaderColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#a0a0a0\",\n\t\tLight: \"#757575\",\n\t}\n\ttheme.DiffHighlightAddedColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#DAFADA\",\n\t\tLight: \"#A5D6A7\",\n\t}\n\ttheme.DiffHighlightRemovedColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#FADADD\",\n\t\tLight: \"#EF9A9A\",\n\t}\n\ttheme.DiffAddedBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#303A30\",\n\t\tLight: \"#E8F5E9\",\n\t}\n\ttheme.DiffRemovedBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#3A3030\",\n\t\tLight: \"#FFEBEE\",\n\t}\n\ttheme.DiffContextBgColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBackground,\n\t\tLight: lightBackground,\n\t}\n\ttheme.DiffLineNumberColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#888888\",\n\t\tLight: \"#9E9E9E\",\n\t}\n\ttheme.DiffAddedLineNumberBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#293229\",\n\t\tLight: \"#C8E6C9\",\n\t}\n\ttheme.DiffRemovedLineNumberBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#332929\",\n\t\tLight: \"#FFCDD2\",\n\t}\n\n\t// Markdown colors\n\ttheme.MarkdownTextColor = lipgloss.AdaptiveColor{\n\t\tDark: darkForeground,\n\t\tLight: lightForeground,\n\t}\n\ttheme.MarkdownHeadingColor = lipgloss.AdaptiveColor{\n\t\tDark: darkSecondary,\n\t\tLight: lightSecondary,\n\t}\n\ttheme.MarkdownLinkColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPrimary,\n\t\tLight: lightPrimary,\n\t}\n\ttheme.MarkdownLinkTextColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.MarkdownCodeColor = lipgloss.AdaptiveColor{\n\t\tDark: darkGreen,\n\t\tLight: lightGreen,\n\t}\n\ttheme.MarkdownBlockQuoteColor = lipgloss.AdaptiveColor{\n\t\tDark: darkYellow,\n\t\tLight: lightYellow,\n\t}\n\ttheme.MarkdownEmphColor = lipgloss.AdaptiveColor{\n\t\tDark: darkYellow,\n\t\tLight: lightYellow,\n\t}\n\ttheme.MarkdownStrongColor = lipgloss.AdaptiveColor{\n\t\tDark: darkAccent,\n\t\tLight: lightAccent,\n\t}\n\ttheme.MarkdownHorizontalRuleColor = lipgloss.AdaptiveColor{\n\t\tDark: darkComment,\n\t\tLight: lightComment,\n\t}\n\ttheme.MarkdownListItemColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPrimary,\n\t\tLight: lightPrimary,\n\t}\n\ttheme.MarkdownListEnumerationColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.MarkdownImageColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPrimary,\n\t\tLight: lightPrimary,\n\t}\n\ttheme.MarkdownImageTextColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.MarkdownCodeBlockColor = lipgloss.AdaptiveColor{\n\t\tDark: darkForeground,\n\t\tLight: lightForeground,\n\t}\n\n\t// Syntax highlighting colors\n\ttheme.SyntaxCommentColor = lipgloss.AdaptiveColor{\n\t\tDark: darkComment,\n\t\tLight: lightComment,\n\t}\n\ttheme.SyntaxKeywordColor = lipgloss.AdaptiveColor{\n\t\tDark: darkSecondary,\n\t\tLight: lightSecondary,\n\t}\n\ttheme.SyntaxFunctionColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPrimary,\n\t\tLight: lightPrimary,\n\t}\n\ttheme.SyntaxVariableColor = lipgloss.AdaptiveColor{\n\t\tDark: darkRed,\n\t\tLight: lightRed,\n\t}\n\ttheme.SyntaxStringColor = lipgloss.AdaptiveColor{\n\t\tDark: darkGreen,\n\t\tLight: lightGreen,\n\t}\n\ttheme.SyntaxNumberColor = lipgloss.AdaptiveColor{\n\t\tDark: darkAccent,\n\t\tLight: lightAccent,\n\t}\n\ttheme.SyntaxTypeColor = lipgloss.AdaptiveColor{\n\t\tDark: darkYellow,\n\t\tLight: lightYellow,\n\t}\n\ttheme.SyntaxOperatorColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.SyntaxPunctuationColor = lipgloss.AdaptiveColor{\n\t\tDark: darkForeground,\n\t\tLight: lightForeground,\n\t}\n\n\treturn theme\n}\n\nfunc init() {\n\t// Register the OpenCode theme with the theme manager\n\tRegisterTheme(\"opencode\", NewOpenCodeTheme())\n}\n\n"], ["/opencode/internal/tui/theme/tron.go", "package theme\n\nimport (\n\t\"github.com/charmbracelet/lipgloss\"\n)\n\n// TronTheme implements the Theme interface with Tron-inspired colors.\n// It provides both dark and light variants, though Tron is primarily a dark theme.\ntype TronTheme struct {\n\tBaseTheme\n}\n\n// NewTronTheme creates a new instance of the Tron theme.\nfunc NewTronTheme() *TronTheme {\n\t// Tron color palette\n\t// Inspired by the Tron movie's neon aesthetic\n\tdarkBackground := \"#0c141f\"\n\tdarkCurrentLine := \"#1a2633\"\n\tdarkSelection := \"#1a2633\"\n\tdarkForeground := \"#caf0ff\"\n\tdarkComment := \"#4d6b87\"\n\tdarkCyan := \"#00d9ff\"\n\tdarkBlue := \"#007fff\"\n\tdarkOrange := \"#ff9000\"\n\tdarkPink := \"#ff00a0\"\n\tdarkPurple := \"#b73fff\"\n\tdarkRed := \"#ff3333\"\n\tdarkYellow := \"#ffcc00\"\n\tdarkGreen := \"#00ff8f\"\n\tdarkBorder := \"#1a2633\"\n\n\t// Light mode approximation\n\tlightBackground := \"#f0f8ff\"\n\tlightCurrentLine := \"#e0f0ff\"\n\tlightSelection := \"#d0e8ff\"\n\tlightForeground := \"#0c141f\"\n\tlightComment := \"#4d6b87\"\n\tlightCyan := \"#0097b3\"\n\tlightBlue := \"#0066cc\"\n\tlightOrange := \"#cc7300\"\n\tlightPink := \"#cc0080\"\n\tlightPurple := \"#9932cc\"\n\tlightRed := \"#cc2929\"\n\tlightYellow := \"#cc9900\"\n\tlightGreen := \"#00cc72\"\n\tlightBorder := \"#d0e8ff\"\n\n\ttheme := &TronTheme{}\n\n\t// Base colors\n\ttheme.PrimaryColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.SecondaryColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBlue,\n\t\tLight: lightBlue,\n\t}\n\ttheme.AccentColor = lipgloss.AdaptiveColor{\n\t\tDark: darkOrange,\n\t\tLight: lightOrange,\n\t}\n\n\t// Status colors\n\ttheme.ErrorColor = lipgloss.AdaptiveColor{\n\t\tDark: darkRed,\n\t\tLight: lightRed,\n\t}\n\ttheme.WarningColor = lipgloss.AdaptiveColor{\n\t\tDark: darkOrange,\n\t\tLight: lightOrange,\n\t}\n\ttheme.SuccessColor = lipgloss.AdaptiveColor{\n\t\tDark: darkGreen,\n\t\tLight: lightGreen,\n\t}\n\ttheme.InfoColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\n\t// Text colors\n\ttheme.TextColor = lipgloss.AdaptiveColor{\n\t\tDark: darkForeground,\n\t\tLight: lightForeground,\n\t}\n\ttheme.TextMutedColor = lipgloss.AdaptiveColor{\n\t\tDark: darkComment,\n\t\tLight: lightComment,\n\t}\n\ttheme.TextEmphasizedColor = lipgloss.AdaptiveColor{\n\t\tDark: darkYellow,\n\t\tLight: lightYellow,\n\t}\n\n\t// Background colors\n\ttheme.BackgroundColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBackground,\n\t\tLight: lightBackground,\n\t}\n\ttheme.BackgroundSecondaryColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCurrentLine,\n\t\tLight: lightCurrentLine,\n\t}\n\ttheme.BackgroundDarkerColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#070d14\", // Slightly darker than background\n\t\tLight: \"#ffffff\", // Slightly lighter than background\n\t}\n\n\t// Border colors\n\ttheme.BorderNormalColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBorder,\n\t\tLight: lightBorder,\n\t}\n\ttheme.BorderFocusedColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.BorderDimColor = lipgloss.AdaptiveColor{\n\t\tDark: darkSelection,\n\t\tLight: lightSelection,\n\t}\n\n\t// Diff view colors\n\ttheme.DiffAddedColor = lipgloss.AdaptiveColor{\n\t\tDark: darkGreen,\n\t\tLight: lightGreen,\n\t}\n\ttheme.DiffRemovedColor = lipgloss.AdaptiveColor{\n\t\tDark: darkRed,\n\t\tLight: lightRed,\n\t}\n\ttheme.DiffContextColor = lipgloss.AdaptiveColor{\n\t\tDark: darkComment,\n\t\tLight: lightComment,\n\t}\n\ttheme.DiffHunkHeaderColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBlue,\n\t\tLight: lightBlue,\n\t}\n\ttheme.DiffHighlightAddedColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#00ff8f\",\n\t\tLight: \"#a5d6a7\",\n\t}\n\ttheme.DiffHighlightRemovedColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#ff3333\",\n\t\tLight: \"#ef9a9a\",\n\t}\n\ttheme.DiffAddedBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#0a2a1a\",\n\t\tLight: \"#e8f5e9\",\n\t}\n\ttheme.DiffRemovedBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#2a0a0a\",\n\t\tLight: \"#ffebee\",\n\t}\n\ttheme.DiffContextBgColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBackground,\n\t\tLight: lightBackground,\n\t}\n\ttheme.DiffLineNumberColor = lipgloss.AdaptiveColor{\n\t\tDark: darkComment,\n\t\tLight: lightComment,\n\t}\n\ttheme.DiffAddedLineNumberBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#082015\",\n\t\tLight: \"#c8e6c9\",\n\t}\n\ttheme.DiffRemovedLineNumberBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#200808\",\n\t\tLight: \"#ffcdd2\",\n\t}\n\n\t// Markdown colors\n\ttheme.MarkdownTextColor = lipgloss.AdaptiveColor{\n\t\tDark: darkForeground,\n\t\tLight: lightForeground,\n\t}\n\ttheme.MarkdownHeadingColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.MarkdownLinkColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBlue,\n\t\tLight: lightBlue,\n\t}\n\ttheme.MarkdownLinkTextColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.MarkdownCodeColor = lipgloss.AdaptiveColor{\n\t\tDark: darkGreen,\n\t\tLight: lightGreen,\n\t}\n\ttheme.MarkdownBlockQuoteColor = lipgloss.AdaptiveColor{\n\t\tDark: darkYellow,\n\t\tLight: lightYellow,\n\t}\n\ttheme.MarkdownEmphColor = lipgloss.AdaptiveColor{\n\t\tDark: darkYellow,\n\t\tLight: lightYellow,\n\t}\n\ttheme.MarkdownStrongColor = lipgloss.AdaptiveColor{\n\t\tDark: darkOrange,\n\t\tLight: lightOrange,\n\t}\n\ttheme.MarkdownHorizontalRuleColor = lipgloss.AdaptiveColor{\n\t\tDark: darkComment,\n\t\tLight: lightComment,\n\t}\n\ttheme.MarkdownListItemColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBlue,\n\t\tLight: lightBlue,\n\t}\n\ttheme.MarkdownListEnumerationColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.MarkdownImageColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBlue,\n\t\tLight: lightBlue,\n\t}\n\ttheme.MarkdownImageTextColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.MarkdownCodeBlockColor = lipgloss.AdaptiveColor{\n\t\tDark: darkForeground,\n\t\tLight: lightForeground,\n\t}\n\n\t// Syntax highlighting colors\n\ttheme.SyntaxCommentColor = lipgloss.AdaptiveColor{\n\t\tDark: darkComment,\n\t\tLight: lightComment,\n\t}\n\ttheme.SyntaxKeywordColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.SyntaxFunctionColor = lipgloss.AdaptiveColor{\n\t\tDark: darkGreen,\n\t\tLight: lightGreen,\n\t}\n\ttheme.SyntaxVariableColor = lipgloss.AdaptiveColor{\n\t\tDark: darkOrange,\n\t\tLight: lightOrange,\n\t}\n\ttheme.SyntaxStringColor = lipgloss.AdaptiveColor{\n\t\tDark: darkYellow,\n\t\tLight: lightYellow,\n\t}\n\ttheme.SyntaxNumberColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBlue,\n\t\tLight: lightBlue,\n\t}\n\ttheme.SyntaxTypeColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPurple,\n\t\tLight: lightPurple,\n\t}\n\ttheme.SyntaxOperatorColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPink,\n\t\tLight: lightPink,\n\t}\n\ttheme.SyntaxPunctuationColor = lipgloss.AdaptiveColor{\n\t\tDark: darkForeground,\n\t\tLight: lightForeground,\n\t}\n\n\treturn theme\n}\n\nfunc init() {\n\t// Register the Tron theme with the theme manager\n\tRegisterTheme(\"tron\", NewTronTheme())\n}"], ["/opencode/internal/tui/theme/gruvbox.go", "package theme\n\nimport (\n\t\"github.com/charmbracelet/lipgloss\"\n)\n\n// Gruvbox color palette constants\nconst (\n\t// Dark theme colors\n\tgruvboxDarkBg0 = \"#282828\"\n\tgruvboxDarkBg0Soft = \"#32302f\"\n\tgruvboxDarkBg1 = \"#3c3836\"\n\tgruvboxDarkBg2 = \"#504945\"\n\tgruvboxDarkBg3 = \"#665c54\"\n\tgruvboxDarkBg4 = \"#7c6f64\"\n\tgruvboxDarkFg0 = \"#fbf1c7\"\n\tgruvboxDarkFg1 = \"#ebdbb2\"\n\tgruvboxDarkFg2 = \"#d5c4a1\"\n\tgruvboxDarkFg3 = \"#bdae93\"\n\tgruvboxDarkFg4 = \"#a89984\"\n\tgruvboxDarkGray = \"#928374\"\n\tgruvboxDarkRed = \"#cc241d\"\n\tgruvboxDarkRedBright = \"#fb4934\"\n\tgruvboxDarkGreen = \"#98971a\"\n\tgruvboxDarkGreenBright = \"#b8bb26\"\n\tgruvboxDarkYellow = \"#d79921\"\n\tgruvboxDarkYellowBright = \"#fabd2f\"\n\tgruvboxDarkBlue = \"#458588\"\n\tgruvboxDarkBlueBright = \"#83a598\"\n\tgruvboxDarkPurple = \"#b16286\"\n\tgruvboxDarkPurpleBright = \"#d3869b\"\n\tgruvboxDarkAqua = \"#689d6a\"\n\tgruvboxDarkAquaBright = \"#8ec07c\"\n\tgruvboxDarkOrange = \"#d65d0e\"\n\tgruvboxDarkOrangeBright = \"#fe8019\"\n\n\t// Light theme colors\n\tgruvboxLightBg0 = \"#fbf1c7\"\n\tgruvboxLightBg0Soft = \"#f2e5bc\"\n\tgruvboxLightBg1 = \"#ebdbb2\"\n\tgruvboxLightBg2 = \"#d5c4a1\"\n\tgruvboxLightBg3 = \"#bdae93\"\n\tgruvboxLightBg4 = \"#a89984\"\n\tgruvboxLightFg0 = \"#282828\"\n\tgruvboxLightFg1 = \"#3c3836\"\n\tgruvboxLightFg2 = \"#504945\"\n\tgruvboxLightFg3 = \"#665c54\"\n\tgruvboxLightFg4 = \"#7c6f64\"\n\tgruvboxLightGray = \"#928374\"\n\tgruvboxLightRed = \"#9d0006\"\n\tgruvboxLightRedBright = \"#cc241d\"\n\tgruvboxLightGreen = \"#79740e\"\n\tgruvboxLightGreenBright = \"#98971a\"\n\tgruvboxLightYellow = \"#b57614\"\n\tgruvboxLightYellowBright = \"#d79921\"\n\tgruvboxLightBlue = \"#076678\"\n\tgruvboxLightBlueBright = \"#458588\"\n\tgruvboxLightPurple = \"#8f3f71\"\n\tgruvboxLightPurpleBright = \"#b16286\"\n\tgruvboxLightAqua = \"#427b58\"\n\tgruvboxLightAquaBright = \"#689d6a\"\n\tgruvboxLightOrange = \"#af3a03\"\n\tgruvboxLightOrangeBright = \"#d65d0e\"\n)\n\n// GruvboxTheme implements the Theme interface with Gruvbox colors.\n// It provides both dark and light variants.\ntype GruvboxTheme struct {\n\tBaseTheme\n}\n\n// NewGruvboxTheme creates a new instance of the Gruvbox theme.\nfunc NewGruvboxTheme() *GruvboxTheme {\n\ttheme := &GruvboxTheme{}\n\n\t// Base colors\n\ttheme.PrimaryColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkBlueBright,\n\t\tLight: gruvboxLightBlueBright,\n\t}\n\ttheme.SecondaryColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkPurpleBright,\n\t\tLight: gruvboxLightPurpleBright,\n\t}\n\ttheme.AccentColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkOrangeBright,\n\t\tLight: gruvboxLightOrangeBright,\n\t}\n\n\t// Status colors\n\ttheme.ErrorColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkRedBright,\n\t\tLight: gruvboxLightRedBright,\n\t}\n\ttheme.WarningColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkYellowBright,\n\t\tLight: gruvboxLightYellowBright,\n\t}\n\ttheme.SuccessColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkGreenBright,\n\t\tLight: gruvboxLightGreenBright,\n\t}\n\ttheme.InfoColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkBlueBright,\n\t\tLight: gruvboxLightBlueBright,\n\t}\n\n\t// Text colors\n\ttheme.TextColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkFg1,\n\t\tLight: gruvboxLightFg1,\n\t}\n\ttheme.TextMutedColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkFg4,\n\t\tLight: gruvboxLightFg4,\n\t}\n\ttheme.TextEmphasizedColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkYellowBright,\n\t\tLight: gruvboxLightYellowBright,\n\t}\n\n\t// Background colors\n\ttheme.BackgroundColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkBg0,\n\t\tLight: gruvboxLightBg0,\n\t}\n\ttheme.BackgroundSecondaryColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkBg1,\n\t\tLight: gruvboxLightBg1,\n\t}\n\ttheme.BackgroundDarkerColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkBg0Soft,\n\t\tLight: gruvboxLightBg0Soft,\n\t}\n\n\t// Border colors\n\ttheme.BorderNormalColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkBg2,\n\t\tLight: gruvboxLightBg2,\n\t}\n\ttheme.BorderFocusedColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkBlueBright,\n\t\tLight: gruvboxLightBlueBright,\n\t}\n\ttheme.BorderDimColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkBg1,\n\t\tLight: gruvboxLightBg1,\n\t}\n\n\t// Diff view colors\n\ttheme.DiffAddedColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkGreenBright,\n\t\tLight: gruvboxLightGreenBright,\n\t}\n\ttheme.DiffRemovedColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkRedBright,\n\t\tLight: gruvboxLightRedBright,\n\t}\n\ttheme.DiffContextColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkFg4,\n\t\tLight: gruvboxLightFg4,\n\t}\n\ttheme.DiffHunkHeaderColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkFg3,\n\t\tLight: gruvboxLightFg3,\n\t}\n\ttheme.DiffHighlightAddedColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkGreenBright,\n\t\tLight: gruvboxLightGreenBright,\n\t}\n\ttheme.DiffHighlightRemovedColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkRedBright,\n\t\tLight: gruvboxLightRedBright,\n\t}\n\ttheme.DiffAddedBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#3C4C3C\", // Darker green background\n\t\tLight: \"#E8F5E9\", // Light green background\n\t}\n\ttheme.DiffRemovedBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#4C3C3C\", // Darker red background\n\t\tLight: \"#FFEBEE\", // Light red background\n\t}\n\ttheme.DiffContextBgColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkBg0,\n\t\tLight: gruvboxLightBg0,\n\t}\n\ttheme.DiffLineNumberColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkFg4,\n\t\tLight: gruvboxLightFg4,\n\t}\n\ttheme.DiffAddedLineNumberBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#32432F\", // Slightly darker green\n\t\tLight: \"#C8E6C9\", // Light green\n\t}\n\ttheme.DiffRemovedLineNumberBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#43322F\", // Slightly darker red\n\t\tLight: \"#FFCDD2\", // Light red\n\t}\n\n\t// Markdown colors\n\ttheme.MarkdownTextColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkFg1,\n\t\tLight: gruvboxLightFg1,\n\t}\n\ttheme.MarkdownHeadingColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkYellowBright,\n\t\tLight: gruvboxLightYellowBright,\n\t}\n\ttheme.MarkdownLinkColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkBlueBright,\n\t\tLight: gruvboxLightBlueBright,\n\t}\n\ttheme.MarkdownLinkTextColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkAquaBright,\n\t\tLight: gruvboxLightAquaBright,\n\t}\n\ttheme.MarkdownCodeColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkGreenBright,\n\t\tLight: gruvboxLightGreenBright,\n\t}\n\ttheme.MarkdownBlockQuoteColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkAquaBright,\n\t\tLight: gruvboxLightAquaBright,\n\t}\n\ttheme.MarkdownEmphColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkYellowBright,\n\t\tLight: gruvboxLightYellowBright,\n\t}\n\ttheme.MarkdownStrongColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkOrangeBright,\n\t\tLight: gruvboxLightOrangeBright,\n\t}\n\ttheme.MarkdownHorizontalRuleColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkBg3,\n\t\tLight: gruvboxLightBg3,\n\t}\n\ttheme.MarkdownListItemColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkBlueBright,\n\t\tLight: gruvboxLightBlueBright,\n\t}\n\ttheme.MarkdownListEnumerationColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkBlueBright,\n\t\tLight: gruvboxLightBlueBright,\n\t}\n\ttheme.MarkdownImageColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkPurpleBright,\n\t\tLight: gruvboxLightPurpleBright,\n\t}\n\ttheme.MarkdownImageTextColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkAquaBright,\n\t\tLight: gruvboxLightAquaBright,\n\t}\n\ttheme.MarkdownCodeBlockColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkFg1,\n\t\tLight: gruvboxLightFg1,\n\t}\n\n\t// Syntax highlighting colors\n\ttheme.SyntaxCommentColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkGray,\n\t\tLight: gruvboxLightGray,\n\t}\n\ttheme.SyntaxKeywordColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkRedBright,\n\t\tLight: gruvboxLightRedBright,\n\t}\n\ttheme.SyntaxFunctionColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkGreenBright,\n\t\tLight: gruvboxLightGreenBright,\n\t}\n\ttheme.SyntaxVariableColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkBlueBright,\n\t\tLight: gruvboxLightBlueBright,\n\t}\n\ttheme.SyntaxStringColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkYellowBright,\n\t\tLight: gruvboxLightYellowBright,\n\t}\n\ttheme.SyntaxNumberColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkPurpleBright,\n\t\tLight: gruvboxLightPurpleBright,\n\t}\n\ttheme.SyntaxTypeColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkYellow,\n\t\tLight: gruvboxLightYellow,\n\t}\n\ttheme.SyntaxOperatorColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkAquaBright,\n\t\tLight: gruvboxLightAquaBright,\n\t}\n\ttheme.SyntaxPunctuationColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkFg1,\n\t\tLight: gruvboxLightFg1,\n\t}\n\n\treturn theme\n}\n\nfunc init() {\n\t// Register the Gruvbox theme with the theme manager\n\tRegisterTheme(\"gruvbox\", NewGruvboxTheme())\n}"], ["/opencode/internal/tui/theme/onedark.go", "package theme\n\nimport (\n\t\"github.com/charmbracelet/lipgloss\"\n)\n\n// OneDarkTheme implements the Theme interface with Atom's One Dark colors.\n// It provides both dark and light variants.\ntype OneDarkTheme struct {\n\tBaseTheme\n}\n\n// NewOneDarkTheme creates a new instance of the One Dark theme.\nfunc NewOneDarkTheme() *OneDarkTheme {\n\t// One Dark color palette\n\t// Dark mode colors from Atom One Dark\n\tdarkBackground := \"#282c34\"\n\tdarkCurrentLine := \"#2c313c\"\n\tdarkSelection := \"#3e4451\"\n\tdarkForeground := \"#abb2bf\"\n\tdarkComment := \"#5c6370\"\n\tdarkRed := \"#e06c75\"\n\tdarkOrange := \"#d19a66\"\n\tdarkYellow := \"#e5c07b\"\n\tdarkGreen := \"#98c379\"\n\tdarkCyan := \"#56b6c2\"\n\tdarkBlue := \"#61afef\"\n\tdarkPurple := \"#c678dd\"\n\tdarkBorder := \"#3b4048\"\n\n\t// Light mode colors from Atom One Light\n\tlightBackground := \"#fafafa\"\n\tlightCurrentLine := \"#f0f0f0\"\n\tlightSelection := \"#e5e5e6\"\n\tlightForeground := \"#383a42\"\n\tlightComment := \"#a0a1a7\"\n\tlightRed := \"#e45649\"\n\tlightOrange := \"#da8548\"\n\tlightYellow := \"#c18401\"\n\tlightGreen := \"#50a14f\"\n\tlightCyan := \"#0184bc\"\n\tlightBlue := \"#4078f2\"\n\tlightPurple := \"#a626a4\"\n\tlightBorder := \"#d3d3d3\"\n\n\ttheme := &OneDarkTheme{}\n\n\t// Base colors\n\ttheme.PrimaryColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBlue,\n\t\tLight: lightBlue,\n\t}\n\ttheme.SecondaryColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPurple,\n\t\tLight: lightPurple,\n\t}\n\ttheme.AccentColor = lipgloss.AdaptiveColor{\n\t\tDark: darkOrange,\n\t\tLight: lightOrange,\n\t}\n\n\t// Status colors\n\ttheme.ErrorColor = lipgloss.AdaptiveColor{\n\t\tDark: darkRed,\n\t\tLight: lightRed,\n\t}\n\ttheme.WarningColor = lipgloss.AdaptiveColor{\n\t\tDark: darkOrange,\n\t\tLight: lightOrange,\n\t}\n\ttheme.SuccessColor = lipgloss.AdaptiveColor{\n\t\tDark: darkGreen,\n\t\tLight: lightGreen,\n\t}\n\ttheme.InfoColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBlue,\n\t\tLight: lightBlue,\n\t}\n\n\t// Text colors\n\ttheme.TextColor = lipgloss.AdaptiveColor{\n\t\tDark: darkForeground,\n\t\tLight: lightForeground,\n\t}\n\ttheme.TextMutedColor = lipgloss.AdaptiveColor{\n\t\tDark: darkComment,\n\t\tLight: lightComment,\n\t}\n\ttheme.TextEmphasizedColor = lipgloss.AdaptiveColor{\n\t\tDark: darkYellow,\n\t\tLight: lightYellow,\n\t}\n\n\t// Background colors\n\ttheme.BackgroundColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBackground,\n\t\tLight: lightBackground,\n\t}\n\ttheme.BackgroundSecondaryColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCurrentLine,\n\t\tLight: lightCurrentLine,\n\t}\n\ttheme.BackgroundDarkerColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#21252b\", // Slightly darker than background\n\t\tLight: \"#ffffff\", // Slightly lighter than background\n\t}\n\n\t// Border colors\n\ttheme.BorderNormalColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBorder,\n\t\tLight: lightBorder,\n\t}\n\ttheme.BorderFocusedColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBlue,\n\t\tLight: lightBlue,\n\t}\n\ttheme.BorderDimColor = lipgloss.AdaptiveColor{\n\t\tDark: darkSelection,\n\t\tLight: lightSelection,\n\t}\n\n\t// Diff view colors\n\ttheme.DiffAddedColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#478247\",\n\t\tLight: \"#2E7D32\",\n\t}\n\ttheme.DiffRemovedColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#7C4444\",\n\t\tLight: \"#C62828\",\n\t}\n\ttheme.DiffContextColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#a0a0a0\",\n\t\tLight: \"#757575\",\n\t}\n\ttheme.DiffHunkHeaderColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#a0a0a0\",\n\t\tLight: \"#757575\",\n\t}\n\ttheme.DiffHighlightAddedColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#DAFADA\",\n\t\tLight: \"#A5D6A7\",\n\t}\n\ttheme.DiffHighlightRemovedColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#FADADD\",\n\t\tLight: \"#EF9A9A\",\n\t}\n\ttheme.DiffAddedBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#303A30\",\n\t\tLight: \"#E8F5E9\",\n\t}\n\ttheme.DiffRemovedBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#3A3030\",\n\t\tLight: \"#FFEBEE\",\n\t}\n\ttheme.DiffContextBgColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBackground,\n\t\tLight: lightBackground,\n\t}\n\ttheme.DiffLineNumberColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#888888\",\n\t\tLight: \"#9E9E9E\",\n\t}\n\ttheme.DiffAddedLineNumberBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#293229\",\n\t\tLight: \"#C8E6C9\",\n\t}\n\ttheme.DiffRemovedLineNumberBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#332929\",\n\t\tLight: \"#FFCDD2\",\n\t}\n\n\t// Markdown colors\n\ttheme.MarkdownTextColor = lipgloss.AdaptiveColor{\n\t\tDark: darkForeground,\n\t\tLight: lightForeground,\n\t}\n\ttheme.MarkdownHeadingColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPurple,\n\t\tLight: lightPurple,\n\t}\n\ttheme.MarkdownLinkColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBlue,\n\t\tLight: lightBlue,\n\t}\n\ttheme.MarkdownLinkTextColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.MarkdownCodeColor = lipgloss.AdaptiveColor{\n\t\tDark: darkGreen,\n\t\tLight: lightGreen,\n\t}\n\ttheme.MarkdownBlockQuoteColor = lipgloss.AdaptiveColor{\n\t\tDark: darkYellow,\n\t\tLight: lightYellow,\n\t}\n\ttheme.MarkdownEmphColor = lipgloss.AdaptiveColor{\n\t\tDark: darkYellow,\n\t\tLight: lightYellow,\n\t}\n\ttheme.MarkdownStrongColor = lipgloss.AdaptiveColor{\n\t\tDark: darkOrange,\n\t\tLight: lightOrange,\n\t}\n\ttheme.MarkdownHorizontalRuleColor = lipgloss.AdaptiveColor{\n\t\tDark: darkComment,\n\t\tLight: lightComment,\n\t}\n\ttheme.MarkdownListItemColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBlue,\n\t\tLight: lightBlue,\n\t}\n\ttheme.MarkdownListEnumerationColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.MarkdownImageColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBlue,\n\t\tLight: lightBlue,\n\t}\n\ttheme.MarkdownImageTextColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.MarkdownCodeBlockColor = lipgloss.AdaptiveColor{\n\t\tDark: darkForeground,\n\t\tLight: lightForeground,\n\t}\n\n\t// Syntax highlighting colors\n\ttheme.SyntaxCommentColor = lipgloss.AdaptiveColor{\n\t\tDark: darkComment,\n\t\tLight: lightComment,\n\t}\n\ttheme.SyntaxKeywordColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPurple,\n\t\tLight: lightPurple,\n\t}\n\ttheme.SyntaxFunctionColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBlue,\n\t\tLight: lightBlue,\n\t}\n\ttheme.SyntaxVariableColor = lipgloss.AdaptiveColor{\n\t\tDark: darkRed,\n\t\tLight: lightRed,\n\t}\n\ttheme.SyntaxStringColor = lipgloss.AdaptiveColor{\n\t\tDark: darkGreen,\n\t\tLight: lightGreen,\n\t}\n\ttheme.SyntaxNumberColor = lipgloss.AdaptiveColor{\n\t\tDark: darkOrange,\n\t\tLight: lightOrange,\n\t}\n\ttheme.SyntaxTypeColor = lipgloss.AdaptiveColor{\n\t\tDark: darkYellow,\n\t\tLight: lightYellow,\n\t}\n\ttheme.SyntaxOperatorColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.SyntaxPunctuationColor = lipgloss.AdaptiveColor{\n\t\tDark: darkForeground,\n\t\tLight: lightForeground,\n\t}\n\n\treturn theme\n}\n\nfunc init() {\n\t// Register the One Dark theme with the theme manager\n\tRegisterTheme(\"onedark\", NewOneDarkTheme())\n}"], ["/opencode/internal/llm/provider/vertexai.go", "package provider\n\nimport (\n\t\"context\"\n\t\"os\"\n\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n\t\"google.golang.org/genai\"\n)\n\ntype VertexAIClient ProviderClient\n\nfunc newVertexAIClient(opts providerClientOptions) VertexAIClient {\n\tgeminiOpts := geminiOptions{}\n\tfor _, o := range opts.geminiOptions {\n\t\to(&geminiOpts)\n\t}\n\n\tclient, err := genai.NewClient(context.Background(), &genai.ClientConfig{\n\t\tProject: os.Getenv(\"VERTEXAI_PROJECT\"),\n\t\tLocation: os.Getenv(\"VERTEXAI_LOCATION\"),\n\t\tBackend: genai.BackendVertexAI,\n\t})\n\tif err != nil {\n\t\tlogging.Error(\"Failed to create VertexAI client\", \"error\", err)\n\t\treturn nil\n\t}\n\n\treturn &geminiClient{\n\t\tproviderOptions: opts,\n\t\toptions: geminiOpts,\n\t\tclient: client,\n\t}\n}\n"], ["/opencode/internal/config/init.go", "package config\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"path/filepath\"\n)\n\nconst (\n\t// InitFlagFilename is the name of the file that indicates whether the project has been initialized\n\tInitFlagFilename = \"init\"\n)\n\n// ProjectInitFlag represents the initialization status for a project directory\ntype ProjectInitFlag struct {\n\tInitialized bool `json:\"initialized\"`\n}\n\n// ShouldShowInitDialog checks if the initialization dialog should be shown for the current directory\nfunc ShouldShowInitDialog() (bool, error) {\n\tif cfg == nil {\n\t\treturn false, fmt.Errorf(\"config not loaded\")\n\t}\n\n\t// Create the flag file path\n\tflagFilePath := filepath.Join(cfg.Data.Directory, InitFlagFilename)\n\n\t// Check if the flag file exists\n\t_, err := os.Stat(flagFilePath)\n\tif err == nil {\n\t\t// File exists, don't show the dialog\n\t\treturn false, nil\n\t}\n\n\t// If the error is not \"file not found\", return the error\n\tif !os.IsNotExist(err) {\n\t\treturn false, fmt.Errorf(\"failed to check init flag file: %w\", err)\n\t}\n\n\t// File doesn't exist, show the dialog\n\treturn true, nil\n}\n\n// MarkProjectInitialized marks the current project as initialized\nfunc MarkProjectInitialized() error {\n\tif cfg == nil {\n\t\treturn fmt.Errorf(\"config not loaded\")\n\t}\n\t// Create the flag file path\n\tflagFilePath := filepath.Join(cfg.Data.Directory, InitFlagFilename)\n\n\t// Create an empty file to mark the project as initialized\n\tfile, err := os.Create(flagFilePath)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to create init flag file: %w\", err)\n\t}\n\tdefer file.Close()\n\n\treturn nil\n}\n\n"], ["/opencode/internal/db/querier.go", "// Code generated by sqlc. DO NOT EDIT.\n// versions:\n// sqlc v1.29.0\n\npackage db\n\nimport (\n\t\"context\"\n)\n\ntype Querier interface {\n\tCreateFile(ctx context.Context, arg CreateFileParams) (File, error)\n\tCreateMessage(ctx context.Context, arg CreateMessageParams) (Message, error)\n\tCreateSession(ctx context.Context, arg CreateSessionParams) (Session, error)\n\tDeleteFile(ctx context.Context, id string) error\n\tDeleteMessage(ctx context.Context, id string) error\n\tDeleteSession(ctx context.Context, id string) error\n\tDeleteSessionFiles(ctx context.Context, sessionID string) error\n\tDeleteSessionMessages(ctx context.Context, sessionID string) error\n\tGetFile(ctx context.Context, id string) (File, error)\n\tGetFileByPathAndSession(ctx context.Context, arg GetFileByPathAndSessionParams) (File, error)\n\tGetMessage(ctx context.Context, id string) (Message, error)\n\tGetSessionByID(ctx context.Context, id string) (Session, error)\n\tListFilesByPath(ctx context.Context, path string) ([]File, error)\n\tListFilesBySession(ctx context.Context, sessionID string) ([]File, error)\n\tListLatestSessionFiles(ctx context.Context, sessionID string) ([]File, error)\n\tListMessagesBySession(ctx context.Context, sessionID string) ([]Message, error)\n\tListNewFiles(ctx context.Context) ([]File, error)\n\tListSessions(ctx context.Context) ([]Session, error)\n\tUpdateFile(ctx context.Context, arg UpdateFileParams) (File, error)\n\tUpdateMessage(ctx context.Context, arg UpdateMessageParams) error\n\tUpdateSession(ctx context.Context, arg UpdateSessionParams) (Session, error)\n}\n\nvar _ Querier = (*Queries)(nil)\n"], ["/opencode/internal/lsp/protocol.go", "package lsp\n\nimport (\n\t\"encoding/json\"\n)\n\n// Message represents a JSON-RPC 2.0 message\ntype Message struct {\n\tJSONRPC string `json:\"jsonrpc\"`\n\tID int32 `json:\"id,omitempty\"`\n\tMethod string `json:\"method,omitempty\"`\n\tParams json.RawMessage `json:\"params,omitempty\"`\n\tResult json.RawMessage `json:\"result,omitempty\"`\n\tError *ResponseError `json:\"error,omitempty\"`\n}\n\n// ResponseError represents a JSON-RPC 2.0 error\ntype ResponseError struct {\n\tCode int `json:\"code\"`\n\tMessage string `json:\"message\"`\n}\n\nfunc NewRequest(id int32, method string, params any) (*Message, error) {\n\tparamsJSON, err := json.Marshal(params)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Message{\n\t\tJSONRPC: \"2.0\",\n\t\tID: id,\n\t\tMethod: method,\n\t\tParams: paramsJSON,\n\t}, nil\n}\n\nfunc NewNotification(method string, params any) (*Message, error) {\n\tparamsJSON, err := json.Marshal(params)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Message{\n\t\tJSONRPC: \"2.0\",\n\t\tMethod: method,\n\t\tParams: paramsJSON,\n\t}, nil\n}\n"], ["/opencode/internal/lsp/language.go", "package lsp\n\nimport (\n\t\"path/filepath\"\n\t\"strings\"\n\n\t\"github.com/opencode-ai/opencode/internal/lsp/protocol\"\n)\n\nfunc DetectLanguageID(uri string) protocol.LanguageKind {\n\text := strings.ToLower(filepath.Ext(uri))\n\tswitch ext {\n\tcase \".abap\":\n\t\treturn protocol.LangABAP\n\tcase \".bat\":\n\t\treturn protocol.LangWindowsBat\n\tcase \".bib\", \".bibtex\":\n\t\treturn protocol.LangBibTeX\n\tcase \".clj\":\n\t\treturn protocol.LangClojure\n\tcase \".coffee\":\n\t\treturn protocol.LangCoffeescript\n\tcase \".c\":\n\t\treturn protocol.LangC\n\tcase \".cpp\", \".cxx\", \".cc\", \".c++\":\n\t\treturn protocol.LangCPP\n\tcase \".cs\":\n\t\treturn protocol.LangCSharp\n\tcase \".css\":\n\t\treturn protocol.LangCSS\n\tcase \".d\":\n\t\treturn protocol.LangD\n\tcase \".pas\", \".pascal\":\n\t\treturn protocol.LangDelphi\n\tcase \".diff\", \".patch\":\n\t\treturn protocol.LangDiff\n\tcase \".dart\":\n\t\treturn protocol.LangDart\n\tcase \".dockerfile\":\n\t\treturn protocol.LangDockerfile\n\tcase \".ex\", \".exs\":\n\t\treturn protocol.LangElixir\n\tcase \".erl\", \".hrl\":\n\t\treturn protocol.LangErlang\n\tcase \".fs\", \".fsi\", \".fsx\", \".fsscript\":\n\t\treturn protocol.LangFSharp\n\tcase \".gitcommit\":\n\t\treturn protocol.LangGitCommit\n\tcase \".gitrebase\":\n\t\treturn protocol.LangGitRebase\n\tcase \".go\":\n\t\treturn protocol.LangGo\n\tcase \".groovy\":\n\t\treturn protocol.LangGroovy\n\tcase \".hbs\", \".handlebars\":\n\t\treturn protocol.LangHandlebars\n\tcase \".hs\":\n\t\treturn protocol.LangHaskell\n\tcase \".html\", \".htm\":\n\t\treturn protocol.LangHTML\n\tcase \".ini\":\n\t\treturn protocol.LangIni\n\tcase \".java\":\n\t\treturn protocol.LangJava\n\tcase \".js\":\n\t\treturn protocol.LangJavaScript\n\tcase \".jsx\":\n\t\treturn protocol.LangJavaScriptReact\n\tcase \".json\":\n\t\treturn protocol.LangJSON\n\tcase \".tex\", \".latex\":\n\t\treturn protocol.LangLaTeX\n\tcase \".less\":\n\t\treturn protocol.LangLess\n\tcase \".lua\":\n\t\treturn protocol.LangLua\n\tcase \".makefile\", \"makefile\":\n\t\treturn protocol.LangMakefile\n\tcase \".md\", \".markdown\":\n\t\treturn protocol.LangMarkdown\n\tcase \".m\":\n\t\treturn protocol.LangObjectiveC\n\tcase \".mm\":\n\t\treturn protocol.LangObjectiveCPP\n\tcase \".pl\":\n\t\treturn protocol.LangPerl\n\tcase \".pm\":\n\t\treturn protocol.LangPerl6\n\tcase \".php\":\n\t\treturn protocol.LangPHP\n\tcase \".ps1\", \".psm1\":\n\t\treturn protocol.LangPowershell\n\tcase \".pug\", \".jade\":\n\t\treturn protocol.LangPug\n\tcase \".py\":\n\t\treturn protocol.LangPython\n\tcase \".r\":\n\t\treturn protocol.LangR\n\tcase \".cshtml\", \".razor\":\n\t\treturn protocol.LangRazor\n\tcase \".rb\":\n\t\treturn protocol.LangRuby\n\tcase \".rs\":\n\t\treturn protocol.LangRust\n\tcase \".scss\":\n\t\treturn protocol.LangSCSS\n\tcase \".sass\":\n\t\treturn protocol.LangSASS\n\tcase \".scala\":\n\t\treturn protocol.LangScala\n\tcase \".shader\":\n\t\treturn protocol.LangShaderLab\n\tcase \".sh\", \".bash\", \".zsh\", \".ksh\":\n\t\treturn protocol.LangShellScript\n\tcase \".sql\":\n\t\treturn protocol.LangSQL\n\tcase \".swift\":\n\t\treturn protocol.LangSwift\n\tcase \".ts\":\n\t\treturn protocol.LangTypeScript\n\tcase \".tsx\":\n\t\treturn protocol.LangTypeScriptReact\n\tcase \".xml\":\n\t\treturn protocol.LangXML\n\tcase \".xsl\":\n\t\treturn protocol.LangXSL\n\tcase \".yaml\", \".yml\":\n\t\treturn protocol.LangYAML\n\tdefault:\n\t\treturn protocol.LanguageKind(\"\") // Unknown language\n\t}\n}\n"], ["/opencode/internal/llm/models/copilot.go", "package models\n\nconst (\n\tProviderCopilot ModelProvider = \"copilot\"\n\n\t// GitHub Copilot models\n\tCopilotGTP35Turbo ModelID = \"copilot.gpt-3.5-turbo\"\n\tCopilotGPT4o ModelID = \"copilot.gpt-4o\"\n\tCopilotGPT4oMini ModelID = \"copilot.gpt-4o-mini\"\n\tCopilotGPT41 ModelID = \"copilot.gpt-4.1\"\n\tCopilotClaude35 ModelID = \"copilot.claude-3.5-sonnet\"\n\tCopilotClaude37 ModelID = \"copilot.claude-3.7-sonnet\"\n\tCopilotClaude4 ModelID = \"copilot.claude-sonnet-4\"\n\tCopilotO1 ModelID = \"copilot.o1\"\n\tCopilotO3Mini ModelID = \"copilot.o3-mini\"\n\tCopilotO4Mini ModelID = \"copilot.o4-mini\"\n\tCopilotGemini20 ModelID = \"copilot.gemini-2.0-flash\"\n\tCopilotGemini25 ModelID = \"copilot.gemini-2.5-pro\"\n\tCopilotGPT4 ModelID = \"copilot.gpt-4\"\n\tCopilotClaude37Thought ModelID = \"copilot.claude-3.7-sonnet-thought\"\n)\n\nvar CopilotAnthropicModels = []ModelID{\n\tCopilotClaude35,\n\tCopilotClaude37,\n\tCopilotClaude37Thought,\n\tCopilotClaude4,\n}\n\n// GitHub Copilot models available through GitHub's API\nvar CopilotModels = map[ModelID]Model{\n\tCopilotGTP35Turbo: {\n\t\tID: CopilotGTP35Turbo,\n\t\tName: \"GitHub Copilot GPT-3.5-turbo\",\n\t\tProvider: ProviderCopilot,\n\t\tAPIModel: \"gpt-3.5-turbo\",\n\t\tCostPer1MIn: 0.0, // Included in GitHub Copilot subscription\n\t\tCostPer1MInCached: 0.0,\n\t\tCostPer1MOutCached: 0.0,\n\t\tCostPer1MOut: 0.0,\n\t\tContextWindow: 16_384,\n\t\tDefaultMaxTokens: 4096,\n\t\tSupportsAttachments: true,\n\t},\n\tCopilotGPT4o: {\n\t\tID: CopilotGPT4o,\n\t\tName: \"GitHub Copilot GPT-4o\",\n\t\tProvider: ProviderCopilot,\n\t\tAPIModel: \"gpt-4o\",\n\t\tCostPer1MIn: 0.0, // Included in GitHub Copilot subscription\n\t\tCostPer1MInCached: 0.0,\n\t\tCostPer1MOutCached: 0.0,\n\t\tCostPer1MOut: 0.0,\n\t\tContextWindow: 128_000,\n\t\tDefaultMaxTokens: 16384,\n\t\tSupportsAttachments: true,\n\t},\n\tCopilotGPT4oMini: {\n\t\tID: CopilotGPT4oMini,\n\t\tName: \"GitHub Copilot GPT-4o Mini\",\n\t\tProvider: ProviderCopilot,\n\t\tAPIModel: \"gpt-4o-mini\",\n\t\tCostPer1MIn: 0.0, // Included in GitHub Copilot subscription\n\t\tCostPer1MInCached: 0.0,\n\t\tCostPer1MOutCached: 0.0,\n\t\tCostPer1MOut: 0.0,\n\t\tContextWindow: 128_000,\n\t\tDefaultMaxTokens: 4096,\n\t\tSupportsAttachments: true,\n\t},\n\tCopilotGPT41: {\n\t\tID: CopilotGPT41,\n\t\tName: \"GitHub Copilot GPT-4.1\",\n\t\tProvider: ProviderCopilot,\n\t\tAPIModel: \"gpt-4.1\",\n\t\tCostPer1MIn: 0.0, // Included in GitHub Copilot subscription\n\t\tCostPer1MInCached: 0.0,\n\t\tCostPer1MOutCached: 0.0,\n\t\tCostPer1MOut: 0.0,\n\t\tContextWindow: 128_000,\n\t\tDefaultMaxTokens: 16384,\n\t\tCanReason: true,\n\t\tSupportsAttachments: true,\n\t},\n\tCopilotClaude35: {\n\t\tID: CopilotClaude35,\n\t\tName: \"GitHub Copilot Claude 3.5 Sonnet\",\n\t\tProvider: ProviderCopilot,\n\t\tAPIModel: \"claude-3.5-sonnet\",\n\t\tCostPer1MIn: 0.0, // Included in GitHub Copilot subscription\n\t\tCostPer1MInCached: 0.0,\n\t\tCostPer1MOutCached: 0.0,\n\t\tCostPer1MOut: 0.0,\n\t\tContextWindow: 90_000,\n\t\tDefaultMaxTokens: 8192,\n\t\tSupportsAttachments: true,\n\t},\n\tCopilotClaude37: {\n\t\tID: CopilotClaude37,\n\t\tName: \"GitHub Copilot Claude 3.7 Sonnet\",\n\t\tProvider: ProviderCopilot,\n\t\tAPIModel: \"claude-3.7-sonnet\",\n\t\tCostPer1MIn: 0.0, // Included in GitHub Copilot subscription\n\t\tCostPer1MInCached: 0.0,\n\t\tCostPer1MOutCached: 0.0,\n\t\tCostPer1MOut: 0.0,\n\t\tContextWindow: 200_000,\n\t\tDefaultMaxTokens: 16384,\n\t\tSupportsAttachments: true,\n\t},\n\tCopilotClaude4: {\n\t\tID: CopilotClaude4,\n\t\tName: \"GitHub Copilot Claude Sonnet 4\",\n\t\tProvider: ProviderCopilot,\n\t\tAPIModel: \"claude-sonnet-4\",\n\t\tCostPer1MIn: 0.0, // Included in GitHub Copilot subscription\n\t\tCostPer1MInCached: 0.0,\n\t\tCostPer1MOutCached: 0.0,\n\t\tCostPer1MOut: 0.0,\n\t\tContextWindow: 128_000,\n\t\tDefaultMaxTokens: 16000,\n\t\tSupportsAttachments: true,\n\t},\n\tCopilotO1: {\n\t\tID: CopilotO1,\n\t\tName: \"GitHub Copilot o1\",\n\t\tProvider: ProviderCopilot,\n\t\tAPIModel: \"o1\",\n\t\tCostPer1MIn: 0.0, // Included in GitHub Copilot subscription\n\t\tCostPer1MInCached: 0.0,\n\t\tCostPer1MOutCached: 0.0,\n\t\tCostPer1MOut: 0.0,\n\t\tContextWindow: 200_000,\n\t\tDefaultMaxTokens: 100_000,\n\t\tCanReason: true,\n\t\tSupportsAttachments: false,\n\t},\n\tCopilotO3Mini: {\n\t\tID: CopilotO3Mini,\n\t\tName: \"GitHub Copilot o3-mini\",\n\t\tProvider: ProviderCopilot,\n\t\tAPIModel: \"o3-mini\",\n\t\tCostPer1MIn: 0.0, // Included in GitHub Copilot subscription\n\t\tCostPer1MInCached: 0.0,\n\t\tCostPer1MOutCached: 0.0,\n\t\tCostPer1MOut: 0.0,\n\t\tContextWindow: 200_000,\n\t\tDefaultMaxTokens: 100_000,\n\t\tCanReason: true,\n\t\tSupportsAttachments: false,\n\t},\n\tCopilotO4Mini: {\n\t\tID: CopilotO4Mini,\n\t\tName: \"GitHub Copilot o4-mini\",\n\t\tProvider: ProviderCopilot,\n\t\tAPIModel: \"o4-mini\",\n\t\tCostPer1MIn: 0.0, // Included in GitHub Copilot subscription\n\t\tCostPer1MInCached: 0.0,\n\t\tCostPer1MOutCached: 0.0,\n\t\tCostPer1MOut: 0.0,\n\t\tContextWindow: 128_000,\n\t\tDefaultMaxTokens: 16_384,\n\t\tCanReason: true,\n\t\tSupportsAttachments: true,\n\t},\n\tCopilotGemini20: {\n\t\tID: CopilotGemini20,\n\t\tName: \"GitHub Copilot Gemini 2.0 Flash\",\n\t\tProvider: ProviderCopilot,\n\t\tAPIModel: \"gemini-2.0-flash-001\",\n\t\tCostPer1MIn: 0.0, // Included in GitHub Copilot subscription\n\t\tCostPer1MInCached: 0.0,\n\t\tCostPer1MOutCached: 0.0,\n\t\tCostPer1MOut: 0.0,\n\t\tContextWindow: 1_000_000,\n\t\tDefaultMaxTokens: 8192,\n\t\tSupportsAttachments: true,\n\t},\n\tCopilotGemini25: {\n\t\tID: CopilotGemini25,\n\t\tName: \"GitHub Copilot Gemini 2.5 Pro\",\n\t\tProvider: ProviderCopilot,\n\t\tAPIModel: \"gemini-2.5-pro\",\n\t\tCostPer1MIn: 0.0, // Included in GitHub Copilot subscription\n\t\tCostPer1MInCached: 0.0,\n\t\tCostPer1MOutCached: 0.0,\n\t\tCostPer1MOut: 0.0,\n\t\tContextWindow: 128_000,\n\t\tDefaultMaxTokens: 64000,\n\t\tSupportsAttachments: true,\n\t},\n\tCopilotGPT4: {\n\t\tID: CopilotGPT4,\n\t\tName: \"GitHub Copilot GPT-4\",\n\t\tProvider: ProviderCopilot,\n\t\tAPIModel: \"gpt-4\",\n\t\tCostPer1MIn: 0.0, // Included in GitHub Copilot subscription\n\t\tCostPer1MInCached: 0.0,\n\t\tCostPer1MOutCached: 0.0,\n\t\tCostPer1MOut: 0.0,\n\t\tContextWindow: 32_768,\n\t\tDefaultMaxTokens: 4096,\n\t\tSupportsAttachments: true,\n\t},\n\tCopilotClaude37Thought: {\n\t\tID: CopilotClaude37Thought,\n\t\tName: \"GitHub Copilot Claude 3.7 Sonnet Thinking\",\n\t\tProvider: ProviderCopilot,\n\t\tAPIModel: \"claude-3.7-sonnet-thought\",\n\t\tCostPer1MIn: 0.0, // Included in GitHub Copilot subscription\n\t\tCostPer1MInCached: 0.0,\n\t\tCostPer1MOutCached: 0.0,\n\t\tCostPer1MOut: 0.0,\n\t\tContextWindow: 200_000,\n\t\tDefaultMaxTokens: 16384,\n\t\tCanReason: true,\n\t\tSupportsAttachments: true,\n\t},\n}\n"], ["/opencode/internal/version/version.go", "package version\n\nimport \"runtime/debug\"\n\n// Build-time parameters set via -ldflags\nvar Version = \"unknown\"\n\n// A user may install pug using `go install github.com/opencode-ai/opencode@latest`.\n// without -ldflags, in which case the version above is unset. As a workaround\n// we use the embedded build version that *is* set when using `go install` (and\n// is only set for `go install` and not for `go build`).\nfunc init() {\n\tinfo, ok := debug.ReadBuildInfo()\n\tif !ok {\n\t\t// < go v1.18\n\t\treturn\n\t}\n\tmainVersion := info.Main.Version\n\tif mainVersion == \"\" || mainVersion == \"(devel)\" {\n\t\t// bin not built using `go install`\n\t\treturn\n\t}\n\t// bin built using `go install`\n\tVersion = mainVersion\n}\n"], ["/opencode/internal/db/models.go", "// Code generated by sqlc. DO NOT EDIT.\n// versions:\n// sqlc v1.29.0\n\npackage db\n\nimport (\n\t\"database/sql\"\n)\n\ntype File struct {\n\tID string `json:\"id\"`\n\tSessionID string `json:\"session_id\"`\n\tPath string `json:\"path\"`\n\tContent string `json:\"content\"`\n\tVersion string `json:\"version\"`\n\tCreatedAt int64 `json:\"created_at\"`\n\tUpdatedAt int64 `json:\"updated_at\"`\n}\n\ntype Message struct {\n\tID string `json:\"id\"`\n\tSessionID string `json:\"session_id\"`\n\tRole string `json:\"role\"`\n\tParts string `json:\"parts\"`\n\tModel sql.NullString `json:\"model\"`\n\tCreatedAt int64 `json:\"created_at\"`\n\tUpdatedAt int64 `json:\"updated_at\"`\n\tFinishedAt sql.NullInt64 `json:\"finished_at\"`\n}\n\ntype Session struct {\n\tID string `json:\"id\"`\n\tParentSessionID sql.NullString `json:\"parent_session_id\"`\n\tTitle string `json:\"title\"`\n\tMessageCount int64 `json:\"message_count\"`\n\tPromptTokens int64 `json:\"prompt_tokens\"`\n\tCompletionTokens int64 `json:\"completion_tokens\"`\n\tCost float64 `json:\"cost\"`\n\tUpdatedAt int64 `json:\"updated_at\"`\n\tCreatedAt int64 `json:\"created_at\"`\n\tSummaryMessageID sql.NullString `json:\"summary_message_id\"`\n}\n"], ["/opencode/internal/tui/theme/theme.go", "package theme\n\nimport (\n\t\"github.com/charmbracelet/lipgloss\"\n)\n\n// Theme defines the interface for all UI themes in the application.\n// All colors must be defined as lipgloss.AdaptiveColor to support\n// both light and dark terminal backgrounds.\ntype Theme interface {\n\t// Base colors\n\tPrimary() lipgloss.AdaptiveColor\n\tSecondary() lipgloss.AdaptiveColor\n\tAccent() lipgloss.AdaptiveColor\n\n\t// Status colors\n\tError() lipgloss.AdaptiveColor\n\tWarning() lipgloss.AdaptiveColor\n\tSuccess() lipgloss.AdaptiveColor\n\tInfo() lipgloss.AdaptiveColor\n\n\t// Text colors\n\tText() lipgloss.AdaptiveColor\n\tTextMuted() lipgloss.AdaptiveColor\n\tTextEmphasized() lipgloss.AdaptiveColor\n\n\t// Background colors\n\tBackground() lipgloss.AdaptiveColor\n\tBackgroundSecondary() lipgloss.AdaptiveColor\n\tBackgroundDarker() lipgloss.AdaptiveColor\n\n\t// Border colors\n\tBorderNormal() lipgloss.AdaptiveColor\n\tBorderFocused() lipgloss.AdaptiveColor\n\tBorderDim() lipgloss.AdaptiveColor\n\n\t// Diff view colors\n\tDiffAdded() lipgloss.AdaptiveColor\n\tDiffRemoved() lipgloss.AdaptiveColor\n\tDiffContext() lipgloss.AdaptiveColor\n\tDiffHunkHeader() lipgloss.AdaptiveColor\n\tDiffHighlightAdded() lipgloss.AdaptiveColor\n\tDiffHighlightRemoved() lipgloss.AdaptiveColor\n\tDiffAddedBg() lipgloss.AdaptiveColor\n\tDiffRemovedBg() lipgloss.AdaptiveColor\n\tDiffContextBg() lipgloss.AdaptiveColor\n\tDiffLineNumber() lipgloss.AdaptiveColor\n\tDiffAddedLineNumberBg() lipgloss.AdaptiveColor\n\tDiffRemovedLineNumberBg() lipgloss.AdaptiveColor\n\n\t// Markdown colors\n\tMarkdownText() lipgloss.AdaptiveColor\n\tMarkdownHeading() lipgloss.AdaptiveColor\n\tMarkdownLink() lipgloss.AdaptiveColor\n\tMarkdownLinkText() lipgloss.AdaptiveColor\n\tMarkdownCode() lipgloss.AdaptiveColor\n\tMarkdownBlockQuote() lipgloss.AdaptiveColor\n\tMarkdownEmph() lipgloss.AdaptiveColor\n\tMarkdownStrong() lipgloss.AdaptiveColor\n\tMarkdownHorizontalRule() lipgloss.AdaptiveColor\n\tMarkdownListItem() lipgloss.AdaptiveColor\n\tMarkdownListEnumeration() lipgloss.AdaptiveColor\n\tMarkdownImage() lipgloss.AdaptiveColor\n\tMarkdownImageText() lipgloss.AdaptiveColor\n\tMarkdownCodeBlock() lipgloss.AdaptiveColor\n\n\t// Syntax highlighting colors\n\tSyntaxComment() lipgloss.AdaptiveColor\n\tSyntaxKeyword() lipgloss.AdaptiveColor\n\tSyntaxFunction() lipgloss.AdaptiveColor\n\tSyntaxVariable() lipgloss.AdaptiveColor\n\tSyntaxString() lipgloss.AdaptiveColor\n\tSyntaxNumber() lipgloss.AdaptiveColor\n\tSyntaxType() lipgloss.AdaptiveColor\n\tSyntaxOperator() lipgloss.AdaptiveColor\n\tSyntaxPunctuation() lipgloss.AdaptiveColor\n}\n\n// BaseTheme provides a default implementation of the Theme interface\n// that can be embedded in concrete theme implementations.\ntype BaseTheme struct {\n\t// Base colors\n\tPrimaryColor lipgloss.AdaptiveColor\n\tSecondaryColor lipgloss.AdaptiveColor\n\tAccentColor lipgloss.AdaptiveColor\n\n\t// Status colors\n\tErrorColor lipgloss.AdaptiveColor\n\tWarningColor lipgloss.AdaptiveColor\n\tSuccessColor lipgloss.AdaptiveColor\n\tInfoColor lipgloss.AdaptiveColor\n\n\t// Text colors\n\tTextColor lipgloss.AdaptiveColor\n\tTextMutedColor lipgloss.AdaptiveColor\n\tTextEmphasizedColor lipgloss.AdaptiveColor\n\n\t// Background colors\n\tBackgroundColor lipgloss.AdaptiveColor\n\tBackgroundSecondaryColor lipgloss.AdaptiveColor\n\tBackgroundDarkerColor lipgloss.AdaptiveColor\n\n\t// Border colors\n\tBorderNormalColor lipgloss.AdaptiveColor\n\tBorderFocusedColor lipgloss.AdaptiveColor\n\tBorderDimColor lipgloss.AdaptiveColor\n\n\t// Diff view colors\n\tDiffAddedColor lipgloss.AdaptiveColor\n\tDiffRemovedColor lipgloss.AdaptiveColor\n\tDiffContextColor lipgloss.AdaptiveColor\n\tDiffHunkHeaderColor lipgloss.AdaptiveColor\n\tDiffHighlightAddedColor lipgloss.AdaptiveColor\n\tDiffHighlightRemovedColor lipgloss.AdaptiveColor\n\tDiffAddedBgColor lipgloss.AdaptiveColor\n\tDiffRemovedBgColor lipgloss.AdaptiveColor\n\tDiffContextBgColor lipgloss.AdaptiveColor\n\tDiffLineNumberColor lipgloss.AdaptiveColor\n\tDiffAddedLineNumberBgColor lipgloss.AdaptiveColor\n\tDiffRemovedLineNumberBgColor lipgloss.AdaptiveColor\n\n\t// Markdown colors\n\tMarkdownTextColor lipgloss.AdaptiveColor\n\tMarkdownHeadingColor lipgloss.AdaptiveColor\n\tMarkdownLinkColor lipgloss.AdaptiveColor\n\tMarkdownLinkTextColor lipgloss.AdaptiveColor\n\tMarkdownCodeColor lipgloss.AdaptiveColor\n\tMarkdownBlockQuoteColor lipgloss.AdaptiveColor\n\tMarkdownEmphColor lipgloss.AdaptiveColor\n\tMarkdownStrongColor lipgloss.AdaptiveColor\n\tMarkdownHorizontalRuleColor lipgloss.AdaptiveColor\n\tMarkdownListItemColor lipgloss.AdaptiveColor\n\tMarkdownListEnumerationColor lipgloss.AdaptiveColor\n\tMarkdownImageColor lipgloss.AdaptiveColor\n\tMarkdownImageTextColor lipgloss.AdaptiveColor\n\tMarkdownCodeBlockColor lipgloss.AdaptiveColor\n\n\t// Syntax highlighting colors\n\tSyntaxCommentColor lipgloss.AdaptiveColor\n\tSyntaxKeywordColor lipgloss.AdaptiveColor\n\tSyntaxFunctionColor lipgloss.AdaptiveColor\n\tSyntaxVariableColor lipgloss.AdaptiveColor\n\tSyntaxStringColor lipgloss.AdaptiveColor\n\tSyntaxNumberColor lipgloss.AdaptiveColor\n\tSyntaxTypeColor lipgloss.AdaptiveColor\n\tSyntaxOperatorColor lipgloss.AdaptiveColor\n\tSyntaxPunctuationColor lipgloss.AdaptiveColor\n}\n\n// Implement the Theme interface for BaseTheme\nfunc (t *BaseTheme) Primary() lipgloss.AdaptiveColor { return t.PrimaryColor }\nfunc (t *BaseTheme) Secondary() lipgloss.AdaptiveColor { return t.SecondaryColor }\nfunc (t *BaseTheme) Accent() lipgloss.AdaptiveColor { return t.AccentColor }\n\nfunc (t *BaseTheme) Error() lipgloss.AdaptiveColor { return t.ErrorColor }\nfunc (t *BaseTheme) Warning() lipgloss.AdaptiveColor { return t.WarningColor }\nfunc (t *BaseTheme) Success() lipgloss.AdaptiveColor { return t.SuccessColor }\nfunc (t *BaseTheme) Info() lipgloss.AdaptiveColor { return t.InfoColor }\n\nfunc (t *BaseTheme) Text() lipgloss.AdaptiveColor { return t.TextColor }\nfunc (t *BaseTheme) TextMuted() lipgloss.AdaptiveColor { return t.TextMutedColor }\nfunc (t *BaseTheme) TextEmphasized() lipgloss.AdaptiveColor { return t.TextEmphasizedColor }\n\nfunc (t *BaseTheme) Background() lipgloss.AdaptiveColor { return t.BackgroundColor }\nfunc (t *BaseTheme) BackgroundSecondary() lipgloss.AdaptiveColor { return t.BackgroundSecondaryColor }\nfunc (t *BaseTheme) BackgroundDarker() lipgloss.AdaptiveColor { return t.BackgroundDarkerColor }\n\nfunc (t *BaseTheme) BorderNormal() lipgloss.AdaptiveColor { return t.BorderNormalColor }\nfunc (t *BaseTheme) BorderFocused() lipgloss.AdaptiveColor { return t.BorderFocusedColor }\nfunc (t *BaseTheme) BorderDim() lipgloss.AdaptiveColor { return t.BorderDimColor }\n\nfunc (t *BaseTheme) DiffAdded() lipgloss.AdaptiveColor { return t.DiffAddedColor }\nfunc (t *BaseTheme) DiffRemoved() lipgloss.AdaptiveColor { return t.DiffRemovedColor }\nfunc (t *BaseTheme) DiffContext() lipgloss.AdaptiveColor { return t.DiffContextColor }\nfunc (t *BaseTheme) DiffHunkHeader() lipgloss.AdaptiveColor { return t.DiffHunkHeaderColor }\nfunc (t *BaseTheme) DiffHighlightAdded() lipgloss.AdaptiveColor { return t.DiffHighlightAddedColor }\nfunc (t *BaseTheme) DiffHighlightRemoved() lipgloss.AdaptiveColor { return t.DiffHighlightRemovedColor }\nfunc (t *BaseTheme) DiffAddedBg() lipgloss.AdaptiveColor { return t.DiffAddedBgColor }\nfunc (t *BaseTheme) DiffRemovedBg() lipgloss.AdaptiveColor { return t.DiffRemovedBgColor }\nfunc (t *BaseTheme) DiffContextBg() lipgloss.AdaptiveColor { return t.DiffContextBgColor }\nfunc (t *BaseTheme) DiffLineNumber() lipgloss.AdaptiveColor { return t.DiffLineNumberColor }\nfunc (t *BaseTheme) DiffAddedLineNumberBg() lipgloss.AdaptiveColor { return t.DiffAddedLineNumberBgColor }\nfunc (t *BaseTheme) DiffRemovedLineNumberBg() lipgloss.AdaptiveColor { return t.DiffRemovedLineNumberBgColor }\n\nfunc (t *BaseTheme) MarkdownText() lipgloss.AdaptiveColor { return t.MarkdownTextColor }\nfunc (t *BaseTheme) MarkdownHeading() lipgloss.AdaptiveColor { return t.MarkdownHeadingColor }\nfunc (t *BaseTheme) MarkdownLink() lipgloss.AdaptiveColor { return t.MarkdownLinkColor }\nfunc (t *BaseTheme) MarkdownLinkText() lipgloss.AdaptiveColor { return t.MarkdownLinkTextColor }\nfunc (t *BaseTheme) MarkdownCode() lipgloss.AdaptiveColor { return t.MarkdownCodeColor }\nfunc (t *BaseTheme) MarkdownBlockQuote() lipgloss.AdaptiveColor { return t.MarkdownBlockQuoteColor }\nfunc (t *BaseTheme) MarkdownEmph() lipgloss.AdaptiveColor { return t.MarkdownEmphColor }\nfunc (t *BaseTheme) MarkdownStrong() lipgloss.AdaptiveColor { return t.MarkdownStrongColor }\nfunc (t *BaseTheme) MarkdownHorizontalRule() lipgloss.AdaptiveColor { return t.MarkdownHorizontalRuleColor }\nfunc (t *BaseTheme) MarkdownListItem() lipgloss.AdaptiveColor { return t.MarkdownListItemColor }\nfunc (t *BaseTheme) MarkdownListEnumeration() lipgloss.AdaptiveColor { return t.MarkdownListEnumerationColor }\nfunc (t *BaseTheme) MarkdownImage() lipgloss.AdaptiveColor { return t.MarkdownImageColor }\nfunc (t *BaseTheme) MarkdownImageText() lipgloss.AdaptiveColor { return t.MarkdownImageTextColor }\nfunc (t *BaseTheme) MarkdownCodeBlock() lipgloss.AdaptiveColor { return t.MarkdownCodeBlockColor }\n\nfunc (t *BaseTheme) SyntaxComment() lipgloss.AdaptiveColor { return t.SyntaxCommentColor }\nfunc (t *BaseTheme) SyntaxKeyword() lipgloss.AdaptiveColor { return t.SyntaxKeywordColor }\nfunc (t *BaseTheme) SyntaxFunction() lipgloss.AdaptiveColor { return t.SyntaxFunctionColor }\nfunc (t *BaseTheme) SyntaxVariable() lipgloss.AdaptiveColor { return t.SyntaxVariableColor }\nfunc (t *BaseTheme) SyntaxString() lipgloss.AdaptiveColor { return t.SyntaxStringColor }\nfunc (t *BaseTheme) SyntaxNumber() lipgloss.AdaptiveColor { return t.SyntaxNumberColor }\nfunc (t *BaseTheme) SyntaxType() lipgloss.AdaptiveColor { return t.SyntaxTypeColor }\nfunc (t *BaseTheme) SyntaxOperator() lipgloss.AdaptiveColor { return t.SyntaxOperatorColor }\nfunc (t *BaseTheme) SyntaxPunctuation() lipgloss.AdaptiveColor { return t.SyntaxPunctuationColor }"], ["/opencode/internal/llm/models/groq.go", "package models\n\nconst (\n\tProviderGROQ ModelProvider = \"groq\"\n\n\t// GROQ\n\tQWENQwq ModelID = \"qwen-qwq\"\n\n\t// GROQ preview models\n\tLlama4Scout ModelID = \"meta-llama/llama-4-scout-17b-16e-instruct\"\n\tLlama4Maverick ModelID = \"meta-llama/llama-4-maverick-17b-128e-instruct\"\n\tLlama3_3_70BVersatile ModelID = \"llama-3.3-70b-versatile\"\n\tDeepseekR1DistillLlama70b ModelID = \"deepseek-r1-distill-llama-70b\"\n)\n\nvar GroqModels = map[ModelID]Model{\n\t//\n\t// GROQ\n\tQWENQwq: {\n\t\tID: QWENQwq,\n\t\tName: \"Qwen Qwq\",\n\t\tProvider: ProviderGROQ,\n\t\tAPIModel: \"qwen-qwq-32b\",\n\t\tCostPer1MIn: 0.29,\n\t\tCostPer1MInCached: 0.275,\n\t\tCostPer1MOutCached: 0.0,\n\t\tCostPer1MOut: 0.39,\n\t\tContextWindow: 128_000,\n\t\tDefaultMaxTokens: 50000,\n\t\t// for some reason, the groq api doesn't like the reasoningEffort parameter\n\t\tCanReason: false,\n\t\tSupportsAttachments: false,\n\t},\n\n\tLlama4Scout: {\n\t\tID: Llama4Scout,\n\t\tName: \"Llama4Scout\",\n\t\tProvider: ProviderGROQ,\n\t\tAPIModel: \"meta-llama/llama-4-scout-17b-16e-instruct\",\n\t\tCostPer1MIn: 0.11,\n\t\tCostPer1MInCached: 0,\n\t\tCostPer1MOutCached: 0,\n\t\tCostPer1MOut: 0.34,\n\t\tContextWindow: 128_000, // 10M when?\n\t\tSupportsAttachments: true,\n\t},\n\n\tLlama4Maverick: {\n\t\tID: Llama4Maverick,\n\t\tName: \"Llama4Maverick\",\n\t\tProvider: ProviderGROQ,\n\t\tAPIModel: \"meta-llama/llama-4-maverick-17b-128e-instruct\",\n\t\tCostPer1MIn: 0.20,\n\t\tCostPer1MInCached: 0,\n\t\tCostPer1MOutCached: 0,\n\t\tCostPer1MOut: 0.20,\n\t\tContextWindow: 128_000,\n\t\tSupportsAttachments: true,\n\t},\n\n\tLlama3_3_70BVersatile: {\n\t\tID: Llama3_3_70BVersatile,\n\t\tName: \"Llama3_3_70BVersatile\",\n\t\tProvider: ProviderGROQ,\n\t\tAPIModel: \"llama-3.3-70b-versatile\",\n\t\tCostPer1MIn: 0.59,\n\t\tCostPer1MInCached: 0,\n\t\tCostPer1MOutCached: 0,\n\t\tCostPer1MOut: 0.79,\n\t\tContextWindow: 128_000,\n\t\tSupportsAttachments: false,\n\t},\n\n\tDeepseekR1DistillLlama70b: {\n\t\tID: DeepseekR1DistillLlama70b,\n\t\tName: \"DeepseekR1DistillLlama70b\",\n\t\tProvider: ProviderGROQ,\n\t\tAPIModel: \"deepseek-r1-distill-llama-70b\",\n\t\tCostPer1MIn: 0.75,\n\t\tCostPer1MInCached: 0,\n\t\tCostPer1MOutCached: 0,\n\t\tCostPer1MOut: 0.99,\n\t\tContextWindow: 128_000,\n\t\tCanReason: true,\n\t\tSupportsAttachments: false,\n\t},\n}\n"], ["/opencode/internal/llm/prompt/task.go", "package prompt\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/opencode-ai/opencode/internal/llm/models\"\n)\n\nfunc TaskPrompt(_ models.ModelProvider) string {\n\tagentPrompt := `You are an agent for OpenCode. Given the user's prompt, you should use the tools available to you to answer the user's question.\nNotes:\n1. IMPORTANT: You should be concise, direct, and to the point, since your responses will be displayed on a command line interface. Answer the user's question directly, without elaboration, explanation, or details. One word answers are best. Avoid introductions, conclusions, and explanations. You MUST avoid text before/after your response, such as \"The answer is .\", \"Here is the content of the file...\" or \"Based on the information provided, the answer is...\" or \"Here is what I will do next...\".\n2. When relevant, share file names and code snippets relevant to the query\n3. Any file paths you return in your final response MUST be absolute. DO NOT use relative paths.`\n\n\treturn fmt.Sprintf(\"%s\\n%s\\n\", agentPrompt, getEnvironmentInfo())\n}\n"], ["/opencode/internal/llm/models/openrouter.go", "package models\n\nconst (\n\tProviderOpenRouter ModelProvider = \"openrouter\"\n\n\tOpenRouterGPT41 ModelID = \"openrouter.gpt-4.1\"\n\tOpenRouterGPT41Mini ModelID = \"openrouter.gpt-4.1-mini\"\n\tOpenRouterGPT41Nano ModelID = \"openrouter.gpt-4.1-nano\"\n\tOpenRouterGPT45Preview ModelID = \"openrouter.gpt-4.5-preview\"\n\tOpenRouterGPT4o ModelID = \"openrouter.gpt-4o\"\n\tOpenRouterGPT4oMini ModelID = \"openrouter.gpt-4o-mini\"\n\tOpenRouterO1 ModelID = \"openrouter.o1\"\n\tOpenRouterO1Pro ModelID = \"openrouter.o1-pro\"\n\tOpenRouterO1Mini ModelID = \"openrouter.o1-mini\"\n\tOpenRouterO3 ModelID = \"openrouter.o3\"\n\tOpenRouterO3Mini ModelID = \"openrouter.o3-mini\"\n\tOpenRouterO4Mini ModelID = \"openrouter.o4-mini\"\n\tOpenRouterGemini25Flash ModelID = \"openrouter.gemini-2.5-flash\"\n\tOpenRouterGemini25 ModelID = \"openrouter.gemini-2.5\"\n\tOpenRouterClaude35Sonnet ModelID = \"openrouter.claude-3.5-sonnet\"\n\tOpenRouterClaude3Haiku ModelID = \"openrouter.claude-3-haiku\"\n\tOpenRouterClaude37Sonnet ModelID = \"openrouter.claude-3.7-sonnet\"\n\tOpenRouterClaude35Haiku ModelID = \"openrouter.claude-3.5-haiku\"\n\tOpenRouterClaude3Opus ModelID = \"openrouter.claude-3-opus\"\n\tOpenRouterDeepSeekR1Free ModelID = \"openrouter.deepseek-r1-free\"\n)\n\nvar OpenRouterModels = map[ModelID]Model{\n\tOpenRouterGPT41: {\n\t\tID: OpenRouterGPT41,\n\t\tName: \"OpenRouter – GPT 4.1\",\n\t\tProvider: ProviderOpenRouter,\n\t\tAPIModel: \"openai/gpt-4.1\",\n\t\tCostPer1MIn: OpenAIModels[GPT41].CostPer1MIn,\n\t\tCostPer1MInCached: OpenAIModels[GPT41].CostPer1MInCached,\n\t\tCostPer1MOut: OpenAIModels[GPT41].CostPer1MOut,\n\t\tCostPer1MOutCached: OpenAIModels[GPT41].CostPer1MOutCached,\n\t\tContextWindow: OpenAIModels[GPT41].ContextWindow,\n\t\tDefaultMaxTokens: OpenAIModels[GPT41].DefaultMaxTokens,\n\t},\n\tOpenRouterGPT41Mini: {\n\t\tID: OpenRouterGPT41Mini,\n\t\tName: \"OpenRouter – GPT 4.1 mini\",\n\t\tProvider: ProviderOpenRouter,\n\t\tAPIModel: \"openai/gpt-4.1-mini\",\n\t\tCostPer1MIn: OpenAIModels[GPT41Mini].CostPer1MIn,\n\t\tCostPer1MInCached: OpenAIModels[GPT41Mini].CostPer1MInCached,\n\t\tCostPer1MOut: OpenAIModels[GPT41Mini].CostPer1MOut,\n\t\tCostPer1MOutCached: OpenAIModels[GPT41Mini].CostPer1MOutCached,\n\t\tContextWindow: OpenAIModels[GPT41Mini].ContextWindow,\n\t\tDefaultMaxTokens: OpenAIModels[GPT41Mini].DefaultMaxTokens,\n\t},\n\tOpenRouterGPT41Nano: {\n\t\tID: OpenRouterGPT41Nano,\n\t\tName: \"OpenRouter – GPT 4.1 nano\",\n\t\tProvider: ProviderOpenRouter,\n\t\tAPIModel: \"openai/gpt-4.1-nano\",\n\t\tCostPer1MIn: OpenAIModels[GPT41Nano].CostPer1MIn,\n\t\tCostPer1MInCached: OpenAIModels[GPT41Nano].CostPer1MInCached,\n\t\tCostPer1MOut: OpenAIModels[GPT41Nano].CostPer1MOut,\n\t\tCostPer1MOutCached: OpenAIModels[GPT41Nano].CostPer1MOutCached,\n\t\tContextWindow: OpenAIModels[GPT41Nano].ContextWindow,\n\t\tDefaultMaxTokens: OpenAIModels[GPT41Nano].DefaultMaxTokens,\n\t},\n\tOpenRouterGPT45Preview: {\n\t\tID: OpenRouterGPT45Preview,\n\t\tName: \"OpenRouter – GPT 4.5 preview\",\n\t\tProvider: ProviderOpenRouter,\n\t\tAPIModel: \"openai/gpt-4.5-preview\",\n\t\tCostPer1MIn: OpenAIModels[GPT45Preview].CostPer1MIn,\n\t\tCostPer1MInCached: OpenAIModels[GPT45Preview].CostPer1MInCached,\n\t\tCostPer1MOut: OpenAIModels[GPT45Preview].CostPer1MOut,\n\t\tCostPer1MOutCached: OpenAIModels[GPT45Preview].CostPer1MOutCached,\n\t\tContextWindow: OpenAIModels[GPT45Preview].ContextWindow,\n\t\tDefaultMaxTokens: OpenAIModels[GPT45Preview].DefaultMaxTokens,\n\t},\n\tOpenRouterGPT4o: {\n\t\tID: OpenRouterGPT4o,\n\t\tName: \"OpenRouter – GPT 4o\",\n\t\tProvider: ProviderOpenRouter,\n\t\tAPIModel: \"openai/gpt-4o\",\n\t\tCostPer1MIn: OpenAIModels[GPT4o].CostPer1MIn,\n\t\tCostPer1MInCached: OpenAIModels[GPT4o].CostPer1MInCached,\n\t\tCostPer1MOut: OpenAIModels[GPT4o].CostPer1MOut,\n\t\tCostPer1MOutCached: OpenAIModels[GPT4o].CostPer1MOutCached,\n\t\tContextWindow: OpenAIModels[GPT4o].ContextWindow,\n\t\tDefaultMaxTokens: OpenAIModels[GPT4o].DefaultMaxTokens,\n\t},\n\tOpenRouterGPT4oMini: {\n\t\tID: OpenRouterGPT4oMini,\n\t\tName: \"OpenRouter – GPT 4o mini\",\n\t\tProvider: ProviderOpenRouter,\n\t\tAPIModel: \"openai/gpt-4o-mini\",\n\t\tCostPer1MIn: OpenAIModels[GPT4oMini].CostPer1MIn,\n\t\tCostPer1MInCached: OpenAIModels[GPT4oMini].CostPer1MInCached,\n\t\tCostPer1MOut: OpenAIModels[GPT4oMini].CostPer1MOut,\n\t\tCostPer1MOutCached: OpenAIModels[GPT4oMini].CostPer1MOutCached,\n\t\tContextWindow: OpenAIModels[GPT4oMini].ContextWindow,\n\t},\n\tOpenRouterO1: {\n\t\tID: OpenRouterO1,\n\t\tName: \"OpenRouter – O1\",\n\t\tProvider: ProviderOpenRouter,\n\t\tAPIModel: \"openai/o1\",\n\t\tCostPer1MIn: OpenAIModels[O1].CostPer1MIn,\n\t\tCostPer1MInCached: OpenAIModels[O1].CostPer1MInCached,\n\t\tCostPer1MOut: OpenAIModels[O1].CostPer1MOut,\n\t\tCostPer1MOutCached: OpenAIModels[O1].CostPer1MOutCached,\n\t\tContextWindow: OpenAIModels[O1].ContextWindow,\n\t\tDefaultMaxTokens: OpenAIModels[O1].DefaultMaxTokens,\n\t\tCanReason: OpenAIModels[O1].CanReason,\n\t},\n\tOpenRouterO1Pro: {\n\t\tID: OpenRouterO1Pro,\n\t\tName: \"OpenRouter – o1 pro\",\n\t\tProvider: ProviderOpenRouter,\n\t\tAPIModel: \"openai/o1-pro\",\n\t\tCostPer1MIn: OpenAIModels[O1Pro].CostPer1MIn,\n\t\tCostPer1MInCached: OpenAIModels[O1Pro].CostPer1MInCached,\n\t\tCostPer1MOut: OpenAIModels[O1Pro].CostPer1MOut,\n\t\tCostPer1MOutCached: OpenAIModels[O1Pro].CostPer1MOutCached,\n\t\tContextWindow: OpenAIModels[O1Pro].ContextWindow,\n\t\tDefaultMaxTokens: OpenAIModels[O1Pro].DefaultMaxTokens,\n\t\tCanReason: OpenAIModels[O1Pro].CanReason,\n\t},\n\tOpenRouterO1Mini: {\n\t\tID: OpenRouterO1Mini,\n\t\tName: \"OpenRouter – o1 mini\",\n\t\tProvider: ProviderOpenRouter,\n\t\tAPIModel: \"openai/o1-mini\",\n\t\tCostPer1MIn: OpenAIModels[O1Mini].CostPer1MIn,\n\t\tCostPer1MInCached: OpenAIModels[O1Mini].CostPer1MInCached,\n\t\tCostPer1MOut: OpenAIModels[O1Mini].CostPer1MOut,\n\t\tCostPer1MOutCached: OpenAIModels[O1Mini].CostPer1MOutCached,\n\t\tContextWindow: OpenAIModels[O1Mini].ContextWindow,\n\t\tDefaultMaxTokens: OpenAIModels[O1Mini].DefaultMaxTokens,\n\t\tCanReason: OpenAIModels[O1Mini].CanReason,\n\t},\n\tOpenRouterO3: {\n\t\tID: OpenRouterO3,\n\t\tName: \"OpenRouter – o3\",\n\t\tProvider: ProviderOpenRouter,\n\t\tAPIModel: \"openai/o3\",\n\t\tCostPer1MIn: OpenAIModels[O3].CostPer1MIn,\n\t\tCostPer1MInCached: OpenAIModels[O3].CostPer1MInCached,\n\t\tCostPer1MOut: OpenAIModels[O3].CostPer1MOut,\n\t\tCostPer1MOutCached: OpenAIModels[O3].CostPer1MOutCached,\n\t\tContextWindow: OpenAIModels[O3].ContextWindow,\n\t\tDefaultMaxTokens: OpenAIModels[O3].DefaultMaxTokens,\n\t\tCanReason: OpenAIModels[O3].CanReason,\n\t},\n\tOpenRouterO3Mini: {\n\t\tID: OpenRouterO3Mini,\n\t\tName: \"OpenRouter – o3 mini\",\n\t\tProvider: ProviderOpenRouter,\n\t\tAPIModel: \"openai/o3-mini-high\",\n\t\tCostPer1MIn: OpenAIModels[O3Mini].CostPer1MIn,\n\t\tCostPer1MInCached: OpenAIModels[O3Mini].CostPer1MInCached,\n\t\tCostPer1MOut: OpenAIModels[O3Mini].CostPer1MOut,\n\t\tCostPer1MOutCached: OpenAIModels[O3Mini].CostPer1MOutCached,\n\t\tContextWindow: OpenAIModels[O3Mini].ContextWindow,\n\t\tDefaultMaxTokens: OpenAIModels[O3Mini].DefaultMaxTokens,\n\t\tCanReason: OpenAIModels[O3Mini].CanReason,\n\t},\n\tOpenRouterO4Mini: {\n\t\tID: OpenRouterO4Mini,\n\t\tName: \"OpenRouter – o4 mini\",\n\t\tProvider: ProviderOpenRouter,\n\t\tAPIModel: \"openai/o4-mini-high\",\n\t\tCostPer1MIn: OpenAIModels[O4Mini].CostPer1MIn,\n\t\tCostPer1MInCached: OpenAIModels[O4Mini].CostPer1MInCached,\n\t\tCostPer1MOut: OpenAIModels[O4Mini].CostPer1MOut,\n\t\tCostPer1MOutCached: OpenAIModels[O4Mini].CostPer1MOutCached,\n\t\tContextWindow: OpenAIModels[O4Mini].ContextWindow,\n\t\tDefaultMaxTokens: OpenAIModels[O4Mini].DefaultMaxTokens,\n\t\tCanReason: OpenAIModels[O4Mini].CanReason,\n\t},\n\tOpenRouterGemini25Flash: {\n\t\tID: OpenRouterGemini25Flash,\n\t\tName: \"OpenRouter – Gemini 2.5 Flash\",\n\t\tProvider: ProviderOpenRouter,\n\t\tAPIModel: \"google/gemini-2.5-flash-preview:thinking\",\n\t\tCostPer1MIn: GeminiModels[Gemini25Flash].CostPer1MIn,\n\t\tCostPer1MInCached: GeminiModels[Gemini25Flash].CostPer1MInCached,\n\t\tCostPer1MOut: GeminiModels[Gemini25Flash].CostPer1MOut,\n\t\tCostPer1MOutCached: GeminiModels[Gemini25Flash].CostPer1MOutCached,\n\t\tContextWindow: GeminiModels[Gemini25Flash].ContextWindow,\n\t\tDefaultMaxTokens: GeminiModels[Gemini25Flash].DefaultMaxTokens,\n\t},\n\tOpenRouterGemini25: {\n\t\tID: OpenRouterGemini25,\n\t\tName: \"OpenRouter – Gemini 2.5 Pro\",\n\t\tProvider: ProviderOpenRouter,\n\t\tAPIModel: \"google/gemini-2.5-pro-preview-03-25\",\n\t\tCostPer1MIn: GeminiModels[Gemini25].CostPer1MIn,\n\t\tCostPer1MInCached: GeminiModels[Gemini25].CostPer1MInCached,\n\t\tCostPer1MOut: GeminiModels[Gemini25].CostPer1MOut,\n\t\tCostPer1MOutCached: GeminiModels[Gemini25].CostPer1MOutCached,\n\t\tContextWindow: GeminiModels[Gemini25].ContextWindow,\n\t\tDefaultMaxTokens: GeminiModels[Gemini25].DefaultMaxTokens,\n\t},\n\tOpenRouterClaude35Sonnet: {\n\t\tID: OpenRouterClaude35Sonnet,\n\t\tName: \"OpenRouter – Claude 3.5 Sonnet\",\n\t\tProvider: ProviderOpenRouter,\n\t\tAPIModel: \"anthropic/claude-3.5-sonnet\",\n\t\tCostPer1MIn: AnthropicModels[Claude35Sonnet].CostPer1MIn,\n\t\tCostPer1MInCached: AnthropicModels[Claude35Sonnet].CostPer1MInCached,\n\t\tCostPer1MOut: AnthropicModels[Claude35Sonnet].CostPer1MOut,\n\t\tCostPer1MOutCached: AnthropicModels[Claude35Sonnet].CostPer1MOutCached,\n\t\tContextWindow: AnthropicModels[Claude35Sonnet].ContextWindow,\n\t\tDefaultMaxTokens: AnthropicModels[Claude35Sonnet].DefaultMaxTokens,\n\t},\n\tOpenRouterClaude3Haiku: {\n\t\tID: OpenRouterClaude3Haiku,\n\t\tName: \"OpenRouter – Claude 3 Haiku\",\n\t\tProvider: ProviderOpenRouter,\n\t\tAPIModel: \"anthropic/claude-3-haiku\",\n\t\tCostPer1MIn: AnthropicModels[Claude3Haiku].CostPer1MIn,\n\t\tCostPer1MInCached: AnthropicModels[Claude3Haiku].CostPer1MInCached,\n\t\tCostPer1MOut: AnthropicModels[Claude3Haiku].CostPer1MOut,\n\t\tCostPer1MOutCached: AnthropicModels[Claude3Haiku].CostPer1MOutCached,\n\t\tContextWindow: AnthropicModels[Claude3Haiku].ContextWindow,\n\t\tDefaultMaxTokens: AnthropicModels[Claude3Haiku].DefaultMaxTokens,\n\t},\n\tOpenRouterClaude37Sonnet: {\n\t\tID: OpenRouterClaude37Sonnet,\n\t\tName: \"OpenRouter – Claude 3.7 Sonnet\",\n\t\tProvider: ProviderOpenRouter,\n\t\tAPIModel: \"anthropic/claude-3.7-sonnet\",\n\t\tCostPer1MIn: AnthropicModels[Claude37Sonnet].CostPer1MIn,\n\t\tCostPer1MInCached: AnthropicModels[Claude37Sonnet].CostPer1MInCached,\n\t\tCostPer1MOut: AnthropicModels[Claude37Sonnet].CostPer1MOut,\n\t\tCostPer1MOutCached: AnthropicModels[Claude37Sonnet].CostPer1MOutCached,\n\t\tContextWindow: AnthropicModels[Claude37Sonnet].ContextWindow,\n\t\tDefaultMaxTokens: AnthropicModels[Claude37Sonnet].DefaultMaxTokens,\n\t\tCanReason: AnthropicModels[Claude37Sonnet].CanReason,\n\t},\n\tOpenRouterClaude35Haiku: {\n\t\tID: OpenRouterClaude35Haiku,\n\t\tName: \"OpenRouter – Claude 3.5 Haiku\",\n\t\tProvider: ProviderOpenRouter,\n\t\tAPIModel: \"anthropic/claude-3.5-haiku\",\n\t\tCostPer1MIn: AnthropicModels[Claude35Haiku].CostPer1MIn,\n\t\tCostPer1MInCached: AnthropicModels[Claude35Haiku].CostPer1MInCached,\n\t\tCostPer1MOut: AnthropicModels[Claude35Haiku].CostPer1MOut,\n\t\tCostPer1MOutCached: AnthropicModels[Claude35Haiku].CostPer1MOutCached,\n\t\tContextWindow: AnthropicModels[Claude35Haiku].ContextWindow,\n\t\tDefaultMaxTokens: AnthropicModels[Claude35Haiku].DefaultMaxTokens,\n\t},\n\tOpenRouterClaude3Opus: {\n\t\tID: OpenRouterClaude3Opus,\n\t\tName: \"OpenRouter – Claude 3 Opus\",\n\t\tProvider: ProviderOpenRouter,\n\t\tAPIModel: \"anthropic/claude-3-opus\",\n\t\tCostPer1MIn: AnthropicModels[Claude3Opus].CostPer1MIn,\n\t\tCostPer1MInCached: AnthropicModels[Claude3Opus].CostPer1MInCached,\n\t\tCostPer1MOut: AnthropicModels[Claude3Opus].CostPer1MOut,\n\t\tCostPer1MOutCached: AnthropicModels[Claude3Opus].CostPer1MOutCached,\n\t\tContextWindow: AnthropicModels[Claude3Opus].ContextWindow,\n\t\tDefaultMaxTokens: AnthropicModels[Claude3Opus].DefaultMaxTokens,\n\t},\n\n\tOpenRouterDeepSeekR1Free: {\n\t\tID: OpenRouterDeepSeekR1Free,\n\t\tName: \"OpenRouter – DeepSeek R1 Free\",\n\t\tProvider: ProviderOpenRouter,\n\t\tAPIModel: \"deepseek/deepseek-r1-0528:free\",\n\t\tCostPer1MIn: 0,\n\t\tCostPer1MInCached: 0,\n\t\tCostPer1MOut: 0,\n\t\tCostPer1MOutCached: 0,\n\t\tContextWindow: 163_840,\n\t\tDefaultMaxTokens: 10000,\n\t},\n}\n"], ["/opencode/internal/llm/models/openai.go", "package models\n\nconst (\n\tProviderOpenAI ModelProvider = \"openai\"\n\n\tGPT41 ModelID = \"gpt-4.1\"\n\tGPT41Mini ModelID = \"gpt-4.1-mini\"\n\tGPT41Nano ModelID = \"gpt-4.1-nano\"\n\tGPT45Preview ModelID = \"gpt-4.5-preview\"\n\tGPT4o ModelID = \"gpt-4o\"\n\tGPT4oMini ModelID = \"gpt-4o-mini\"\n\tO1 ModelID = \"o1\"\n\tO1Pro ModelID = \"o1-pro\"\n\tO1Mini ModelID = \"o1-mini\"\n\tO3 ModelID = \"o3\"\n\tO3Mini ModelID = \"o3-mini\"\n\tO4Mini ModelID = \"o4-mini\"\n)\n\nvar OpenAIModels = map[ModelID]Model{\n\tGPT41: {\n\t\tID: GPT41,\n\t\tName: \"GPT 4.1\",\n\t\tProvider: ProviderOpenAI,\n\t\tAPIModel: \"gpt-4.1\",\n\t\tCostPer1MIn: 2.00,\n\t\tCostPer1MInCached: 0.50,\n\t\tCostPer1MOutCached: 0.0,\n\t\tCostPer1MOut: 8.00,\n\t\tContextWindow: 1_047_576,\n\t\tDefaultMaxTokens: 20000,\n\t\tSupportsAttachments: true,\n\t},\n\tGPT41Mini: {\n\t\tID: GPT41Mini,\n\t\tName: \"GPT 4.1 mini\",\n\t\tProvider: ProviderOpenAI,\n\t\tAPIModel: \"gpt-4.1\",\n\t\tCostPer1MIn: 0.40,\n\t\tCostPer1MInCached: 0.10,\n\t\tCostPer1MOutCached: 0.0,\n\t\tCostPer1MOut: 1.60,\n\t\tContextWindow: 200_000,\n\t\tDefaultMaxTokens: 20000,\n\t\tSupportsAttachments: true,\n\t},\n\tGPT41Nano: {\n\t\tID: GPT41Nano,\n\t\tName: \"GPT 4.1 nano\",\n\t\tProvider: ProviderOpenAI,\n\t\tAPIModel: \"gpt-4.1-nano\",\n\t\tCostPer1MIn: 0.10,\n\t\tCostPer1MInCached: 0.025,\n\t\tCostPer1MOutCached: 0.0,\n\t\tCostPer1MOut: 0.40,\n\t\tContextWindow: 1_047_576,\n\t\tDefaultMaxTokens: 20000,\n\t\tSupportsAttachments: true,\n\t},\n\tGPT45Preview: {\n\t\tID: GPT45Preview,\n\t\tName: \"GPT 4.5 preview\",\n\t\tProvider: ProviderOpenAI,\n\t\tAPIModel: \"gpt-4.5-preview\",\n\t\tCostPer1MIn: 75.00,\n\t\tCostPer1MInCached: 37.50,\n\t\tCostPer1MOutCached: 0.0,\n\t\tCostPer1MOut: 150.00,\n\t\tContextWindow: 128_000,\n\t\tDefaultMaxTokens: 15000,\n\t\tSupportsAttachments: true,\n\t},\n\tGPT4o: {\n\t\tID: GPT4o,\n\t\tName: \"GPT 4o\",\n\t\tProvider: ProviderOpenAI,\n\t\tAPIModel: \"gpt-4o\",\n\t\tCostPer1MIn: 2.50,\n\t\tCostPer1MInCached: 1.25,\n\t\tCostPer1MOutCached: 0.0,\n\t\tCostPer1MOut: 10.00,\n\t\tContextWindow: 128_000,\n\t\tDefaultMaxTokens: 4096,\n\t\tSupportsAttachments: true,\n\t},\n\tGPT4oMini: {\n\t\tID: GPT4oMini,\n\t\tName: \"GPT 4o mini\",\n\t\tProvider: ProviderOpenAI,\n\t\tAPIModel: \"gpt-4o-mini\",\n\t\tCostPer1MIn: 0.15,\n\t\tCostPer1MInCached: 0.075,\n\t\tCostPer1MOutCached: 0.0,\n\t\tCostPer1MOut: 0.60,\n\t\tContextWindow: 128_000,\n\t\tSupportsAttachments: true,\n\t},\n\tO1: {\n\t\tID: O1,\n\t\tName: \"O1\",\n\t\tProvider: ProviderOpenAI,\n\t\tAPIModel: \"o1\",\n\t\tCostPer1MIn: 15.00,\n\t\tCostPer1MInCached: 7.50,\n\t\tCostPer1MOutCached: 0.0,\n\t\tCostPer1MOut: 60.00,\n\t\tContextWindow: 200_000,\n\t\tDefaultMaxTokens: 50000,\n\t\tCanReason: true,\n\t\tSupportsAttachments: true,\n\t},\n\tO1Pro: {\n\t\tID: O1Pro,\n\t\tName: \"o1 pro\",\n\t\tProvider: ProviderOpenAI,\n\t\tAPIModel: \"o1-pro\",\n\t\tCostPer1MIn: 150.00,\n\t\tCostPer1MInCached: 0.0,\n\t\tCostPer1MOutCached: 0.0,\n\t\tCostPer1MOut: 600.00,\n\t\tContextWindow: 200_000,\n\t\tDefaultMaxTokens: 50000,\n\t\tCanReason: true,\n\t\tSupportsAttachments: true,\n\t},\n\tO1Mini: {\n\t\tID: O1Mini,\n\t\tName: \"o1 mini\",\n\t\tProvider: ProviderOpenAI,\n\t\tAPIModel: \"o1-mini\",\n\t\tCostPer1MIn: 1.10,\n\t\tCostPer1MInCached: 0.55,\n\t\tCostPer1MOutCached: 0.0,\n\t\tCostPer1MOut: 4.40,\n\t\tContextWindow: 128_000,\n\t\tDefaultMaxTokens: 50000,\n\t\tCanReason: true,\n\t\tSupportsAttachments: true,\n\t},\n\tO3: {\n\t\tID: O3,\n\t\tName: \"o3\",\n\t\tProvider: ProviderOpenAI,\n\t\tAPIModel: \"o3\",\n\t\tCostPer1MIn: 10.00,\n\t\tCostPer1MInCached: 2.50,\n\t\tCostPer1MOutCached: 0.0,\n\t\tCostPer1MOut: 40.00,\n\t\tContextWindow: 200_000,\n\t\tCanReason: true,\n\t\tSupportsAttachments: true,\n\t},\n\tO3Mini: {\n\t\tID: O3Mini,\n\t\tName: \"o3 mini\",\n\t\tProvider: ProviderOpenAI,\n\t\tAPIModel: \"o3-mini\",\n\t\tCostPer1MIn: 1.10,\n\t\tCostPer1MInCached: 0.55,\n\t\tCostPer1MOutCached: 0.0,\n\t\tCostPer1MOut: 4.40,\n\t\tContextWindow: 200_000,\n\t\tDefaultMaxTokens: 50000,\n\t\tCanReason: true,\n\t\tSupportsAttachments: false,\n\t},\n\tO4Mini: {\n\t\tID: O4Mini,\n\t\tName: \"o4 mini\",\n\t\tProvider: ProviderOpenAI,\n\t\tAPIModel: \"o4-mini\",\n\t\tCostPer1MIn: 1.10,\n\t\tCostPer1MInCached: 0.275,\n\t\tCostPer1MOutCached: 0.0,\n\t\tCostPer1MOut: 4.40,\n\t\tContextWindow: 128_000,\n\t\tDefaultMaxTokens: 50000,\n\t\tCanReason: true,\n\t\tSupportsAttachments: true,\n\t},\n}\n"], ["/opencode/internal/llm/models/azure.go", "package models\n\nconst ProviderAzure ModelProvider = \"azure\"\n\nconst (\n\tAzureGPT41 ModelID = \"azure.gpt-4.1\"\n\tAzureGPT41Mini ModelID = \"azure.gpt-4.1-mini\"\n\tAzureGPT41Nano ModelID = \"azure.gpt-4.1-nano\"\n\tAzureGPT45Preview ModelID = \"azure.gpt-4.5-preview\"\n\tAzureGPT4o ModelID = \"azure.gpt-4o\"\n\tAzureGPT4oMini ModelID = \"azure.gpt-4o-mini\"\n\tAzureO1 ModelID = \"azure.o1\"\n\tAzureO1Mini ModelID = \"azure.o1-mini\"\n\tAzureO3 ModelID = \"azure.o3\"\n\tAzureO3Mini ModelID = \"azure.o3-mini\"\n\tAzureO4Mini ModelID = \"azure.o4-mini\"\n)\n\nvar AzureModels = map[ModelID]Model{\n\tAzureGPT41: {\n\t\tID: AzureGPT41,\n\t\tName: \"Azure OpenAI – GPT 4.1\",\n\t\tProvider: ProviderAzure,\n\t\tAPIModel: \"gpt-4.1\",\n\t\tCostPer1MIn: OpenAIModels[GPT41].CostPer1MIn,\n\t\tCostPer1MInCached: OpenAIModels[GPT41].CostPer1MInCached,\n\t\tCostPer1MOut: OpenAIModels[GPT41].CostPer1MOut,\n\t\tCostPer1MOutCached: OpenAIModels[GPT41].CostPer1MOutCached,\n\t\tContextWindow: OpenAIModels[GPT41].ContextWindow,\n\t\tDefaultMaxTokens: OpenAIModels[GPT41].DefaultMaxTokens,\n\t\tSupportsAttachments: true,\n\t},\n\tAzureGPT41Mini: {\n\t\tID: AzureGPT41Mini,\n\t\tName: \"Azure OpenAI – GPT 4.1 mini\",\n\t\tProvider: ProviderAzure,\n\t\tAPIModel: \"gpt-4.1-mini\",\n\t\tCostPer1MIn: OpenAIModels[GPT41Mini].CostPer1MIn,\n\t\tCostPer1MInCached: OpenAIModels[GPT41Mini].CostPer1MInCached,\n\t\tCostPer1MOut: OpenAIModels[GPT41Mini].CostPer1MOut,\n\t\tCostPer1MOutCached: OpenAIModels[GPT41Mini].CostPer1MOutCached,\n\t\tContextWindow: OpenAIModels[GPT41Mini].ContextWindow,\n\t\tDefaultMaxTokens: OpenAIModels[GPT41Mini].DefaultMaxTokens,\n\t\tSupportsAttachments: true,\n\t},\n\tAzureGPT41Nano: {\n\t\tID: AzureGPT41Nano,\n\t\tName: \"Azure OpenAI – GPT 4.1 nano\",\n\t\tProvider: ProviderAzure,\n\t\tAPIModel: \"gpt-4.1-nano\",\n\t\tCostPer1MIn: OpenAIModels[GPT41Nano].CostPer1MIn,\n\t\tCostPer1MInCached: OpenAIModels[GPT41Nano].CostPer1MInCached,\n\t\tCostPer1MOut: OpenAIModels[GPT41Nano].CostPer1MOut,\n\t\tCostPer1MOutCached: OpenAIModels[GPT41Nano].CostPer1MOutCached,\n\t\tContextWindow: OpenAIModels[GPT41Nano].ContextWindow,\n\t\tDefaultMaxTokens: OpenAIModels[GPT41Nano].DefaultMaxTokens,\n\t\tSupportsAttachments: true,\n\t},\n\tAzureGPT45Preview: {\n\t\tID: AzureGPT45Preview,\n\t\tName: \"Azure OpenAI – GPT 4.5 preview\",\n\t\tProvider: ProviderAzure,\n\t\tAPIModel: \"gpt-4.5-preview\",\n\t\tCostPer1MIn: OpenAIModels[GPT45Preview].CostPer1MIn,\n\t\tCostPer1MInCached: OpenAIModels[GPT45Preview].CostPer1MInCached,\n\t\tCostPer1MOut: OpenAIModels[GPT45Preview].CostPer1MOut,\n\t\tCostPer1MOutCached: OpenAIModels[GPT45Preview].CostPer1MOutCached,\n\t\tContextWindow: OpenAIModels[GPT45Preview].ContextWindow,\n\t\tDefaultMaxTokens: OpenAIModels[GPT45Preview].DefaultMaxTokens,\n\t\tSupportsAttachments: true,\n\t},\n\tAzureGPT4o: {\n\t\tID: AzureGPT4o,\n\t\tName: \"Azure OpenAI – GPT-4o\",\n\t\tProvider: ProviderAzure,\n\t\tAPIModel: \"gpt-4o\",\n\t\tCostPer1MIn: OpenAIModels[GPT4o].CostPer1MIn,\n\t\tCostPer1MInCached: OpenAIModels[GPT4o].CostPer1MInCached,\n\t\tCostPer1MOut: OpenAIModels[GPT4o].CostPer1MOut,\n\t\tCostPer1MOutCached: OpenAIModels[GPT4o].CostPer1MOutCached,\n\t\tContextWindow: OpenAIModels[GPT4o].ContextWindow,\n\t\tDefaultMaxTokens: OpenAIModels[GPT4o].DefaultMaxTokens,\n\t\tSupportsAttachments: true,\n\t},\n\tAzureGPT4oMini: {\n\t\tID: AzureGPT4oMini,\n\t\tName: \"Azure OpenAI – GPT-4o mini\",\n\t\tProvider: ProviderAzure,\n\t\tAPIModel: \"gpt-4o-mini\",\n\t\tCostPer1MIn: OpenAIModels[GPT4oMini].CostPer1MIn,\n\t\tCostPer1MInCached: OpenAIModels[GPT4oMini].CostPer1MInCached,\n\t\tCostPer1MOut: OpenAIModels[GPT4oMini].CostPer1MOut,\n\t\tCostPer1MOutCached: OpenAIModels[GPT4oMini].CostPer1MOutCached,\n\t\tContextWindow: OpenAIModels[GPT4oMini].ContextWindow,\n\t\tDefaultMaxTokens: OpenAIModels[GPT4oMini].DefaultMaxTokens,\n\t\tSupportsAttachments: true,\n\t},\n\tAzureO1: {\n\t\tID: AzureO1,\n\t\tName: \"Azure OpenAI – O1\",\n\t\tProvider: ProviderAzure,\n\t\tAPIModel: \"o1\",\n\t\tCostPer1MIn: OpenAIModels[O1].CostPer1MIn,\n\t\tCostPer1MInCached: OpenAIModels[O1].CostPer1MInCached,\n\t\tCostPer1MOut: OpenAIModels[O1].CostPer1MOut,\n\t\tCostPer1MOutCached: OpenAIModels[O1].CostPer1MOutCached,\n\t\tContextWindow: OpenAIModels[O1].ContextWindow,\n\t\tDefaultMaxTokens: OpenAIModels[O1].DefaultMaxTokens,\n\t\tCanReason: OpenAIModels[O1].CanReason,\n\t\tSupportsAttachments: true,\n\t},\n\tAzureO1Mini: {\n\t\tID: AzureO1Mini,\n\t\tName: \"Azure OpenAI – O1 mini\",\n\t\tProvider: ProviderAzure,\n\t\tAPIModel: \"o1-mini\",\n\t\tCostPer1MIn: OpenAIModels[O1Mini].CostPer1MIn,\n\t\tCostPer1MInCached: OpenAIModels[O1Mini].CostPer1MInCached,\n\t\tCostPer1MOut: OpenAIModels[O1Mini].CostPer1MOut,\n\t\tCostPer1MOutCached: OpenAIModels[O1Mini].CostPer1MOutCached,\n\t\tContextWindow: OpenAIModels[O1Mini].ContextWindow,\n\t\tDefaultMaxTokens: OpenAIModels[O1Mini].DefaultMaxTokens,\n\t\tCanReason: OpenAIModels[O1Mini].CanReason,\n\t\tSupportsAttachments: true,\n\t},\n\tAzureO3: {\n\t\tID: AzureO3,\n\t\tName: \"Azure OpenAI – O3\",\n\t\tProvider: ProviderAzure,\n\t\tAPIModel: \"o3\",\n\t\tCostPer1MIn: OpenAIModels[O3].CostPer1MIn,\n\t\tCostPer1MInCached: OpenAIModels[O3].CostPer1MInCached,\n\t\tCostPer1MOut: OpenAIModels[O3].CostPer1MOut,\n\t\tCostPer1MOutCached: OpenAIModels[O3].CostPer1MOutCached,\n\t\tContextWindow: OpenAIModels[O3].ContextWindow,\n\t\tDefaultMaxTokens: OpenAIModels[O3].DefaultMaxTokens,\n\t\tCanReason: OpenAIModels[O3].CanReason,\n\t\tSupportsAttachments: true,\n\t},\n\tAzureO3Mini: {\n\t\tID: AzureO3Mini,\n\t\tName: \"Azure OpenAI – O3 mini\",\n\t\tProvider: ProviderAzure,\n\t\tAPIModel: \"o3-mini\",\n\t\tCostPer1MIn: OpenAIModels[O3Mini].CostPer1MIn,\n\t\tCostPer1MInCached: OpenAIModels[O3Mini].CostPer1MInCached,\n\t\tCostPer1MOut: OpenAIModels[O3Mini].CostPer1MOut,\n\t\tCostPer1MOutCached: OpenAIModels[O3Mini].CostPer1MOutCached,\n\t\tContextWindow: OpenAIModels[O3Mini].ContextWindow,\n\t\tDefaultMaxTokens: OpenAIModels[O3Mini].DefaultMaxTokens,\n\t\tCanReason: OpenAIModels[O3Mini].CanReason,\n\t\tSupportsAttachments: false,\n\t},\n\tAzureO4Mini: {\n\t\tID: AzureO4Mini,\n\t\tName: \"Azure OpenAI – O4 mini\",\n\t\tProvider: ProviderAzure,\n\t\tAPIModel: \"o4-mini\",\n\t\tCostPer1MIn: OpenAIModels[O4Mini].CostPer1MIn,\n\t\tCostPer1MInCached: OpenAIModels[O4Mini].CostPer1MInCached,\n\t\tCostPer1MOut: OpenAIModels[O4Mini].CostPer1MOut,\n\t\tCostPer1MOutCached: OpenAIModels[O4Mini].CostPer1MOutCached,\n\t\tContextWindow: OpenAIModels[O4Mini].ContextWindow,\n\t\tDefaultMaxTokens: OpenAIModels[O4Mini].DefaultMaxTokens,\n\t\tCanReason: OpenAIModels[O4Mini].CanReason,\n\t\tSupportsAttachments: true,\n\t},\n}\n"], ["/opencode/internal/llm/models/anthropic.go", "package models\n\nconst (\n\tProviderAnthropic ModelProvider = \"anthropic\"\n\n\t// Models\n\tClaude35Sonnet ModelID = \"claude-3.5-sonnet\"\n\tClaude3Haiku ModelID = \"claude-3-haiku\"\n\tClaude37Sonnet ModelID = \"claude-3.7-sonnet\"\n\tClaude35Haiku ModelID = \"claude-3.5-haiku\"\n\tClaude3Opus ModelID = \"claude-3-opus\"\n\tClaude4Opus ModelID = \"claude-4-opus\"\n\tClaude4Sonnet ModelID = \"claude-4-sonnet\"\n)\n\n// https://docs.anthropic.com/en/docs/about-claude/models/all-models\nvar AnthropicModels = map[ModelID]Model{\n\tClaude35Sonnet: {\n\t\tID: Claude35Sonnet,\n\t\tName: \"Claude 3.5 Sonnet\",\n\t\tProvider: ProviderAnthropic,\n\t\tAPIModel: \"claude-3-5-sonnet-latest\",\n\t\tCostPer1MIn: 3.0,\n\t\tCostPer1MInCached: 3.75,\n\t\tCostPer1MOutCached: 0.30,\n\t\tCostPer1MOut: 15.0,\n\t\tContextWindow: 200000,\n\t\tDefaultMaxTokens: 5000,\n\t\tSupportsAttachments: true,\n\t},\n\tClaude3Haiku: {\n\t\tID: Claude3Haiku,\n\t\tName: \"Claude 3 Haiku\",\n\t\tProvider: ProviderAnthropic,\n\t\tAPIModel: \"claude-3-haiku-20240307\", // doesn't support \"-latest\"\n\t\tCostPer1MIn: 0.25,\n\t\tCostPer1MInCached: 0.30,\n\t\tCostPer1MOutCached: 0.03,\n\t\tCostPer1MOut: 1.25,\n\t\tContextWindow: 200000,\n\t\tDefaultMaxTokens: 4096,\n\t\tSupportsAttachments: true,\n\t},\n\tClaude37Sonnet: {\n\t\tID: Claude37Sonnet,\n\t\tName: \"Claude 3.7 Sonnet\",\n\t\tProvider: ProviderAnthropic,\n\t\tAPIModel: \"claude-3-7-sonnet-latest\",\n\t\tCostPer1MIn: 3.0,\n\t\tCostPer1MInCached: 3.75,\n\t\tCostPer1MOutCached: 0.30,\n\t\tCostPer1MOut: 15.0,\n\t\tContextWindow: 200000,\n\t\tDefaultMaxTokens: 50000,\n\t\tCanReason: true,\n\t\tSupportsAttachments: true,\n\t},\n\tClaude35Haiku: {\n\t\tID: Claude35Haiku,\n\t\tName: \"Claude 3.5 Haiku\",\n\t\tProvider: ProviderAnthropic,\n\t\tAPIModel: \"claude-3-5-haiku-latest\",\n\t\tCostPer1MIn: 0.80,\n\t\tCostPer1MInCached: 1.0,\n\t\tCostPer1MOutCached: 0.08,\n\t\tCostPer1MOut: 4.0,\n\t\tContextWindow: 200000,\n\t\tDefaultMaxTokens: 4096,\n\t\tSupportsAttachments: true,\n\t},\n\tClaude3Opus: {\n\t\tID: Claude3Opus,\n\t\tName: \"Claude 3 Opus\",\n\t\tProvider: ProviderAnthropic,\n\t\tAPIModel: \"claude-3-opus-latest\",\n\t\tCostPer1MIn: 15.0,\n\t\tCostPer1MInCached: 18.75,\n\t\tCostPer1MOutCached: 1.50,\n\t\tCostPer1MOut: 75.0,\n\t\tContextWindow: 200000,\n\t\tDefaultMaxTokens: 4096,\n\t\tSupportsAttachments: true,\n\t},\n\tClaude4Sonnet: {\n\t\tID: Claude4Sonnet,\n\t\tName: \"Claude 4 Sonnet\",\n\t\tProvider: ProviderAnthropic,\n\t\tAPIModel: \"claude-sonnet-4-20250514\",\n\t\tCostPer1MIn: 3.0,\n\t\tCostPer1MInCached: 3.75,\n\t\tCostPer1MOutCached: 0.30,\n\t\tCostPer1MOut: 15.0,\n\t\tContextWindow: 200000,\n\t\tDefaultMaxTokens: 50000,\n\t\tCanReason: true,\n\t\tSupportsAttachments: true,\n\t},\n\tClaude4Opus: {\n\t\tID: Claude4Opus,\n\t\tName: \"Claude 4 Opus\",\n\t\tProvider: ProviderAnthropic,\n\t\tAPIModel: \"claude-opus-4-20250514\",\n\t\tCostPer1MIn: 15.0,\n\t\tCostPer1MInCached: 18.75,\n\t\tCostPer1MOutCached: 1.50,\n\t\tCostPer1MOut: 75.0,\n\t\tContextWindow: 200000,\n\t\tDefaultMaxTokens: 4096,\n\t\tSupportsAttachments: true,\n\t},\n}\n"], ["/opencode/internal/llm/models/gemini.go", "package models\n\nconst (\n\tProviderGemini ModelProvider = \"gemini\"\n\n\t// Models\n\tGemini25Flash ModelID = \"gemini-2.5-flash\"\n\tGemini25 ModelID = \"gemini-2.5\"\n\tGemini20Flash ModelID = \"gemini-2.0-flash\"\n\tGemini20FlashLite ModelID = \"gemini-2.0-flash-lite\"\n)\n\nvar GeminiModels = map[ModelID]Model{\n\tGemini25Flash: {\n\t\tID: Gemini25Flash,\n\t\tName: \"Gemini 2.5 Flash\",\n\t\tProvider: ProviderGemini,\n\t\tAPIModel: \"gemini-2.5-flash-preview-04-17\",\n\t\tCostPer1MIn: 0.15,\n\t\tCostPer1MInCached: 0,\n\t\tCostPer1MOutCached: 0,\n\t\tCostPer1MOut: 0.60,\n\t\tContextWindow: 1000000,\n\t\tDefaultMaxTokens: 50000,\n\t\tSupportsAttachments: true,\n\t},\n\tGemini25: {\n\t\tID: Gemini25,\n\t\tName: \"Gemini 2.5 Pro\",\n\t\tProvider: ProviderGemini,\n\t\tAPIModel: \"gemini-2.5-pro-preview-05-06\",\n\t\tCostPer1MIn: 1.25,\n\t\tCostPer1MInCached: 0,\n\t\tCostPer1MOutCached: 0,\n\t\tCostPer1MOut: 10,\n\t\tContextWindow: 1000000,\n\t\tDefaultMaxTokens: 50000,\n\t\tSupportsAttachments: true,\n\t},\n\n\tGemini20Flash: {\n\t\tID: Gemini20Flash,\n\t\tName: \"Gemini 2.0 Flash\",\n\t\tProvider: ProviderGemini,\n\t\tAPIModel: \"gemini-2.0-flash\",\n\t\tCostPer1MIn: 0.10,\n\t\tCostPer1MInCached: 0,\n\t\tCostPer1MOutCached: 0,\n\t\tCostPer1MOut: 0.40,\n\t\tContextWindow: 1000000,\n\t\tDefaultMaxTokens: 6000,\n\t\tSupportsAttachments: true,\n\t},\n\tGemini20FlashLite: {\n\t\tID: Gemini20FlashLite,\n\t\tName: \"Gemini 2.0 Flash Lite\",\n\t\tProvider: ProviderGemini,\n\t\tAPIModel: \"gemini-2.0-flash-lite\",\n\t\tCostPer1MIn: 0.05,\n\t\tCostPer1MInCached: 0,\n\t\tCostPer1MOutCached: 0,\n\t\tCostPer1MOut: 0.30,\n\t\tContextWindow: 1000000,\n\t\tDefaultMaxTokens: 6000,\n\t\tSupportsAttachments: true,\n\t},\n}\n"], ["/opencode/internal/llm/models/vertexai.go", "package models\n\nconst (\n\tProviderVertexAI ModelProvider = \"vertexai\"\n\n\t// Models\n\tVertexAIGemini25Flash ModelID = \"vertexai.gemini-2.5-flash\"\n\tVertexAIGemini25 ModelID = \"vertexai.gemini-2.5\"\n)\n\nvar VertexAIGeminiModels = map[ModelID]Model{\n\tVertexAIGemini25Flash: {\n\t\tID: VertexAIGemini25Flash,\n\t\tName: \"VertexAI: Gemini 2.5 Flash\",\n\t\tProvider: ProviderVertexAI,\n\t\tAPIModel: \"gemini-2.5-flash-preview-04-17\",\n\t\tCostPer1MIn: GeminiModels[Gemini25Flash].CostPer1MIn,\n\t\tCostPer1MInCached: GeminiModels[Gemini25Flash].CostPer1MInCached,\n\t\tCostPer1MOut: GeminiModels[Gemini25Flash].CostPer1MOut,\n\t\tCostPer1MOutCached: GeminiModels[Gemini25Flash].CostPer1MOutCached,\n\t\tContextWindow: GeminiModels[Gemini25Flash].ContextWindow,\n\t\tDefaultMaxTokens: GeminiModels[Gemini25Flash].DefaultMaxTokens,\n\t\tSupportsAttachments: true,\n\t},\n\tVertexAIGemini25: {\n\t\tID: VertexAIGemini25,\n\t\tName: \"VertexAI: Gemini 2.5 Pro\",\n\t\tProvider: ProviderVertexAI,\n\t\tAPIModel: \"gemini-2.5-pro-preview-03-25\",\n\t\tCostPer1MIn: GeminiModels[Gemini25].CostPer1MIn,\n\t\tCostPer1MInCached: GeminiModels[Gemini25].CostPer1MInCached,\n\t\tCostPer1MOut: GeminiModels[Gemini25].CostPer1MOut,\n\t\tCostPer1MOutCached: GeminiModels[Gemini25].CostPer1MOutCached,\n\t\tContextWindow: GeminiModels[Gemini25].ContextWindow,\n\t\tDefaultMaxTokens: GeminiModels[Gemini25].DefaultMaxTokens,\n\t\tSupportsAttachments: true,\n\t},\n}\n"], ["/opencode/internal/llm/models/xai.go", "package models\n\nconst (\n\tProviderXAI ModelProvider = \"xai\"\n\n\tXAIGrok3Beta ModelID = \"grok-3-beta\"\n\tXAIGrok3MiniBeta ModelID = \"grok-3-mini-beta\"\n\tXAIGrok3FastBeta ModelID = \"grok-3-fast-beta\"\n\tXAiGrok3MiniFastBeta ModelID = \"grok-3-mini-fast-beta\"\n)\n\nvar XAIModels = map[ModelID]Model{\n\tXAIGrok3Beta: {\n\t\tID: XAIGrok3Beta,\n\t\tName: \"Grok3 Beta\",\n\t\tProvider: ProviderXAI,\n\t\tAPIModel: \"grok-3-beta\",\n\t\tCostPer1MIn: 3.0,\n\t\tCostPer1MInCached: 0,\n\t\tCostPer1MOut: 15,\n\t\tCostPer1MOutCached: 0,\n\t\tContextWindow: 131_072,\n\t\tDefaultMaxTokens: 20_000,\n\t},\n\tXAIGrok3MiniBeta: {\n\t\tID: XAIGrok3MiniBeta,\n\t\tName: \"Grok3 Mini Beta\",\n\t\tProvider: ProviderXAI,\n\t\tAPIModel: \"grok-3-mini-beta\",\n\t\tCostPer1MIn: 0.3,\n\t\tCostPer1MInCached: 0,\n\t\tCostPer1MOut: 0.5,\n\t\tCostPer1MOutCached: 0,\n\t\tContextWindow: 131_072,\n\t\tDefaultMaxTokens: 20_000,\n\t},\n\tXAIGrok3FastBeta: {\n\t\tID: XAIGrok3FastBeta,\n\t\tName: \"Grok3 Fast Beta\",\n\t\tProvider: ProviderXAI,\n\t\tAPIModel: \"grok-3-fast-beta\",\n\t\tCostPer1MIn: 5,\n\t\tCostPer1MInCached: 0,\n\t\tCostPer1MOut: 25,\n\t\tCostPer1MOutCached: 0,\n\t\tContextWindow: 131_072,\n\t\tDefaultMaxTokens: 20_000,\n\t},\n\tXAiGrok3MiniFastBeta: {\n\t\tID: XAiGrok3MiniFastBeta,\n\t\tName: \"Grok3 Mini Fast Beta\",\n\t\tProvider: ProviderXAI,\n\t\tAPIModel: \"grok-3-mini-fast-beta\",\n\t\tCostPer1MIn: 0.6,\n\t\tCostPer1MInCached: 0,\n\t\tCostPer1MOut: 4.0,\n\t\tCostPer1MOutCached: 0,\n\t\tContextWindow: 131_072,\n\t\tDefaultMaxTokens: 20_000,\n\t},\n}\n"], ["/opencode/internal/pubsub/events.go", "package pubsub\n\nimport \"context\"\n\nconst (\n\tCreatedEvent EventType = \"created\"\n\tUpdatedEvent EventType = \"updated\"\n\tDeletedEvent EventType = \"deleted\"\n)\n\ntype Suscriber[T any] interface {\n\tSubscribe(context.Context) <-chan Event[T]\n}\n\ntype (\n\t// EventType identifies the type of event\n\tEventType string\n\n\t// Event represents an event in the lifecycle of a resource\n\tEvent[T any] struct {\n\t\tType EventType\n\t\tPayload T\n\t}\n\n\tPublisher[T any] interface {\n\t\tPublish(EventType, T)\n\t}\n)\n"], ["/opencode/internal/llm/prompt/title.go", "package prompt\n\nimport \"github.com/opencode-ai/opencode/internal/llm/models\"\n\nfunc TitlePrompt(_ models.ModelProvider) string {\n\treturn `you will generate a short title based on the first message a user begins a conversation with\n- ensure it is not more than 50 characters long\n- the title should be a summary of the user's message\n- it should be one line long\n- do not use quotes or colons\n- the entire text you return will be used as the title\n- never return anything that is more than one sentence (one line) long`\n}\n"], ["/opencode/internal/llm/prompt/summarizer.go", "package prompt\n\nimport \"github.com/opencode-ai/opencode/internal/llm/models\"\n\nfunc SummarizerPrompt(_ models.ModelProvider) string {\n\treturn `You are a helpful AI assistant tasked with summarizing conversations.\n\nWhen asked to summarize, provide a detailed but concise summary of the conversation. \nFocus on information that would be helpful for continuing the conversation, including:\n- What was done\n- What is currently being worked on\n- Which files are being modified\n- What needs to be done next\n\nYour summary should be comprehensive enough to provide context but concise enough to be quickly understood.`\n}\n"], ["/opencode/internal/logging/message.go", "package logging\n\nimport (\n\t\"time\"\n)\n\n// LogMessage is the event payload for a log message\ntype LogMessage struct {\n\tID string\n\tTime time.Time\n\tLevel string\n\tPersist bool // used when we want to show the mesage in the status bar\n\tPersistTime time.Duration // used when we want to show the mesage in the status bar\n\tMessage string `json:\"msg\"`\n\tAttributes []Attr\n}\n\ntype Attr struct {\n\tKey string\n\tValue string\n}\n"], ["/opencode/main.go", "package main\n\nimport (\n\t\"github.com/opencode-ai/opencode/cmd\"\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n)\n\nfunc main() {\n\tdefer logging.RecoverPanic(\"main\", func() {\n\t\tlogging.ErrorPersist(\"Application terminated due to unhandled panic\")\n\t})\n\n\tcmd.Execute()\n}\n"], ["/opencode/internal/tui/page/page.go", "package page\n\ntype PageID string\n\n// PageChangeMsg is used to change the current page\ntype PageChangeMsg struct {\n\tID PageID\n}\n"], ["/opencode/internal/tui/styles/icons.go", "package styles\n\nconst (\n\tOpenCodeIcon string = \"⌬\"\n\n\tCheckIcon string = \"✓\"\n\tErrorIcon string = \"✖\"\n\tWarningIcon string = \"⚠\"\n\tInfoIcon string = \"\"\n\tHintIcon string = \"i\"\n\tSpinnerIcon string = \"...\"\n\tLoadingIcon string = \"⟳\"\n\tDocumentIcon string = \"🖼\"\n)\n"], ["/opencode/internal/message/attachment.go", "package message\n\ntype Attachment struct {\n\tFilePath string\n\tFileName string\n\tMimeType string\n\tContent []byte\n}\n"], ["/opencode/internal/lsp/protocol/tables.go", "package protocol\n\nvar TableKindMap = map[SymbolKind]string{\n\tFile: \"File\",\n\tModule: \"Module\",\n\tNamespace: \"Namespace\",\n\tPackage: \"Package\",\n\tClass: \"Class\",\n\tMethod: \"Method\",\n\tProperty: \"Property\",\n\tField: \"Field\",\n\tConstructor: \"Constructor\",\n\tEnum: \"Enum\",\n\tInterface: \"Interface\",\n\tFunction: \"Function\",\n\tVariable: \"Variable\",\n\tConstant: \"Constant\",\n\tString: \"String\",\n\tNumber: \"Number\",\n\tBoolean: \"Boolean\",\n\tArray: \"Array\",\n\tObject: \"Object\",\n\tKey: \"Key\",\n\tNull: \"Null\",\n\tEnumMember: \"EnumMember\",\n\tStruct: \"Struct\",\n\tEvent: \"Event\",\n\tOperator: \"Operator\",\n\tTypeParameter: \"TypeParameter\",\n}\n"], ["/opencode/internal/db/embed.go", "package db\n\nimport \"embed\"\n\n//go:embed migrations/*.sql\nvar FS embed.FS\n"]], "task_instance_info": {"created_time": "2025-08-20 20:58:37", "created_task_model": "DeepSeek-R1", "function_skeleton": "func (m *messagesCmp) SetSession (session session.Session) tea.Cmd {}", "code_description": "This code segment functions to: Update the active communication session context by loading associated historical data records and resetting display parameters to reflect the changed state while initiating visual interface regeneration processes."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```go\n[TASK_BEGIN]\nfunc (m *messagesCmp) SetSession(session session.Session) tea.Cmd {\n\tm.session = session\n\tm.messages = make([]message.Message, 0)\n\tm.currentMsgID = \"\"\n\tm.cachedContent = make(map[string]cacheItem)\n\tm.rendering = false\n\treturn m.app.Messages.ListBySession(context.Background(), session.ID)\n}\n[TASK_END]\n```", "inference_time": "2025-08-20 20-59-06"}, "editdistance_info": {"edit_distance": 30.597, "calculate_time": "2025-08-20 20:59:06", "true_code_clean": "func (m *messagesCmp) SetSession(session session.Session) tea.Cmd {\n\tif m.session.ID == session.ID {\n\t\treturn nil\n\t}\n\tm.session = session\n\tmessages, err := m.app.Messages.List(context.Background(), session.ID)\n\tif err != nil {\n\t\treturn util.ReportError(err)\n\t}\n\tm.messages = messages\n\tif len(m.messages) > 0 {\n\t\tm.currentMsgID = m.messages[len(m.messages)-1].ID\n\t}\n\tdelete(m.cachedContent, m.currentMsgID)\n\tm.rendering = true\n\treturn func() tea.Msg {\n\t\tm.renderView()\n\t\treturn renderFinishedMsg{}\n\t}\n}", "predict_code_clean": "func (m *messagesCmp) SetSession(session session.Session) tea.Cmd {\n\tm.session = session\n\tm.messages = make([]message.Message, 0)\n\tm.currentMsgID = \"\"\n\tm.cachedContent = make(map[string]cacheItem)\n\tm.rendering = false\n\treturn m.app.Messages.ListBySession(context.Background(), session.ID)\n}"}}
{"repo_name": "opencode", "file_name": "/opencode/internal/lsp/language.go", "inference_info": {"prefix_code": "package lsp\n\nimport (\n\t\"path/filepath\"\n\t\"strings\"\n\n\t\"github.com/opencode-ai/opencode/internal/lsp/protocol\"\n)\n\n", "suffix_code": "\n", "middle_code": "func DetectLanguageID(uri string) protocol.LanguageKind {\n\text := strings.ToLower(filepath.Ext(uri))\n\tswitch ext {\n\tcase \".abap\":\n\t\treturn protocol.LangABAP\n\tcase \".bat\":\n\t\treturn protocol.LangWindowsBat\n\tcase \".bib\", \".bibtex\":\n\t\treturn protocol.LangBibTeX\n\tcase \".clj\":\n\t\treturn protocol.LangClojure\n\tcase \".coffee\":\n\t\treturn protocol.LangCoffeescript\n\tcase \".c\":\n\t\treturn protocol.LangC\n\tcase \".cpp\", \".cxx\", \".cc\", \".c++\":\n\t\treturn protocol.LangCPP\n\tcase \".cs\":\n\t\treturn protocol.LangCSharp\n\tcase \".css\":\n\t\treturn protocol.LangCSS\n\tcase \".d\":\n\t\treturn protocol.LangD\n\tcase \".pas\", \".pascal\":\n\t\treturn protocol.LangDelphi\n\tcase \".diff\", \".patch\":\n\t\treturn protocol.LangDiff\n\tcase \".dart\":\n\t\treturn protocol.LangDart\n\tcase \".dockerfile\":\n\t\treturn protocol.LangDockerfile\n\tcase \".ex\", \".exs\":\n\t\treturn protocol.LangElixir\n\tcase \".erl\", \".hrl\":\n\t\treturn protocol.LangErlang\n\tcase \".fs\", \".fsi\", \".fsx\", \".fsscript\":\n\t\treturn protocol.LangFSharp\n\tcase \".gitcommit\":\n\t\treturn protocol.LangGitCommit\n\tcase \".gitrebase\":\n\t\treturn protocol.LangGitRebase\n\tcase \".go\":\n\t\treturn protocol.LangGo\n\tcase \".groovy\":\n\t\treturn protocol.LangGroovy\n\tcase \".hbs\", \".handlebars\":\n\t\treturn protocol.LangHandlebars\n\tcase \".hs\":\n\t\treturn protocol.LangHaskell\n\tcase \".html\", \".htm\":\n\t\treturn protocol.LangHTML\n\tcase \".ini\":\n\t\treturn protocol.LangIni\n\tcase \".java\":\n\t\treturn protocol.LangJava\n\tcase \".js\":\n\t\treturn protocol.LangJavaScript\n\tcase \".jsx\":\n\t\treturn protocol.LangJavaScriptReact\n\tcase \".json\":\n\t\treturn protocol.LangJSON\n\tcase \".tex\", \".latex\":\n\t\treturn protocol.LangLaTeX\n\tcase \".less\":\n\t\treturn protocol.LangLess\n\tcase \".lua\":\n\t\treturn protocol.LangLua\n\tcase \".makefile\", \"makefile\":\n\t\treturn protocol.LangMakefile\n\tcase \".md\", \".markdown\":\n\t\treturn protocol.LangMarkdown\n\tcase \".m\":\n\t\treturn protocol.LangObjectiveC\n\tcase \".mm\":\n\t\treturn protocol.LangObjectiveCPP\n\tcase \".pl\":\n\t\treturn protocol.LangPerl\n\tcase \".pm\":\n\t\treturn protocol.LangPerl6\n\tcase \".php\":\n\t\treturn protocol.LangPHP\n\tcase \".ps1\", \".psm1\":\n\t\treturn protocol.LangPowershell\n\tcase \".pug\", \".jade\":\n\t\treturn protocol.LangPug\n\tcase \".py\":\n\t\treturn protocol.LangPython\n\tcase \".r\":\n\t\treturn protocol.LangR\n\tcase \".cshtml\", \".razor\":\n\t\treturn protocol.LangRazor\n\tcase \".rb\":\n\t\treturn protocol.LangRuby\n\tcase \".rs\":\n\t\treturn protocol.LangRust\n\tcase \".scss\":\n\t\treturn protocol.LangSCSS\n\tcase \".sass\":\n\t\treturn protocol.LangSASS\n\tcase \".scala\":\n\t\treturn protocol.LangScala\n\tcase \".shader\":\n\t\treturn protocol.LangShaderLab\n\tcase \".sh\", \".bash\", \".zsh\", \".ksh\":\n\t\treturn protocol.LangShellScript\n\tcase \".sql\":\n\t\treturn protocol.LangSQL\n\tcase \".swift\":\n\t\treturn protocol.LangSwift\n\tcase \".ts\":\n\t\treturn protocol.LangTypeScript\n\tcase \".tsx\":\n\t\treturn protocol.LangTypeScriptReact\n\tcase \".xml\":\n\t\treturn protocol.LangXML\n\tcase \".xsl\":\n\t\treturn protocol.LangXSL\n\tcase \".yaml\", \".yml\":\n\t\treturn protocol.LangYAML\n\tdefault:\n\t\treturn protocol.LanguageKind(\"\") \n\t}\n}", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "go", "sub_task_type": null}, "context_code": [["/opencode/internal/lsp/watcher/watcher.go", "package watcher\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com/bmatcuk/doublestar/v4\"\n\t\"github.com/fsnotify/fsnotify\"\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n\t\"github.com/opencode-ai/opencode/internal/lsp\"\n\t\"github.com/opencode-ai/opencode/internal/lsp/protocol\"\n)\n\n// WorkspaceWatcher manages LSP file watching\ntype WorkspaceWatcher struct {\n\tclient *lsp.Client\n\tworkspacePath string\n\n\tdebounceTime time.Duration\n\tdebounceMap map[string]*time.Timer\n\tdebounceMu sync.Mutex\n\n\t// File watchers registered by the server\n\tregistrations []protocol.FileSystemWatcher\n\tregistrationMu sync.RWMutex\n}\n\n// NewWorkspaceWatcher creates a new workspace watcher\nfunc NewWorkspaceWatcher(client *lsp.Client) *WorkspaceWatcher {\n\treturn &WorkspaceWatcher{\n\t\tclient: client,\n\t\tdebounceTime: 300 * time.Millisecond,\n\t\tdebounceMap: make(map[string]*time.Timer),\n\t\tregistrations: []protocol.FileSystemWatcher{},\n\t}\n}\n\n// AddRegistrations adds file watchers to track\nfunc (w *WorkspaceWatcher) AddRegistrations(ctx context.Context, id string, watchers []protocol.FileSystemWatcher) {\n\tcnf := config.Get()\n\n\tlogging.Debug(\"Adding file watcher registrations\")\n\tw.registrationMu.Lock()\n\tdefer w.registrationMu.Unlock()\n\n\t// Add new watchers\n\tw.registrations = append(w.registrations, watchers...)\n\n\t// Print detailed registration information for debugging\n\tif cnf.DebugLSP {\n\t\tlogging.Debug(\"Adding file watcher registrations\",\n\t\t\t\"id\", id,\n\t\t\t\"watchers\", len(watchers),\n\t\t\t\"total\", len(w.registrations),\n\t\t)\n\n\t\tfor i, watcher := range watchers {\n\t\t\tlogging.Debug(\"Registration\", \"index\", i+1)\n\n\t\t\t// Log the GlobPattern\n\t\t\tswitch v := watcher.GlobPattern.Value.(type) {\n\t\t\tcase string:\n\t\t\t\tlogging.Debug(\"GlobPattern\", \"pattern\", v)\n\t\t\tcase protocol.RelativePattern:\n\t\t\t\tlogging.Debug(\"GlobPattern\", \"pattern\", v.Pattern)\n\n\t\t\t\t// Log BaseURI details\n\t\t\t\tswitch u := v.BaseURI.Value.(type) {\n\t\t\t\tcase string:\n\t\t\t\t\tlogging.Debug(\"BaseURI\", \"baseURI\", u)\n\t\t\t\tcase protocol.DocumentUri:\n\t\t\t\t\tlogging.Debug(\"BaseURI\", \"baseURI\", u)\n\t\t\t\tdefault:\n\t\t\t\t\tlogging.Debug(\"BaseURI\", \"baseURI\", u)\n\t\t\t\t}\n\t\t\tdefault:\n\t\t\t\tlogging.Debug(\"GlobPattern\", \"unknown type\", fmt.Sprintf(\"%T\", v))\n\t\t\t}\n\n\t\t\t// Log WatchKind\n\t\t\twatchKind := protocol.WatchKind(protocol.WatchChange | protocol.WatchCreate | protocol.WatchDelete)\n\t\t\tif watcher.Kind != nil {\n\t\t\t\twatchKind = *watcher.Kind\n\t\t\t}\n\n\t\t\tlogging.Debug(\"WatchKind\", \"kind\", watchKind)\n\t\t}\n\t}\n\n\t// Determine server type for specialized handling\n\tserverName := getServerNameFromContext(ctx)\n\tlogging.Debug(\"Server type detected\", \"serverName\", serverName)\n\n\t// Check if this server has sent file watchers\n\thasFileWatchers := len(watchers) > 0\n\n\t// For servers that need file preloading, we'll use a smart approach\n\tif shouldPreloadFiles(serverName) || !hasFileWatchers {\n\t\tgo func() {\n\t\t\tstartTime := time.Now()\n\t\t\tfilesOpened := 0\n\n\t\t\t// Determine max files to open based on server type\n\t\t\tmaxFilesToOpen := 50 // Default conservative limit\n\n\t\t\tswitch serverName {\n\t\t\tcase \"typescript\", \"typescript-language-server\", \"tsserver\", \"vtsls\":\n\t\t\t\t// TypeScript servers benefit from seeing more files\n\t\t\t\tmaxFilesToOpen = 100\n\t\t\tcase \"java\", \"jdtls\":\n\t\t\t\t// Java servers need to see many files for project model\n\t\t\t\tmaxFilesToOpen = 200\n\t\t\t}\n\n\t\t\t// First, open high-priority files\n\t\t\thighPriorityFilesOpened := w.openHighPriorityFiles(ctx, serverName)\n\t\t\tfilesOpened += highPriorityFilesOpened\n\n\t\t\tif cnf.DebugLSP {\n\t\t\t\tlogging.Debug(\"Opened high-priority files\",\n\t\t\t\t\t\"count\", highPriorityFilesOpened,\n\t\t\t\t\t\"serverName\", serverName)\n\t\t\t}\n\n\t\t\t// If we've already opened enough high-priority files, we might not need more\n\t\t\tif filesOpened >= maxFilesToOpen {\n\t\t\t\tif cnf.DebugLSP {\n\t\t\t\t\tlogging.Debug(\"Reached file limit with high-priority files\",\n\t\t\t\t\t\t\"filesOpened\", filesOpened,\n\t\t\t\t\t\t\"maxFiles\", maxFilesToOpen)\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\t// For the remaining slots, walk the directory and open matching files\n\n\t\t\terr := filepath.WalkDir(w.workspacePath, func(path string, d os.DirEntry, err error) error {\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\n\t\t\t\t// Skip directories that should be excluded\n\t\t\t\tif d.IsDir() {\n\t\t\t\t\tif path != w.workspacePath && shouldExcludeDir(path) {\n\t\t\t\t\t\tif cnf.DebugLSP {\n\t\t\t\t\t\t\tlogging.Debug(\"Skipping excluded directory\", \"path\", path)\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn filepath.SkipDir\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\t// Process files, but limit the total number\n\t\t\t\t\tif filesOpened < maxFilesToOpen {\n\t\t\t\t\t\t// Only process if it's not already open (high-priority files were opened earlier)\n\t\t\t\t\t\tif !w.client.IsFileOpen(path) {\n\t\t\t\t\t\t\tw.openMatchingFile(ctx, path)\n\t\t\t\t\t\t\tfilesOpened++\n\n\t\t\t\t\t\t\t// Add a small delay after every 10 files to prevent overwhelming the server\n\t\t\t\t\t\t\tif filesOpened%10 == 0 {\n\t\t\t\t\t\t\t\ttime.Sleep(50 * time.Millisecond)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// We've reached our limit, stop walking\n\t\t\t\t\t\treturn filepath.SkipAll\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\treturn nil\n\t\t\t})\n\n\t\t\telapsedTime := time.Since(startTime)\n\t\t\tif cnf.DebugLSP {\n\t\t\t\tlogging.Debug(\"Limited workspace scan complete\",\n\t\t\t\t\t\"filesOpened\", filesOpened,\n\t\t\t\t\t\"maxFiles\", maxFilesToOpen,\n\t\t\t\t\t\"elapsedTime\", elapsedTime.Seconds(),\n\t\t\t\t\t\"workspacePath\", w.workspacePath,\n\t\t\t\t)\n\t\t\t}\n\n\t\t\tif err != nil && cnf.DebugLSP {\n\t\t\t\tlogging.Debug(\"Error scanning workspace for files to open\", \"error\", err)\n\t\t\t}\n\t\t}()\n\t} else if cnf.DebugLSP {\n\t\tlogging.Debug(\"Using on-demand file loading for server\", \"server\", serverName)\n\t}\n}\n\n// openHighPriorityFiles opens important files for the server type\n// Returns the number of files opened\nfunc (w *WorkspaceWatcher) openHighPriorityFiles(ctx context.Context, serverName string) int {\n\tcnf := config.Get()\n\tfilesOpened := 0\n\n\t// Define patterns for high-priority files based on server type\n\tvar patterns []string\n\n\tswitch serverName {\n\tcase \"typescript\", \"typescript-language-server\", \"tsserver\", \"vtsls\":\n\t\tpatterns = []string{\n\t\t\t\"**/tsconfig.json\",\n\t\t\t\"**/package.json\",\n\t\t\t\"**/jsconfig.json\",\n\t\t\t\"**/index.ts\",\n\t\t\t\"**/index.js\",\n\t\t\t\"**/main.ts\",\n\t\t\t\"**/main.js\",\n\t\t}\n\tcase \"gopls\":\n\t\tpatterns = []string{\n\t\t\t\"**/go.mod\",\n\t\t\t\"**/go.sum\",\n\t\t\t\"**/main.go\",\n\t\t}\n\tcase \"rust-analyzer\":\n\t\tpatterns = []string{\n\t\t\t\"**/Cargo.toml\",\n\t\t\t\"**/Cargo.lock\",\n\t\t\t\"**/src/lib.rs\",\n\t\t\t\"**/src/main.rs\",\n\t\t}\n\tcase \"python\", \"pyright\", \"pylsp\":\n\t\tpatterns = []string{\n\t\t\t\"**/pyproject.toml\",\n\t\t\t\"**/setup.py\",\n\t\t\t\"**/requirements.txt\",\n\t\t\t\"**/__init__.py\",\n\t\t\t\"**/__main__.py\",\n\t\t}\n\tcase \"clangd\":\n\t\tpatterns = []string{\n\t\t\t\"**/CMakeLists.txt\",\n\t\t\t\"**/Makefile\",\n\t\t\t\"**/compile_commands.json\",\n\t\t}\n\tcase \"java\", \"jdtls\":\n\t\tpatterns = []string{\n\t\t\t\"**/pom.xml\",\n\t\t\t\"**/build.gradle\",\n\t\t\t\"**/src/main/java/**/*.java\",\n\t\t}\n\tdefault:\n\t\t// For unknown servers, use common configuration files\n\t\tpatterns = []string{\n\t\t\t\"**/package.json\",\n\t\t\t\"**/Makefile\",\n\t\t\t\"**/CMakeLists.txt\",\n\t\t\t\"**/.editorconfig\",\n\t\t}\n\t}\n\n\t// For each pattern, find and open matching files\n\tfor _, pattern := range patterns {\n\t\t// Use doublestar.Glob to find files matching the pattern (supports ** patterns)\n\t\tmatches, err := doublestar.Glob(os.DirFS(w.workspacePath), pattern)\n\t\tif err != nil {\n\t\t\tif cnf.DebugLSP {\n\t\t\t\tlogging.Debug(\"Error finding high-priority files\", \"pattern\", pattern, \"error\", err)\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\tfor _, match := range matches {\n\t\t\t// Convert relative path to absolute\n\t\t\tfullPath := filepath.Join(w.workspacePath, match)\n\n\t\t\t// Skip directories and excluded files\n\t\t\tinfo, err := os.Stat(fullPath)\n\t\t\tif err != nil || info.IsDir() || shouldExcludeFile(fullPath) {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// Open the file\n\t\t\tif err := w.client.OpenFile(ctx, fullPath); err != nil {\n\t\t\t\tif cnf.DebugLSP {\n\t\t\t\t\tlogging.Debug(\"Error opening high-priority file\", \"path\", fullPath, \"error\", err)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tfilesOpened++\n\t\t\t\tif cnf.DebugLSP {\n\t\t\t\t\tlogging.Debug(\"Opened high-priority file\", \"path\", fullPath)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Add a small delay to prevent overwhelming the server\n\t\t\ttime.Sleep(20 * time.Millisecond)\n\n\t\t\t// Limit the number of files opened per pattern\n\t\t\tif filesOpened >= 5 && (serverName != \"java\" && serverName != \"jdtls\") {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\treturn filesOpened\n}\n\n// WatchWorkspace sets up file watching for a workspace\nfunc (w *WorkspaceWatcher) WatchWorkspace(ctx context.Context, workspacePath string) {\n\tcnf := config.Get()\n\tw.workspacePath = workspacePath\n\n\t// Store the watcher in the context for later use\n\tctx = context.WithValue(ctx, \"workspaceWatcher\", w)\n\n\t// If the server name isn't already in the context, try to detect it\n\tif _, ok := ctx.Value(\"serverName\").(string); !ok {\n\t\tserverName := getServerNameFromContext(ctx)\n\t\tctx = context.WithValue(ctx, \"serverName\", serverName)\n\t}\n\n\tserverName := getServerNameFromContext(ctx)\n\tlogging.Debug(\"Starting workspace watcher\", \"workspacePath\", workspacePath, \"serverName\", serverName)\n\n\t// Register handler for file watcher registrations from the server\n\tlsp.RegisterFileWatchHandler(func(id string, watchers []protocol.FileSystemWatcher) {\n\t\tw.AddRegistrations(ctx, id, watchers)\n\t})\n\n\twatcher, err := fsnotify.NewWatcher()\n\tif err != nil {\n\t\tlogging.Error(\"Error creating watcher\", \"error\", err)\n\t}\n\tdefer watcher.Close()\n\n\t// Watch the workspace recursively\n\terr = filepath.WalkDir(workspacePath, func(path string, d os.DirEntry, err error) error {\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Skip excluded directories (except workspace root)\n\t\tif d.IsDir() && path != workspacePath {\n\t\t\tif shouldExcludeDir(path) {\n\t\t\t\tif cnf.DebugLSP {\n\t\t\t\t\tlogging.Debug(\"Skipping excluded directory\", \"path\", path)\n\t\t\t\t}\n\t\t\t\treturn filepath.SkipDir\n\t\t\t}\n\t\t}\n\n\t\t// Add directories to watcher\n\t\tif d.IsDir() {\n\t\t\terr = watcher.Add(path)\n\t\t\tif err != nil {\n\t\t\t\tlogging.Error(\"Error watching path\", \"path\", path, \"error\", err)\n\t\t\t}\n\t\t}\n\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\tlogging.Error(\"Error walking workspace\", \"error\", err)\n\t}\n\n\t// Event loop\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn\n\t\tcase event, ok := <-watcher.Events:\n\t\t\tif !ok {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\turi := fmt.Sprintf(\"file://%s\", event.Name)\n\n\t\t\t// Add new directories to the watcher\n\t\t\tif event.Op&fsnotify.Create != 0 {\n\t\t\t\tif info, err := os.Stat(event.Name); err == nil {\n\t\t\t\t\tif info.IsDir() {\n\t\t\t\t\t\t// Skip excluded directories\n\t\t\t\t\t\tif !shouldExcludeDir(event.Name) {\n\t\t\t\t\t\t\tif err := watcher.Add(event.Name); err != nil {\n\t\t\t\t\t\t\t\tlogging.Error(\"Error adding directory to watcher\", \"path\", event.Name, \"error\", err)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// For newly created files\n\t\t\t\t\t\tif !shouldExcludeFile(event.Name) {\n\t\t\t\t\t\t\tw.openMatchingFile(ctx, event.Name)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Debug logging\n\t\t\tif cnf.DebugLSP {\n\t\t\t\tmatched, kind := w.isPathWatched(event.Name)\n\t\t\t\tlogging.Debug(\"File event\",\n\t\t\t\t\t\"path\", event.Name,\n\t\t\t\t\t\"operation\", event.Op.String(),\n\t\t\t\t\t\"watched\", matched,\n\t\t\t\t\t\"kind\", kind,\n\t\t\t\t)\n\n\t\t\t}\n\n\t\t\t// Check if this path should be watched according to server registrations\n\t\t\tif watched, watchKind := w.isPathWatched(event.Name); watched {\n\t\t\t\tswitch {\n\t\t\t\tcase event.Op&fsnotify.Write != 0:\n\t\t\t\t\tif watchKind&protocol.WatchChange != 0 {\n\t\t\t\t\t\tw.debounceHandleFileEvent(ctx, uri, protocol.FileChangeType(protocol.Changed))\n\t\t\t\t\t}\n\t\t\t\tcase event.Op&fsnotify.Create != 0:\n\t\t\t\t\t// Already handled earlier in the event loop\n\t\t\t\t\t// Just send the notification if needed\n\t\t\t\t\tinfo, err := os.Stat(event.Name)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlogging.Error(\"Error getting file info\", \"path\", event.Name, \"error\", err)\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\tif !info.IsDir() && watchKind&protocol.WatchCreate != 0 {\n\t\t\t\t\t\tw.debounceHandleFileEvent(ctx, uri, protocol.FileChangeType(protocol.Created))\n\t\t\t\t\t}\n\t\t\t\tcase event.Op&fsnotify.Remove != 0:\n\t\t\t\t\tif watchKind&protocol.WatchDelete != 0 {\n\t\t\t\t\t\tw.handleFileEvent(ctx, uri, protocol.FileChangeType(protocol.Deleted))\n\t\t\t\t\t}\n\t\t\t\tcase event.Op&fsnotify.Rename != 0:\n\t\t\t\t\t// For renames, first delete\n\t\t\t\t\tif watchKind&protocol.WatchDelete != 0 {\n\t\t\t\t\t\tw.handleFileEvent(ctx, uri, protocol.FileChangeType(protocol.Deleted))\n\t\t\t\t\t}\n\n\t\t\t\t\t// Then check if the new file exists and create an event\n\t\t\t\t\tif info, err := os.Stat(event.Name); err == nil && !info.IsDir() {\n\t\t\t\t\t\tif watchKind&protocol.WatchCreate != 0 {\n\t\t\t\t\t\t\tw.debounceHandleFileEvent(ctx, uri, protocol.FileChangeType(protocol.Created))\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\tcase err, ok := <-watcher.Errors:\n\t\t\tif !ok {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tlogging.Error(\"Error watching file\", \"error\", err)\n\t\t}\n\t}\n}\n\n// isPathWatched checks if a path should be watched based on server registrations\nfunc (w *WorkspaceWatcher) isPathWatched(path string) (bool, protocol.WatchKind) {\n\tw.registrationMu.RLock()\n\tdefer w.registrationMu.RUnlock()\n\n\t// If no explicit registrations, watch everything\n\tif len(w.registrations) == 0 {\n\t\treturn true, protocol.WatchKind(protocol.WatchChange | protocol.WatchCreate | protocol.WatchDelete)\n\t}\n\n\t// Check each registration\n\tfor _, reg := range w.registrations {\n\t\tisMatch := w.matchesPattern(path, reg.GlobPattern)\n\t\tif isMatch {\n\t\t\tkind := protocol.WatchKind(protocol.WatchChange | protocol.WatchCreate | protocol.WatchDelete)\n\t\t\tif reg.Kind != nil {\n\t\t\t\tkind = *reg.Kind\n\t\t\t}\n\t\t\treturn true, kind\n\t\t}\n\t}\n\n\treturn false, 0\n}\n\n// matchesGlob handles advanced glob patterns including ** and alternatives\nfunc matchesGlob(pattern, path string) bool {\n\t// Handle file extension patterns with braces like *.{go,mod,sum}\n\tif strings.Contains(pattern, \"{\") && strings.Contains(pattern, \"}\") {\n\t\t// Extract extensions from pattern like \"*.{go,mod,sum}\"\n\t\tparts := strings.SplitN(pattern, \"{\", 2)\n\t\tif len(parts) == 2 {\n\t\t\tprefix := parts[0]\n\t\t\textPart := strings.SplitN(parts[1], \"}\", 2)\n\t\t\tif len(extPart) == 2 {\n\t\t\t\textensions := strings.Split(extPart[0], \",\")\n\t\t\t\tsuffix := extPart[1]\n\n\t\t\t\t// Check if the path matches any of the extensions\n\t\t\t\tfor _, ext := range extensions {\n\t\t\t\t\textPattern := prefix + ext + suffix\n\t\t\t\t\tisMatch := matchesSimpleGlob(extPattern, path)\n\t\t\t\t\tif isMatch {\n\t\t\t\t\t\treturn true\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t}\n\n\treturn matchesSimpleGlob(pattern, path)\n}\n\n// matchesSimpleGlob handles glob patterns with ** wildcards\nfunc matchesSimpleGlob(pattern, path string) bool {\n\t// Handle special case for **/*.ext pattern (common in LSP)\n\tif strings.HasPrefix(pattern, \"**/\") {\n\t\trest := strings.TrimPrefix(pattern, \"**/\")\n\n\t\t// If the rest is a simple file extension pattern like *.go\n\t\tif strings.HasPrefix(rest, \"*.\") {\n\t\t\text := strings.TrimPrefix(rest, \"*\")\n\t\t\tisMatch := strings.HasSuffix(path, ext)\n\t\t\treturn isMatch\n\t\t}\n\n\t\t// Otherwise, try to check if the path ends with the rest part\n\t\tisMatch := strings.HasSuffix(path, rest)\n\n\t\t// If it matches directly, great!\n\t\tif isMatch {\n\t\t\treturn true\n\t\t}\n\n\t\t// Otherwise, check if any path component matches\n\t\tpathComponents := strings.Split(path, \"/\")\n\t\tfor i := range pathComponents {\n\t\t\tsubPath := strings.Join(pathComponents[i:], \"/\")\n\t\t\tif strings.HasSuffix(subPath, rest) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\n\t\treturn false\n\t}\n\n\t// Handle other ** wildcard pattern cases\n\tif strings.Contains(pattern, \"**\") {\n\t\tparts := strings.Split(pattern, \"**\")\n\n\t\t// Validate the path starts with the first part\n\t\tif !strings.HasPrefix(path, parts[0]) && parts[0] != \"\" {\n\t\t\treturn false\n\t\t}\n\n\t\t// For patterns like \"**/*.go\", just check the suffix\n\t\tif len(parts) == 2 && parts[0] == \"\" {\n\t\t\tisMatch := strings.HasSuffix(path, parts[1])\n\t\t\treturn isMatch\n\t\t}\n\n\t\t// For other patterns, handle middle part\n\t\tremaining := strings.TrimPrefix(path, parts[0])\n\t\tif len(parts) == 2 {\n\t\t\tisMatch := strings.HasSuffix(remaining, parts[1])\n\t\t\treturn isMatch\n\t\t}\n\t}\n\n\t// Handle simple * wildcard for file extension patterns (*.go, *.sum, etc)\n\tif strings.HasPrefix(pattern, \"*.\") {\n\t\text := strings.TrimPrefix(pattern, \"*\")\n\t\tisMatch := strings.HasSuffix(path, ext)\n\t\treturn isMatch\n\t}\n\n\t// Fall back to simple matching for simpler patterns\n\tmatched, err := filepath.Match(pattern, path)\n\tif err != nil {\n\t\tlogging.Error(\"Error matching pattern\", \"pattern\", pattern, \"path\", path, \"error\", err)\n\t\treturn false\n\t}\n\n\treturn matched\n}\n\n// matchesPattern checks if a path matches the glob pattern\nfunc (w *WorkspaceWatcher) matchesPattern(path string, pattern protocol.GlobPattern) bool {\n\tpatternInfo, err := pattern.AsPattern()\n\tif err != nil {\n\t\tlogging.Error(\"Error parsing pattern\", \"pattern\", pattern, \"error\", err)\n\t\treturn false\n\t}\n\n\tbasePath := patternInfo.GetBasePath()\n\tpatternText := patternInfo.GetPattern()\n\n\tpath = filepath.ToSlash(path)\n\n\t// For simple patterns without base path\n\tif basePath == \"\" {\n\t\t// Check if the pattern matches the full path or just the file extension\n\t\tfullPathMatch := matchesGlob(patternText, path)\n\t\tbaseNameMatch := matchesGlob(patternText, filepath.Base(path))\n\n\t\treturn fullPathMatch || baseNameMatch\n\t}\n\n\t// For relative patterns\n\tbasePath = strings.TrimPrefix(basePath, \"file://\")\n\tbasePath = filepath.ToSlash(basePath)\n\n\t// Make path relative to basePath for matching\n\trelPath, err := filepath.Rel(basePath, path)\n\tif err != nil {\n\t\tlogging.Error(\"Error getting relative path\", \"path\", path, \"basePath\", basePath, \"error\", err)\n\t\treturn false\n\t}\n\trelPath = filepath.ToSlash(relPath)\n\n\tisMatch := matchesGlob(patternText, relPath)\n\n\treturn isMatch\n}\n\n// debounceHandleFileEvent handles file events with debouncing to reduce notifications\nfunc (w *WorkspaceWatcher) debounceHandleFileEvent(ctx context.Context, uri string, changeType protocol.FileChangeType) {\n\tw.debounceMu.Lock()\n\tdefer w.debounceMu.Unlock()\n\n\t// Create a unique key based on URI and change type\n\tkey := fmt.Sprintf(\"%s:%d\", uri, changeType)\n\n\t// Cancel existing timer if any\n\tif timer, exists := w.debounceMap[key]; exists {\n\t\ttimer.Stop()\n\t}\n\n\t// Create new timer\n\tw.debounceMap[key] = time.AfterFunc(w.debounceTime, func() {\n\t\tw.handleFileEvent(ctx, uri, changeType)\n\n\t\t// Cleanup timer after execution\n\t\tw.debounceMu.Lock()\n\t\tdelete(w.debounceMap, key)\n\t\tw.debounceMu.Unlock()\n\t})\n}\n\n// handleFileEvent sends file change notifications\nfunc (w *WorkspaceWatcher) handleFileEvent(ctx context.Context, uri string, changeType protocol.FileChangeType) {\n\t// If the file is open and it's a change event, use didChange notification\n\tfilePath := uri[7:] // Remove \"file://\" prefix\n\tif changeType == protocol.FileChangeType(protocol.Deleted) {\n\t\tw.client.ClearDiagnosticsForURI(protocol.DocumentUri(uri))\n\t} else if changeType == protocol.FileChangeType(protocol.Changed) && w.client.IsFileOpen(filePath) {\n\t\terr := w.client.NotifyChange(ctx, filePath)\n\t\tif err != nil {\n\t\t\tlogging.Error(\"Error notifying change\", \"error\", err)\n\t\t}\n\t\treturn\n\t}\n\n\t// Notify LSP server about the file event using didChangeWatchedFiles\n\tif err := w.notifyFileEvent(ctx, uri, changeType); err != nil {\n\t\tlogging.Error(\"Error notifying LSP server about file event\", \"error\", err)\n\t}\n}\n\n// notifyFileEvent sends a didChangeWatchedFiles notification for a file event\nfunc (w *WorkspaceWatcher) notifyFileEvent(ctx context.Context, uri string, changeType protocol.FileChangeType) error {\n\tcnf := config.Get()\n\tif cnf.DebugLSP {\n\t\tlogging.Debug(\"Notifying file event\",\n\t\t\t\"uri\", uri,\n\t\t\t\"changeType\", changeType,\n\t\t)\n\t}\n\n\tparams := protocol.DidChangeWatchedFilesParams{\n\t\tChanges: []protocol.FileEvent{\n\t\t\t{\n\t\t\t\tURI: protocol.DocumentUri(uri),\n\t\t\t\tType: changeType,\n\t\t\t},\n\t\t},\n\t}\n\n\treturn w.client.DidChangeWatchedFiles(ctx, params)\n}\n\n// getServerNameFromContext extracts the server name from the context\n// This is a best-effort function that tries to identify which LSP server we're dealing with\nfunc getServerNameFromContext(ctx context.Context) string {\n\t// First check if the server name is directly stored in the context\n\tif serverName, ok := ctx.Value(\"serverName\").(string); ok && serverName != \"\" {\n\t\treturn strings.ToLower(serverName)\n\t}\n\n\t// Otherwise, try to extract server name from the client command path\n\tif w, ok := ctx.Value(\"workspaceWatcher\").(*WorkspaceWatcher); ok && w != nil && w.client != nil && w.client.Cmd != nil {\n\t\tpath := strings.ToLower(w.client.Cmd.Path)\n\n\t\t// Extract server name from path\n\t\tif strings.Contains(path, \"typescript\") || strings.Contains(path, \"tsserver\") || strings.Contains(path, \"vtsls\") {\n\t\t\treturn \"typescript\"\n\t\t} else if strings.Contains(path, \"gopls\") {\n\t\t\treturn \"gopls\"\n\t\t} else if strings.Contains(path, \"rust-analyzer\") {\n\t\t\treturn \"rust-analyzer\"\n\t\t} else if strings.Contains(path, \"pyright\") || strings.Contains(path, \"pylsp\") || strings.Contains(path, \"python\") {\n\t\t\treturn \"python\"\n\t\t} else if strings.Contains(path, \"clangd\") {\n\t\t\treturn \"clangd\"\n\t\t} else if strings.Contains(path, \"jdtls\") || strings.Contains(path, \"java\") {\n\t\t\treturn \"java\"\n\t\t}\n\n\t\t// Return the base name as fallback\n\t\treturn filepath.Base(path)\n\t}\n\n\treturn \"unknown\"\n}\n\n// shouldPreloadFiles determines if we should preload files for a specific language server\n// Some servers work better with preloaded files, others don't need it\nfunc shouldPreloadFiles(serverName string) bool {\n\t// TypeScript/JavaScript servers typically need some files preloaded\n\t// to properly resolve imports and provide intellisense\n\tswitch serverName {\n\tcase \"typescript\", \"typescript-language-server\", \"tsserver\", \"vtsls\":\n\t\treturn true\n\tcase \"java\", \"jdtls\":\n\t\t// Java servers often need to see source files to build the project model\n\t\treturn true\n\tdefault:\n\t\t// For most servers, we'll use lazy loading by default\n\t\treturn false\n\t}\n}\n\n// Common patterns for directories and files to exclude\n// TODO: make configurable\nvar (\n\texcludedDirNames = map[string]bool{\n\t\t\".git\": true,\n\t\t\"node_modules\": true,\n\t\t\"dist\": true,\n\t\t\"build\": true,\n\t\t\"out\": true,\n\t\t\"bin\": true,\n\t\t\".idea\": true,\n\t\t\".vscode\": true,\n\t\t\".cache\": true,\n\t\t\"coverage\": true,\n\t\t\"target\": true, // Rust build output\n\t\t\"vendor\": true, // Go vendor directory\n\t}\n\n\texcludedFileExtensions = map[string]bool{\n\t\t\".swp\": true,\n\t\t\".swo\": true,\n\t\t\".tmp\": true,\n\t\t\".temp\": true,\n\t\t\".bak\": true,\n\t\t\".log\": true,\n\t\t\".o\": true, // Object files\n\t\t\".so\": true, // Shared libraries\n\t\t\".dylib\": true, // macOS shared libraries\n\t\t\".dll\": true, // Windows shared libraries\n\t\t\".a\": true, // Static libraries\n\t\t\".exe\": true, // Windows executables\n\t\t\".lock\": true, // Lock files\n\t}\n\n\t// Large binary files that shouldn't be opened\n\tlargeBinaryExtensions = map[string]bool{\n\t\t\".png\": true,\n\t\t\".jpg\": true,\n\t\t\".jpeg\": true,\n\t\t\".gif\": true,\n\t\t\".bmp\": true,\n\t\t\".ico\": true,\n\t\t\".zip\": true,\n\t\t\".tar\": true,\n\t\t\".gz\": true,\n\t\t\".rar\": true,\n\t\t\".7z\": true,\n\t\t\".pdf\": true,\n\t\t\".mp3\": true,\n\t\t\".mp4\": true,\n\t\t\".mov\": true,\n\t\t\".wav\": true,\n\t\t\".wasm\": true,\n\t}\n\n\t// Maximum file size to open (5MB)\n\tmaxFileSize int64 = 5 * 1024 * 1024\n)\n\n// shouldExcludeDir returns true if the directory should be excluded from watching/opening\nfunc shouldExcludeDir(dirPath string) bool {\n\tdirName := filepath.Base(dirPath)\n\n\t// Skip dot directories\n\tif strings.HasPrefix(dirName, \".\") {\n\t\treturn true\n\t}\n\n\t// Skip common excluded directories\n\tif excludedDirNames[dirName] {\n\t\treturn true\n\t}\n\n\treturn false\n}\n\n// shouldExcludeFile returns true if the file should be excluded from opening\nfunc shouldExcludeFile(filePath string) bool {\n\tfileName := filepath.Base(filePath)\n\tcnf := config.Get()\n\t// Skip dot files\n\tif strings.HasPrefix(fileName, \".\") {\n\t\treturn true\n\t}\n\n\t// Check file extension\n\text := strings.ToLower(filepath.Ext(filePath))\n\tif excludedFileExtensions[ext] || largeBinaryExtensions[ext] {\n\t\treturn true\n\t}\n\n\t// Skip temporary files\n\tif strings.HasSuffix(filePath, \"~\") {\n\t\treturn true\n\t}\n\n\t// Check file size\n\tinfo, err := os.Stat(filePath)\n\tif err != nil {\n\t\t// If we can't stat the file, skip it\n\t\treturn true\n\t}\n\n\t// Skip large files\n\tif info.Size() > maxFileSize {\n\t\tif cnf.DebugLSP {\n\t\t\tlogging.Debug(\"Skipping large file\",\n\t\t\t\t\"path\", filePath,\n\t\t\t\t\"size\", info.Size(),\n\t\t\t\t\"maxSize\", maxFileSize,\n\t\t\t\t\"debug\", cnf.Debug,\n\t\t\t\t\"sizeMB\", float64(info.Size())/(1024*1024),\n\t\t\t\t\"maxSizeMB\", float64(maxFileSize)/(1024*1024),\n\t\t\t)\n\t\t}\n\t\treturn true\n\t}\n\n\treturn false\n}\n\n// openMatchingFile opens a file if it matches any of the registered patterns\nfunc (w *WorkspaceWatcher) openMatchingFile(ctx context.Context, path string) {\n\tcnf := config.Get()\n\t// Skip directories\n\tinfo, err := os.Stat(path)\n\tif err != nil || info.IsDir() {\n\t\treturn\n\t}\n\n\t// Skip excluded files\n\tif shouldExcludeFile(path) {\n\t\treturn\n\t}\n\n\t// Check if this path should be watched according to server registrations\n\tif watched, _ := w.isPathWatched(path); watched {\n\t\t// Get server name for specialized handling\n\t\tserverName := getServerNameFromContext(ctx)\n\n\t\t// Check if the file is a high-priority file that should be opened immediately\n\t\t// This helps with project initialization for certain language servers\n\t\tif isHighPriorityFile(path, serverName) {\n\t\t\tif cnf.DebugLSP {\n\t\t\t\tlogging.Debug(\"Opening high-priority file\", \"path\", path, \"serverName\", serverName)\n\t\t\t}\n\t\t\tif err := w.client.OpenFile(ctx, path); err != nil && cnf.DebugLSP {\n\t\t\t\tlogging.Error(\"Error opening high-priority file\", \"path\", path, \"error\", err)\n\t\t\t}\n\t\t\treturn\n\t\t}\n\n\t\t// For non-high-priority files, we'll use different strategies based on server type\n\t\tif shouldPreloadFiles(serverName) {\n\t\t\t// For servers that benefit from preloading, open files but with limits\n\n\t\t\t// Check file size - for preloading we're more conservative\n\t\t\tif info.Size() > (1 * 1024 * 1024) { // 1MB limit for preloaded files\n\t\t\t\tif cnf.DebugLSP {\n\t\t\t\t\tlogging.Debug(\"Skipping large file for preloading\", \"path\", path, \"size\", info.Size())\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\t// Check file extension for common source files\n\t\t\text := strings.ToLower(filepath.Ext(path))\n\n\t\t\t// Only preload source files for the specific language\n\t\t\tshouldOpen := false\n\n\t\t\tswitch serverName {\n\t\t\tcase \"typescript\", \"typescript-language-server\", \"tsserver\", \"vtsls\":\n\t\t\t\tshouldOpen = ext == \".ts\" || ext == \".js\" || ext == \".tsx\" || ext == \".jsx\"\n\t\t\tcase \"gopls\":\n\t\t\t\tshouldOpen = ext == \".go\"\n\t\t\tcase \"rust-analyzer\":\n\t\t\t\tshouldOpen = ext == \".rs\"\n\t\t\tcase \"python\", \"pyright\", \"pylsp\":\n\t\t\t\tshouldOpen = ext == \".py\"\n\t\t\tcase \"clangd\":\n\t\t\t\tshouldOpen = ext == \".c\" || ext == \".cpp\" || ext == \".h\" || ext == \".hpp\"\n\t\t\tcase \"java\", \"jdtls\":\n\t\t\t\tshouldOpen = ext == \".java\"\n\t\t\tdefault:\n\t\t\t\t// For unknown servers, be conservative\n\t\t\t\tshouldOpen = false\n\t\t\t}\n\n\t\t\tif shouldOpen {\n\t\t\t\t// Don't need to check if it's already open - the client.OpenFile handles that\n\t\t\t\tif err := w.client.OpenFile(ctx, path); err != nil && cnf.DebugLSP {\n\t\t\t\t\tlogging.Error(\"Error opening file\", \"path\", path, \"error\", err)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\n// isHighPriorityFile determines if a file should be opened immediately\n// regardless of the preloading strategy\nfunc isHighPriorityFile(path string, serverName string) bool {\n\tfileName := filepath.Base(path)\n\text := filepath.Ext(path)\n\n\tswitch serverName {\n\tcase \"typescript\", \"typescript-language-server\", \"tsserver\", \"vtsls\":\n\t\t// For TypeScript, we want to open configuration files immediately\n\t\treturn fileName == \"tsconfig.json\" ||\n\t\t\tfileName == \"package.json\" ||\n\t\t\tfileName == \"jsconfig.json\" ||\n\t\t\t// Also open main entry points\n\t\t\tfileName == \"index.ts\" ||\n\t\t\tfileName == \"index.js\" ||\n\t\t\tfileName == \"main.ts\" ||\n\t\t\tfileName == \"main.js\"\n\tcase \"gopls\":\n\t\t// For Go, we want to open go.mod files immediately\n\t\treturn fileName == \"go.mod\" ||\n\t\t\tfileName == \"go.sum\" ||\n\t\t\t// Also open main.go files\n\t\t\tfileName == \"main.go\"\n\tcase \"rust-analyzer\":\n\t\t// For Rust, we want to open Cargo.toml files immediately\n\t\treturn fileName == \"Cargo.toml\" ||\n\t\t\tfileName == \"Cargo.lock\" ||\n\t\t\t// Also open lib.rs and main.rs\n\t\t\tfileName == \"lib.rs\" ||\n\t\t\tfileName == \"main.rs\"\n\tcase \"python\", \"pyright\", \"pylsp\":\n\t\t// For Python, open key project files\n\t\treturn fileName == \"pyproject.toml\" ||\n\t\t\tfileName == \"setup.py\" ||\n\t\t\tfileName == \"requirements.txt\" ||\n\t\t\tfileName == \"__init__.py\" ||\n\t\t\tfileName == \"__main__.py\"\n\tcase \"clangd\":\n\t\t// For C/C++, open key project files\n\t\treturn fileName == \"CMakeLists.txt\" ||\n\t\t\tfileName == \"Makefile\" ||\n\t\t\tfileName == \"compile_commands.json\"\n\tcase \"java\", \"jdtls\":\n\t\t// For Java, open key project files\n\t\treturn fileName == \"pom.xml\" ||\n\t\t\tfileName == \"build.gradle\" ||\n\t\t\text == \".java\" // Java servers often need to see source files\n\t}\n\n\t// For unknown servers, prioritize common configuration files\n\treturn fileName == \"package.json\" ||\n\t\tfileName == \"Makefile\" ||\n\t\tfileName == \"CMakeLists.txt\" ||\n\t\tfileName == \".editorconfig\"\n}\n"], ["/opencode/internal/lsp/client.go", "package lsp\n\nimport (\n\t\"bufio\"\n\t\"context\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"os/exec\"\n\t\"path/filepath\"\n\t\"strings\"\n\t\"sync\"\n\t\"sync/atomic\"\n\t\"time\"\n\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n\t\"github.com/opencode-ai/opencode/internal/lsp/protocol\"\n)\n\ntype Client struct {\n\tCmd *exec.Cmd\n\tstdin io.WriteCloser\n\tstdout *bufio.Reader\n\tstderr io.ReadCloser\n\n\t// Request ID counter\n\tnextID atomic.Int32\n\n\t// Response handlers\n\thandlers map[int32]chan *Message\n\thandlersMu sync.RWMutex\n\n\t// Server request handlers\n\tserverRequestHandlers map[string]ServerRequestHandler\n\tserverHandlersMu sync.RWMutex\n\n\t// Notification handlers\n\tnotificationHandlers map[string]NotificationHandler\n\tnotificationMu sync.RWMutex\n\n\t// Diagnostic cache\n\tdiagnostics map[protocol.DocumentUri][]protocol.Diagnostic\n\tdiagnosticsMu sync.RWMutex\n\n\t// Files are currently opened by the LSP\n\topenFiles map[string]*OpenFileInfo\n\topenFilesMu sync.RWMutex\n\n\t// Server state\n\tserverState atomic.Value\n}\n\nfunc NewClient(ctx context.Context, command string, args ...string) (*Client, error) {\n\tcmd := exec.CommandContext(ctx, command, args...)\n\t// Copy env\n\tcmd.Env = os.Environ()\n\n\tstdin, err := cmd.StdinPipe()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to create stdin pipe: %w\", err)\n\t}\n\n\tstdout, err := cmd.StdoutPipe()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to create stdout pipe: %w\", err)\n\t}\n\n\tstderr, err := cmd.StderrPipe()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to create stderr pipe: %w\", err)\n\t}\n\n\tclient := &Client{\n\t\tCmd: cmd,\n\t\tstdin: stdin,\n\t\tstdout: bufio.NewReader(stdout),\n\t\tstderr: stderr,\n\t\thandlers: make(map[int32]chan *Message),\n\t\tnotificationHandlers: make(map[string]NotificationHandler),\n\t\tserverRequestHandlers: make(map[string]ServerRequestHandler),\n\t\tdiagnostics: make(map[protocol.DocumentUri][]protocol.Diagnostic),\n\t\topenFiles: make(map[string]*OpenFileInfo),\n\t}\n\n\t// Initialize server state\n\tclient.serverState.Store(StateStarting)\n\n\t// Start the LSP server process\n\tif err := cmd.Start(); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to start LSP server: %w\", err)\n\t}\n\n\t// Handle stderr in a separate goroutine\n\tgo func() {\n\t\tscanner := bufio.NewScanner(stderr)\n\t\tfor scanner.Scan() {\n\t\t\tfmt.Fprintf(os.Stderr, \"LSP Server: %s\\n\", scanner.Text())\n\t\t}\n\t\tif err := scanner.Err(); err != nil {\n\t\t\tfmt.Fprintf(os.Stderr, \"Error reading stderr: %v\\n\", err)\n\t\t}\n\t}()\n\n\t// Start message handling loop\n\tgo func() {\n\t\tdefer logging.RecoverPanic(\"LSP-message-handler\", func() {\n\t\t\tlogging.ErrorPersist(\"LSP message handler crashed, LSP functionality may be impaired\")\n\t\t})\n\t\tclient.handleMessages()\n\t}()\n\n\treturn client, nil\n}\n\nfunc (c *Client) RegisterNotificationHandler(method string, handler NotificationHandler) {\n\tc.notificationMu.Lock()\n\tdefer c.notificationMu.Unlock()\n\tc.notificationHandlers[method] = handler\n}\n\nfunc (c *Client) RegisterServerRequestHandler(method string, handler ServerRequestHandler) {\n\tc.serverHandlersMu.Lock()\n\tdefer c.serverHandlersMu.Unlock()\n\tc.serverRequestHandlers[method] = handler\n}\n\nfunc (c *Client) InitializeLSPClient(ctx context.Context, workspaceDir string) (*protocol.InitializeResult, error) {\n\tinitParams := &protocol.InitializeParams{\n\t\tWorkspaceFoldersInitializeParams: protocol.WorkspaceFoldersInitializeParams{\n\t\t\tWorkspaceFolders: []protocol.WorkspaceFolder{\n\t\t\t\t{\n\t\t\t\t\tURI: protocol.URI(\"file://\" + workspaceDir),\n\t\t\t\t\tName: workspaceDir,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\n\t\tXInitializeParams: protocol.XInitializeParams{\n\t\t\tProcessID: int32(os.Getpid()),\n\t\t\tClientInfo: &protocol.ClientInfo{\n\t\t\t\tName: \"mcp-language-server\",\n\t\t\t\tVersion: \"0.1.0\",\n\t\t\t},\n\t\t\tRootPath: workspaceDir,\n\t\t\tRootURI: protocol.DocumentUri(\"file://\" + workspaceDir),\n\t\t\tCapabilities: protocol.ClientCapabilities{\n\t\t\t\tWorkspace: protocol.WorkspaceClientCapabilities{\n\t\t\t\t\tConfiguration: true,\n\t\t\t\t\tDidChangeConfiguration: protocol.DidChangeConfigurationClientCapabilities{\n\t\t\t\t\t\tDynamicRegistration: true,\n\t\t\t\t\t},\n\t\t\t\t\tDidChangeWatchedFiles: protocol.DidChangeWatchedFilesClientCapabilities{\n\t\t\t\t\t\tDynamicRegistration: true,\n\t\t\t\t\t\tRelativePatternSupport: true,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tTextDocument: protocol.TextDocumentClientCapabilities{\n\t\t\t\t\tSynchronization: &protocol.TextDocumentSyncClientCapabilities{\n\t\t\t\t\t\tDynamicRegistration: true,\n\t\t\t\t\t\tDidSave: true,\n\t\t\t\t\t},\n\t\t\t\t\tCompletion: protocol.CompletionClientCapabilities{\n\t\t\t\t\t\tCompletionItem: protocol.ClientCompletionItemOptions{},\n\t\t\t\t\t},\n\t\t\t\t\tCodeLens: &protocol.CodeLensClientCapabilities{\n\t\t\t\t\t\tDynamicRegistration: true,\n\t\t\t\t\t},\n\t\t\t\t\tDocumentSymbol: protocol.DocumentSymbolClientCapabilities{},\n\t\t\t\t\tCodeAction: protocol.CodeActionClientCapabilities{\n\t\t\t\t\t\tCodeActionLiteralSupport: protocol.ClientCodeActionLiteralOptions{\n\t\t\t\t\t\t\tCodeActionKind: protocol.ClientCodeActionKindOptions{\n\t\t\t\t\t\t\t\tValueSet: []protocol.CodeActionKind{},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\tPublishDiagnostics: protocol.PublishDiagnosticsClientCapabilities{\n\t\t\t\t\t\tVersionSupport: true,\n\t\t\t\t\t},\n\t\t\t\t\tSemanticTokens: protocol.SemanticTokensClientCapabilities{\n\t\t\t\t\t\tRequests: protocol.ClientSemanticTokensRequestOptions{\n\t\t\t\t\t\t\tRange: &protocol.Or_ClientSemanticTokensRequestOptions_range{},\n\t\t\t\t\t\t\tFull: &protocol.Or_ClientSemanticTokensRequestOptions_full{},\n\t\t\t\t\t\t},\n\t\t\t\t\t\tTokenTypes: []string{},\n\t\t\t\t\t\tTokenModifiers: []string{},\n\t\t\t\t\t\tFormats: []protocol.TokenFormat{},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tWindow: protocol.WindowClientCapabilities{},\n\t\t\t},\n\t\t\tInitializationOptions: map[string]any{\n\t\t\t\t\"codelenses\": map[string]bool{\n\t\t\t\t\t\"generate\": true,\n\t\t\t\t\t\"regenerate_cgo\": true,\n\t\t\t\t\t\"test\": true,\n\t\t\t\t\t\"tidy\": true,\n\t\t\t\t\t\"upgrade_dependency\": true,\n\t\t\t\t\t\"vendor\": true,\n\t\t\t\t\t\"vulncheck\": false,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\tvar result protocol.InitializeResult\n\tif err := c.Call(ctx, \"initialize\", initParams, &result); err != nil {\n\t\treturn nil, fmt.Errorf(\"initialize failed: %w\", err)\n\t}\n\n\tif err := c.Notify(ctx, \"initialized\", struct{}{}); err != nil {\n\t\treturn nil, fmt.Errorf(\"initialized notification failed: %w\", err)\n\t}\n\n\t// Register handlers\n\tc.RegisterServerRequestHandler(\"workspace/applyEdit\", HandleApplyEdit)\n\tc.RegisterServerRequestHandler(\"workspace/configuration\", HandleWorkspaceConfiguration)\n\tc.RegisterServerRequestHandler(\"client/registerCapability\", HandleRegisterCapability)\n\tc.RegisterNotificationHandler(\"window/showMessage\", HandleServerMessage)\n\tc.RegisterNotificationHandler(\"textDocument/publishDiagnostics\",\n\t\tfunc(params json.RawMessage) { HandleDiagnostics(c, params) })\n\n\t// Notify the LSP server\n\terr := c.Initialized(ctx, protocol.InitializedParams{})\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"initialization failed: %w\", err)\n\t}\n\n\treturn &result, nil\n}\n\nfunc (c *Client) Close() error {\n\t// Try to close all open files first\n\tctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)\n\tdefer cancel()\n\n\t// Attempt to close files but continue shutdown regardless\n\tc.CloseAllFiles(ctx)\n\n\t// Close stdin to signal the server\n\tif err := c.stdin.Close(); err != nil {\n\t\treturn fmt.Errorf(\"failed to close stdin: %w\", err)\n\t}\n\n\t// Use a channel to handle the Wait with timeout\n\tdone := make(chan error, 1)\n\tgo func() {\n\t\tdone <- c.Cmd.Wait()\n\t}()\n\n\t// Wait for process to exit with timeout\n\tselect {\n\tcase err := <-done:\n\t\treturn err\n\tcase <-time.After(2 * time.Second):\n\t\t// If we timeout, try to kill the process\n\t\tif err := c.Cmd.Process.Kill(); err != nil {\n\t\t\treturn fmt.Errorf(\"failed to kill process: %w\", err)\n\t\t}\n\t\treturn fmt.Errorf(\"process killed after timeout\")\n\t}\n}\n\ntype ServerState int\n\nconst (\n\tStateStarting ServerState = iota\n\tStateReady\n\tStateError\n)\n\n// GetServerState returns the current state of the LSP server\nfunc (c *Client) GetServerState() ServerState {\n\tif val := c.serverState.Load(); val != nil {\n\t\treturn val.(ServerState)\n\t}\n\treturn StateStarting\n}\n\n// SetServerState sets the current state of the LSP server\nfunc (c *Client) SetServerState(state ServerState) {\n\tc.serverState.Store(state)\n}\n\n// WaitForServerReady waits for the server to be ready by polling the server\n// with a simple request until it responds successfully or times out\nfunc (c *Client) WaitForServerReady(ctx context.Context) error {\n\tcnf := config.Get()\n\n\t// Set initial state\n\tc.SetServerState(StateStarting)\n\n\t// Create a context with timeout\n\tctx, cancel := context.WithTimeout(ctx, 30*time.Second)\n\tdefer cancel()\n\n\t// Try to ping the server with a simple request\n\tticker := time.NewTicker(500 * time.Millisecond)\n\tdefer ticker.Stop()\n\n\tif cnf.DebugLSP {\n\t\tlogging.Debug(\"Waiting for LSP server to be ready...\")\n\t}\n\n\t// Determine server type for specialized initialization\n\tserverType := c.detectServerType()\n\n\t// For TypeScript-like servers, we need to open some key files first\n\tif serverType == ServerTypeTypeScript {\n\t\tif cnf.DebugLSP {\n\t\t\tlogging.Debug(\"TypeScript-like server detected, opening key configuration files\")\n\t\t}\n\t\tc.openKeyConfigFiles(ctx)\n\t}\n\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\tc.SetServerState(StateError)\n\t\t\treturn fmt.Errorf(\"timeout waiting for LSP server to be ready\")\n\t\tcase <-ticker.C:\n\t\t\t// Try a ping method appropriate for this server type\n\t\t\terr := c.pingServerByType(ctx, serverType)\n\t\t\tif err == nil {\n\t\t\t\t// Server responded successfully\n\t\t\t\tc.SetServerState(StateReady)\n\t\t\t\tif cnf.DebugLSP {\n\t\t\t\t\tlogging.Debug(\"LSP server is ready\")\n\t\t\t\t}\n\t\t\t\treturn nil\n\t\t\t} else {\n\t\t\t\tlogging.Debug(\"LSP server not ready yet\", \"error\", err, \"serverType\", serverType)\n\t\t\t}\n\n\t\t\tif cnf.DebugLSP {\n\t\t\t\tlogging.Debug(\"LSP server not ready yet\", \"error\", err, \"serverType\", serverType)\n\t\t\t}\n\t\t}\n\t}\n}\n\n// ServerType represents the type of LSP server\ntype ServerType int\n\nconst (\n\tServerTypeUnknown ServerType = iota\n\tServerTypeGo\n\tServerTypeTypeScript\n\tServerTypeRust\n\tServerTypePython\n\tServerTypeGeneric\n)\n\n// detectServerType tries to determine what type of LSP server we're dealing with\nfunc (c *Client) detectServerType() ServerType {\n\tif c.Cmd == nil {\n\t\treturn ServerTypeUnknown\n\t}\n\n\tcmdPath := strings.ToLower(c.Cmd.Path)\n\n\tswitch {\n\tcase strings.Contains(cmdPath, \"gopls\"):\n\t\treturn ServerTypeGo\n\tcase strings.Contains(cmdPath, \"typescript\") || strings.Contains(cmdPath, \"vtsls\") || strings.Contains(cmdPath, \"tsserver\"):\n\t\treturn ServerTypeTypeScript\n\tcase strings.Contains(cmdPath, \"rust-analyzer\"):\n\t\treturn ServerTypeRust\n\tcase strings.Contains(cmdPath, \"pyright\") || strings.Contains(cmdPath, \"pylsp\") || strings.Contains(cmdPath, \"python\"):\n\t\treturn ServerTypePython\n\tdefault:\n\t\treturn ServerTypeGeneric\n\t}\n}\n\n// openKeyConfigFiles opens important configuration files that help initialize the server\nfunc (c *Client) openKeyConfigFiles(ctx context.Context) {\n\tworkDir := config.WorkingDirectory()\n\tserverType := c.detectServerType()\n\n\tvar filesToOpen []string\n\n\tswitch serverType {\n\tcase ServerTypeTypeScript:\n\t\t// TypeScript servers need these config files to properly initialize\n\t\tfilesToOpen = []string{\n\t\t\tfilepath.Join(workDir, \"tsconfig.json\"),\n\t\t\tfilepath.Join(workDir, \"package.json\"),\n\t\t\tfilepath.Join(workDir, \"jsconfig.json\"),\n\t\t}\n\n\t\t// Also find and open a few TypeScript files to help the server initialize\n\t\tc.openTypeScriptFiles(ctx, workDir)\n\tcase ServerTypeGo:\n\t\tfilesToOpen = []string{\n\t\t\tfilepath.Join(workDir, \"go.mod\"),\n\t\t\tfilepath.Join(workDir, \"go.sum\"),\n\t\t}\n\tcase ServerTypeRust:\n\t\tfilesToOpen = []string{\n\t\t\tfilepath.Join(workDir, \"Cargo.toml\"),\n\t\t\tfilepath.Join(workDir, \"Cargo.lock\"),\n\t\t}\n\t}\n\n\t// Try to open each file, ignoring errors if they don't exist\n\tfor _, file := range filesToOpen {\n\t\tif _, err := os.Stat(file); err == nil {\n\t\t\t// File exists, try to open it\n\t\t\tif err := c.OpenFile(ctx, file); err != nil {\n\t\t\t\tlogging.Debug(\"Failed to open key config file\", \"file\", file, \"error\", err)\n\t\t\t} else {\n\t\t\t\tlogging.Debug(\"Opened key config file for initialization\", \"file\", file)\n\t\t\t}\n\t\t}\n\t}\n}\n\n// pingServerByType sends a ping request appropriate for the server type\nfunc (c *Client) pingServerByType(ctx context.Context, serverType ServerType) error {\n\tswitch serverType {\n\tcase ServerTypeTypeScript:\n\t\t// For TypeScript, try a document symbol request on an open file\n\t\treturn c.pingTypeScriptServer(ctx)\n\tcase ServerTypeGo:\n\t\t// For Go, workspace/symbol works well\n\t\treturn c.pingWithWorkspaceSymbol(ctx)\n\tcase ServerTypeRust:\n\t\t// For Rust, workspace/symbol works well\n\t\treturn c.pingWithWorkspaceSymbol(ctx)\n\tdefault:\n\t\t// Default ping method\n\t\treturn c.pingWithWorkspaceSymbol(ctx)\n\t}\n}\n\n// pingTypeScriptServer tries to ping a TypeScript server with appropriate methods\nfunc (c *Client) pingTypeScriptServer(ctx context.Context) error {\n\t// First try workspace/symbol which works for many servers\n\tif err := c.pingWithWorkspaceSymbol(ctx); err == nil {\n\t\treturn nil\n\t}\n\n\t// If that fails, try to find an open file and request document symbols\n\tc.openFilesMu.RLock()\n\tdefer c.openFilesMu.RUnlock()\n\n\t// If we have any open files, try to get document symbols for one\n\tfor uri := range c.openFiles {\n\t\tfilePath := strings.TrimPrefix(uri, \"file://\")\n\t\tif strings.HasSuffix(filePath, \".ts\") || strings.HasSuffix(filePath, \".js\") ||\n\t\t\tstrings.HasSuffix(filePath, \".tsx\") || strings.HasSuffix(filePath, \".jsx\") {\n\t\t\tvar symbols []protocol.DocumentSymbol\n\t\t\terr := c.Call(ctx, \"textDocument/documentSymbol\", protocol.DocumentSymbolParams{\n\t\t\t\tTextDocument: protocol.TextDocumentIdentifier{\n\t\t\t\t\tURI: protocol.DocumentUri(uri),\n\t\t\t\t},\n\t\t\t}, &symbols)\n\t\t\tif err == nil {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\t}\n\n\t// If we have no open TypeScript files, try to find and open one\n\tworkDir := config.WorkingDirectory()\n\terr := filepath.WalkDir(workDir, func(path string, d os.DirEntry, err error) error {\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Skip directories and non-TypeScript files\n\t\tif d.IsDir() {\n\t\t\treturn nil\n\t\t}\n\n\t\text := filepath.Ext(path)\n\t\tif ext == \".ts\" || ext == \".js\" || ext == \".tsx\" || ext == \".jsx\" {\n\t\t\t// Found a TypeScript file, try to open it\n\t\t\tif err := c.OpenFile(ctx, path); err == nil {\n\t\t\t\t// Successfully opened, stop walking\n\t\t\t\treturn filepath.SkipAll\n\t\t\t}\n\t\t}\n\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\tlogging.Debug(\"Error walking directory for TypeScript files\", \"error\", err)\n\t}\n\n\t// Final fallback - just try a generic capability\n\treturn c.pingWithServerCapabilities(ctx)\n}\n\n// openTypeScriptFiles finds and opens TypeScript files to help initialize the server\nfunc (c *Client) openTypeScriptFiles(ctx context.Context, workDir string) {\n\tcnf := config.Get()\n\tfilesOpened := 0\n\tmaxFilesToOpen := 5 // Limit to a reasonable number of files\n\n\t// Find and open TypeScript files\n\terr := filepath.WalkDir(workDir, func(path string, d os.DirEntry, err error) error {\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Skip directories and non-TypeScript files\n\t\tif d.IsDir() {\n\t\t\t// Skip common directories to avoid wasting time\n\t\t\tif shouldSkipDir(path) {\n\t\t\t\treturn filepath.SkipDir\n\t\t\t}\n\t\t\treturn nil\n\t\t}\n\n\t\t// Check if we've opened enough files\n\t\tif filesOpened >= maxFilesToOpen {\n\t\t\treturn filepath.SkipAll\n\t\t}\n\n\t\t// Check file extension\n\t\text := filepath.Ext(path)\n\t\tif ext == \".ts\" || ext == \".tsx\" || ext == \".js\" || ext == \".jsx\" {\n\t\t\t// Try to open the file\n\t\t\tif err := c.OpenFile(ctx, path); err == nil {\n\t\t\t\tfilesOpened++\n\t\t\t\tif cnf.DebugLSP {\n\t\t\t\t\tlogging.Debug(\"Opened TypeScript file for initialization\", \"file\", path)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn nil\n\t})\n\n\tif err != nil && cnf.DebugLSP {\n\t\tlogging.Debug(\"Error walking directory for TypeScript files\", \"error\", err)\n\t}\n\n\tif cnf.DebugLSP {\n\t\tlogging.Debug(\"Opened TypeScript files for initialization\", \"count\", filesOpened)\n\t}\n}\n\n// shouldSkipDir returns true if the directory should be skipped during file search\nfunc shouldSkipDir(path string) bool {\n\tdirName := filepath.Base(path)\n\n\t// Skip hidden directories\n\tif strings.HasPrefix(dirName, \".\") {\n\t\treturn true\n\t}\n\n\t// Skip common directories that won't contain relevant source files\n\tskipDirs := map[string]bool{\n\t\t\"node_modules\": true,\n\t\t\"dist\": true,\n\t\t\"build\": true,\n\t\t\"coverage\": true,\n\t\t\"vendor\": true,\n\t\t\"target\": true,\n\t}\n\n\treturn skipDirs[dirName]\n}\n\n// pingWithWorkspaceSymbol tries a workspace/symbol request\nfunc (c *Client) pingWithWorkspaceSymbol(ctx context.Context) error {\n\tvar result []protocol.SymbolInformation\n\treturn c.Call(ctx, \"workspace/symbol\", protocol.WorkspaceSymbolParams{\n\t\tQuery: \"\",\n\t}, &result)\n}\n\n// pingWithServerCapabilities tries to get server capabilities\nfunc (c *Client) pingWithServerCapabilities(ctx context.Context) error {\n\t// This is a very lightweight request that should work for most servers\n\treturn c.Notify(ctx, \"$/cancelRequest\", struct{ ID int }{ID: -1})\n}\n\ntype OpenFileInfo struct {\n\tVersion int32\n\tURI protocol.DocumentUri\n}\n\nfunc (c *Client) OpenFile(ctx context.Context, filepath string) error {\n\turi := fmt.Sprintf(\"file://%s\", filepath)\n\n\tc.openFilesMu.Lock()\n\tif _, exists := c.openFiles[uri]; exists {\n\t\tc.openFilesMu.Unlock()\n\t\treturn nil // Already open\n\t}\n\tc.openFilesMu.Unlock()\n\n\t// Skip files that do not exist or cannot be read\n\tcontent, err := os.ReadFile(filepath)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error reading file: %w\", err)\n\t}\n\n\tparams := protocol.DidOpenTextDocumentParams{\n\t\tTextDocument: protocol.TextDocumentItem{\n\t\t\tURI: protocol.DocumentUri(uri),\n\t\t\tLanguageID: DetectLanguageID(uri),\n\t\t\tVersion: 1,\n\t\t\tText: string(content),\n\t\t},\n\t}\n\n\tif err := c.Notify(ctx, \"textDocument/didOpen\", params); err != nil {\n\t\treturn err\n\t}\n\n\tc.openFilesMu.Lock()\n\tc.openFiles[uri] = &OpenFileInfo{\n\t\tVersion: 1,\n\t\tURI: protocol.DocumentUri(uri),\n\t}\n\tc.openFilesMu.Unlock()\n\n\treturn nil\n}\n\nfunc (c *Client) NotifyChange(ctx context.Context, filepath string) error {\n\turi := fmt.Sprintf(\"file://%s\", filepath)\n\n\tcontent, err := os.ReadFile(filepath)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error reading file: %w\", err)\n\t}\n\n\tc.openFilesMu.Lock()\n\tfileInfo, isOpen := c.openFiles[uri]\n\tif !isOpen {\n\t\tc.openFilesMu.Unlock()\n\t\treturn fmt.Errorf(\"cannot notify change for unopened file: %s\", filepath)\n\t}\n\n\t// Increment version\n\tfileInfo.Version++\n\tversion := fileInfo.Version\n\tc.openFilesMu.Unlock()\n\n\tparams := protocol.DidChangeTextDocumentParams{\n\t\tTextDocument: protocol.VersionedTextDocumentIdentifier{\n\t\t\tTextDocumentIdentifier: protocol.TextDocumentIdentifier{\n\t\t\t\tURI: protocol.DocumentUri(uri),\n\t\t\t},\n\t\t\tVersion: version,\n\t\t},\n\t\tContentChanges: []protocol.TextDocumentContentChangeEvent{\n\t\t\t{\n\t\t\t\tValue: protocol.TextDocumentContentChangeWholeDocument{\n\t\t\t\t\tText: string(content),\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\treturn c.Notify(ctx, \"textDocument/didChange\", params)\n}\n\nfunc (c *Client) CloseFile(ctx context.Context, filepath string) error {\n\tcnf := config.Get()\n\turi := fmt.Sprintf(\"file://%s\", filepath)\n\n\tc.openFilesMu.Lock()\n\tif _, exists := c.openFiles[uri]; !exists {\n\t\tc.openFilesMu.Unlock()\n\t\treturn nil // Already closed\n\t}\n\tc.openFilesMu.Unlock()\n\n\tparams := protocol.DidCloseTextDocumentParams{\n\t\tTextDocument: protocol.TextDocumentIdentifier{\n\t\t\tURI: protocol.DocumentUri(uri),\n\t\t},\n\t}\n\n\tif cnf.DebugLSP {\n\t\tlogging.Debug(\"Closing file\", \"file\", filepath)\n\t}\n\tif err := c.Notify(ctx, \"textDocument/didClose\", params); err != nil {\n\t\treturn err\n\t}\n\n\tc.openFilesMu.Lock()\n\tdelete(c.openFiles, uri)\n\tc.openFilesMu.Unlock()\n\n\treturn nil\n}\n\nfunc (c *Client) IsFileOpen(filepath string) bool {\n\turi := fmt.Sprintf(\"file://%s\", filepath)\n\tc.openFilesMu.RLock()\n\tdefer c.openFilesMu.RUnlock()\n\t_, exists := c.openFiles[uri]\n\treturn exists\n}\n\n// CloseAllFiles closes all currently open files\nfunc (c *Client) CloseAllFiles(ctx context.Context) {\n\tcnf := config.Get()\n\tc.openFilesMu.Lock()\n\tfilesToClose := make([]string, 0, len(c.openFiles))\n\n\t// First collect all URIs that need to be closed\n\tfor uri := range c.openFiles {\n\t\t// Convert URI back to file path by trimming \"file://\" prefix\n\t\tfilePath := strings.TrimPrefix(uri, \"file://\")\n\t\tfilesToClose = append(filesToClose, filePath)\n\t}\n\tc.openFilesMu.Unlock()\n\n\t// Then close them all\n\tfor _, filePath := range filesToClose {\n\t\terr := c.CloseFile(ctx, filePath)\n\t\tif err != nil && cnf.DebugLSP {\n\t\t\tlogging.Warn(\"Error closing file\", \"file\", filePath, \"error\", err)\n\t\t}\n\t}\n\n\tif cnf.DebugLSP {\n\t\tlogging.Debug(\"Closed all files\", \"files\", filesToClose)\n\t}\n}\n\nfunc (c *Client) GetFileDiagnostics(uri protocol.DocumentUri) []protocol.Diagnostic {\n\tc.diagnosticsMu.RLock()\n\tdefer c.diagnosticsMu.RUnlock()\n\n\treturn c.diagnostics[uri]\n}\n\n// GetDiagnostics returns all diagnostics for all files\nfunc (c *Client) GetDiagnostics() map[protocol.DocumentUri][]protocol.Diagnostic {\n\treturn c.diagnostics\n}\n\n// OpenFileOnDemand opens a file only if it's not already open\n// This is used for lazy-loading files when they're actually needed\nfunc (c *Client) OpenFileOnDemand(ctx context.Context, filepath string) error {\n\t// Check if the file is already open\n\tif c.IsFileOpen(filepath) {\n\t\treturn nil\n\t}\n\n\t// Open the file\n\treturn c.OpenFile(ctx, filepath)\n}\n\n// GetDiagnosticsForFile ensures a file is open and returns its diagnostics\n// This is useful for on-demand diagnostics when using lazy loading\nfunc (c *Client) GetDiagnosticsForFile(ctx context.Context, filepath string) ([]protocol.Diagnostic, error) {\n\turi := fmt.Sprintf(\"file://%s\", filepath)\n\tdocumentUri := protocol.DocumentUri(uri)\n\n\t// Make sure the file is open\n\tif !c.IsFileOpen(filepath) {\n\t\tif err := c.OpenFile(ctx, filepath); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to open file for diagnostics: %w\", err)\n\t\t}\n\n\t\t// Give the LSP server a moment to process the file\n\t\ttime.Sleep(100 * time.Millisecond)\n\t}\n\n\t// Get diagnostics\n\tc.diagnosticsMu.RLock()\n\tdiagnostics := c.diagnostics[documentUri]\n\tc.diagnosticsMu.RUnlock()\n\n\treturn diagnostics, nil\n}\n\n// ClearDiagnosticsForURI removes diagnostics for a specific URI from the cache\nfunc (c *Client) ClearDiagnosticsForURI(uri protocol.DocumentUri) {\n\tc.diagnosticsMu.Lock()\n\tdefer c.diagnosticsMu.Unlock()\n\tdelete(c.diagnostics, uri)\n}\n"], ["/opencode/internal/tui/components/core/status.go", "package core\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\t\"time\"\n\n\ttea \"github.com/charmbracelet/bubbletea\"\n\t\"github.com/charmbracelet/lipgloss\"\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/llm/models\"\n\t\"github.com/opencode-ai/opencode/internal/lsp\"\n\t\"github.com/opencode-ai/opencode/internal/lsp/protocol\"\n\t\"github.com/opencode-ai/opencode/internal/pubsub\"\n\t\"github.com/opencode-ai/opencode/internal/session\"\n\t\"github.com/opencode-ai/opencode/internal/tui/components/chat\"\n\t\"github.com/opencode-ai/opencode/internal/tui/styles\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n\t\"github.com/opencode-ai/opencode/internal/tui/util\"\n)\n\ntype StatusCmp interface {\n\ttea.Model\n}\n\ntype statusCmp struct {\n\tinfo util.InfoMsg\n\twidth int\n\tmessageTTL time.Duration\n\tlspClients map[string]*lsp.Client\n\tsession session.Session\n}\n\n// clearMessageCmd is a command that clears status messages after a timeout\nfunc (m statusCmp) clearMessageCmd(ttl time.Duration) tea.Cmd {\n\treturn tea.Tick(ttl, func(time.Time) tea.Msg {\n\t\treturn util.ClearStatusMsg{}\n\t})\n}\n\nfunc (m statusCmp) Init() tea.Cmd {\n\treturn nil\n}\n\nfunc (m statusCmp) Update(msg tea.Msg) (tea.Model, tea.Cmd) {\n\tswitch msg := msg.(type) {\n\tcase tea.WindowSizeMsg:\n\t\tm.width = msg.Width\n\t\treturn m, nil\n\tcase chat.SessionSelectedMsg:\n\t\tm.session = msg\n\tcase chat.SessionClearedMsg:\n\t\tm.session = session.Session{}\n\tcase pubsub.Event[session.Session]:\n\t\tif msg.Type == pubsub.UpdatedEvent {\n\t\t\tif m.session.ID == msg.Payload.ID {\n\t\t\t\tm.session = msg.Payload\n\t\t\t}\n\t\t}\n\tcase util.InfoMsg:\n\t\tm.info = msg\n\t\tttl := msg.TTL\n\t\tif ttl == 0 {\n\t\t\tttl = m.messageTTL\n\t\t}\n\t\treturn m, m.clearMessageCmd(ttl)\n\tcase util.ClearStatusMsg:\n\t\tm.info = util.InfoMsg{}\n\t}\n\treturn m, nil\n}\n\nvar helpWidget = \"\"\n\n// getHelpWidget returns the help widget with current theme colors\nfunc getHelpWidget() string {\n\tt := theme.CurrentTheme()\n\thelpText := \"ctrl+? help\"\n\n\treturn styles.Padded().\n\t\tBackground(t.TextMuted()).\n\t\tForeground(t.BackgroundDarker()).\n\t\tBold(true).\n\t\tRender(helpText)\n}\n\nfunc formatTokensAndCost(tokens, contextWindow int64, cost float64) string {\n\t// Format tokens in human-readable format (e.g., 110K, 1.2M)\n\tvar formattedTokens string\n\tswitch {\n\tcase tokens >= 1_000_000:\n\t\tformattedTokens = fmt.Sprintf(\"%.1fM\", float64(tokens)/1_000_000)\n\tcase tokens >= 1_000:\n\t\tformattedTokens = fmt.Sprintf(\"%.1fK\", float64(tokens)/1_000)\n\tdefault:\n\t\tformattedTokens = fmt.Sprintf(\"%d\", tokens)\n\t}\n\n\t// Remove .0 suffix if present\n\tif strings.HasSuffix(formattedTokens, \".0K\") {\n\t\tformattedTokens = strings.Replace(formattedTokens, \".0K\", \"K\", 1)\n\t}\n\tif strings.HasSuffix(formattedTokens, \".0M\") {\n\t\tformattedTokens = strings.Replace(formattedTokens, \".0M\", \"M\", 1)\n\t}\n\n\t// Format cost with $ symbol and 2 decimal places\n\tformattedCost := fmt.Sprintf(\"$%.2f\", cost)\n\n\tpercentage := (float64(tokens) / float64(contextWindow)) * 100\n\tif percentage > 80 {\n\t\t// add the warning icon and percentage\n\t\tformattedTokens = fmt.Sprintf(\"%s(%d%%)\", styles.WarningIcon, int(percentage))\n\t}\n\n\treturn fmt.Sprintf(\"Context: %s, Cost: %s\", formattedTokens, formattedCost)\n}\n\nfunc (m statusCmp) View() string {\n\tt := theme.CurrentTheme()\n\tmodelID := config.Get().Agents[config.AgentCoder].Model\n\tmodel := models.SupportedModels[modelID]\n\n\t// Initialize the help widget\n\tstatus := getHelpWidget()\n\n\ttokenInfoWidth := 0\n\tif m.session.ID != \"\" {\n\t\ttotalTokens := m.session.PromptTokens + m.session.CompletionTokens\n\t\ttokens := formatTokensAndCost(totalTokens, model.ContextWindow, m.session.Cost)\n\t\ttokensStyle := styles.Padded().\n\t\t\tBackground(t.Text()).\n\t\t\tForeground(t.BackgroundSecondary())\n\t\tpercentage := (float64(totalTokens) / float64(model.ContextWindow)) * 100\n\t\tif percentage > 80 {\n\t\t\ttokensStyle = tokensStyle.Background(t.Warning())\n\t\t}\n\t\ttokenInfoWidth = lipgloss.Width(tokens) + 2\n\t\tstatus += tokensStyle.Render(tokens)\n\t}\n\n\tdiagnostics := styles.Padded().\n\t\tBackground(t.BackgroundDarker()).\n\t\tRender(m.projectDiagnostics())\n\n\tavailableWidht := max(0, m.width-lipgloss.Width(helpWidget)-lipgloss.Width(m.model())-lipgloss.Width(diagnostics)-tokenInfoWidth)\n\n\tif m.info.Msg != \"\" {\n\t\tinfoStyle := styles.Padded().\n\t\t\tForeground(t.Background()).\n\t\t\tWidth(availableWidht)\n\n\t\tswitch m.info.Type {\n\t\tcase util.InfoTypeInfo:\n\t\t\tinfoStyle = infoStyle.Background(t.Info())\n\t\tcase util.InfoTypeWarn:\n\t\t\tinfoStyle = infoStyle.Background(t.Warning())\n\t\tcase util.InfoTypeError:\n\t\t\tinfoStyle = infoStyle.Background(t.Error())\n\t\t}\n\n\t\tinfoWidth := availableWidht - 10\n\t\t// Truncate message if it's longer than available width\n\t\tmsg := m.info.Msg\n\t\tif len(msg) > infoWidth && infoWidth > 0 {\n\t\t\tmsg = msg[:infoWidth] + \"...\"\n\t\t}\n\t\tstatus += infoStyle.Render(msg)\n\t} else {\n\t\tstatus += styles.Padded().\n\t\t\tForeground(t.Text()).\n\t\t\tBackground(t.BackgroundSecondary()).\n\t\t\tWidth(availableWidht).\n\t\t\tRender(\"\")\n\t}\n\n\tstatus += diagnostics\n\tstatus += m.model()\n\treturn status\n}\n\nfunc (m *statusCmp) projectDiagnostics() string {\n\tt := theme.CurrentTheme()\n\n\t// Check if any LSP server is still initializing\n\tinitializing := false\n\tfor _, client := range m.lspClients {\n\t\tif client.GetServerState() == lsp.StateStarting {\n\t\t\tinitializing = true\n\t\t\tbreak\n\t\t}\n\t}\n\n\t// If any server is initializing, show that status\n\tif initializing {\n\t\treturn lipgloss.NewStyle().\n\t\t\tBackground(t.BackgroundDarker()).\n\t\t\tForeground(t.Warning()).\n\t\t\tRender(fmt.Sprintf(\"%s Initializing LSP...\", styles.SpinnerIcon))\n\t}\n\n\terrorDiagnostics := []protocol.Diagnostic{}\n\twarnDiagnostics := []protocol.Diagnostic{}\n\thintDiagnostics := []protocol.Diagnostic{}\n\tinfoDiagnostics := []protocol.Diagnostic{}\n\tfor _, client := range m.lspClients {\n\t\tfor _, d := range client.GetDiagnostics() {\n\t\t\tfor _, diag := range d {\n\t\t\t\tswitch diag.Severity {\n\t\t\t\tcase protocol.SeverityError:\n\t\t\t\t\terrorDiagnostics = append(errorDiagnostics, diag)\n\t\t\t\tcase protocol.SeverityWarning:\n\t\t\t\t\twarnDiagnostics = append(warnDiagnostics, diag)\n\t\t\t\tcase protocol.SeverityHint:\n\t\t\t\t\thintDiagnostics = append(hintDiagnostics, diag)\n\t\t\t\tcase protocol.SeverityInformation:\n\t\t\t\t\tinfoDiagnostics = append(infoDiagnostics, diag)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif len(errorDiagnostics) == 0 && len(warnDiagnostics) == 0 && len(hintDiagnostics) == 0 && len(infoDiagnostics) == 0 {\n\t\treturn \"No diagnostics\"\n\t}\n\n\tdiagnostics := []string{}\n\n\tif len(errorDiagnostics) > 0 {\n\t\terrStr := lipgloss.NewStyle().\n\t\t\tBackground(t.BackgroundDarker()).\n\t\t\tForeground(t.Error()).\n\t\t\tRender(fmt.Sprintf(\"%s %d\", styles.ErrorIcon, len(errorDiagnostics)))\n\t\tdiagnostics = append(diagnostics, errStr)\n\t}\n\tif len(warnDiagnostics) > 0 {\n\t\twarnStr := lipgloss.NewStyle().\n\t\t\tBackground(t.BackgroundDarker()).\n\t\t\tForeground(t.Warning()).\n\t\t\tRender(fmt.Sprintf(\"%s %d\", styles.WarningIcon, len(warnDiagnostics)))\n\t\tdiagnostics = append(diagnostics, warnStr)\n\t}\n\tif len(hintDiagnostics) > 0 {\n\t\thintStr := lipgloss.NewStyle().\n\t\t\tBackground(t.BackgroundDarker()).\n\t\t\tForeground(t.Text()).\n\t\t\tRender(fmt.Sprintf(\"%s %d\", styles.HintIcon, len(hintDiagnostics)))\n\t\tdiagnostics = append(diagnostics, hintStr)\n\t}\n\tif len(infoDiagnostics) > 0 {\n\t\tinfoStr := lipgloss.NewStyle().\n\t\t\tBackground(t.BackgroundDarker()).\n\t\t\tForeground(t.Info()).\n\t\t\tRender(fmt.Sprintf(\"%s %d\", styles.InfoIcon, len(infoDiagnostics)))\n\t\tdiagnostics = append(diagnostics, infoStr)\n\t}\n\n\treturn strings.Join(diagnostics, \" \")\n}\n\nfunc (m statusCmp) availableFooterMsgWidth(diagnostics, tokenInfo string) int {\n\ttokensWidth := 0\n\tif m.session.ID != \"\" {\n\t\ttokensWidth = lipgloss.Width(tokenInfo) + 2\n\t}\n\treturn max(0, m.width-lipgloss.Width(helpWidget)-lipgloss.Width(m.model())-lipgloss.Width(diagnostics)-tokensWidth)\n}\n\nfunc (m statusCmp) model() string {\n\tt := theme.CurrentTheme()\n\n\tcfg := config.Get()\n\n\tcoder, ok := cfg.Agents[config.AgentCoder]\n\tif !ok {\n\t\treturn \"Unknown\"\n\t}\n\tmodel := models.SupportedModels[coder.Model]\n\n\treturn styles.Padded().\n\t\tBackground(t.Secondary()).\n\t\tForeground(t.Background()).\n\t\tRender(model.Name)\n}\n\nfunc NewStatusCmp(lspClients map[string]*lsp.Client) StatusCmp {\n\thelpWidget = getHelpWidget()\n\n\treturn &statusCmp{\n\t\tmessageTTL: 10 * time.Second,\n\t\tlspClients: lspClients,\n\t}\n}\n"], ["/opencode/internal/lsp/handlers.go", "package lsp\n\nimport (\n\t\"encoding/json\"\n\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n\t\"github.com/opencode-ai/opencode/internal/lsp/protocol\"\n\t\"github.com/opencode-ai/opencode/internal/lsp/util\"\n)\n\n// Requests\n\nfunc HandleWorkspaceConfiguration(params json.RawMessage) (any, error) {\n\treturn []map[string]any{{}}, nil\n}\n\nfunc HandleRegisterCapability(params json.RawMessage) (any, error) {\n\tvar registerParams protocol.RegistrationParams\n\tif err := json.Unmarshal(params, ®isterParams); err != nil {\n\t\tlogging.Error(\"Error unmarshaling registration params\", \"error\", err)\n\t\treturn nil, err\n\t}\n\n\tfor _, reg := range registerParams.Registrations {\n\t\tswitch reg.Method {\n\t\tcase \"workspace/didChangeWatchedFiles\":\n\t\t\t// Parse the registration options\n\t\t\toptionsJSON, err := json.Marshal(reg.RegisterOptions)\n\t\t\tif err != nil {\n\t\t\t\tlogging.Error(\"Error marshaling registration options\", \"error\", err)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tvar options protocol.DidChangeWatchedFilesRegistrationOptions\n\t\t\tif err := json.Unmarshal(optionsJSON, &options); err != nil {\n\t\t\t\tlogging.Error(\"Error unmarshaling registration options\", \"error\", err)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// Store the file watchers registrations\n\t\t\tnotifyFileWatchRegistration(reg.ID, options.Watchers)\n\t\t}\n\t}\n\n\treturn nil, nil\n}\n\nfunc HandleApplyEdit(params json.RawMessage) (any, error) {\n\tvar edit protocol.ApplyWorkspaceEditParams\n\tif err := json.Unmarshal(params, &edit); err != nil {\n\t\treturn nil, err\n\t}\n\n\terr := util.ApplyWorkspaceEdit(edit.Edit)\n\tif err != nil {\n\t\tlogging.Error(\"Error applying workspace edit\", \"error\", err)\n\t\treturn protocol.ApplyWorkspaceEditResult{Applied: false, FailureReason: err.Error()}, nil\n\t}\n\n\treturn protocol.ApplyWorkspaceEditResult{Applied: true}, nil\n}\n\n// FileWatchRegistrationHandler is a function that will be called when file watch registrations are received\ntype FileWatchRegistrationHandler func(id string, watchers []protocol.FileSystemWatcher)\n\n// fileWatchHandler holds the current handler for file watch registrations\nvar fileWatchHandler FileWatchRegistrationHandler\n\n// RegisterFileWatchHandler sets the handler for file watch registrations\nfunc RegisterFileWatchHandler(handler FileWatchRegistrationHandler) {\n\tfileWatchHandler = handler\n}\n\n// notifyFileWatchRegistration notifies the handler about new file watch registrations\nfunc notifyFileWatchRegistration(id string, watchers []protocol.FileSystemWatcher) {\n\tif fileWatchHandler != nil {\n\t\tfileWatchHandler(id, watchers)\n\t}\n}\n\n// Notifications\n\nfunc HandleServerMessage(params json.RawMessage) {\n\tcnf := config.Get()\n\tvar msg struct {\n\t\tType int `json:\"type\"`\n\t\tMessage string `json:\"message\"`\n\t}\n\tif err := json.Unmarshal(params, &msg); err == nil {\n\t\tif cnf.DebugLSP {\n\t\t\tlogging.Debug(\"Server message\", \"type\", msg.Type, \"message\", msg.Message)\n\t\t}\n\t}\n}\n\nfunc HandleDiagnostics(client *Client, params json.RawMessage) {\n\tvar diagParams protocol.PublishDiagnosticsParams\n\tif err := json.Unmarshal(params, &diagParams); err != nil {\n\t\tlogging.Error(\"Error unmarshaling diagnostics params\", \"error\", err)\n\t\treturn\n\t}\n\n\tclient.diagnosticsMu.Lock()\n\tdefer client.diagnosticsMu.Unlock()\n\n\tclient.diagnostics[diagParams.URI] = diagParams.Diagnostics\n}\n"], ["/opencode/internal/lsp/protocol/tsdocument-changes.go", "// Copyright 2022 The Go Authors. All rights reserved.\n// Use of this source code is governed by a BSD-style\n// license that can be found in the LICENSE file.\n\npackage protocol\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n)\n\n// DocumentChange is a union of various file edit operations.\n//\n// Exactly one field of this struct is non-nil; see [DocumentChange.Valid].\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#resourceChanges\ntype DocumentChange struct {\n\tTextDocumentEdit *TextDocumentEdit\n\tCreateFile *CreateFile\n\tRenameFile *RenameFile\n\tDeleteFile *DeleteFile\n}\n\n// Valid reports whether the DocumentChange sum-type value is valid,\n// that is, exactly one of create, delete, edit, or rename.\nfunc (ch DocumentChange) Valid() bool {\n\tn := 0\n\tif ch.TextDocumentEdit != nil {\n\t\tn++\n\t}\n\tif ch.CreateFile != nil {\n\t\tn++\n\t}\n\tif ch.RenameFile != nil {\n\t\tn++\n\t}\n\tif ch.DeleteFile != nil {\n\t\tn++\n\t}\n\treturn n == 1\n}\n\nfunc (d *DocumentChange) UnmarshalJSON(data []byte) error {\n\tvar m map[string]any\n\tif err := json.Unmarshal(data, &m); err != nil {\n\t\treturn err\n\t}\n\n\tif _, ok := m[\"textDocument\"]; ok {\n\t\td.TextDocumentEdit = new(TextDocumentEdit)\n\t\treturn json.Unmarshal(data, d.TextDocumentEdit)\n\t}\n\n\t// The {Create,Rename,Delete}File types all share a 'kind' field.\n\tkind := m[\"kind\"]\n\tswitch kind {\n\tcase \"create\":\n\t\td.CreateFile = new(CreateFile)\n\t\treturn json.Unmarshal(data, d.CreateFile)\n\tcase \"rename\":\n\t\td.RenameFile = new(RenameFile)\n\t\treturn json.Unmarshal(data, d.RenameFile)\n\tcase \"delete\":\n\t\td.DeleteFile = new(DeleteFile)\n\t\treturn json.Unmarshal(data, d.DeleteFile)\n\t}\n\treturn fmt.Errorf(\"DocumentChanges: unexpected kind: %q\", kind)\n}\n\nfunc (d *DocumentChange) MarshalJSON() ([]byte, error) {\n\tif d.TextDocumentEdit != nil {\n\t\treturn json.Marshal(d.TextDocumentEdit)\n\t} else if d.CreateFile != nil {\n\t\treturn json.Marshal(d.CreateFile)\n\t} else if d.RenameFile != nil {\n\t\treturn json.Marshal(d.RenameFile)\n\t} else if d.DeleteFile != nil {\n\t\treturn json.Marshal(d.DeleteFile)\n\t}\n\treturn nil, fmt.Errorf(\"empty DocumentChanges union value\")\n}\n"], ["/opencode/internal/tui/components/dialog/filepicker.go", "package dialog\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"sort\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/charmbracelet/bubbles/key\"\n\t\"github.com/charmbracelet/bubbles/textinput\"\n\t\"github.com/charmbracelet/bubbles/viewport\"\n\ttea \"github.com/charmbracelet/bubbletea\"\n\t\"github.com/charmbracelet/lipgloss\"\n\t\"github.com/opencode-ai/opencode/internal/app\"\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n\t\"github.com/opencode-ai/opencode/internal/message\"\n\t\"github.com/opencode-ai/opencode/internal/tui/image\"\n\t\"github.com/opencode-ai/opencode/internal/tui/styles\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n\t\"github.com/opencode-ai/opencode/internal/tui/util\"\n)\n\nconst (\n\tmaxAttachmentSize = int64(5 * 1024 * 1024) // 5MB\n\tdownArrow = \"down\"\n\tupArrow = \"up\"\n)\n\ntype FilePrickerKeyMap struct {\n\tEnter key.Binding\n\tDown key.Binding\n\tUp key.Binding\n\tForward key.Binding\n\tBackward key.Binding\n\tOpenFilePicker key.Binding\n\tEsc key.Binding\n\tInsertCWD key.Binding\n}\n\nvar filePickerKeyMap = FilePrickerKeyMap{\n\tEnter: key.NewBinding(\n\t\tkey.WithKeys(\"enter\"),\n\t\tkey.WithHelp(\"enter\", \"select file/enter directory\"),\n\t),\n\tDown: key.NewBinding(\n\t\tkey.WithKeys(\"j\", downArrow),\n\t\tkey.WithHelp(\"↓/j\", \"down\"),\n\t),\n\tUp: key.NewBinding(\n\t\tkey.WithKeys(\"k\", upArrow),\n\t\tkey.WithHelp(\"↑/k\", \"up\"),\n\t),\n\tForward: key.NewBinding(\n\t\tkey.WithKeys(\"l\"),\n\t\tkey.WithHelp(\"l\", \"enter directory\"),\n\t),\n\tBackward: key.NewBinding(\n\t\tkey.WithKeys(\"h\", \"backspace\"),\n\t\tkey.WithHelp(\"h/backspace\", \"go back\"),\n\t),\n\tOpenFilePicker: key.NewBinding(\n\t\tkey.WithKeys(\"ctrl+f\"),\n\t\tkey.WithHelp(\"ctrl+f\", \"open file picker\"),\n\t),\n\tEsc: key.NewBinding(\n\t\tkey.WithKeys(\"esc\"),\n\t\tkey.WithHelp(\"esc\", \"close/exit\"),\n\t),\n\tInsertCWD: key.NewBinding(\n\t\tkey.WithKeys(\"i\"),\n\t\tkey.WithHelp(\"i\", \"manual path input\"),\n\t),\n}\n\ntype filepickerCmp struct {\n\tbasePath string\n\twidth int\n\theight int\n\tcursor int\n\terr error\n\tcursorChain stack\n\tviewport viewport.Model\n\tdirs []os.DirEntry\n\tcwdDetails *DirNode\n\tselectedFile string\n\tcwd textinput.Model\n\tShowFilePicker bool\n\tapp *app.App\n}\n\ntype DirNode struct {\n\tparent *DirNode\n\tchild *DirNode\n\tdirectory string\n}\ntype stack []int\n\nfunc (s stack) Push(v int) stack {\n\treturn append(s, v)\n}\n\nfunc (s stack) Pop() (stack, int) {\n\tl := len(s)\n\treturn s[:l-1], s[l-1]\n}\n\ntype AttachmentAddedMsg struct {\n\tAttachment message.Attachment\n}\n\nfunc (f *filepickerCmp) Init() tea.Cmd {\n\treturn nil\n}\n\nfunc (f *filepickerCmp) Update(msg tea.Msg) (tea.Model, tea.Cmd) {\n\tvar cmd tea.Cmd\n\tswitch msg := msg.(type) {\n\tcase tea.WindowSizeMsg:\n\t\tf.width = 60\n\t\tf.height = 20\n\t\tf.viewport.Width = 80\n\t\tf.viewport.Height = 22\n\t\tf.cursor = 0\n\t\tf.getCurrentFileBelowCursor()\n\tcase tea.KeyMsg:\n\t\tif f.cwd.Focused() {\n\t\t\tf.cwd, cmd = f.cwd.Update(msg)\n\t\t}\n\t\tswitch {\n\t\tcase key.Matches(msg, filePickerKeyMap.InsertCWD):\n\t\t\tf.cwd.Focus()\n\t\t\treturn f, cmd\n\t\tcase key.Matches(msg, filePickerKeyMap.Esc):\n\t\t\tif f.cwd.Focused() {\n\t\t\t\tf.cwd.Blur()\n\t\t\t}\n\t\tcase key.Matches(msg, filePickerKeyMap.Down):\n\t\t\tif !f.cwd.Focused() || msg.String() == downArrow {\n\t\t\t\tif f.cursor < len(f.dirs)-1 {\n\t\t\t\t\tf.cursor++\n\t\t\t\t\tf.getCurrentFileBelowCursor()\n\t\t\t\t}\n\t\t\t}\n\t\tcase key.Matches(msg, filePickerKeyMap.Up):\n\t\t\tif !f.cwd.Focused() || msg.String() == upArrow {\n\t\t\t\tif f.cursor > 0 {\n\t\t\t\t\tf.cursor--\n\t\t\t\t\tf.getCurrentFileBelowCursor()\n\t\t\t\t}\n\t\t\t}\n\t\tcase key.Matches(msg, filePickerKeyMap.Enter):\n\t\t\tvar path string\n\t\t\tvar isPathDir bool\n\t\t\tif f.cwd.Focused() {\n\t\t\t\tpath = f.cwd.Value()\n\t\t\t\tfileInfo, err := os.Stat(path)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlogging.ErrorPersist(\"Invalid path\")\n\t\t\t\t\treturn f, cmd\n\t\t\t\t}\n\t\t\t\tisPathDir = fileInfo.IsDir()\n\t\t\t} else {\n\t\t\t\tpath = filepath.Join(f.cwdDetails.directory, \"/\", f.dirs[f.cursor].Name())\n\t\t\t\tisPathDir = f.dirs[f.cursor].IsDir()\n\t\t\t}\n\t\t\tif isPathDir {\n\t\t\t\tnewWorkingDir := DirNode{parent: f.cwdDetails, directory: path}\n\t\t\t\tf.cwdDetails.child = &newWorkingDir\n\t\t\t\tf.cwdDetails = f.cwdDetails.child\n\t\t\t\tf.cursorChain = f.cursorChain.Push(f.cursor)\n\t\t\t\tf.dirs = readDir(f.cwdDetails.directory, false)\n\t\t\t\tf.cursor = 0\n\t\t\t\tf.cwd.SetValue(f.cwdDetails.directory)\n\t\t\t\tf.getCurrentFileBelowCursor()\n\t\t\t} else {\n\t\t\t\tf.selectedFile = path\n\t\t\t\treturn f.addAttachmentToMessage()\n\t\t\t}\n\t\tcase key.Matches(msg, filePickerKeyMap.Esc):\n\t\t\tif !f.cwd.Focused() {\n\t\t\t\tf.cursorChain = make(stack, 0)\n\t\t\t\tf.cursor = 0\n\t\t\t} else {\n\t\t\t\tf.cwd.Blur()\n\t\t\t}\n\t\tcase key.Matches(msg, filePickerKeyMap.Forward):\n\t\t\tif !f.cwd.Focused() {\n\t\t\t\tif f.dirs[f.cursor].IsDir() {\n\t\t\t\t\tpath := filepath.Join(f.cwdDetails.directory, \"/\", f.dirs[f.cursor].Name())\n\t\t\t\t\tnewWorkingDir := DirNode{parent: f.cwdDetails, directory: path}\n\t\t\t\t\tf.cwdDetails.child = &newWorkingDir\n\t\t\t\t\tf.cwdDetails = f.cwdDetails.child\n\t\t\t\t\tf.cursorChain = f.cursorChain.Push(f.cursor)\n\t\t\t\t\tf.dirs = readDir(f.cwdDetails.directory, false)\n\t\t\t\t\tf.cursor = 0\n\t\t\t\t\tf.cwd.SetValue(f.cwdDetails.directory)\n\t\t\t\t\tf.getCurrentFileBelowCursor()\n\t\t\t\t}\n\t\t\t}\n\t\tcase key.Matches(msg, filePickerKeyMap.Backward):\n\t\t\tif !f.cwd.Focused() {\n\t\t\t\tif len(f.cursorChain) != 0 && f.cwdDetails.parent != nil {\n\t\t\t\t\tf.cursorChain, f.cursor = f.cursorChain.Pop()\n\t\t\t\t\tf.cwdDetails = f.cwdDetails.parent\n\t\t\t\t\tf.cwdDetails.child = nil\n\t\t\t\t\tf.dirs = readDir(f.cwdDetails.directory, false)\n\t\t\t\t\tf.cwd.SetValue(f.cwdDetails.directory)\n\t\t\t\t\tf.getCurrentFileBelowCursor()\n\t\t\t\t}\n\t\t\t}\n\t\tcase key.Matches(msg, filePickerKeyMap.OpenFilePicker):\n\t\t\tf.dirs = readDir(f.cwdDetails.directory, false)\n\t\t\tf.cursor = 0\n\t\t\tf.getCurrentFileBelowCursor()\n\t\t}\n\t}\n\treturn f, cmd\n}\n\nfunc (f *filepickerCmp) addAttachmentToMessage() (tea.Model, tea.Cmd) {\n\tmodeInfo := GetSelectedModel(config.Get())\n\tif !modeInfo.SupportsAttachments {\n\t\tlogging.ErrorPersist(fmt.Sprintf(\"Model %s doesn't support attachments\", modeInfo.Name))\n\t\treturn f, nil\n\t}\n\n\tselectedFilePath := f.selectedFile\n\tif !isExtSupported(selectedFilePath) {\n\t\tlogging.ErrorPersist(\"Unsupported file\")\n\t\treturn f, nil\n\t}\n\n\tisFileLarge, err := image.ValidateFileSize(selectedFilePath, maxAttachmentSize)\n\tif err != nil {\n\t\tlogging.ErrorPersist(\"unable to read the image\")\n\t\treturn f, nil\n\t}\n\tif isFileLarge {\n\t\tlogging.ErrorPersist(\"file too large, max 5MB\")\n\t\treturn f, nil\n\t}\n\n\tcontent, err := os.ReadFile(selectedFilePath)\n\tif err != nil {\n\t\tlogging.ErrorPersist(\"Unable read selected file\")\n\t\treturn f, nil\n\t}\n\n\tmimeBufferSize := min(512, len(content))\n\tmimeType := http.DetectContentType(content[:mimeBufferSize])\n\tfileName := filepath.Base(selectedFilePath)\n\tattachment := message.Attachment{FilePath: selectedFilePath, FileName: fileName, MimeType: mimeType, Content: content}\n\tf.selectedFile = \"\"\n\treturn f, util.CmdHandler(AttachmentAddedMsg{attachment})\n}\n\nfunc (f *filepickerCmp) View() string {\n\tt := theme.CurrentTheme()\n\tconst maxVisibleDirs = 20\n\tconst maxWidth = 80\n\n\tadjustedWidth := maxWidth\n\tfor _, file := range f.dirs {\n\t\tif len(file.Name()) > adjustedWidth-4 { // Account for padding\n\t\t\tadjustedWidth = len(file.Name()) + 4\n\t\t}\n\t}\n\tadjustedWidth = max(30, min(adjustedWidth, f.width-15)) + 1\n\n\tfiles := make([]string, 0, maxVisibleDirs)\n\tstartIdx := 0\n\n\tif len(f.dirs) > maxVisibleDirs {\n\t\thalfVisible := maxVisibleDirs / 2\n\t\tif f.cursor >= halfVisible && f.cursor < len(f.dirs)-halfVisible {\n\t\t\tstartIdx = f.cursor - halfVisible\n\t\t} else if f.cursor >= len(f.dirs)-halfVisible {\n\t\t\tstartIdx = len(f.dirs) - maxVisibleDirs\n\t\t}\n\t}\n\n\tendIdx := min(startIdx+maxVisibleDirs, len(f.dirs))\n\n\tfor i := startIdx; i < endIdx; i++ {\n\t\tfile := f.dirs[i]\n\t\titemStyle := styles.BaseStyle().Width(adjustedWidth)\n\n\t\tif i == f.cursor {\n\t\t\titemStyle = itemStyle.\n\t\t\t\tBackground(t.Primary()).\n\t\t\t\tForeground(t.Background()).\n\t\t\t\tBold(true)\n\t\t}\n\t\tfilename := file.Name()\n\n\t\tif len(filename) > adjustedWidth-4 {\n\t\t\tfilename = filename[:adjustedWidth-7] + \"...\"\n\t\t}\n\t\tif file.IsDir() {\n\t\t\tfilename = filename + \"/\"\n\t\t}\n\t\t// No need to reassign filename if it's not changing\n\n\t\tfiles = append(files, itemStyle.Padding(0, 1).Render(filename))\n\t}\n\n\t// Pad to always show exactly 21 lines\n\tfor len(files) < maxVisibleDirs {\n\t\tfiles = append(files, styles.BaseStyle().Width(adjustedWidth).Render(\"\"))\n\t}\n\n\tcurrentPath := styles.BaseStyle().\n\t\tHeight(1).\n\t\tWidth(adjustedWidth).\n\t\tRender(f.cwd.View())\n\n\tviewportstyle := lipgloss.NewStyle().\n\t\tWidth(f.viewport.Width).\n\t\tBackground(t.Background()).\n\t\tBorder(lipgloss.RoundedBorder()).\n\t\tBorderForeground(t.TextMuted()).\n\t\tBorderBackground(t.Background()).\n\t\tPadding(2).\n\t\tRender(f.viewport.View())\n\tvar insertExitText string\n\tif f.IsCWDFocused() {\n\t\tinsertExitText = \"Press esc to exit typing path\"\n\t} else {\n\t\tinsertExitText = \"Press i to start typing path\"\n\t}\n\n\tcontent := lipgloss.JoinVertical(\n\t\tlipgloss.Left,\n\t\tcurrentPath,\n\t\tstyles.BaseStyle().Width(adjustedWidth).Render(\"\"),\n\t\tstyles.BaseStyle().Width(adjustedWidth).Render(lipgloss.JoinVertical(lipgloss.Left, files...)),\n\t\tstyles.BaseStyle().Width(adjustedWidth).Render(\"\"),\n\t\tstyles.BaseStyle().Foreground(t.TextMuted()).Width(adjustedWidth).Render(insertExitText),\n\t)\n\n\tf.cwd.SetValue(f.cwd.Value())\n\tcontentStyle := styles.BaseStyle().Padding(1, 2).\n\t\tBorder(lipgloss.RoundedBorder()).\n\t\tBorderBackground(t.Background()).\n\t\tBorderForeground(t.TextMuted()).\n\t\tWidth(lipgloss.Width(content) + 4)\n\n\treturn lipgloss.JoinHorizontal(lipgloss.Center, contentStyle.Render(content), viewportstyle)\n}\n\ntype FilepickerCmp interface {\n\ttea.Model\n\tToggleFilepicker(showFilepicker bool)\n\tIsCWDFocused() bool\n}\n\nfunc (f *filepickerCmp) ToggleFilepicker(showFilepicker bool) {\n\tf.ShowFilePicker = showFilepicker\n}\n\nfunc (f *filepickerCmp) IsCWDFocused() bool {\n\treturn f.cwd.Focused()\n}\n\nfunc NewFilepickerCmp(app *app.App) FilepickerCmp {\n\thomepath, err := os.UserHomeDir()\n\tif err != nil {\n\t\tlogging.Error(\"error loading user files\")\n\t\treturn nil\n\t}\n\tbaseDir := DirNode{parent: nil, directory: homepath}\n\tdirs := readDir(homepath, false)\n\tviewport := viewport.New(0, 0)\n\tcurrentDirectory := textinput.New()\n\tcurrentDirectory.CharLimit = 200\n\tcurrentDirectory.Width = 44\n\tcurrentDirectory.Cursor.Blink = true\n\tcurrentDirectory.SetValue(baseDir.directory)\n\treturn &filepickerCmp{cwdDetails: &baseDir, dirs: dirs, cursorChain: make(stack, 0), viewport: viewport, cwd: currentDirectory, app: app}\n}\n\nfunc (f *filepickerCmp) getCurrentFileBelowCursor() {\n\tif len(f.dirs) == 0 || f.cursor < 0 || f.cursor >= len(f.dirs) {\n\t\tlogging.Error(fmt.Sprintf(\"Invalid cursor position. Dirs length: %d, Cursor: %d\", len(f.dirs), f.cursor))\n\t\tf.viewport.SetContent(\"Preview unavailable\")\n\t\treturn\n\t}\n\n\tdir := f.dirs[f.cursor]\n\tfilename := dir.Name()\n\tif !dir.IsDir() && isExtSupported(filename) {\n\t\tfullPath := f.cwdDetails.directory + \"/\" + dir.Name()\n\n\t\tgo func() {\n\t\t\timageString, err := image.ImagePreview(f.viewport.Width-4, fullPath)\n\t\t\tif err != nil {\n\t\t\t\tlogging.Error(err.Error())\n\t\t\t\tf.viewport.SetContent(\"Preview unavailable\")\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tf.viewport.SetContent(imageString)\n\t\t}()\n\t} else {\n\t\tf.viewport.SetContent(\"Preview unavailable\")\n\t}\n}\n\nfunc readDir(path string, showHidden bool) []os.DirEntry {\n\tlogging.Info(fmt.Sprintf(\"Reading directory: %s\", path))\n\n\tentriesChan := make(chan []os.DirEntry, 1)\n\terrChan := make(chan error, 1)\n\n\tgo func() {\n\t\tdirEntries, err := os.ReadDir(path)\n\t\tif err != nil {\n\t\t\tlogging.ErrorPersist(err.Error())\n\t\t\terrChan <- err\n\t\t\treturn\n\t\t}\n\t\tentriesChan <- dirEntries\n\t}()\n\n\tselect {\n\tcase dirEntries := <-entriesChan:\n\t\tsort.Slice(dirEntries, func(i, j int) bool {\n\t\t\tif dirEntries[i].IsDir() == dirEntries[j].IsDir() {\n\t\t\t\treturn dirEntries[i].Name() < dirEntries[j].Name()\n\t\t\t}\n\t\t\treturn dirEntries[i].IsDir()\n\t\t})\n\n\t\tif showHidden {\n\t\t\treturn dirEntries\n\t\t}\n\n\t\tvar sanitizedDirEntries []os.DirEntry\n\t\tfor _, dirEntry := range dirEntries {\n\t\t\tisHidden, _ := IsHidden(dirEntry.Name())\n\t\t\tif !isHidden {\n\t\t\t\tif dirEntry.IsDir() || isExtSupported(dirEntry.Name()) {\n\t\t\t\t\tsanitizedDirEntries = append(sanitizedDirEntries, dirEntry)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn sanitizedDirEntries\n\n\tcase err := <-errChan:\n\t\tlogging.ErrorPersist(fmt.Sprintf(\"Error reading directory %s\", path), err)\n\t\treturn []os.DirEntry{}\n\n\tcase <-time.After(5 * time.Second):\n\t\tlogging.ErrorPersist(fmt.Sprintf(\"Timeout reading directory %s\", path), nil)\n\t\treturn []os.DirEntry{}\n\t}\n}\n\nfunc IsHidden(file string) (bool, error) {\n\treturn strings.HasPrefix(file, \".\"), nil\n}\n\nfunc isExtSupported(path string) bool {\n\text := strings.ToLower(filepath.Ext(path))\n\treturn (ext == \".jpg\" || ext == \".jpeg\" || ext == \".webp\" || ext == \".png\")\n}\n"], ["/opencode/internal/tui/components/chat/message.go", "package chat\n\nimport (\n\t\"context\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"path/filepath\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/charmbracelet/lipgloss\"\n\t\"github.com/charmbracelet/x/ansi\"\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/diff\"\n\t\"github.com/opencode-ai/opencode/internal/llm/agent\"\n\t\"github.com/opencode-ai/opencode/internal/llm/models\"\n\t\"github.com/opencode-ai/opencode/internal/llm/tools\"\n\t\"github.com/opencode-ai/opencode/internal/message\"\n\t\"github.com/opencode-ai/opencode/internal/tui/styles\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n)\n\ntype uiMessageType int\n\nconst (\n\tuserMessageType uiMessageType = iota\n\tassistantMessageType\n\ttoolMessageType\n\n\tmaxResultHeight = 10\n)\n\ntype uiMessage struct {\n\tID string\n\tmessageType uiMessageType\n\tposition int\n\theight int\n\tcontent string\n}\n\nfunc toMarkdown(content string, focused bool, width int) string {\n\tr := styles.GetMarkdownRenderer(width)\n\trendered, _ := r.Render(content)\n\treturn rendered\n}\n\nfunc renderMessage(msg string, isUser bool, isFocused bool, width int, info ...string) string {\n\tt := theme.CurrentTheme()\n\n\tstyle := styles.BaseStyle().\n\t\tWidth(width - 1).\n\t\tBorderLeft(true).\n\t\tForeground(t.TextMuted()).\n\t\tBorderForeground(t.Primary()).\n\t\tBorderStyle(lipgloss.ThickBorder())\n\n\tif isUser {\n\t\tstyle = style.BorderForeground(t.Secondary())\n\t}\n\n\t// Apply markdown formatting and handle background color\n\tparts := []string{\n\t\tstyles.ForceReplaceBackgroundWithLipgloss(toMarkdown(msg, isFocused, width), t.Background()),\n\t}\n\n\t// Remove newline at the end\n\tparts[0] = strings.TrimSuffix(parts[0], \"\\n\")\n\tif len(info) > 0 {\n\t\tparts = append(parts, info...)\n\t}\n\n\trendered := style.Render(\n\t\tlipgloss.JoinVertical(\n\t\t\tlipgloss.Left,\n\t\t\tparts...,\n\t\t),\n\t)\n\n\treturn rendered\n}\n\nfunc renderUserMessage(msg message.Message, isFocused bool, width int, position int) uiMessage {\n\tvar styledAttachments []string\n\tt := theme.CurrentTheme()\n\tattachmentStyles := styles.BaseStyle().\n\t\tMarginLeft(1).\n\t\tBackground(t.TextMuted()).\n\t\tForeground(t.Text())\n\tfor _, attachment := range msg.BinaryContent() {\n\t\tfile := filepath.Base(attachment.Path)\n\t\tvar filename string\n\t\tif len(file) > 10 {\n\t\t\tfilename = fmt.Sprintf(\" %s %s...\", styles.DocumentIcon, file[0:7])\n\t\t} else {\n\t\t\tfilename = fmt.Sprintf(\" %s %s\", styles.DocumentIcon, file)\n\t\t}\n\t\tstyledAttachments = append(styledAttachments, attachmentStyles.Render(filename))\n\t}\n\tcontent := \"\"\n\tif len(styledAttachments) > 0 {\n\t\tattachmentContent := styles.BaseStyle().Width(width).Render(lipgloss.JoinHorizontal(lipgloss.Left, styledAttachments...))\n\t\tcontent = renderMessage(msg.Content().String(), true, isFocused, width, attachmentContent)\n\t} else {\n\t\tcontent = renderMessage(msg.Content().String(), true, isFocused, width)\n\t}\n\tuserMsg := uiMessage{\n\t\tID: msg.ID,\n\t\tmessageType: userMessageType,\n\t\tposition: position,\n\t\theight: lipgloss.Height(content),\n\t\tcontent: content,\n\t}\n\treturn userMsg\n}\n\n// Returns multiple uiMessages because of the tool calls\nfunc renderAssistantMessage(\n\tmsg message.Message,\n\tmsgIndex int,\n\tallMessages []message.Message, // we need this to get tool results and the user message\n\tmessagesService message.Service, // We need this to get the task tool messages\n\tfocusedUIMessageId string,\n\tisSummary bool,\n\twidth int,\n\tposition int,\n) []uiMessage {\n\tmessages := []uiMessage{}\n\tcontent := msg.Content().String()\n\tthinking := msg.IsThinking()\n\tthinkingContent := msg.ReasoningContent().Thinking\n\tfinished := msg.IsFinished()\n\tfinishData := msg.FinishPart()\n\tinfo := []string{}\n\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\n\t// Add finish info if available\n\tif finished {\n\t\tswitch finishData.Reason {\n\t\tcase message.FinishReasonEndTurn:\n\t\t\ttook := formatTimestampDiff(msg.CreatedAt, finishData.Time)\n\t\t\tinfo = append(info, baseStyle.\n\t\t\t\tWidth(width-1).\n\t\t\t\tForeground(t.TextMuted()).\n\t\t\t\tRender(fmt.Sprintf(\" %s (%s)\", models.SupportedModels[msg.Model].Name, took)),\n\t\t\t)\n\t\tcase message.FinishReasonCanceled:\n\t\t\tinfo = append(info, baseStyle.\n\t\t\t\tWidth(width-1).\n\t\t\t\tForeground(t.TextMuted()).\n\t\t\t\tRender(fmt.Sprintf(\" %s (%s)\", models.SupportedModels[msg.Model].Name, \"canceled\")),\n\t\t\t)\n\t\tcase message.FinishReasonError:\n\t\t\tinfo = append(info, baseStyle.\n\t\t\t\tWidth(width-1).\n\t\t\t\tForeground(t.TextMuted()).\n\t\t\t\tRender(fmt.Sprintf(\" %s (%s)\", models.SupportedModels[msg.Model].Name, \"error\")),\n\t\t\t)\n\t\tcase message.FinishReasonPermissionDenied:\n\t\t\tinfo = append(info, baseStyle.\n\t\t\t\tWidth(width-1).\n\t\t\t\tForeground(t.TextMuted()).\n\t\t\t\tRender(fmt.Sprintf(\" %s (%s)\", models.SupportedModels[msg.Model].Name, \"permission denied\")),\n\t\t\t)\n\t\t}\n\t}\n\tif content != \"\" || (finished && finishData.Reason == message.FinishReasonEndTurn) {\n\t\tif content == \"\" {\n\t\t\tcontent = \"*Finished without output*\"\n\t\t}\n\t\tif isSummary {\n\t\t\tinfo = append(info, baseStyle.Width(width-1).Foreground(t.TextMuted()).Render(\" (summary)\"))\n\t\t}\n\n\t\tcontent = renderMessage(content, false, true, width, info...)\n\t\tmessages = append(messages, uiMessage{\n\t\t\tID: msg.ID,\n\t\t\tmessageType: assistantMessageType,\n\t\t\tposition: position,\n\t\t\theight: lipgloss.Height(content),\n\t\t\tcontent: content,\n\t\t})\n\t\tposition += messages[0].height\n\t\tposition++ // for the space\n\t} else if thinking && thinkingContent != \"\" {\n\t\t// Render the thinking content\n\t\tcontent = renderMessage(thinkingContent, false, msg.ID == focusedUIMessageId, width)\n\t}\n\n\tfor i, toolCall := range msg.ToolCalls() {\n\t\ttoolCallContent := renderToolMessage(\n\t\t\ttoolCall,\n\t\t\tallMessages,\n\t\t\tmessagesService,\n\t\t\tfocusedUIMessageId,\n\t\t\tfalse,\n\t\t\twidth,\n\t\t\ti+1,\n\t\t)\n\t\tmessages = append(messages, toolCallContent)\n\t\tposition += toolCallContent.height\n\t\tposition++ // for the space\n\t}\n\treturn messages\n}\n\nfunc findToolResponse(toolCallID string, futureMessages []message.Message) *message.ToolResult {\n\tfor _, msg := range futureMessages {\n\t\tfor _, result := range msg.ToolResults() {\n\t\t\tif result.ToolCallID == toolCallID {\n\t\t\t\treturn &result\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc toolName(name string) string {\n\tswitch name {\n\tcase agent.AgentToolName:\n\t\treturn \"Task\"\n\tcase tools.BashToolName:\n\t\treturn \"Bash\"\n\tcase tools.EditToolName:\n\t\treturn \"Edit\"\n\tcase tools.FetchToolName:\n\t\treturn \"Fetch\"\n\tcase tools.GlobToolName:\n\t\treturn \"Glob\"\n\tcase tools.GrepToolName:\n\t\treturn \"Grep\"\n\tcase tools.LSToolName:\n\t\treturn \"List\"\n\tcase tools.SourcegraphToolName:\n\t\treturn \"Sourcegraph\"\n\tcase tools.ViewToolName:\n\t\treturn \"View\"\n\tcase tools.WriteToolName:\n\t\treturn \"Write\"\n\tcase tools.PatchToolName:\n\t\treturn \"Patch\"\n\t}\n\treturn name\n}\n\nfunc getToolAction(name string) string {\n\tswitch name {\n\tcase agent.AgentToolName:\n\t\treturn \"Preparing prompt...\"\n\tcase tools.BashToolName:\n\t\treturn \"Building command...\"\n\tcase tools.EditToolName:\n\t\treturn \"Preparing edit...\"\n\tcase tools.FetchToolName:\n\t\treturn \"Writing fetch...\"\n\tcase tools.GlobToolName:\n\t\treturn \"Finding files...\"\n\tcase tools.GrepToolName:\n\t\treturn \"Searching content...\"\n\tcase tools.LSToolName:\n\t\treturn \"Listing directory...\"\n\tcase tools.SourcegraphToolName:\n\t\treturn \"Searching code...\"\n\tcase tools.ViewToolName:\n\t\treturn \"Reading file...\"\n\tcase tools.WriteToolName:\n\t\treturn \"Preparing write...\"\n\tcase tools.PatchToolName:\n\t\treturn \"Preparing patch...\"\n\t}\n\treturn \"Working...\"\n}\n\n// renders params, params[0] (params[1]=params[2] ....)\nfunc renderParams(paramsWidth int, params ...string) string {\n\tif len(params) == 0 {\n\t\treturn \"\"\n\t}\n\tmainParam := params[0]\n\tif len(mainParam) > paramsWidth {\n\t\tmainParam = mainParam[:paramsWidth-3] + \"...\"\n\t}\n\n\tif len(params) == 1 {\n\t\treturn mainParam\n\t}\n\totherParams := params[1:]\n\t// create pairs of key/value\n\t// if odd number of params, the last one is a key without value\n\tif len(otherParams)%2 != 0 {\n\t\totherParams = append(otherParams, \"\")\n\t}\n\tparts := make([]string, 0, len(otherParams)/2)\n\tfor i := 0; i < len(otherParams); i += 2 {\n\t\tkey := otherParams[i]\n\t\tvalue := otherParams[i+1]\n\t\tif value == \"\" {\n\t\t\tcontinue\n\t\t}\n\t\tparts = append(parts, fmt.Sprintf(\"%s=%s\", key, value))\n\t}\n\n\tpartsRendered := strings.Join(parts, \", \")\n\tremainingWidth := paramsWidth - lipgloss.Width(partsRendered) - 5 // for the space\n\tif remainingWidth < 30 {\n\t\t// No space for the params, just show the main\n\t\treturn mainParam\n\t}\n\n\tif len(parts) > 0 {\n\t\tmainParam = fmt.Sprintf(\"%s (%s)\", mainParam, strings.Join(parts, \", \"))\n\t}\n\n\treturn ansi.Truncate(mainParam, paramsWidth, \"...\")\n}\n\nfunc removeWorkingDirPrefix(path string) string {\n\twd := config.WorkingDirectory()\n\tif strings.HasPrefix(path, wd) {\n\t\tpath = strings.TrimPrefix(path, wd)\n\t}\n\tif strings.HasPrefix(path, \"/\") {\n\t\tpath = strings.TrimPrefix(path, \"/\")\n\t}\n\tif strings.HasPrefix(path, \"./\") {\n\t\tpath = strings.TrimPrefix(path, \"./\")\n\t}\n\tif strings.HasPrefix(path, \"../\") {\n\t\tpath = strings.TrimPrefix(path, \"../\")\n\t}\n\treturn path\n}\n\nfunc renderToolParams(paramWidth int, toolCall message.ToolCall) string {\n\tparams := \"\"\n\tswitch toolCall.Name {\n\tcase agent.AgentToolName:\n\t\tvar params agent.AgentParams\n\t\tjson.Unmarshal([]byte(toolCall.Input), ¶ms)\n\t\tprompt := strings.ReplaceAll(params.Prompt, \"\\n\", \" \")\n\t\treturn renderParams(paramWidth, prompt)\n\tcase tools.BashToolName:\n\t\tvar params tools.BashParams\n\t\tjson.Unmarshal([]byte(toolCall.Input), ¶ms)\n\t\tcommand := strings.ReplaceAll(params.Command, \"\\n\", \" \")\n\t\treturn renderParams(paramWidth, command)\n\tcase tools.EditToolName:\n\t\tvar params tools.EditParams\n\t\tjson.Unmarshal([]byte(toolCall.Input), ¶ms)\n\t\tfilePath := removeWorkingDirPrefix(params.FilePath)\n\t\treturn renderParams(paramWidth, filePath)\n\tcase tools.FetchToolName:\n\t\tvar params tools.FetchParams\n\t\tjson.Unmarshal([]byte(toolCall.Input), ¶ms)\n\t\turl := params.URL\n\t\ttoolParams := []string{\n\t\t\turl,\n\t\t}\n\t\tif params.Format != \"\" {\n\t\t\ttoolParams = append(toolParams, \"format\", params.Format)\n\t\t}\n\t\tif params.Timeout != 0 {\n\t\t\ttoolParams = append(toolParams, \"timeout\", (time.Duration(params.Timeout) * time.Second).String())\n\t\t}\n\t\treturn renderParams(paramWidth, toolParams...)\n\tcase tools.GlobToolName:\n\t\tvar params tools.GlobParams\n\t\tjson.Unmarshal([]byte(toolCall.Input), ¶ms)\n\t\tpattern := params.Pattern\n\t\ttoolParams := []string{\n\t\t\tpattern,\n\t\t}\n\t\tif params.Path != \"\" {\n\t\t\ttoolParams = append(toolParams, \"path\", params.Path)\n\t\t}\n\t\treturn renderParams(paramWidth, toolParams...)\n\tcase tools.GrepToolName:\n\t\tvar params tools.GrepParams\n\t\tjson.Unmarshal([]byte(toolCall.Input), ¶ms)\n\t\tpattern := params.Pattern\n\t\ttoolParams := []string{\n\t\t\tpattern,\n\t\t}\n\t\tif params.Path != \"\" {\n\t\t\ttoolParams = append(toolParams, \"path\", params.Path)\n\t\t}\n\t\tif params.Include != \"\" {\n\t\t\ttoolParams = append(toolParams, \"include\", params.Include)\n\t\t}\n\t\tif params.LiteralText {\n\t\t\ttoolParams = append(toolParams, \"literal\", \"true\")\n\t\t}\n\t\treturn renderParams(paramWidth, toolParams...)\n\tcase tools.LSToolName:\n\t\tvar params tools.LSParams\n\t\tjson.Unmarshal([]byte(toolCall.Input), ¶ms)\n\t\tpath := params.Path\n\t\tif path == \"\" {\n\t\t\tpath = \".\"\n\t\t}\n\t\treturn renderParams(paramWidth, path)\n\tcase tools.SourcegraphToolName:\n\t\tvar params tools.SourcegraphParams\n\t\tjson.Unmarshal([]byte(toolCall.Input), ¶ms)\n\t\treturn renderParams(paramWidth, params.Query)\n\tcase tools.ViewToolName:\n\t\tvar params tools.ViewParams\n\t\tjson.Unmarshal([]byte(toolCall.Input), ¶ms)\n\t\tfilePath := removeWorkingDirPrefix(params.FilePath)\n\t\ttoolParams := []string{\n\t\t\tfilePath,\n\t\t}\n\t\tif params.Limit != 0 {\n\t\t\ttoolParams = append(toolParams, \"limit\", fmt.Sprintf(\"%d\", params.Limit))\n\t\t}\n\t\tif params.Offset != 0 {\n\t\t\ttoolParams = append(toolParams, \"offset\", fmt.Sprintf(\"%d\", params.Offset))\n\t\t}\n\t\treturn renderParams(paramWidth, toolParams...)\n\tcase tools.WriteToolName:\n\t\tvar params tools.WriteParams\n\t\tjson.Unmarshal([]byte(toolCall.Input), ¶ms)\n\t\tfilePath := removeWorkingDirPrefix(params.FilePath)\n\t\treturn renderParams(paramWidth, filePath)\n\tdefault:\n\t\tinput := strings.ReplaceAll(toolCall.Input, \"\\n\", \" \")\n\t\tparams = renderParams(paramWidth, input)\n\t}\n\treturn params\n}\n\nfunc truncateHeight(content string, height int) string {\n\tlines := strings.Split(content, \"\\n\")\n\tif len(lines) > height {\n\t\treturn strings.Join(lines[:height], \"\\n\")\n\t}\n\treturn content\n}\n\nfunc renderToolResponse(toolCall message.ToolCall, response message.ToolResult, width int) string {\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\n\tif response.IsError {\n\t\terrContent := fmt.Sprintf(\"Error: %s\", strings.ReplaceAll(response.Content, \"\\n\", \" \"))\n\t\terrContent = ansi.Truncate(errContent, width-1, \"...\")\n\t\treturn baseStyle.\n\t\t\tWidth(width).\n\t\t\tForeground(t.Error()).\n\t\t\tRender(errContent)\n\t}\n\n\tresultContent := truncateHeight(response.Content, maxResultHeight)\n\tswitch toolCall.Name {\n\tcase agent.AgentToolName:\n\t\treturn styles.ForceReplaceBackgroundWithLipgloss(\n\t\t\ttoMarkdown(resultContent, false, width),\n\t\t\tt.Background(),\n\t\t)\n\tcase tools.BashToolName:\n\t\tresultContent = fmt.Sprintf(\"```bash\\n%s\\n```\", resultContent)\n\t\treturn styles.ForceReplaceBackgroundWithLipgloss(\n\t\t\ttoMarkdown(resultContent, true, width),\n\t\t\tt.Background(),\n\t\t)\n\tcase tools.EditToolName:\n\t\tmetadata := tools.EditResponseMetadata{}\n\t\tjson.Unmarshal([]byte(response.Metadata), &metadata)\n\t\ttruncDiff := truncateHeight(metadata.Diff, maxResultHeight)\n\t\tformattedDiff, _ := diff.FormatDiff(truncDiff, diff.WithTotalWidth(width))\n\t\treturn formattedDiff\n\tcase tools.FetchToolName:\n\t\tvar params tools.FetchParams\n\t\tjson.Unmarshal([]byte(toolCall.Input), ¶ms)\n\t\tmdFormat := \"markdown\"\n\t\tswitch params.Format {\n\t\tcase \"text\":\n\t\t\tmdFormat = \"text\"\n\t\tcase \"html\":\n\t\t\tmdFormat = \"html\"\n\t\t}\n\t\tresultContent = fmt.Sprintf(\"```%s\\n%s\\n```\", mdFormat, resultContent)\n\t\treturn styles.ForceReplaceBackgroundWithLipgloss(\n\t\t\ttoMarkdown(resultContent, true, width),\n\t\t\tt.Background(),\n\t\t)\n\tcase tools.GlobToolName:\n\t\treturn baseStyle.Width(width).Foreground(t.TextMuted()).Render(resultContent)\n\tcase tools.GrepToolName:\n\t\treturn baseStyle.Width(width).Foreground(t.TextMuted()).Render(resultContent)\n\tcase tools.LSToolName:\n\t\treturn baseStyle.Width(width).Foreground(t.TextMuted()).Render(resultContent)\n\tcase tools.SourcegraphToolName:\n\t\treturn baseStyle.Width(width).Foreground(t.TextMuted()).Render(resultContent)\n\tcase tools.ViewToolName:\n\t\tmetadata := tools.ViewResponseMetadata{}\n\t\tjson.Unmarshal([]byte(response.Metadata), &metadata)\n\t\text := filepath.Ext(metadata.FilePath)\n\t\tif ext == \"\" {\n\t\t\text = \"\"\n\t\t} else {\n\t\t\text = strings.ToLower(ext[1:])\n\t\t}\n\t\tresultContent = fmt.Sprintf(\"```%s\\n%s\\n```\", ext, truncateHeight(metadata.Content, maxResultHeight))\n\t\treturn styles.ForceReplaceBackgroundWithLipgloss(\n\t\t\ttoMarkdown(resultContent, true, width),\n\t\t\tt.Background(),\n\t\t)\n\tcase tools.WriteToolName:\n\t\tparams := tools.WriteParams{}\n\t\tjson.Unmarshal([]byte(toolCall.Input), ¶ms)\n\t\tmetadata := tools.WriteResponseMetadata{}\n\t\tjson.Unmarshal([]byte(response.Metadata), &metadata)\n\t\text := filepath.Ext(params.FilePath)\n\t\tif ext == \"\" {\n\t\t\text = \"\"\n\t\t} else {\n\t\t\text = strings.ToLower(ext[1:])\n\t\t}\n\t\tresultContent = fmt.Sprintf(\"```%s\\n%s\\n```\", ext, truncateHeight(params.Content, maxResultHeight))\n\t\treturn styles.ForceReplaceBackgroundWithLipgloss(\n\t\t\ttoMarkdown(resultContent, true, width),\n\t\t\tt.Background(),\n\t\t)\n\tdefault:\n\t\tresultContent = fmt.Sprintf(\"```text\\n%s\\n```\", resultContent)\n\t\treturn styles.ForceReplaceBackgroundWithLipgloss(\n\t\t\ttoMarkdown(resultContent, true, width),\n\t\t\tt.Background(),\n\t\t)\n\t}\n}\n\nfunc renderToolMessage(\n\ttoolCall message.ToolCall,\n\tallMessages []message.Message,\n\tmessagesService message.Service,\n\tfocusedUIMessageId string,\n\tnested bool,\n\twidth int,\n\tposition int,\n) uiMessage {\n\tif nested {\n\t\twidth = width - 3\n\t}\n\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\n\tstyle := baseStyle.\n\t\tWidth(width - 1).\n\t\tBorderLeft(true).\n\t\tBorderStyle(lipgloss.ThickBorder()).\n\t\tPaddingLeft(1).\n\t\tBorderForeground(t.TextMuted())\n\n\tresponse := findToolResponse(toolCall.ID, allMessages)\n\ttoolNameText := baseStyle.Foreground(t.TextMuted()).\n\t\tRender(fmt.Sprintf(\"%s: \", toolName(toolCall.Name)))\n\n\tif !toolCall.Finished {\n\t\t// Get a brief description of what the tool is doing\n\t\ttoolAction := getToolAction(toolCall.Name)\n\n\t\tprogressText := baseStyle.\n\t\t\tWidth(width - 2 - lipgloss.Width(toolNameText)).\n\t\t\tForeground(t.TextMuted()).\n\t\t\tRender(fmt.Sprintf(\"%s\", toolAction))\n\n\t\tcontent := style.Render(lipgloss.JoinHorizontal(lipgloss.Left, toolNameText, progressText))\n\t\ttoolMsg := uiMessage{\n\t\t\tmessageType: toolMessageType,\n\t\t\tposition: position,\n\t\t\theight: lipgloss.Height(content),\n\t\t\tcontent: content,\n\t\t}\n\t\treturn toolMsg\n\t}\n\n\tparams := renderToolParams(width-2-lipgloss.Width(toolNameText), toolCall)\n\tresponseContent := \"\"\n\tif response != nil {\n\t\tresponseContent = renderToolResponse(toolCall, *response, width-2)\n\t\tresponseContent = strings.TrimSuffix(responseContent, \"\\n\")\n\t} else {\n\t\tresponseContent = baseStyle.\n\t\t\tItalic(true).\n\t\t\tWidth(width - 2).\n\t\t\tForeground(t.TextMuted()).\n\t\t\tRender(\"Waiting for response...\")\n\t}\n\n\tparts := []string{}\n\tif !nested {\n\t\tformattedParams := baseStyle.\n\t\t\tWidth(width - 2 - lipgloss.Width(toolNameText)).\n\t\t\tForeground(t.TextMuted()).\n\t\t\tRender(params)\n\n\t\tparts = append(parts, lipgloss.JoinHorizontal(lipgloss.Left, toolNameText, formattedParams))\n\t} else {\n\t\tprefix := baseStyle.\n\t\t\tForeground(t.TextMuted()).\n\t\t\tRender(\" └ \")\n\t\tformattedParams := baseStyle.\n\t\t\tWidth(width - 2 - lipgloss.Width(toolNameText)).\n\t\t\tForeground(t.TextMuted()).\n\t\t\tRender(params)\n\t\tparts = append(parts, lipgloss.JoinHorizontal(lipgloss.Left, prefix, toolNameText, formattedParams))\n\t}\n\n\tif toolCall.Name == agent.AgentToolName {\n\t\ttaskMessages, _ := messagesService.List(context.Background(), toolCall.ID)\n\t\ttoolCalls := []message.ToolCall{}\n\t\tfor _, v := range taskMessages {\n\t\t\ttoolCalls = append(toolCalls, v.ToolCalls()...)\n\t\t}\n\t\tfor _, call := range toolCalls {\n\t\t\trendered := renderToolMessage(call, []message.Message{}, messagesService, focusedUIMessageId, true, width, 0)\n\t\t\tparts = append(parts, rendered.content)\n\t\t}\n\t}\n\tif responseContent != \"\" && !nested {\n\t\tparts = append(parts, responseContent)\n\t}\n\n\tcontent := style.Render(\n\t\tlipgloss.JoinVertical(\n\t\t\tlipgloss.Left,\n\t\t\tparts...,\n\t\t),\n\t)\n\tif nested {\n\t\tcontent = lipgloss.JoinVertical(\n\t\t\tlipgloss.Left,\n\t\t\tparts...,\n\t\t)\n\t}\n\ttoolMsg := uiMessage{\n\t\tmessageType: toolMessageType,\n\t\tposition: position,\n\t\theight: lipgloss.Height(content),\n\t\tcontent: content,\n\t}\n\treturn toolMsg\n}\n\n// Helper function to format the time difference between two Unix timestamps\nfunc formatTimestampDiff(start, end int64) string {\n\tdiffSeconds := float64(end-start) / 1000.0 // Convert to seconds\n\tif diffSeconds < 1 {\n\t\treturn fmt.Sprintf(\"%dms\", int(diffSeconds*1000))\n\t}\n\tif diffSeconds < 60 {\n\t\treturn fmt.Sprintf(\"%.1fs\", diffSeconds)\n\t}\n\treturn fmt.Sprintf(\"%.1fm\", diffSeconds/60)\n}\n"], ["/opencode/internal/llm/provider/gemini.go", "package provider\n\nimport (\n\t\"context\"\n\t\"encoding/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/google/uuid\"\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/llm/tools\"\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n\t\"github.com/opencode-ai/opencode/internal/message\"\n\t\"google.golang.org/genai\"\n)\n\ntype geminiOptions struct {\n\tdisableCache bool\n}\n\ntype GeminiOption func(*geminiOptions)\n\ntype geminiClient struct {\n\tproviderOptions providerClientOptions\n\toptions geminiOptions\n\tclient *genai.Client\n}\n\ntype GeminiClient ProviderClient\n\nfunc newGeminiClient(opts providerClientOptions) GeminiClient {\n\tgeminiOpts := geminiOptions{}\n\tfor _, o := range opts.geminiOptions {\n\t\to(&geminiOpts)\n\t}\n\n\tclient, err := genai.NewClient(context.Background(), &genai.ClientConfig{APIKey: opts.apiKey, Backend: genai.BackendGeminiAPI})\n\tif err != nil {\n\t\tlogging.Error(\"Failed to create Gemini client\", \"error\", err)\n\t\treturn nil\n\t}\n\n\treturn &geminiClient{\n\t\tproviderOptions: opts,\n\t\toptions: geminiOpts,\n\t\tclient: client,\n\t}\n}\n\nfunc (g *geminiClient) convertMessages(messages []message.Message) []*genai.Content {\n\tvar history []*genai.Content\n\tfor _, msg := range messages {\n\t\tswitch msg.Role {\n\t\tcase message.User:\n\t\t\tvar parts []*genai.Part\n\t\t\tparts = append(parts, &genai.Part{Text: msg.Content().String()})\n\t\t\tfor _, binaryContent := range msg.BinaryContent() {\n\t\t\t\timageFormat := strings.Split(binaryContent.MIMEType, \"/\")\n\t\t\t\tparts = append(parts, &genai.Part{InlineData: &genai.Blob{\n\t\t\t\t\tMIMEType: imageFormat[1],\n\t\t\t\t\tData: binaryContent.Data,\n\t\t\t\t}})\n\t\t\t}\n\t\t\thistory = append(history, &genai.Content{\n\t\t\t\tParts: parts,\n\t\t\t\tRole: \"user\",\n\t\t\t})\n\t\tcase message.Assistant:\n\t\t\tvar assistantParts []*genai.Part\n\n\t\t\tif msg.Content().String() != \"\" {\n\t\t\t\tassistantParts = append(assistantParts, &genai.Part{Text: msg.Content().String()})\n\t\t\t}\n\n\t\t\tif len(msg.ToolCalls()) > 0 {\n\t\t\t\tfor _, call := range msg.ToolCalls() {\n\t\t\t\t\targs, _ := parseJsonToMap(call.Input)\n\t\t\t\t\tassistantParts = append(assistantParts, &genai.Part{\n\t\t\t\t\t\tFunctionCall: &genai.FunctionCall{\n\t\t\t\t\t\t\tName: call.Name,\n\t\t\t\t\t\t\tArgs: args,\n\t\t\t\t\t\t},\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif len(assistantParts) > 0 {\n\t\t\t\thistory = append(history, &genai.Content{\n\t\t\t\t\tRole: \"model\",\n\t\t\t\t\tParts: assistantParts,\n\t\t\t\t})\n\t\t\t}\n\n\t\tcase message.Tool:\n\t\t\tfor _, result := range msg.ToolResults() {\n\t\t\t\tresponse := map[string]interface{}{\"result\": result.Content}\n\t\t\t\tparsed, err := parseJsonToMap(result.Content)\n\t\t\t\tif err == nil {\n\t\t\t\t\tresponse = parsed\n\t\t\t\t}\n\n\t\t\t\tvar toolCall message.ToolCall\n\t\t\t\tfor _, m := range messages {\n\t\t\t\t\tif m.Role == message.Assistant {\n\t\t\t\t\t\tfor _, call := range m.ToolCalls() {\n\t\t\t\t\t\t\tif call.ID == result.ToolCallID {\n\t\t\t\t\t\t\t\ttoolCall = call\n\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\thistory = append(history, &genai.Content{\n\t\t\t\t\tParts: []*genai.Part{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tFunctionResponse: &genai.FunctionResponse{\n\t\t\t\t\t\t\t\tName: toolCall.Name,\n\t\t\t\t\t\t\t\tResponse: response,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\tRole: \"function\",\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\t}\n\n\treturn history\n}\n\nfunc (g *geminiClient) convertTools(tools []tools.BaseTool) []*genai.Tool {\n\tgeminiTool := &genai.Tool{}\n\tgeminiTool.FunctionDeclarations = make([]*genai.FunctionDeclaration, 0, len(tools))\n\n\tfor _, tool := range tools {\n\t\tinfo := tool.Info()\n\t\tdeclaration := &genai.FunctionDeclaration{\n\t\t\tName: info.Name,\n\t\t\tDescription: info.Description,\n\t\t\tParameters: &genai.Schema{\n\t\t\t\tType: genai.TypeObject,\n\t\t\t\tProperties: convertSchemaProperties(info.Parameters),\n\t\t\t\tRequired: info.Required,\n\t\t\t},\n\t\t}\n\n\t\tgeminiTool.FunctionDeclarations = append(geminiTool.FunctionDeclarations, declaration)\n\t}\n\n\treturn []*genai.Tool{geminiTool}\n}\n\nfunc (g *geminiClient) finishReason(reason genai.FinishReason) message.FinishReason {\n\tswitch {\n\tcase reason == genai.FinishReasonStop:\n\t\treturn message.FinishReasonEndTurn\n\tcase reason == genai.FinishReasonMaxTokens:\n\t\treturn message.FinishReasonMaxTokens\n\tdefault:\n\t\treturn message.FinishReasonUnknown\n\t}\n}\n\nfunc (g *geminiClient) send(ctx context.Context, messages []message.Message, tools []tools.BaseTool) (*ProviderResponse, error) {\n\t// Convert messages\n\tgeminiMessages := g.convertMessages(messages)\n\n\tcfg := config.Get()\n\tif cfg.Debug {\n\t\tjsonData, _ := json.Marshal(geminiMessages)\n\t\tlogging.Debug(\"Prepared messages\", \"messages\", string(jsonData))\n\t}\n\n\thistory := geminiMessages[:len(geminiMessages)-1] // All but last message\n\tlastMsg := geminiMessages[len(geminiMessages)-1]\n\tconfig := &genai.GenerateContentConfig{\n\t\tMaxOutputTokens: int32(g.providerOptions.maxTokens),\n\t\tSystemInstruction: &genai.Content{\n\t\t\tParts: []*genai.Part{{Text: g.providerOptions.systemMessage}},\n\t\t},\n\t}\n\tif len(tools) > 0 {\n\t\tconfig.Tools = g.convertTools(tools)\n\t}\n\tchat, _ := g.client.Chats.Create(ctx, g.providerOptions.model.APIModel, config, history)\n\n\tattempts := 0\n\tfor {\n\t\tattempts++\n\t\tvar toolCalls []message.ToolCall\n\n\t\tvar lastMsgParts []genai.Part\n\t\tfor _, part := range lastMsg.Parts {\n\t\t\tlastMsgParts = append(lastMsgParts, *part)\n\t\t}\n\t\tresp, err := chat.SendMessage(ctx, lastMsgParts...)\n\t\t// If there is an error we are going to see if we can retry the call\n\t\tif err != nil {\n\t\t\tretry, after, retryErr := g.shouldRetry(attempts, err)\n\t\t\tif retryErr != nil {\n\t\t\t\treturn nil, retryErr\n\t\t\t}\n\t\t\tif retry {\n\t\t\t\tlogging.WarnPersist(fmt.Sprintf(\"Retrying due to rate limit... attempt %d of %d\", attempts, maxRetries), logging.PersistTimeArg, time.Millisecond*time.Duration(after+100))\n\t\t\t\tselect {\n\t\t\t\tcase <-ctx.Done():\n\t\t\t\t\treturn nil, ctx.Err()\n\t\t\t\tcase <-time.After(time.Duration(after) * time.Millisecond):\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn nil, retryErr\n\t\t}\n\n\t\tcontent := \"\"\n\n\t\tif len(resp.Candidates) > 0 && resp.Candidates[0].Content != nil {\n\t\t\tfor _, part := range resp.Candidates[0].Content.Parts {\n\t\t\t\tswitch {\n\t\t\t\tcase part.Text != \"\":\n\t\t\t\t\tcontent = string(part.Text)\n\t\t\t\tcase part.FunctionCall != nil:\n\t\t\t\t\tid := \"call_\" + uuid.New().String()\n\t\t\t\t\targs, _ := json.Marshal(part.FunctionCall.Args)\n\t\t\t\t\ttoolCalls = append(toolCalls, message.ToolCall{\n\t\t\t\t\t\tID: id,\n\t\t\t\t\t\tName: part.FunctionCall.Name,\n\t\t\t\t\t\tInput: string(args),\n\t\t\t\t\t\tType: \"function\",\n\t\t\t\t\t\tFinished: true,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tfinishReason := message.FinishReasonEndTurn\n\t\tif len(resp.Candidates) > 0 {\n\t\t\tfinishReason = g.finishReason(resp.Candidates[0].FinishReason)\n\t\t}\n\t\tif len(toolCalls) > 0 {\n\t\t\tfinishReason = message.FinishReasonToolUse\n\t\t}\n\n\t\treturn &ProviderResponse{\n\t\t\tContent: content,\n\t\t\tToolCalls: toolCalls,\n\t\t\tUsage: g.usage(resp),\n\t\t\tFinishReason: finishReason,\n\t\t}, nil\n\t}\n}\n\nfunc (g *geminiClient) stream(ctx context.Context, messages []message.Message, tools []tools.BaseTool) <-chan ProviderEvent {\n\t// Convert messages\n\tgeminiMessages := g.convertMessages(messages)\n\n\tcfg := config.Get()\n\tif cfg.Debug {\n\t\tjsonData, _ := json.Marshal(geminiMessages)\n\t\tlogging.Debug(\"Prepared messages\", \"messages\", string(jsonData))\n\t}\n\n\thistory := geminiMessages[:len(geminiMessages)-1] // All but last message\n\tlastMsg := geminiMessages[len(geminiMessages)-1]\n\tconfig := &genai.GenerateContentConfig{\n\t\tMaxOutputTokens: int32(g.providerOptions.maxTokens),\n\t\tSystemInstruction: &genai.Content{\n\t\t\tParts: []*genai.Part{{Text: g.providerOptions.systemMessage}},\n\t\t},\n\t}\n\tif len(tools) > 0 {\n\t\tconfig.Tools = g.convertTools(tools)\n\t}\n\tchat, _ := g.client.Chats.Create(ctx, g.providerOptions.model.APIModel, config, history)\n\n\tattempts := 0\n\teventChan := make(chan ProviderEvent)\n\n\tgo func() {\n\t\tdefer close(eventChan)\n\n\t\tfor {\n\t\t\tattempts++\n\n\t\t\tcurrentContent := \"\"\n\t\t\ttoolCalls := []message.ToolCall{}\n\t\t\tvar finalResp *genai.GenerateContentResponse\n\n\t\t\teventChan <- ProviderEvent{Type: EventContentStart}\n\n\t\t\tvar lastMsgParts []genai.Part\n\n\t\t\tfor _, part := range lastMsg.Parts {\n\t\t\t\tlastMsgParts = append(lastMsgParts, *part)\n\t\t\t}\n\t\t\tfor resp, err := range chat.SendMessageStream(ctx, lastMsgParts...) {\n\t\t\t\tif err != nil {\n\t\t\t\t\tretry, after, retryErr := g.shouldRetry(attempts, err)\n\t\t\t\t\tif retryErr != nil {\n\t\t\t\t\t\teventChan <- ProviderEvent{Type: EventError, Error: retryErr}\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\tif retry {\n\t\t\t\t\t\tlogging.WarnPersist(fmt.Sprintf(\"Retrying due to rate limit... attempt %d of %d\", attempts, maxRetries), logging.PersistTimeArg, time.Millisecond*time.Duration(after+100))\n\t\t\t\t\t\tselect {\n\t\t\t\t\t\tcase <-ctx.Done():\n\t\t\t\t\t\t\tif ctx.Err() != nil {\n\t\t\t\t\t\t\t\teventChan <- ProviderEvent{Type: EventError, Error: ctx.Err()}\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\treturn\n\t\t\t\t\t\tcase <-time.After(time.Duration(after) * time.Millisecond):\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\teventChan <- ProviderEvent{Type: EventError, Error: err}\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tfinalResp = resp\n\n\t\t\t\tif len(resp.Candidates) > 0 && resp.Candidates[0].Content != nil {\n\t\t\t\t\tfor _, part := range resp.Candidates[0].Content.Parts {\n\t\t\t\t\t\tswitch {\n\t\t\t\t\t\tcase part.Text != \"\":\n\t\t\t\t\t\t\tdelta := string(part.Text)\n\t\t\t\t\t\t\tif delta != \"\" {\n\t\t\t\t\t\t\t\teventChan <- ProviderEvent{\n\t\t\t\t\t\t\t\t\tType: EventContentDelta,\n\t\t\t\t\t\t\t\t\tContent: delta,\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tcurrentContent += delta\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\tcase part.FunctionCall != nil:\n\t\t\t\t\t\t\tid := \"call_\" + uuid.New().String()\n\t\t\t\t\t\t\targs, _ := json.Marshal(part.FunctionCall.Args)\n\t\t\t\t\t\t\tnewCall := message.ToolCall{\n\t\t\t\t\t\t\t\tID: id,\n\t\t\t\t\t\t\t\tName: part.FunctionCall.Name,\n\t\t\t\t\t\t\t\tInput: string(args),\n\t\t\t\t\t\t\t\tType: \"function\",\n\t\t\t\t\t\t\t\tFinished: true,\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tisNew := true\n\t\t\t\t\t\t\tfor _, existing := range toolCalls {\n\t\t\t\t\t\t\t\tif existing.Name == newCall.Name && existing.Input == newCall.Input {\n\t\t\t\t\t\t\t\t\tisNew = false\n\t\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif isNew {\n\t\t\t\t\t\t\t\ttoolCalls = append(toolCalls, newCall)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\teventChan <- ProviderEvent{Type: EventContentStop}\n\n\t\t\tif finalResp != nil {\n\n\t\t\t\tfinishReason := message.FinishReasonEndTurn\n\t\t\t\tif len(finalResp.Candidates) > 0 {\n\t\t\t\t\tfinishReason = g.finishReason(finalResp.Candidates[0].FinishReason)\n\t\t\t\t}\n\t\t\t\tif len(toolCalls) > 0 {\n\t\t\t\t\tfinishReason = message.FinishReasonToolUse\n\t\t\t\t}\n\t\t\t\teventChan <- ProviderEvent{\n\t\t\t\t\tType: EventComplete,\n\t\t\t\t\tResponse: &ProviderResponse{\n\t\t\t\t\t\tContent: currentContent,\n\t\t\t\t\t\tToolCalls: toolCalls,\n\t\t\t\t\t\tUsage: g.usage(finalResp),\n\t\t\t\t\t\tFinishReason: finishReason,\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\n\t\t}\n\t}()\n\n\treturn eventChan\n}\n\nfunc (g *geminiClient) shouldRetry(attempts int, err error) (bool, int64, error) {\n\t// Check if error is a rate limit error\n\tif attempts > maxRetries {\n\t\treturn false, 0, fmt.Errorf(\"maximum retry attempts reached for rate limit: %d retries\", maxRetries)\n\t}\n\n\t// Gemini doesn't have a standard error type we can check against\n\t// So we'll check the error message for rate limit indicators\n\tif errors.Is(err, io.EOF) {\n\t\treturn false, 0, err\n\t}\n\n\terrMsg := err.Error()\n\tisRateLimit := false\n\n\t// Check for common rate limit error messages\n\tif contains(errMsg, \"rate limit\", \"quota exceeded\", \"too many requests\") {\n\t\tisRateLimit = true\n\t}\n\n\tif !isRateLimit {\n\t\treturn false, 0, err\n\t}\n\n\t// Calculate backoff with jitter\n\tbackoffMs := 2000 * (1 << (attempts - 1))\n\tjitterMs := int(float64(backoffMs) * 0.2)\n\tretryMs := backoffMs + jitterMs\n\n\treturn true, int64(retryMs), nil\n}\n\nfunc (g *geminiClient) toolCalls(resp *genai.GenerateContentResponse) []message.ToolCall {\n\tvar toolCalls []message.ToolCall\n\n\tif len(resp.Candidates) > 0 && resp.Candidates[0].Content != nil {\n\t\tfor _, part := range resp.Candidates[0].Content.Parts {\n\t\t\tif part.FunctionCall != nil {\n\t\t\t\tid := \"call_\" + uuid.New().String()\n\t\t\t\targs, _ := json.Marshal(part.FunctionCall.Args)\n\t\t\t\ttoolCalls = append(toolCalls, message.ToolCall{\n\t\t\t\t\tID: id,\n\t\t\t\t\tName: part.FunctionCall.Name,\n\t\t\t\t\tInput: string(args),\n\t\t\t\t\tType: \"function\",\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\t}\n\n\treturn toolCalls\n}\n\nfunc (g *geminiClient) usage(resp *genai.GenerateContentResponse) TokenUsage {\n\tif resp == nil || resp.UsageMetadata == nil {\n\t\treturn TokenUsage{}\n\t}\n\n\treturn TokenUsage{\n\t\tInputTokens: int64(resp.UsageMetadata.PromptTokenCount),\n\t\tOutputTokens: int64(resp.UsageMetadata.CandidatesTokenCount),\n\t\tCacheCreationTokens: 0, // Not directly provided by Gemini\n\t\tCacheReadTokens: int64(resp.UsageMetadata.CachedContentTokenCount),\n\t}\n}\n\nfunc WithGeminiDisableCache() GeminiOption {\n\treturn func(options *geminiOptions) {\n\t\toptions.disableCache = true\n\t}\n}\n\n// Helper functions\nfunc parseJsonToMap(jsonStr string) (map[string]interface{}, error) {\n\tvar result map[string]interface{}\n\terr := json.Unmarshal([]byte(jsonStr), &result)\n\treturn result, err\n}\n\nfunc convertSchemaProperties(parameters map[string]interface{}) map[string]*genai.Schema {\n\tproperties := make(map[string]*genai.Schema)\n\n\tfor name, param := range parameters {\n\t\tproperties[name] = convertToSchema(param)\n\t}\n\n\treturn properties\n}\n\nfunc convertToSchema(param interface{}) *genai.Schema {\n\tschema := &genai.Schema{Type: genai.TypeString}\n\n\tparamMap, ok := param.(map[string]interface{})\n\tif !ok {\n\t\treturn schema\n\t}\n\n\tif desc, ok := paramMap[\"description\"].(string); ok {\n\t\tschema.Description = desc\n\t}\n\n\ttypeVal, hasType := paramMap[\"type\"]\n\tif !hasType {\n\t\treturn schema\n\t}\n\n\ttypeStr, ok := typeVal.(string)\n\tif !ok {\n\t\treturn schema\n\t}\n\n\tschema.Type = mapJSONTypeToGenAI(typeStr)\n\n\tswitch typeStr {\n\tcase \"array\":\n\t\tschema.Items = processArrayItems(paramMap)\n\tcase \"object\":\n\t\tif props, ok := paramMap[\"properties\"].(map[string]interface{}); ok {\n\t\t\tschema.Properties = convertSchemaProperties(props)\n\t\t}\n\t}\n\n\treturn schema\n}\n\nfunc processArrayItems(paramMap map[string]interface{}) *genai.Schema {\n\titems, ok := paramMap[\"items\"].(map[string]interface{})\n\tif !ok {\n\t\treturn nil\n\t}\n\n\treturn convertToSchema(items)\n}\n\nfunc mapJSONTypeToGenAI(jsonType string) genai.Type {\n\tswitch jsonType {\n\tcase \"string\":\n\t\treturn genai.TypeString\n\tcase \"number\":\n\t\treturn genai.TypeNumber\n\tcase \"integer\":\n\t\treturn genai.TypeInteger\n\tcase \"boolean\":\n\t\treturn genai.TypeBoolean\n\tcase \"array\":\n\t\treturn genai.TypeArray\n\tcase \"object\":\n\t\treturn genai.TypeObject\n\tdefault:\n\t\treturn genai.TypeString // Default to string for unknown types\n\t}\n}\n\nfunc contains(s string, substrs ...string) bool {\n\tfor _, substr := range substrs {\n\t\tif strings.Contains(strings.ToLower(s), strings.ToLower(substr)) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n"], ["/opencode/internal/tui/components/logs/details.go", "package logs\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/charmbracelet/bubbles/key\"\n\t\"github.com/charmbracelet/bubbles/viewport\"\n\ttea \"github.com/charmbracelet/bubbletea\"\n\t\"github.com/charmbracelet/lipgloss\"\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n\t\"github.com/opencode-ai/opencode/internal/tui/layout\"\n\t\"github.com/opencode-ai/opencode/internal/tui/styles\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n)\n\ntype DetailComponent interface {\n\ttea.Model\n\tlayout.Sizeable\n\tlayout.Bindings\n}\n\ntype detailCmp struct {\n\twidth, height int\n\tcurrentLog logging.LogMessage\n\tviewport viewport.Model\n}\n\nfunc (i *detailCmp) Init() tea.Cmd {\n\tmessages := logging.List()\n\tif len(messages) == 0 {\n\t\treturn nil\n\t}\n\ti.currentLog = messages[0]\n\treturn nil\n}\n\nfunc (i *detailCmp) Update(msg tea.Msg) (tea.Model, tea.Cmd) {\n\tswitch msg := msg.(type) {\n\tcase selectedLogMsg:\n\t\tif msg.ID != i.currentLog.ID {\n\t\t\ti.currentLog = logging.LogMessage(msg)\n\t\t\ti.updateContent()\n\t\t}\n\t}\n\n\treturn i, nil\n}\n\nfunc (i *detailCmp) updateContent() {\n\tvar content strings.Builder\n\tt := theme.CurrentTheme()\n\n\t// Format the header with timestamp and level\n\ttimeStyle := lipgloss.NewStyle().Foreground(t.TextMuted())\n\tlevelStyle := getLevelStyle(i.currentLog.Level)\n\n\theader := lipgloss.JoinHorizontal(\n\t\tlipgloss.Center,\n\t\ttimeStyle.Render(i.currentLog.Time.Format(time.RFC3339)),\n\t\t\" \",\n\t\tlevelStyle.Render(i.currentLog.Level),\n\t)\n\n\tcontent.WriteString(lipgloss.NewStyle().Bold(true).Render(header))\n\tcontent.WriteString(\"\\n\\n\")\n\n\t// Message with styling\n\tmessageStyle := lipgloss.NewStyle().Bold(true).Foreground(t.Text())\n\tcontent.WriteString(messageStyle.Render(\"Message:\"))\n\tcontent.WriteString(\"\\n\")\n\tcontent.WriteString(lipgloss.NewStyle().Padding(0, 2).Render(i.currentLog.Message))\n\tcontent.WriteString(\"\\n\\n\")\n\n\t// Attributes section\n\tif len(i.currentLog.Attributes) > 0 {\n\t\tattrHeaderStyle := lipgloss.NewStyle().Bold(true).Foreground(t.Text())\n\t\tcontent.WriteString(attrHeaderStyle.Render(\"Attributes:\"))\n\t\tcontent.WriteString(\"\\n\")\n\n\t\t// Create a table-like display for attributes\n\t\tkeyStyle := lipgloss.NewStyle().Foreground(t.Primary()).Bold(true)\n\t\tvalueStyle := lipgloss.NewStyle().Foreground(t.Text())\n\n\t\tfor _, attr := range i.currentLog.Attributes {\n\t\t\tattrLine := fmt.Sprintf(\"%s: %s\",\n\t\t\t\tkeyStyle.Render(attr.Key),\n\t\t\t\tvalueStyle.Render(attr.Value),\n\t\t\t)\n\t\t\tcontent.WriteString(lipgloss.NewStyle().Padding(0, 2).Render(attrLine))\n\t\t\tcontent.WriteString(\"\\n\")\n\t\t}\n\t}\n\n\ti.viewport.SetContent(content.String())\n}\n\nfunc getLevelStyle(level string) lipgloss.Style {\n\tstyle := lipgloss.NewStyle().Bold(true)\n\tt := theme.CurrentTheme()\n\t\n\tswitch strings.ToLower(level) {\n\tcase \"info\":\n\t\treturn style.Foreground(t.Info())\n\tcase \"warn\", \"warning\":\n\t\treturn style.Foreground(t.Warning())\n\tcase \"error\", \"err\":\n\t\treturn style.Foreground(t.Error())\n\tcase \"debug\":\n\t\treturn style.Foreground(t.Success())\n\tdefault:\n\t\treturn style.Foreground(t.Text())\n\t}\n}\n\nfunc (i *detailCmp) View() string {\n\tt := theme.CurrentTheme()\n\treturn styles.ForceReplaceBackgroundWithLipgloss(i.viewport.View(), t.Background())\n}\n\nfunc (i *detailCmp) GetSize() (int, int) {\n\treturn i.width, i.height\n}\n\nfunc (i *detailCmp) SetSize(width int, height int) tea.Cmd {\n\ti.width = width\n\ti.height = height\n\ti.viewport.Width = i.width\n\ti.viewport.Height = i.height\n\ti.updateContent()\n\treturn nil\n}\n\nfunc (i *detailCmp) BindingKeys() []key.Binding {\n\treturn layout.KeyMapToSlice(i.viewport.KeyMap)\n}\n\nfunc NewLogsDetails() DetailComponent {\n\treturn &detailCmp{\n\t\tviewport: viewport.New(0, 0),\n\t}\n}\n"], ["/opencode/internal/fileutil/fileutil.go", "package fileutil\n\nimport (\n\t\"fmt\"\n\t\"io/fs\"\n\t\"os\"\n\t\"os/exec\"\n\t\"path/filepath\"\n\t\"sort\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/bmatcuk/doublestar/v4\"\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n)\n\nvar (\n\trgPath string\n\tfzfPath string\n)\n\nfunc init() {\n\tvar err error\n\trgPath, err = exec.LookPath(\"rg\")\n\tif err != nil {\n\t\tlogging.Warn(\"Ripgrep (rg) not found in $PATH. Some features might be limited or slower.\")\n\t\trgPath = \"\"\n\t}\n\tfzfPath, err = exec.LookPath(\"fzf\")\n\tif err != nil {\n\t\tlogging.Warn(\"FZF not found in $PATH. Some features might be limited or slower.\")\n\t\tfzfPath = \"\"\n\t}\n}\n\nfunc GetRgCmd(globPattern string) *exec.Cmd {\n\tif rgPath == \"\" {\n\t\treturn nil\n\t}\n\trgArgs := []string{\n\t\t\"--files\",\n\t\t\"-L\",\n\t\t\"--null\",\n\t}\n\tif globPattern != \"\" {\n\t\tif !filepath.IsAbs(globPattern) && !strings.HasPrefix(globPattern, \"/\") {\n\t\t\tglobPattern = \"/\" + globPattern\n\t\t}\n\t\trgArgs = append(rgArgs, \"--glob\", globPattern)\n\t}\n\tcmd := exec.Command(rgPath, rgArgs...)\n\tcmd.Dir = \".\"\n\treturn cmd\n}\n\nfunc GetFzfCmd(query string) *exec.Cmd {\n\tif fzfPath == \"\" {\n\t\treturn nil\n\t}\n\tfzfArgs := []string{\n\t\t\"--filter\",\n\t\tquery,\n\t\t\"--read0\",\n\t\t\"--print0\",\n\t}\n\tcmd := exec.Command(fzfPath, fzfArgs...)\n\tcmd.Dir = \".\"\n\treturn cmd\n}\n\ntype FileInfo struct {\n\tPath string\n\tModTime time.Time\n}\n\nfunc SkipHidden(path string) bool {\n\t// Check for hidden files (starting with a dot)\n\tbase := filepath.Base(path)\n\tif base != \".\" && strings.HasPrefix(base, \".\") {\n\t\treturn true\n\t}\n\n\tcommonIgnoredDirs := map[string]bool{\n\t\t\".opencode\": true,\n\t\t\"node_modules\": true,\n\t\t\"vendor\": true,\n\t\t\"dist\": true,\n\t\t\"build\": true,\n\t\t\"target\": true,\n\t\t\".git\": true,\n\t\t\".idea\": true,\n\t\t\".vscode\": true,\n\t\t\"__pycache__\": true,\n\t\t\"bin\": true,\n\t\t\"obj\": true,\n\t\t\"out\": true,\n\t\t\"coverage\": true,\n\t\t\"tmp\": true,\n\t\t\"temp\": true,\n\t\t\"logs\": true,\n\t\t\"generated\": true,\n\t\t\"bower_components\": true,\n\t\t\"jspm_packages\": true,\n\t}\n\n\tparts := strings.Split(path, string(os.PathSeparator))\n\tfor _, part := range parts {\n\t\tif commonIgnoredDirs[part] {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc GlobWithDoublestar(pattern, searchPath string, limit int) ([]string, bool, error) {\n\tfsys := os.DirFS(searchPath)\n\trelPattern := strings.TrimPrefix(pattern, \"/\")\n\tvar matches []FileInfo\n\n\terr := doublestar.GlobWalk(fsys, relPattern, func(path string, d fs.DirEntry) error {\n\t\tif d.IsDir() {\n\t\t\treturn nil\n\t\t}\n\t\tif SkipHidden(path) {\n\t\t\treturn nil\n\t\t}\n\t\tinfo, err := d.Info()\n\t\tif err != nil {\n\t\t\treturn nil\n\t\t}\n\t\tabsPath := path\n\t\tif !strings.HasPrefix(absPath, searchPath) && searchPath != \".\" {\n\t\t\tabsPath = filepath.Join(searchPath, absPath)\n\t\t} else if !strings.HasPrefix(absPath, \"/\") && searchPath == \".\" {\n\t\t\tabsPath = filepath.Join(searchPath, absPath) // Ensure relative paths are joined correctly\n\t\t}\n\n\t\tmatches = append(matches, FileInfo{Path: absPath, ModTime: info.ModTime()})\n\t\tif limit > 0 && len(matches) >= limit*2 {\n\t\t\treturn fs.SkipAll\n\t\t}\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\treturn nil, false, fmt.Errorf(\"glob walk error: %w\", err)\n\t}\n\n\tsort.Slice(matches, func(i, j int) bool {\n\t\treturn matches[i].ModTime.After(matches[j].ModTime)\n\t})\n\n\ttruncated := false\n\tif limit > 0 && len(matches) > limit {\n\t\tmatches = matches[:limit]\n\t\ttruncated = true\n\t}\n\n\tresults := make([]string, len(matches))\n\tfor i, m := range matches {\n\t\tresults[i] = m.Path\n\t}\n\treturn results, truncated, nil\n}\n"], ["/opencode/internal/llm/provider/openai.go", "package provider\n\nimport (\n\t\"context\"\n\t\"encoding/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"time\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n\t\"github.com/openai/openai-go/shared\"\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/llm/models\"\n\t\"github.com/opencode-ai/opencode/internal/llm/tools\"\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n\t\"github.com/opencode-ai/opencode/internal/message\"\n)\n\ntype openaiOptions struct {\n\tbaseURL string\n\tdisableCache bool\n\treasoningEffort string\n\textraHeaders map[string]string\n}\n\ntype OpenAIOption func(*openaiOptions)\n\ntype openaiClient struct {\n\tproviderOptions providerClientOptions\n\toptions openaiOptions\n\tclient openai.Client\n}\n\ntype OpenAIClient ProviderClient\n\nfunc newOpenAIClient(opts providerClientOptions) OpenAIClient {\n\topenaiOpts := openaiOptions{\n\t\treasoningEffort: \"medium\",\n\t}\n\tfor _, o := range opts.openaiOptions {\n\t\to(&openaiOpts)\n\t}\n\n\topenaiClientOptions := []option.RequestOption{}\n\tif opts.apiKey != \"\" {\n\t\topenaiClientOptions = append(openaiClientOptions, option.WithAPIKey(opts.apiKey))\n\t}\n\tif openaiOpts.baseURL != \"\" {\n\t\topenaiClientOptions = append(openaiClientOptions, option.WithBaseURL(openaiOpts.baseURL))\n\t}\n\n\tif openaiOpts.extraHeaders != nil {\n\t\tfor key, value := range openaiOpts.extraHeaders {\n\t\t\topenaiClientOptions = append(openaiClientOptions, option.WithHeader(key, value))\n\t\t}\n\t}\n\n\tclient := openai.NewClient(openaiClientOptions...)\n\treturn &openaiClient{\n\t\tproviderOptions: opts,\n\t\toptions: openaiOpts,\n\t\tclient: client,\n\t}\n}\n\nfunc (o *openaiClient) convertMessages(messages []message.Message) (openaiMessages []openai.ChatCompletionMessageParamUnion) {\n\t// Add system message first\n\topenaiMessages = append(openaiMessages, openai.SystemMessage(o.providerOptions.systemMessage))\n\n\tfor _, msg := range messages {\n\t\tswitch msg.Role {\n\t\tcase message.User:\n\t\t\tvar content []openai.ChatCompletionContentPartUnionParam\n\t\t\ttextBlock := openai.ChatCompletionContentPartTextParam{Text: msg.Content().String()}\n\t\t\tcontent = append(content, openai.ChatCompletionContentPartUnionParam{OfText: &textBlock})\n\t\t\tfor _, binaryContent := range msg.BinaryContent() {\n\t\t\t\timageURL := openai.ChatCompletionContentPartImageImageURLParam{URL: binaryContent.String(models.ProviderOpenAI)}\n\t\t\t\timageBlock := openai.ChatCompletionContentPartImageParam{ImageURL: imageURL}\n\n\t\t\t\tcontent = append(content, openai.ChatCompletionContentPartUnionParam{OfImageURL: &imageBlock})\n\t\t\t}\n\n\t\t\topenaiMessages = append(openaiMessages, openai.UserMessage(content))\n\n\t\tcase message.Assistant:\n\t\t\tassistantMsg := openai.ChatCompletionAssistantMessageParam{\n\t\t\t\tRole: \"assistant\",\n\t\t\t}\n\n\t\t\tif msg.Content().String() != \"\" {\n\t\t\t\tassistantMsg.Content = openai.ChatCompletionAssistantMessageParamContentUnion{\n\t\t\t\t\tOfString: openai.String(msg.Content().String()),\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif len(msg.ToolCalls()) > 0 {\n\t\t\t\tassistantMsg.ToolCalls = make([]openai.ChatCompletionMessageToolCallParam, len(msg.ToolCalls()))\n\t\t\t\tfor i, call := range msg.ToolCalls() {\n\t\t\t\t\tassistantMsg.ToolCalls[i] = openai.ChatCompletionMessageToolCallParam{\n\t\t\t\t\t\tID: call.ID,\n\t\t\t\t\t\tType: \"function\",\n\t\t\t\t\t\tFunction: openai.ChatCompletionMessageToolCallFunctionParam{\n\t\t\t\t\t\t\tName: call.Name,\n\t\t\t\t\t\t\tArguments: call.Input,\n\t\t\t\t\t\t},\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\topenaiMessages = append(openaiMessages, openai.ChatCompletionMessageParamUnion{\n\t\t\t\tOfAssistant: &assistantMsg,\n\t\t\t})\n\n\t\tcase message.Tool:\n\t\t\tfor _, result := range msg.ToolResults() {\n\t\t\t\topenaiMessages = append(openaiMessages,\n\t\t\t\t\topenai.ToolMessage(result.Content, result.ToolCallID),\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn\n}\n\nfunc (o *openaiClient) convertTools(tools []tools.BaseTool) []openai.ChatCompletionToolParam {\n\topenaiTools := make([]openai.ChatCompletionToolParam, len(tools))\n\n\tfor i, tool := range tools {\n\t\tinfo := tool.Info()\n\t\topenaiTools[i] = openai.ChatCompletionToolParam{\n\t\t\tFunction: openai.FunctionDefinitionParam{\n\t\t\t\tName: info.Name,\n\t\t\t\tDescription: openai.String(info.Description),\n\t\t\t\tParameters: openai.FunctionParameters{\n\t\t\t\t\t\"type\": \"object\",\n\t\t\t\t\t\"properties\": info.Parameters,\n\t\t\t\t\t\"required\": info.Required,\n\t\t\t\t},\n\t\t\t},\n\t\t}\n\t}\n\n\treturn openaiTools\n}\n\nfunc (o *openaiClient) finishReason(reason string) message.FinishReason {\n\tswitch reason {\n\tcase \"stop\":\n\t\treturn message.FinishReasonEndTurn\n\tcase \"length\":\n\t\treturn message.FinishReasonMaxTokens\n\tcase \"tool_calls\":\n\t\treturn message.FinishReasonToolUse\n\tdefault:\n\t\treturn message.FinishReasonUnknown\n\t}\n}\n\nfunc (o *openaiClient) preparedParams(messages []openai.ChatCompletionMessageParamUnion, tools []openai.ChatCompletionToolParam) openai.ChatCompletionNewParams {\n\tparams := openai.ChatCompletionNewParams{\n\t\tModel: openai.ChatModel(o.providerOptions.model.APIModel),\n\t\tMessages: messages,\n\t\tTools: tools,\n\t}\n\n\tif o.providerOptions.model.CanReason == true {\n\t\tparams.MaxCompletionTokens = openai.Int(o.providerOptions.maxTokens)\n\t\tswitch o.options.reasoningEffort {\n\t\tcase \"low\":\n\t\t\tparams.ReasoningEffort = shared.ReasoningEffortLow\n\t\tcase \"medium\":\n\t\t\tparams.ReasoningEffort = shared.ReasoningEffortMedium\n\t\tcase \"high\":\n\t\t\tparams.ReasoningEffort = shared.ReasoningEffortHigh\n\t\tdefault:\n\t\t\tparams.ReasoningEffort = shared.ReasoningEffortMedium\n\t\t}\n\t} else {\n\t\tparams.MaxTokens = openai.Int(o.providerOptions.maxTokens)\n\t}\n\n\treturn params\n}\n\nfunc (o *openaiClient) send(ctx context.Context, messages []message.Message, tools []tools.BaseTool) (response *ProviderResponse, err error) {\n\tparams := o.preparedParams(o.convertMessages(messages), o.convertTools(tools))\n\tcfg := config.Get()\n\tif cfg.Debug {\n\t\tjsonData, _ := json.Marshal(params)\n\t\tlogging.Debug(\"Prepared messages\", \"messages\", string(jsonData))\n\t}\n\tattempts := 0\n\tfor {\n\t\tattempts++\n\t\topenaiResponse, err := o.client.Chat.Completions.New(\n\t\t\tctx,\n\t\t\tparams,\n\t\t)\n\t\t// If there is an error we are going to see if we can retry the call\n\t\tif err != nil {\n\t\t\tretry, after, retryErr := o.shouldRetry(attempts, err)\n\t\t\tif retryErr != nil {\n\t\t\t\treturn nil, retryErr\n\t\t\t}\n\t\t\tif retry {\n\t\t\t\tlogging.WarnPersist(fmt.Sprintf(\"Retrying due to rate limit... attempt %d of %d\", attempts, maxRetries), logging.PersistTimeArg, time.Millisecond*time.Duration(after+100))\n\t\t\t\tselect {\n\t\t\t\tcase <-ctx.Done():\n\t\t\t\t\treturn nil, ctx.Err()\n\t\t\t\tcase <-time.After(time.Duration(after) * time.Millisecond):\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn nil, retryErr\n\t\t}\n\n\t\tcontent := \"\"\n\t\tif openaiResponse.Choices[0].Message.Content != \"\" {\n\t\t\tcontent = openaiResponse.Choices[0].Message.Content\n\t\t}\n\n\t\ttoolCalls := o.toolCalls(*openaiResponse)\n\t\tfinishReason := o.finishReason(string(openaiResponse.Choices[0].FinishReason))\n\n\t\tif len(toolCalls) > 0 {\n\t\t\tfinishReason = message.FinishReasonToolUse\n\t\t}\n\n\t\treturn &ProviderResponse{\n\t\t\tContent: content,\n\t\t\tToolCalls: toolCalls,\n\t\t\tUsage: o.usage(*openaiResponse),\n\t\t\tFinishReason: finishReason,\n\t\t}, nil\n\t}\n}\n\nfunc (o *openaiClient) stream(ctx context.Context, messages []message.Message, tools []tools.BaseTool) <-chan ProviderEvent {\n\tparams := o.preparedParams(o.convertMessages(messages), o.convertTools(tools))\n\tparams.StreamOptions = openai.ChatCompletionStreamOptionsParam{\n\t\tIncludeUsage: openai.Bool(true),\n\t}\n\n\tcfg := config.Get()\n\tif cfg.Debug {\n\t\tjsonData, _ := json.Marshal(params)\n\t\tlogging.Debug(\"Prepared messages\", \"messages\", string(jsonData))\n\t}\n\n\tattempts := 0\n\teventChan := make(chan ProviderEvent)\n\n\tgo func() {\n\t\tfor {\n\t\t\tattempts++\n\t\t\topenaiStream := o.client.Chat.Completions.NewStreaming(\n\t\t\t\tctx,\n\t\t\t\tparams,\n\t\t\t)\n\n\t\t\tacc := openai.ChatCompletionAccumulator{}\n\t\t\tcurrentContent := \"\"\n\t\t\ttoolCalls := make([]message.ToolCall, 0)\n\n\t\t\tfor openaiStream.Next() {\n\t\t\t\tchunk := openaiStream.Current()\n\t\t\t\tacc.AddChunk(chunk)\n\n\t\t\t\tfor _, choice := range chunk.Choices {\n\t\t\t\t\tif choice.Delta.Content != \"\" {\n\t\t\t\t\t\teventChan <- ProviderEvent{\n\t\t\t\t\t\t\tType: EventContentDelta,\n\t\t\t\t\t\t\tContent: choice.Delta.Content,\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcurrentContent += choice.Delta.Content\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\terr := openaiStream.Err()\n\t\t\tif err == nil || errors.Is(err, io.EOF) {\n\t\t\t\t// Stream completed successfully\n\t\t\t\tfinishReason := o.finishReason(string(acc.ChatCompletion.Choices[0].FinishReason))\n\t\t\t\tif len(acc.ChatCompletion.Choices[0].Message.ToolCalls) > 0 {\n\t\t\t\t\ttoolCalls = append(toolCalls, o.toolCalls(acc.ChatCompletion)...)\n\t\t\t\t}\n\t\t\t\tif len(toolCalls) > 0 {\n\t\t\t\t\tfinishReason = message.FinishReasonToolUse\n\t\t\t\t}\n\n\t\t\t\teventChan <- ProviderEvent{\n\t\t\t\t\tType: EventComplete,\n\t\t\t\t\tResponse: &ProviderResponse{\n\t\t\t\t\t\tContent: currentContent,\n\t\t\t\t\t\tToolCalls: toolCalls,\n\t\t\t\t\t\tUsage: o.usage(acc.ChatCompletion),\n\t\t\t\t\t\tFinishReason: finishReason,\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t\tclose(eventChan)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\t// If there is an error we are going to see if we can retry the call\n\t\t\tretry, after, retryErr := o.shouldRetry(attempts, err)\n\t\t\tif retryErr != nil {\n\t\t\t\teventChan <- ProviderEvent{Type: EventError, Error: retryErr}\n\t\t\t\tclose(eventChan)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif retry {\n\t\t\t\tlogging.WarnPersist(fmt.Sprintf(\"Retrying due to rate limit... attempt %d of %d\", attempts, maxRetries), logging.PersistTimeArg, time.Millisecond*time.Duration(after+100))\n\t\t\t\tselect {\n\t\t\t\tcase <-ctx.Done():\n\t\t\t\t\t// context cancelled\n\t\t\t\t\tif ctx.Err() == nil {\n\t\t\t\t\t\teventChan <- ProviderEvent{Type: EventError, Error: ctx.Err()}\n\t\t\t\t\t}\n\t\t\t\t\tclose(eventChan)\n\t\t\t\t\treturn\n\t\t\t\tcase <-time.After(time.Duration(after) * time.Millisecond):\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t\teventChan <- ProviderEvent{Type: EventError, Error: retryErr}\n\t\t\tclose(eventChan)\n\t\t\treturn\n\t\t}\n\t}()\n\n\treturn eventChan\n}\n\nfunc (o *openaiClient) shouldRetry(attempts int, err error) (bool, int64, error) {\n\tvar apierr *openai.Error\n\tif !errors.As(err, &apierr) {\n\t\treturn false, 0, err\n\t}\n\n\tif apierr.StatusCode != 429 && apierr.StatusCode != 500 {\n\t\treturn false, 0, err\n\t}\n\n\tif attempts > maxRetries {\n\t\treturn false, 0, fmt.Errorf(\"maximum retry attempts reached for rate limit: %d retries\", maxRetries)\n\t}\n\n\tretryMs := 0\n\tretryAfterValues := apierr.Response.Header.Values(\"Retry-After\")\n\n\tbackoffMs := 2000 * (1 << (attempts - 1))\n\tjitterMs := int(float64(backoffMs) * 0.2)\n\tretryMs = backoffMs + jitterMs\n\tif len(retryAfterValues) > 0 {\n\t\tif _, err := fmt.Sscanf(retryAfterValues[0], \"%d\", &retryMs); err == nil {\n\t\t\tretryMs = retryMs * 1000\n\t\t}\n\t}\n\treturn true, int64(retryMs), nil\n}\n\nfunc (o *openaiClient) toolCalls(completion openai.ChatCompletion) []message.ToolCall {\n\tvar toolCalls []message.ToolCall\n\n\tif len(completion.Choices) > 0 && len(completion.Choices[0].Message.ToolCalls) > 0 {\n\t\tfor _, call := range completion.Choices[0].Message.ToolCalls {\n\t\t\ttoolCall := message.ToolCall{\n\t\t\t\tID: call.ID,\n\t\t\t\tName: call.Function.Name,\n\t\t\t\tInput: call.Function.Arguments,\n\t\t\t\tType: \"function\",\n\t\t\t\tFinished: true,\n\t\t\t}\n\t\t\ttoolCalls = append(toolCalls, toolCall)\n\t\t}\n\t}\n\n\treturn toolCalls\n}\n\nfunc (o *openaiClient) usage(completion openai.ChatCompletion) TokenUsage {\n\tcachedTokens := completion.Usage.PromptTokensDetails.CachedTokens\n\tinputTokens := completion.Usage.PromptTokens - cachedTokens\n\n\treturn TokenUsage{\n\t\tInputTokens: inputTokens,\n\t\tOutputTokens: completion.Usage.CompletionTokens,\n\t\tCacheCreationTokens: 0, // OpenAI doesn't provide this directly\n\t\tCacheReadTokens: cachedTokens,\n\t}\n}\n\nfunc WithOpenAIBaseURL(baseURL string) OpenAIOption {\n\treturn func(options *openaiOptions) {\n\t\toptions.baseURL = baseURL\n\t}\n}\n\nfunc WithOpenAIExtraHeaders(headers map[string]string) OpenAIOption {\n\treturn func(options *openaiOptions) {\n\t\toptions.extraHeaders = headers\n\t}\n}\n\nfunc WithOpenAIDisableCache() OpenAIOption {\n\treturn func(options *openaiOptions) {\n\t\toptions.disableCache = true\n\t}\n}\n\nfunc WithReasoningEffort(effort string) OpenAIOption {\n\treturn func(options *openaiOptions) {\n\t\tdefaultReasoningEffort := \"medium\"\n\t\tswitch effort {\n\t\tcase \"low\", \"medium\", \"high\":\n\t\t\tdefaultReasoningEffort = effort\n\t\tdefault:\n\t\t\tlogging.Warn(\"Invalid reasoning effort, using default: medium\")\n\t\t}\n\t\toptions.reasoningEffort = defaultReasoningEffort\n\t}\n}\n"], ["/opencode/internal/logging/writer.go", "package logging\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"fmt\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com/go-logfmt/logfmt\"\n\t\"github.com/opencode-ai/opencode/internal/pubsub\"\n)\n\nconst (\n\tpersistKeyArg = \"$_persist\"\n\tPersistTimeArg = \"$_persist_time\"\n)\n\ntype LogData struct {\n\tmessages []LogMessage\n\t*pubsub.Broker[LogMessage]\n\tlock sync.Mutex\n}\n\nfunc (l *LogData) Add(msg LogMessage) {\n\tl.lock.Lock()\n\tdefer l.lock.Unlock()\n\tl.messages = append(l.messages, msg)\n\tl.Publish(pubsub.CreatedEvent, msg)\n}\n\nfunc (l *LogData) List() []LogMessage {\n\tl.lock.Lock()\n\tdefer l.lock.Unlock()\n\treturn l.messages\n}\n\nvar defaultLogData = &LogData{\n\tmessages: make([]LogMessage, 0),\n\tBroker: pubsub.NewBroker[LogMessage](),\n}\n\ntype writer struct{}\n\nfunc (w *writer) Write(p []byte) (int, error) {\n\td := logfmt.NewDecoder(bytes.NewReader(p))\n\n\tfor d.ScanRecord() {\n\t\tmsg := LogMessage{\n\t\t\tID: fmt.Sprintf(\"%d\", time.Now().UnixNano()),\n\t\t\tTime: time.Now(),\n\t\t}\n\t\tfor d.ScanKeyval() {\n\t\t\tswitch string(d.Key()) {\n\t\t\tcase \"time\":\n\t\t\t\tparsed, err := time.Parse(time.RFC3339, string(d.Value()))\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn 0, fmt.Errorf(\"parsing time: %w\", err)\n\t\t\t\t}\n\t\t\t\tmsg.Time = parsed\n\t\t\tcase \"level\":\n\t\t\t\tmsg.Level = strings.ToLower(string(d.Value()))\n\t\t\tcase \"msg\":\n\t\t\t\tmsg.Message = string(d.Value())\n\t\t\tdefault:\n\t\t\t\tif string(d.Key()) == persistKeyArg {\n\t\t\t\t\tmsg.Persist = true\n\t\t\t\t} else if string(d.Key()) == PersistTimeArg {\n\t\t\t\t\tparsed, err := time.ParseDuration(string(d.Value()))\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tmsg.PersistTime = parsed\n\t\t\t\t} else {\n\t\t\t\t\tmsg.Attributes = append(msg.Attributes, Attr{\n\t\t\t\t\t\tKey: string(d.Key()),\n\t\t\t\t\t\tValue: string(d.Value()),\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tdefaultLogData.Add(msg)\n\t}\n\tif d.Err() != nil {\n\t\treturn 0, d.Err()\n\t}\n\treturn len(p), nil\n}\n\nfunc NewWriter() *writer {\n\tw := &writer{}\n\treturn w\n}\n\nfunc Subscribe(ctx context.Context) <-chan pubsub.Event[LogMessage] {\n\treturn defaultLogData.Subscribe(ctx)\n}\n\nfunc List() []LogMessage {\n\treturn defaultLogData.List()\n}\n"], ["/opencode/internal/llm/provider/copilot.go", "package provider\n\nimport (\n\t\"context\"\n\t\"encoding/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"net/http\"\n\t\"os\"\n\t\"time\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n\t\"github.com/openai/openai-go/shared\"\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/llm/models\"\n\ttoolsPkg \"github.com/opencode-ai/opencode/internal/llm/tools\"\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n\t\"github.com/opencode-ai/opencode/internal/message\"\n)\n\ntype copilotOptions struct {\n\treasoningEffort string\n\textraHeaders map[string]string\n\tbearerToken string\n}\n\ntype CopilotOption func(*copilotOptions)\n\ntype copilotClient struct {\n\tproviderOptions providerClientOptions\n\toptions copilotOptions\n\tclient openai.Client\n\thttpClient *http.Client\n}\n\ntype CopilotClient ProviderClient\n\n// CopilotTokenResponse represents the response from GitHub's token exchange endpoint\ntype CopilotTokenResponse struct {\n\tToken string `json:\"token\"`\n\tExpiresAt int64 `json:\"expires_at\"`\n}\n\nfunc (c *copilotClient) isAnthropicModel() bool {\n\tfor _, modelId := range models.CopilotAnthropicModels {\n\t\tif c.providerOptions.model.ID == modelId {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n// loadGitHubToken loads the GitHub OAuth token from the standard GitHub CLI/Copilot locations\n\n// exchangeGitHubToken exchanges a GitHub token for a Copilot bearer token\nfunc (c *copilotClient) exchangeGitHubToken(githubToken string) (string, error) {\n\treq, err := http.NewRequest(\"GET\", \"https://api.github.com/copilot_internal/v2/token\", nil)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed to create token exchange request: %w\", err)\n\t}\n\n\treq.Header.Set(\"Authorization\", \"Token \"+githubToken)\n\treq.Header.Set(\"User-Agent\", \"OpenCode/1.0\")\n\n\tresp, err := c.httpClient.Do(req)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed to exchange GitHub token: %w\", err)\n\t}\n\tdefer resp.Body.Close()\n\n\tif resp.StatusCode != http.StatusOK {\n\t\tbody, _ := io.ReadAll(resp.Body)\n\t\treturn \"\", fmt.Errorf(\"token exchange failed with status %d: %s\", resp.StatusCode, string(body))\n\t}\n\n\tvar tokenResp CopilotTokenResponse\n\tif err := json.NewDecoder(resp.Body).Decode(&tokenResp); err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed to decode token response: %w\", err)\n\t}\n\n\treturn tokenResp.Token, nil\n}\n\nfunc newCopilotClient(opts providerClientOptions) CopilotClient {\n\tcopilotOpts := copilotOptions{\n\t\treasoningEffort: \"medium\",\n\t}\n\t// Apply copilot-specific options\n\tfor _, o := range opts.copilotOptions {\n\t\to(&copilotOpts)\n\t}\n\n\t// Create HTTP client for token exchange\n\thttpClient := &http.Client{\n\t\tTimeout: 30 * time.Second,\n\t}\n\n\tvar bearerToken string\n\n\t// If bearer token is already provided, use it\n\tif copilotOpts.bearerToken != \"\" {\n\t\tbearerToken = copilotOpts.bearerToken\n\t} else {\n\t\t// Try to get GitHub token from multiple sources\n\t\tvar githubToken string\n\n\t\t// 1. Environment variable\n\t\tgithubToken = os.Getenv(\"GITHUB_TOKEN\")\n\n\t\t// 2. API key from options\n\t\tif githubToken == \"\" {\n\t\t\tgithubToken = opts.apiKey\n\t\t}\n\n\t\t// 3. Standard GitHub CLI/Copilot locations\n\t\tif githubToken == \"\" {\n\t\t\tvar err error\n\t\t\tgithubToken, err = config.LoadGitHubToken()\n\t\t\tif err != nil {\n\t\t\t\tlogging.Debug(\"Failed to load GitHub token from standard locations\", \"error\", err)\n\t\t\t}\n\t\t}\n\n\t\tif githubToken == \"\" {\n\t\t\tlogging.Error(\"GitHub token is required for Copilot provider. Set GITHUB_TOKEN environment variable, configure it in opencode.json, or ensure GitHub CLI/Copilot is properly authenticated.\")\n\t\t\treturn &copilotClient{\n\t\t\t\tproviderOptions: opts,\n\t\t\t\toptions: copilotOpts,\n\t\t\t\thttpClient: httpClient,\n\t\t\t}\n\t\t}\n\n\t\t// Create a temporary client for token exchange\n\t\ttempClient := &copilotClient{\n\t\t\tproviderOptions: opts,\n\t\t\toptions: copilotOpts,\n\t\t\thttpClient: httpClient,\n\t\t}\n\n\t\t// Exchange GitHub token for bearer token\n\t\tvar err error\n\t\tbearerToken, err = tempClient.exchangeGitHubToken(githubToken)\n\t\tif err != nil {\n\t\t\tlogging.Error(\"Failed to exchange GitHub token for Copilot bearer token\", \"error\", err)\n\t\t\treturn &copilotClient{\n\t\t\t\tproviderOptions: opts,\n\t\t\t\toptions: copilotOpts,\n\t\t\t\thttpClient: httpClient,\n\t\t\t}\n\t\t}\n\t}\n\n\tcopilotOpts.bearerToken = bearerToken\n\n\t// GitHub Copilot API base URL\n\tbaseURL := \"https://api.githubcopilot.com\"\n\n\topenaiClientOptions := []option.RequestOption{\n\t\toption.WithBaseURL(baseURL),\n\t\toption.WithAPIKey(bearerToken), // Use bearer token as API key\n\t}\n\n\t// Add GitHub Copilot specific headers\n\topenaiClientOptions = append(openaiClientOptions,\n\t\toption.WithHeader(\"Editor-Version\", \"OpenCode/1.0\"),\n\t\toption.WithHeader(\"Editor-Plugin-Version\", \"OpenCode/1.0\"),\n\t\toption.WithHeader(\"Copilot-Integration-Id\", \"vscode-chat\"),\n\t)\n\n\t// Add any extra headers\n\tif copilotOpts.extraHeaders != nil {\n\t\tfor key, value := range copilotOpts.extraHeaders {\n\t\t\topenaiClientOptions = append(openaiClientOptions, option.WithHeader(key, value))\n\t\t}\n\t}\n\n\tclient := openai.NewClient(openaiClientOptions...)\n\t// logging.Debug(\"Copilot client created\", \"opts\", opts, \"copilotOpts\", copilotOpts, \"model\", opts.model)\n\treturn &copilotClient{\n\t\tproviderOptions: opts,\n\t\toptions: copilotOpts,\n\t\tclient: client,\n\t\thttpClient: httpClient,\n\t}\n}\n\nfunc (c *copilotClient) convertMessages(messages []message.Message) (copilotMessages []openai.ChatCompletionMessageParamUnion) {\n\t// Add system message first\n\tcopilotMessages = append(copilotMessages, openai.SystemMessage(c.providerOptions.systemMessage))\n\n\tfor _, msg := range messages {\n\t\tswitch msg.Role {\n\t\tcase message.User:\n\t\t\tvar content []openai.ChatCompletionContentPartUnionParam\n\t\t\ttextBlock := openai.ChatCompletionContentPartTextParam{Text: msg.Content().String()}\n\t\t\tcontent = append(content, openai.ChatCompletionContentPartUnionParam{OfText: &textBlock})\n\n\t\t\tfor _, binaryContent := range msg.BinaryContent() {\n\t\t\t\timageURL := openai.ChatCompletionContentPartImageImageURLParam{URL: binaryContent.String(models.ProviderCopilot)}\n\t\t\t\timageBlock := openai.ChatCompletionContentPartImageParam{ImageURL: imageURL}\n\t\t\t\tcontent = append(content, openai.ChatCompletionContentPartUnionParam{OfImageURL: &imageBlock})\n\t\t\t}\n\n\t\t\tcopilotMessages = append(copilotMessages, openai.UserMessage(content))\n\n\t\tcase message.Assistant:\n\t\t\tassistantMsg := openai.ChatCompletionAssistantMessageParam{\n\t\t\t\tRole: \"assistant\",\n\t\t\t}\n\n\t\t\tif msg.Content().String() != \"\" {\n\t\t\t\tassistantMsg.Content = openai.ChatCompletionAssistantMessageParamContentUnion{\n\t\t\t\t\tOfString: openai.String(msg.Content().String()),\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif len(msg.ToolCalls()) > 0 {\n\t\t\t\tassistantMsg.ToolCalls = make([]openai.ChatCompletionMessageToolCallParam, len(msg.ToolCalls()))\n\t\t\t\tfor i, call := range msg.ToolCalls() {\n\t\t\t\t\tassistantMsg.ToolCalls[i] = openai.ChatCompletionMessageToolCallParam{\n\t\t\t\t\t\tID: call.ID,\n\t\t\t\t\t\tType: \"function\",\n\t\t\t\t\t\tFunction: openai.ChatCompletionMessageToolCallFunctionParam{\n\t\t\t\t\t\t\tName: call.Name,\n\t\t\t\t\t\t\tArguments: call.Input,\n\t\t\t\t\t\t},\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tcopilotMessages = append(copilotMessages, openai.ChatCompletionMessageParamUnion{\n\t\t\t\tOfAssistant: &assistantMsg,\n\t\t\t})\n\n\t\tcase message.Tool:\n\t\t\tfor _, result := range msg.ToolResults() {\n\t\t\t\tcopilotMessages = append(copilotMessages,\n\t\t\t\t\topenai.ToolMessage(result.Content, result.ToolCallID),\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn\n}\n\nfunc (c *copilotClient) convertTools(tools []toolsPkg.BaseTool) []openai.ChatCompletionToolParam {\n\tcopilotTools := make([]openai.ChatCompletionToolParam, len(tools))\n\n\tfor i, tool := range tools {\n\t\tinfo := tool.Info()\n\t\tcopilotTools[i] = openai.ChatCompletionToolParam{\n\t\t\tFunction: openai.FunctionDefinitionParam{\n\t\t\t\tName: info.Name,\n\t\t\t\tDescription: openai.String(info.Description),\n\t\t\t\tParameters: openai.FunctionParameters{\n\t\t\t\t\t\"type\": \"object\",\n\t\t\t\t\t\"properties\": info.Parameters,\n\t\t\t\t\t\"required\": info.Required,\n\t\t\t\t},\n\t\t\t},\n\t\t}\n\t}\n\n\treturn copilotTools\n}\n\nfunc (c *copilotClient) finishReason(reason string) message.FinishReason {\n\tswitch reason {\n\tcase \"stop\":\n\t\treturn message.FinishReasonEndTurn\n\tcase \"length\":\n\t\treturn message.FinishReasonMaxTokens\n\tcase \"tool_calls\":\n\t\treturn message.FinishReasonToolUse\n\tdefault:\n\t\treturn message.FinishReasonUnknown\n\t}\n}\n\nfunc (c *copilotClient) preparedParams(messages []openai.ChatCompletionMessageParamUnion, tools []openai.ChatCompletionToolParam) openai.ChatCompletionNewParams {\n\tparams := openai.ChatCompletionNewParams{\n\t\tModel: openai.ChatModel(c.providerOptions.model.APIModel),\n\t\tMessages: messages,\n\t\tTools: tools,\n\t}\n\n\tif c.providerOptions.model.CanReason == true {\n\t\tparams.MaxCompletionTokens = openai.Int(c.providerOptions.maxTokens)\n\t\tswitch c.options.reasoningEffort {\n\t\tcase \"low\":\n\t\t\tparams.ReasoningEffort = shared.ReasoningEffortLow\n\t\tcase \"medium\":\n\t\t\tparams.ReasoningEffort = shared.ReasoningEffortMedium\n\t\tcase \"high\":\n\t\t\tparams.ReasoningEffort = shared.ReasoningEffortHigh\n\t\tdefault:\n\t\t\tparams.ReasoningEffort = shared.ReasoningEffortMedium\n\t\t}\n\t} else {\n\t\tparams.MaxTokens = openai.Int(c.providerOptions.maxTokens)\n\t}\n\n\treturn params\n}\n\nfunc (c *copilotClient) send(ctx context.Context, messages []message.Message, tools []toolsPkg.BaseTool) (response *ProviderResponse, err error) {\n\tparams := c.preparedParams(c.convertMessages(messages), c.convertTools(tools))\n\tcfg := config.Get()\n\tvar sessionId string\n\trequestSeqId := (len(messages) + 1) / 2\n\tif cfg.Debug {\n\t\t// jsonData, _ := json.Marshal(params)\n\t\t// logging.Debug(\"Prepared messages\", \"messages\", string(jsonData))\n\t\tif sid, ok := ctx.Value(toolsPkg.SessionIDContextKey).(string); ok {\n\t\t\tsessionId = sid\n\t\t}\n\t\tjsonData, _ := json.Marshal(params)\n\t\tif sessionId != \"\" {\n\t\t\tfilepath := logging.WriteRequestMessageJson(sessionId, requestSeqId, params)\n\t\t\tlogging.Debug(\"Prepared messages\", \"filepath\", filepath)\n\t\t} else {\n\t\t\tlogging.Debug(\"Prepared messages\", \"messages\", string(jsonData))\n\t\t}\n\t}\n\n\tattempts := 0\n\tfor {\n\t\tattempts++\n\t\tcopilotResponse, err := c.client.Chat.Completions.New(\n\t\t\tctx,\n\t\t\tparams,\n\t\t)\n\n\t\t// If there is an error we are going to see if we can retry the call\n\t\tif err != nil {\n\t\t\tretry, after, retryErr := c.shouldRetry(attempts, err)\n\t\t\tif retryErr != nil {\n\t\t\t\treturn nil, retryErr\n\t\t\t}\n\t\t\tif retry {\n\t\t\t\tlogging.WarnPersist(fmt.Sprintf(\"Retrying due to rate limit... attempt %d of %d\", attempts, maxRetries), logging.PersistTimeArg, time.Millisecond*time.Duration(after+100))\n\t\t\t\tselect {\n\t\t\t\tcase <-ctx.Done():\n\t\t\t\t\treturn nil, ctx.Err()\n\t\t\t\tcase <-time.After(time.Duration(after) * time.Millisecond):\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn nil, retryErr\n\t\t}\n\n\t\tcontent := \"\"\n\t\tif copilotResponse.Choices[0].Message.Content != \"\" {\n\t\t\tcontent = copilotResponse.Choices[0].Message.Content\n\t\t}\n\n\t\ttoolCalls := c.toolCalls(*copilotResponse)\n\t\tfinishReason := c.finishReason(string(copilotResponse.Choices[0].FinishReason))\n\n\t\tif len(toolCalls) > 0 {\n\t\t\tfinishReason = message.FinishReasonToolUse\n\t\t}\n\n\t\treturn &ProviderResponse{\n\t\t\tContent: content,\n\t\t\tToolCalls: toolCalls,\n\t\t\tUsage: c.usage(*copilotResponse),\n\t\t\tFinishReason: finishReason,\n\t\t}, nil\n\t}\n}\n\nfunc (c *copilotClient) stream(ctx context.Context, messages []message.Message, tools []toolsPkg.BaseTool) <-chan ProviderEvent {\n\tparams := c.preparedParams(c.convertMessages(messages), c.convertTools(tools))\n\tparams.StreamOptions = openai.ChatCompletionStreamOptionsParam{\n\t\tIncludeUsage: openai.Bool(true),\n\t}\n\n\tcfg := config.Get()\n\tvar sessionId string\n\trequestSeqId := (len(messages) + 1) / 2\n\tif cfg.Debug {\n\t\tif sid, ok := ctx.Value(toolsPkg.SessionIDContextKey).(string); ok {\n\t\t\tsessionId = sid\n\t\t}\n\t\tjsonData, _ := json.Marshal(params)\n\t\tif sessionId != \"\" {\n\t\t\tfilepath := logging.WriteRequestMessageJson(sessionId, requestSeqId, params)\n\t\t\tlogging.Debug(\"Prepared messages\", \"filepath\", filepath)\n\t\t} else {\n\t\t\tlogging.Debug(\"Prepared messages\", \"messages\", string(jsonData))\n\t\t}\n\n\t}\n\n\tattempts := 0\n\teventChan := make(chan ProviderEvent)\n\n\tgo func() {\n\t\tfor {\n\t\t\tattempts++\n\t\t\tcopilotStream := c.client.Chat.Completions.NewStreaming(\n\t\t\t\tctx,\n\t\t\t\tparams,\n\t\t\t)\n\n\t\t\tacc := openai.ChatCompletionAccumulator{}\n\t\t\tcurrentContent := \"\"\n\t\t\ttoolCalls := make([]message.ToolCall, 0)\n\n\t\t\tvar currentToolCallId string\n\t\t\tvar currentToolCall openai.ChatCompletionMessageToolCall\n\t\t\tvar msgToolCalls []openai.ChatCompletionMessageToolCall\n\t\t\tfor copilotStream.Next() {\n\t\t\t\tchunk := copilotStream.Current()\n\t\t\t\tacc.AddChunk(chunk)\n\n\t\t\t\tif cfg.Debug {\n\t\t\t\t\tlogging.AppendToStreamSessionLogJson(sessionId, requestSeqId, chunk)\n\t\t\t\t}\n\n\t\t\t\tfor _, choice := range chunk.Choices {\n\t\t\t\t\tif choice.Delta.Content != \"\" {\n\t\t\t\t\t\teventChan <- ProviderEvent{\n\t\t\t\t\t\t\tType: EventContentDelta,\n\t\t\t\t\t\t\tContent: choice.Delta.Content,\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcurrentContent += choice.Delta.Content\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif c.isAnthropicModel() {\n\t\t\t\t\t// Monkeypatch adapter for Sonnet-4 multi-tool use\n\t\t\t\t\tfor _, choice := range chunk.Choices {\n\t\t\t\t\t\tif choice.Delta.ToolCalls != nil && len(choice.Delta.ToolCalls) > 0 {\n\t\t\t\t\t\t\ttoolCall := choice.Delta.ToolCalls[0]\n\t\t\t\t\t\t\t// Detect tool use start\n\t\t\t\t\t\t\tif currentToolCallId == \"\" {\n\t\t\t\t\t\t\t\tif toolCall.ID != \"\" {\n\t\t\t\t\t\t\t\t\tcurrentToolCallId = toolCall.ID\n\t\t\t\t\t\t\t\t\tcurrentToolCall = openai.ChatCompletionMessageToolCall{\n\t\t\t\t\t\t\t\t\t\tID: toolCall.ID,\n\t\t\t\t\t\t\t\t\t\tType: \"function\",\n\t\t\t\t\t\t\t\t\t\tFunction: openai.ChatCompletionMessageToolCallFunction{\n\t\t\t\t\t\t\t\t\t\t\tName: toolCall.Function.Name,\n\t\t\t\t\t\t\t\t\t\t\tArguments: toolCall.Function.Arguments,\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t// Delta tool use\n\t\t\t\t\t\t\t\tif toolCall.ID == \"\" {\n\t\t\t\t\t\t\t\t\tcurrentToolCall.Function.Arguments += toolCall.Function.Arguments\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t// Detect new tool use\n\t\t\t\t\t\t\t\t\tif toolCall.ID != currentToolCallId {\n\t\t\t\t\t\t\t\t\t\tmsgToolCalls = append(msgToolCalls, currentToolCall)\n\t\t\t\t\t\t\t\t\t\tcurrentToolCallId = toolCall.ID\n\t\t\t\t\t\t\t\t\t\tcurrentToolCall = openai.ChatCompletionMessageToolCall{\n\t\t\t\t\t\t\t\t\t\t\tID: toolCall.ID,\n\t\t\t\t\t\t\t\t\t\t\tType: \"function\",\n\t\t\t\t\t\t\t\t\t\t\tFunction: openai.ChatCompletionMessageToolCallFunction{\n\t\t\t\t\t\t\t\t\t\t\t\tName: toolCall.Function.Name,\n\t\t\t\t\t\t\t\t\t\t\t\tArguments: toolCall.Function.Arguments,\n\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif choice.FinishReason == \"tool_calls\" {\n\t\t\t\t\t\t\tmsgToolCalls = append(msgToolCalls, currentToolCall)\n\t\t\t\t\t\t\tacc.ChatCompletion.Choices[0].Message.ToolCalls = msgToolCalls\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\terr := copilotStream.Err()\n\t\t\tif err == nil || errors.Is(err, io.EOF) {\n\t\t\t\tif cfg.Debug {\n\t\t\t\t\trespFilepath := logging.WriteChatResponseJson(sessionId, requestSeqId, acc.ChatCompletion)\n\t\t\t\t\tlogging.Debug(\"Chat completion response\", \"filepath\", respFilepath)\n\t\t\t\t}\n\t\t\t\t// Stream completed successfully\n\t\t\t\tfinishReason := c.finishReason(string(acc.ChatCompletion.Choices[0].FinishReason))\n\t\t\t\tif len(acc.ChatCompletion.Choices[0].Message.ToolCalls) > 0 {\n\t\t\t\t\ttoolCalls = append(toolCalls, c.toolCalls(acc.ChatCompletion)...)\n\t\t\t\t}\n\t\t\t\tif len(toolCalls) > 0 {\n\t\t\t\t\tfinishReason = message.FinishReasonToolUse\n\t\t\t\t}\n\n\t\t\t\teventChan <- ProviderEvent{\n\t\t\t\t\tType: EventComplete,\n\t\t\t\t\tResponse: &ProviderResponse{\n\t\t\t\t\t\tContent: currentContent,\n\t\t\t\t\t\tToolCalls: toolCalls,\n\t\t\t\t\t\tUsage: c.usage(acc.ChatCompletion),\n\t\t\t\t\t\tFinishReason: finishReason,\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t\tclose(eventChan)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\t// If there is an error we are going to see if we can retry the call\n\t\t\tretry, after, retryErr := c.shouldRetry(attempts, err)\n\t\t\tif retryErr != nil {\n\t\t\t\teventChan <- ProviderEvent{Type: EventError, Error: retryErr}\n\t\t\t\tclose(eventChan)\n\t\t\t\treturn\n\t\t\t}\n\t\t\t// shouldRetry is not catching the max retries...\n\t\t\t// TODO: Figure out why\n\t\t\tif attempts > maxRetries {\n\t\t\t\tlogging.Warn(\"Maximum retry attempts reached for rate limit\", \"attempts\", attempts, \"max_retries\", maxRetries)\n\t\t\t\tretry = false\n\t\t\t}\n\t\t\tif retry {\n\t\t\t\tlogging.WarnPersist(fmt.Sprintf(\"Retrying due to rate limit... attempt %d of %d (paused for %d ms)\", attempts, maxRetries, after), logging.PersistTimeArg, time.Millisecond*time.Duration(after+100))\n\t\t\t\tselect {\n\t\t\t\tcase <-ctx.Done():\n\t\t\t\t\t// context cancelled\n\t\t\t\t\tif ctx.Err() == nil {\n\t\t\t\t\t\teventChan <- ProviderEvent{Type: EventError, Error: ctx.Err()}\n\t\t\t\t\t}\n\t\t\t\t\tclose(eventChan)\n\t\t\t\t\treturn\n\t\t\t\tcase <-time.After(time.Duration(after) * time.Millisecond):\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t\teventChan <- ProviderEvent{Type: EventError, Error: retryErr}\n\t\t\tclose(eventChan)\n\t\t\treturn\n\t\t}\n\t}()\n\n\treturn eventChan\n}\n\nfunc (c *copilotClient) shouldRetry(attempts int, err error) (bool, int64, error) {\n\tvar apierr *openai.Error\n\tif !errors.As(err, &apierr) {\n\t\treturn false, 0, err\n\t}\n\n\t// Check for token expiration (401 Unauthorized)\n\tif apierr.StatusCode == 401 {\n\t\t// Try to refresh the bearer token\n\t\tvar githubToken string\n\n\t\t// 1. Environment variable\n\t\tgithubToken = os.Getenv(\"GITHUB_TOKEN\")\n\n\t\t// 2. API key from options\n\t\tif githubToken == \"\" {\n\t\t\tgithubToken = c.providerOptions.apiKey\n\t\t}\n\n\t\t// 3. Standard GitHub CLI/Copilot locations\n\t\tif githubToken == \"\" {\n\t\t\tvar err error\n\t\t\tgithubToken, err = config.LoadGitHubToken()\n\t\t\tif err != nil {\n\t\t\t\tlogging.Debug(\"Failed to load GitHub token from standard locations during retry\", \"error\", err)\n\t\t\t}\n\t\t}\n\n\t\tif githubToken != \"\" {\n\t\t\tnewBearerToken, tokenErr := c.exchangeGitHubToken(githubToken)\n\t\t\tif tokenErr == nil {\n\t\t\t\tc.options.bearerToken = newBearerToken\n\t\t\t\t// Update the client with the new token\n\t\t\t\t// Note: This is a simplified approach. In a production system,\n\t\t\t\t// you might want to recreate the entire client with the new token\n\t\t\t\tlogging.Info(\"Refreshed Copilot bearer token\")\n\t\t\t\treturn true, 1000, nil // Retry immediately with new token\n\t\t\t}\n\t\t\tlogging.Error(\"Failed to refresh Copilot bearer token\", \"error\", tokenErr)\n\t\t}\n\t\treturn false, 0, fmt.Errorf(\"authentication failed: %w\", err)\n\t}\n\tlogging.Debug(\"Copilot API Error\", \"status\", apierr.StatusCode, \"headers\", apierr.Response.Header, \"body\", apierr.RawJSON())\n\n\tif apierr.StatusCode != 429 && apierr.StatusCode != 500 {\n\t\treturn false, 0, err\n\t}\n\n\tif apierr.StatusCode == 500 {\n\t\tlogging.Warn(\"Copilot API returned 500 error, retrying\", \"error\", err)\n\t}\n\n\tif attempts > maxRetries {\n\t\treturn false, 0, fmt.Errorf(\"maximum retry attempts reached for rate limit: %d retries\", maxRetries)\n\t}\n\n\tretryMs := 0\n\tretryAfterValues := apierr.Response.Header.Values(\"Retry-After\")\n\n\tbackoffMs := 2000 * (1 << (attempts - 1))\n\tjitterMs := int(float64(backoffMs) * 0.2)\n\tretryMs = backoffMs + jitterMs\n\tif len(retryAfterValues) > 0 {\n\t\tif _, err := fmt.Sscanf(retryAfterValues[0], \"%d\", &retryMs); err == nil {\n\t\t\tretryMs = retryMs * 1000\n\t\t}\n\t}\n\treturn true, int64(retryMs), nil\n}\n\nfunc (c *copilotClient) toolCalls(completion openai.ChatCompletion) []message.ToolCall {\n\tvar toolCalls []message.ToolCall\n\n\tif len(completion.Choices) > 0 && len(completion.Choices[0].Message.ToolCalls) > 0 {\n\t\tfor _, call := range completion.Choices[0].Message.ToolCalls {\n\t\t\ttoolCall := message.ToolCall{\n\t\t\t\tID: call.ID,\n\t\t\t\tName: call.Function.Name,\n\t\t\t\tInput: call.Function.Arguments,\n\t\t\t\tType: \"function\",\n\t\t\t\tFinished: true,\n\t\t\t}\n\t\t\ttoolCalls = append(toolCalls, toolCall)\n\t\t}\n\t}\n\n\treturn toolCalls\n}\n\nfunc (c *copilotClient) usage(completion openai.ChatCompletion) TokenUsage {\n\tcachedTokens := completion.Usage.PromptTokensDetails.CachedTokens\n\tinputTokens := completion.Usage.PromptTokens - cachedTokens\n\n\treturn TokenUsage{\n\t\tInputTokens: inputTokens,\n\t\tOutputTokens: completion.Usage.CompletionTokens,\n\t\tCacheCreationTokens: 0, // GitHub Copilot doesn't provide this directly\n\t\tCacheReadTokens: cachedTokens,\n\t}\n}\n\nfunc WithCopilotReasoningEffort(effort string) CopilotOption {\n\treturn func(options *copilotOptions) {\n\t\tdefaultReasoningEffort := \"medium\"\n\t\tswitch effort {\n\t\tcase \"low\", \"medium\", \"high\":\n\t\t\tdefaultReasoningEffort = effort\n\t\tdefault:\n\t\t\tlogging.Warn(\"Invalid reasoning effort, using default: medium\")\n\t\t}\n\t\toptions.reasoningEffort = defaultReasoningEffort\n\t}\n}\n\nfunc WithCopilotExtraHeaders(headers map[string]string) CopilotOption {\n\treturn func(options *copilotOptions) {\n\t\toptions.extraHeaders = headers\n\t}\n}\n\nfunc WithCopilotBearerToken(bearerToken string) CopilotOption {\n\treturn func(options *copilotOptions) {\n\t\toptions.bearerToken = bearerToken\n\t}\n}\n\n"], ["/opencode/internal/tui/components/dialog/custom_commands.go", "package dialog\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"regexp\"\n\t\"strings\"\n\n\ttea \"github.com/charmbracelet/bubbletea\"\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/tui/util\"\n)\n\n// Command prefix constants\nconst (\n\tUserCommandPrefix = \"user:\"\n\tProjectCommandPrefix = \"project:\"\n)\n\n// namedArgPattern is a regex pattern to find named arguments in the format $NAME\nvar namedArgPattern = regexp.MustCompile(`\\$([A-Z][A-Z0-9_]*)`)\n\n// LoadCustomCommands loads custom commands from both XDG_CONFIG_HOME and project data directory\nfunc LoadCustomCommands() ([]Command, error) {\n\tcfg := config.Get()\n\tif cfg == nil {\n\t\treturn nil, fmt.Errorf(\"config not loaded\")\n\t}\n\n\tvar commands []Command\n\n\t// Load user commands from XDG_CONFIG_HOME/opencode/commands\n\txdgConfigHome := os.Getenv(\"XDG_CONFIG_HOME\")\n\tif xdgConfigHome == \"\" {\n\t\t// Default to ~/.config if XDG_CONFIG_HOME is not set\n\t\thome, err := os.UserHomeDir()\n\t\tif err == nil {\n\t\t\txdgConfigHome = filepath.Join(home, \".config\")\n\t\t}\n\t}\n\n\tif xdgConfigHome != \"\" {\n\t\tuserCommandsDir := filepath.Join(xdgConfigHome, \"opencode\", \"commands\")\n\t\tuserCommands, err := loadCommandsFromDir(userCommandsDir, UserCommandPrefix)\n\t\tif err != nil {\n\t\t\t// Log error but continue - we'll still try to load other commands\n\t\t\tfmt.Printf(\"Warning: failed to load user commands from XDG_CONFIG_HOME: %v\\n\", err)\n\t\t} else {\n\t\t\tcommands = append(commands, userCommands...)\n\t\t}\n\t}\n\n\t// Load commands from $HOME/.opencode/commands\n\thome, err := os.UserHomeDir()\n\tif err == nil {\n\t\thomeCommandsDir := filepath.Join(home, \".opencode\", \"commands\")\n\t\thomeCommands, err := loadCommandsFromDir(homeCommandsDir, UserCommandPrefix)\n\t\tif err != nil {\n\t\t\t// Log error but continue - we'll still try to load other commands\n\t\t\tfmt.Printf(\"Warning: failed to load home commands: %v\\n\", err)\n\t\t} else {\n\t\t\tcommands = append(commands, homeCommands...)\n\t\t}\n\t}\n\n\t// Load project commands from data directory\n\tprojectCommandsDir := filepath.Join(cfg.Data.Directory, \"commands\")\n\tprojectCommands, err := loadCommandsFromDir(projectCommandsDir, ProjectCommandPrefix)\n\tif err != nil {\n\t\t// Log error but return what we have so far\n\t\tfmt.Printf(\"Warning: failed to load project commands: %v\\n\", err)\n\t} else {\n\t\tcommands = append(commands, projectCommands...)\n\t}\n\n\treturn commands, nil\n}\n\n// loadCommandsFromDir loads commands from a specific directory with the given prefix\nfunc loadCommandsFromDir(commandsDir string, prefix string) ([]Command, error) {\n\t// Check if the commands directory exists\n\tif _, err := os.Stat(commandsDir); os.IsNotExist(err) {\n\t\t// Create the commands directory if it doesn't exist\n\t\tif err := os.MkdirAll(commandsDir, 0755); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to create commands directory %s: %w\", commandsDir, err)\n\t\t}\n\t\t// Return empty list since we just created the directory\n\t\treturn []Command{}, nil\n\t}\n\n\tvar commands []Command\n\n\t// Walk through the commands directory and load all .md files\n\terr := filepath.Walk(commandsDir, func(path string, info os.FileInfo, err error) error {\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Skip directories\n\t\tif info.IsDir() {\n\t\t\treturn nil\n\t\t}\n\n\t\t// Only process markdown files\n\t\tif !strings.HasSuffix(strings.ToLower(info.Name()), \".md\") {\n\t\t\treturn nil\n\t\t}\n\n\t\t// Read the file content\n\t\tcontent, err := os.ReadFile(path)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to read command file %s: %w\", path, err)\n\t\t}\n\n\t\t// Get the command ID from the file name without the .md extension\n\t\tcommandID := strings.TrimSuffix(info.Name(), filepath.Ext(info.Name()))\n\n\t\t// Get relative path from commands directory\n\t\trelPath, err := filepath.Rel(commandsDir, path)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to get relative path for %s: %w\", path, err)\n\t\t}\n\n\t\t// Create the command ID from the relative path\n\t\t// Replace directory separators with colons\n\t\tcommandIDPath := strings.ReplaceAll(filepath.Dir(relPath), string(filepath.Separator), \":\")\n\t\tif commandIDPath != \".\" {\n\t\t\tcommandID = commandIDPath + \":\" + commandID\n\t\t}\n\n\t\t// Create a command\n\t\tcommand := Command{\n\t\t\tID: prefix + commandID,\n\t\t\tTitle: prefix + commandID,\n\t\t\tDescription: fmt.Sprintf(\"Custom command from %s\", relPath),\n\t\t\tHandler: func(cmd Command) tea.Cmd {\n\t\t\t\tcommandContent := string(content)\n\n\t\t\t\t// Check for named arguments\n\t\t\t\tmatches := namedArgPattern.FindAllStringSubmatch(commandContent, -1)\n\t\t\t\tif len(matches) > 0 {\n\t\t\t\t\t// Extract unique argument names\n\t\t\t\t\targNames := make([]string, 0)\n\t\t\t\t\targMap := make(map[string]bool)\n\n\t\t\t\t\tfor _, match := range matches {\n\t\t\t\t\t\targName := match[1] // Group 1 is the name without $\n\t\t\t\t\t\tif !argMap[argName] {\n\t\t\t\t\t\t\targMap[argName] = true\n\t\t\t\t\t\t\targNames = append(argNames, argName)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\t// Show multi-arguments dialog for all named arguments\n\t\t\t\t\treturn util.CmdHandler(ShowMultiArgumentsDialogMsg{\n\t\t\t\t\t\tCommandID: cmd.ID,\n\t\t\t\t\t\tContent: commandContent,\n\t\t\t\t\t\tArgNames: argNames,\n\t\t\t\t\t})\n\t\t\t\t}\n\n\t\t\t\t// No arguments needed, run command directly\n\t\t\t\treturn util.CmdHandler(CommandRunCustomMsg{\n\t\t\t\t\tContent: commandContent,\n\t\t\t\t\tArgs: nil, // No arguments\n\t\t\t\t})\n\t\t\t},\n\t\t}\n\n\t\tcommands = append(commands, command)\n\t\treturn nil\n\t})\n\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to load custom commands from %s: %w\", commandsDir, err)\n\t}\n\n\treturn commands, nil\n}\n\n// CommandRunCustomMsg is sent when a custom command is executed\ntype CommandRunCustomMsg struct {\n\tContent string\n\tArgs map[string]string // Map of argument names to values\n}\n"], ["/opencode/internal/llm/provider/anthropic.go", "package provider\n\nimport (\n\t\"context\"\n\t\"encoding/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/anthropics/anthropic-sdk-go\"\n\t\"github.com/anthropics/anthropic-sdk-go/bedrock\"\n\t\"github.com/anthropics/anthropic-sdk-go/option\"\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/llm/models\"\n\ttoolsPkg \"github.com/opencode-ai/opencode/internal/llm/tools\"\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n\t\"github.com/opencode-ai/opencode/internal/message\"\n)\n\ntype anthropicOptions struct {\n\tuseBedrock bool\n\tdisableCache bool\n\tshouldThink func(userMessage string) bool\n}\n\ntype AnthropicOption func(*anthropicOptions)\n\ntype anthropicClient struct {\n\tproviderOptions providerClientOptions\n\toptions anthropicOptions\n\tclient anthropic.Client\n}\n\ntype AnthropicClient ProviderClient\n\nfunc newAnthropicClient(opts providerClientOptions) AnthropicClient {\n\tanthropicOpts := anthropicOptions{}\n\tfor _, o := range opts.anthropicOptions {\n\t\to(&anthropicOpts)\n\t}\n\n\tanthropicClientOptions := []option.RequestOption{}\n\tif opts.apiKey != \"\" {\n\t\tanthropicClientOptions = append(anthropicClientOptions, option.WithAPIKey(opts.apiKey))\n\t}\n\tif anthropicOpts.useBedrock {\n\t\tanthropicClientOptions = append(anthropicClientOptions, bedrock.WithLoadDefaultConfig(context.Background()))\n\t}\n\n\tclient := anthropic.NewClient(anthropicClientOptions...)\n\treturn &anthropicClient{\n\t\tproviderOptions: opts,\n\t\toptions: anthropicOpts,\n\t\tclient: client,\n\t}\n}\n\nfunc (a *anthropicClient) convertMessages(messages []message.Message) (anthropicMessages []anthropic.MessageParam) {\n\tfor i, msg := range messages {\n\t\tcache := false\n\t\tif i > len(messages)-3 {\n\t\t\tcache = true\n\t\t}\n\t\tswitch msg.Role {\n\t\tcase message.User:\n\t\t\tcontent := anthropic.NewTextBlock(msg.Content().String())\n\t\t\tif cache && !a.options.disableCache {\n\t\t\t\tcontent.OfText.CacheControl = anthropic.CacheControlEphemeralParam{\n\t\t\t\t\tType: \"ephemeral\",\n\t\t\t\t}\n\t\t\t}\n\t\t\tvar contentBlocks []anthropic.ContentBlockParamUnion\n\t\t\tcontentBlocks = append(contentBlocks, content)\n\t\t\tfor _, binaryContent := range msg.BinaryContent() {\n\t\t\t\tbase64Image := binaryContent.String(models.ProviderAnthropic)\n\t\t\t\timageBlock := anthropic.NewImageBlockBase64(binaryContent.MIMEType, base64Image)\n\t\t\t\tcontentBlocks = append(contentBlocks, imageBlock)\n\t\t\t}\n\t\t\tanthropicMessages = append(anthropicMessages, anthropic.NewUserMessage(contentBlocks...))\n\n\t\tcase message.Assistant:\n\t\t\tblocks := []anthropic.ContentBlockParamUnion{}\n\t\t\tif msg.Content().String() != \"\" {\n\t\t\t\tcontent := anthropic.NewTextBlock(msg.Content().String())\n\t\t\t\tif cache && !a.options.disableCache {\n\t\t\t\t\tcontent.OfText.CacheControl = anthropic.CacheControlEphemeralParam{\n\t\t\t\t\t\tType: \"ephemeral\",\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tblocks = append(blocks, content)\n\t\t\t}\n\n\t\t\tfor _, toolCall := range msg.ToolCalls() {\n\t\t\t\tvar inputMap map[string]any\n\t\t\t\terr := json.Unmarshal([]byte(toolCall.Input), &inputMap)\n\t\t\t\tif err != nil {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tblocks = append(blocks, anthropic.NewToolUseBlock(toolCall.ID, inputMap, toolCall.Name))\n\t\t\t}\n\n\t\t\tif len(blocks) == 0 {\n\t\t\t\tlogging.Warn(\"There is a message without content, investigate, this should not happen\")\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tanthropicMessages = append(anthropicMessages, anthropic.NewAssistantMessage(blocks...))\n\n\t\tcase message.Tool:\n\t\t\tresults := make([]anthropic.ContentBlockParamUnion, len(msg.ToolResults()))\n\t\t\tfor i, toolResult := range msg.ToolResults() {\n\t\t\t\tresults[i] = anthropic.NewToolResultBlock(toolResult.ToolCallID, toolResult.Content, toolResult.IsError)\n\t\t\t}\n\t\t\tanthropicMessages = append(anthropicMessages, anthropic.NewUserMessage(results...))\n\t\t}\n\t}\n\treturn\n}\n\nfunc (a *anthropicClient) convertTools(tools []toolsPkg.BaseTool) []anthropic.ToolUnionParam {\n\tanthropicTools := make([]anthropic.ToolUnionParam, len(tools))\n\n\tfor i, tool := range tools {\n\t\tinfo := tool.Info()\n\t\ttoolParam := anthropic.ToolParam{\n\t\t\tName: info.Name,\n\t\t\tDescription: anthropic.String(info.Description),\n\t\t\tInputSchema: anthropic.ToolInputSchemaParam{\n\t\t\t\tProperties: info.Parameters,\n\t\t\t\t// TODO: figure out how we can tell claude the required fields?\n\t\t\t},\n\t\t}\n\n\t\tif i == len(tools)-1 && !a.options.disableCache {\n\t\t\ttoolParam.CacheControl = anthropic.CacheControlEphemeralParam{\n\t\t\t\tType: \"ephemeral\",\n\t\t\t}\n\t\t}\n\n\t\tanthropicTools[i] = anthropic.ToolUnionParam{OfTool: &toolParam}\n\t}\n\n\treturn anthropicTools\n}\n\nfunc (a *anthropicClient) finishReason(reason string) message.FinishReason {\n\tswitch reason {\n\tcase \"end_turn\":\n\t\treturn message.FinishReasonEndTurn\n\tcase \"max_tokens\":\n\t\treturn message.FinishReasonMaxTokens\n\tcase \"tool_use\":\n\t\treturn message.FinishReasonToolUse\n\tcase \"stop_sequence\":\n\t\treturn message.FinishReasonEndTurn\n\tdefault:\n\t\treturn message.FinishReasonUnknown\n\t}\n}\n\nfunc (a *anthropicClient) preparedMessages(messages []anthropic.MessageParam, tools []anthropic.ToolUnionParam) anthropic.MessageNewParams {\n\tvar thinkingParam anthropic.ThinkingConfigParamUnion\n\tlastMessage := messages[len(messages)-1]\n\tisUser := lastMessage.Role == anthropic.MessageParamRoleUser\n\tmessageContent := \"\"\n\ttemperature := anthropic.Float(0)\n\tif isUser {\n\t\tfor _, m := range lastMessage.Content {\n\t\t\tif m.OfText != nil && m.OfText.Text != \"\" {\n\t\t\t\tmessageContent = m.OfText.Text\n\t\t\t}\n\t\t}\n\t\tif messageContent != \"\" && a.options.shouldThink != nil && a.options.shouldThink(messageContent) {\n\t\t\tthinkingParam = anthropic.ThinkingConfigParamOfEnabled(int64(float64(a.providerOptions.maxTokens) * 0.8))\n\t\t\ttemperature = anthropic.Float(1)\n\t\t}\n\t}\n\n\treturn anthropic.MessageNewParams{\n\t\tModel: anthropic.Model(a.providerOptions.model.APIModel),\n\t\tMaxTokens: a.providerOptions.maxTokens,\n\t\tTemperature: temperature,\n\t\tMessages: messages,\n\t\tTools: tools,\n\t\tThinking: thinkingParam,\n\t\tSystem: []anthropic.TextBlockParam{\n\t\t\t{\n\t\t\t\tText: a.providerOptions.systemMessage,\n\t\t\t\tCacheControl: anthropic.CacheControlEphemeralParam{\n\t\t\t\t\tType: \"ephemeral\",\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n}\n\nfunc (a *anthropicClient) send(ctx context.Context, messages []message.Message, tools []toolsPkg.BaseTool) (resposne *ProviderResponse, err error) {\n\tpreparedMessages := a.preparedMessages(a.convertMessages(messages), a.convertTools(tools))\n\tcfg := config.Get()\n\tif cfg.Debug {\n\t\tjsonData, _ := json.Marshal(preparedMessages)\n\t\tlogging.Debug(\"Prepared messages\", \"messages\", string(jsonData))\n\t}\n\n\tattempts := 0\n\tfor {\n\t\tattempts++\n\t\tanthropicResponse, err := a.client.Messages.New(\n\t\t\tctx,\n\t\t\tpreparedMessages,\n\t\t)\n\t\t// If there is an error we are going to see if we can retry the call\n\t\tif err != nil {\n\t\t\tlogging.Error(\"Error in Anthropic API call\", \"error\", err)\n\t\t\tretry, after, retryErr := a.shouldRetry(attempts, err)\n\t\t\tif retryErr != nil {\n\t\t\t\treturn nil, retryErr\n\t\t\t}\n\t\t\tif retry {\n\t\t\t\tlogging.WarnPersist(fmt.Sprintf(\"Retrying due to rate limit... attempt %d of %d\", attempts, maxRetries), logging.PersistTimeArg, time.Millisecond*time.Duration(after+100))\n\t\t\t\tselect {\n\t\t\t\tcase <-ctx.Done():\n\t\t\t\t\treturn nil, ctx.Err()\n\t\t\t\tcase <-time.After(time.Duration(after) * time.Millisecond):\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn nil, retryErr\n\t\t}\n\n\t\tcontent := \"\"\n\t\tfor _, block := range anthropicResponse.Content {\n\t\t\tif text, ok := block.AsAny().(anthropic.TextBlock); ok {\n\t\t\t\tcontent += text.Text\n\t\t\t}\n\t\t}\n\n\t\treturn &ProviderResponse{\n\t\t\tContent: content,\n\t\t\tToolCalls: a.toolCalls(*anthropicResponse),\n\t\t\tUsage: a.usage(*anthropicResponse),\n\t\t}, nil\n\t}\n}\n\nfunc (a *anthropicClient) stream(ctx context.Context, messages []message.Message, tools []toolsPkg.BaseTool) <-chan ProviderEvent {\n\tpreparedMessages := a.preparedMessages(a.convertMessages(messages), a.convertTools(tools))\n\tcfg := config.Get()\n\n\tvar sessionId string\n\trequestSeqId := (len(messages) + 1) / 2\n\tif cfg.Debug {\n\t\tif sid, ok := ctx.Value(toolsPkg.SessionIDContextKey).(string); ok {\n\t\t\tsessionId = sid\n\t\t}\n\t\tjsonData, _ := json.Marshal(preparedMessages)\n\t\tif sessionId != \"\" {\n\t\t\tfilepath := logging.WriteRequestMessageJson(sessionId, requestSeqId, preparedMessages)\n\t\t\tlogging.Debug(\"Prepared messages\", \"filepath\", filepath)\n\t\t} else {\n\t\t\tlogging.Debug(\"Prepared messages\", \"messages\", string(jsonData))\n\t\t}\n\n\t}\n\tattempts := 0\n\teventChan := make(chan ProviderEvent)\n\tgo func() {\n\t\tfor {\n\t\t\tattempts++\n\t\t\tanthropicStream := a.client.Messages.NewStreaming(\n\t\t\t\tctx,\n\t\t\t\tpreparedMessages,\n\t\t\t)\n\t\t\taccumulatedMessage := anthropic.Message{}\n\n\t\t\tcurrentToolCallID := \"\"\n\t\t\tfor anthropicStream.Next() {\n\t\t\t\tevent := anthropicStream.Current()\n\t\t\t\terr := accumulatedMessage.Accumulate(event)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlogging.Warn(\"Error accumulating message\", \"error\", err)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tswitch event := event.AsAny().(type) {\n\t\t\t\tcase anthropic.ContentBlockStartEvent:\n\t\t\t\t\tif event.ContentBlock.Type == \"text\" {\n\t\t\t\t\t\teventChan <- ProviderEvent{Type: EventContentStart}\n\t\t\t\t\t} else if event.ContentBlock.Type == \"tool_use\" {\n\t\t\t\t\t\tcurrentToolCallID = event.ContentBlock.ID\n\t\t\t\t\t\teventChan <- ProviderEvent{\n\t\t\t\t\t\t\tType: EventToolUseStart,\n\t\t\t\t\t\t\tToolCall: &message.ToolCall{\n\t\t\t\t\t\t\t\tID: event.ContentBlock.ID,\n\t\t\t\t\t\t\t\tName: event.ContentBlock.Name,\n\t\t\t\t\t\t\t\tFinished: false,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\tcase anthropic.ContentBlockDeltaEvent:\n\t\t\t\t\tif event.Delta.Type == \"thinking_delta\" && event.Delta.Thinking != \"\" {\n\t\t\t\t\t\teventChan <- ProviderEvent{\n\t\t\t\t\t\t\tType: EventThinkingDelta,\n\t\t\t\t\t\t\tThinking: event.Delta.Thinking,\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if event.Delta.Type == \"text_delta\" && event.Delta.Text != \"\" {\n\t\t\t\t\t\teventChan <- ProviderEvent{\n\t\t\t\t\t\t\tType: EventContentDelta,\n\t\t\t\t\t\t\tContent: event.Delta.Text,\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if event.Delta.Type == \"input_json_delta\" {\n\t\t\t\t\t\tif currentToolCallID != \"\" {\n\t\t\t\t\t\t\teventChan <- ProviderEvent{\n\t\t\t\t\t\t\t\tType: EventToolUseDelta,\n\t\t\t\t\t\t\t\tToolCall: &message.ToolCall{\n\t\t\t\t\t\t\t\t\tID: currentToolCallID,\n\t\t\t\t\t\t\t\t\tFinished: false,\n\t\t\t\t\t\t\t\t\tInput: event.Delta.JSON.PartialJSON.Raw(),\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\tcase anthropic.ContentBlockStopEvent:\n\t\t\t\t\tif currentToolCallID != \"\" {\n\t\t\t\t\t\teventChan <- ProviderEvent{\n\t\t\t\t\t\t\tType: EventToolUseStop,\n\t\t\t\t\t\t\tToolCall: &message.ToolCall{\n\t\t\t\t\t\t\t\tID: currentToolCallID,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcurrentToolCallID = \"\"\n\t\t\t\t\t} else {\n\t\t\t\t\t\teventChan <- ProviderEvent{Type: EventContentStop}\n\t\t\t\t\t}\n\n\t\t\t\tcase anthropic.MessageStopEvent:\n\t\t\t\t\tcontent := \"\"\n\t\t\t\t\tfor _, block := range accumulatedMessage.Content {\n\t\t\t\t\t\tif text, ok := block.AsAny().(anthropic.TextBlock); ok {\n\t\t\t\t\t\t\tcontent += text.Text\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\teventChan <- ProviderEvent{\n\t\t\t\t\t\tType: EventComplete,\n\t\t\t\t\t\tResponse: &ProviderResponse{\n\t\t\t\t\t\t\tContent: content,\n\t\t\t\t\t\t\tToolCalls: a.toolCalls(accumulatedMessage),\n\t\t\t\t\t\t\tUsage: a.usage(accumulatedMessage),\n\t\t\t\t\t\t\tFinishReason: a.finishReason(string(accumulatedMessage.StopReason)),\n\t\t\t\t\t\t},\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\terr := anthropicStream.Err()\n\t\t\tif err == nil || errors.Is(err, io.EOF) {\n\t\t\t\tclose(eventChan)\n\t\t\t\treturn\n\t\t\t}\n\t\t\t// If there is an error we are going to see if we can retry the call\n\t\t\tretry, after, retryErr := a.shouldRetry(attempts, err)\n\t\t\tif retryErr != nil {\n\t\t\t\teventChan <- ProviderEvent{Type: EventError, Error: retryErr}\n\t\t\t\tclose(eventChan)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif retry {\n\t\t\t\tlogging.WarnPersist(fmt.Sprintf(\"Retrying due to rate limit... attempt %d of %d\", attempts, maxRetries), logging.PersistTimeArg, time.Millisecond*time.Duration(after+100))\n\t\t\t\tselect {\n\t\t\t\tcase <-ctx.Done():\n\t\t\t\t\t// context cancelled\n\t\t\t\t\tif ctx.Err() != nil {\n\t\t\t\t\t\teventChan <- ProviderEvent{Type: EventError, Error: ctx.Err()}\n\t\t\t\t\t}\n\t\t\t\t\tclose(eventChan)\n\t\t\t\t\treturn\n\t\t\t\tcase <-time.After(time.Duration(after) * time.Millisecond):\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t\tif ctx.Err() != nil {\n\t\t\t\teventChan <- ProviderEvent{Type: EventError, Error: ctx.Err()}\n\t\t\t}\n\n\t\t\tclose(eventChan)\n\t\t\treturn\n\t\t}\n\t}()\n\treturn eventChan\n}\n\nfunc (a *anthropicClient) shouldRetry(attempts int, err error) (bool, int64, error) {\n\tvar apierr *anthropic.Error\n\tif !errors.As(err, &apierr) {\n\t\treturn false, 0, err\n\t}\n\n\tif apierr.StatusCode != 429 && apierr.StatusCode != 529 {\n\t\treturn false, 0, err\n\t}\n\n\tif attempts > maxRetries {\n\t\treturn false, 0, fmt.Errorf(\"maximum retry attempts reached for rate limit: %d retries\", maxRetries)\n\t}\n\n\tretryMs := 0\n\tretryAfterValues := apierr.Response.Header.Values(\"Retry-After\")\n\n\tbackoffMs := 2000 * (1 << (attempts - 1))\n\tjitterMs := int(float64(backoffMs) * 0.2)\n\tretryMs = backoffMs + jitterMs\n\tif len(retryAfterValues) > 0 {\n\t\tif _, err := fmt.Sscanf(retryAfterValues[0], \"%d\", &retryMs); err == nil {\n\t\t\tretryMs = retryMs * 1000\n\t\t}\n\t}\n\treturn true, int64(retryMs), nil\n}\n\nfunc (a *anthropicClient) toolCalls(msg anthropic.Message) []message.ToolCall {\n\tvar toolCalls []message.ToolCall\n\n\tfor _, block := range msg.Content {\n\t\tswitch variant := block.AsAny().(type) {\n\t\tcase anthropic.ToolUseBlock:\n\t\t\ttoolCall := message.ToolCall{\n\t\t\t\tID: variant.ID,\n\t\t\t\tName: variant.Name,\n\t\t\t\tInput: string(variant.Input),\n\t\t\t\tType: string(variant.Type),\n\t\t\t\tFinished: true,\n\t\t\t}\n\t\t\ttoolCalls = append(toolCalls, toolCall)\n\t\t}\n\t}\n\n\treturn toolCalls\n}\n\nfunc (a *anthropicClient) usage(msg anthropic.Message) TokenUsage {\n\treturn TokenUsage{\n\t\tInputTokens: msg.Usage.InputTokens,\n\t\tOutputTokens: msg.Usage.OutputTokens,\n\t\tCacheCreationTokens: msg.Usage.CacheCreationInputTokens,\n\t\tCacheReadTokens: msg.Usage.CacheReadInputTokens,\n\t}\n}\n\nfunc WithAnthropicBedrock(useBedrock bool) AnthropicOption {\n\treturn func(options *anthropicOptions) {\n\t\toptions.useBedrock = useBedrock\n\t}\n}\n\nfunc WithAnthropicDisableCache() AnthropicOption {\n\treturn func(options *anthropicOptions) {\n\t\toptions.disableCache = true\n\t}\n}\n\nfunc DefaultShouldThinkFn(s string) bool {\n\treturn strings.Contains(strings.ToLower(s), \"think\")\n}\n\nfunc WithAnthropicShouldThinkFn(fn func(string) bool) AnthropicOption {\n\treturn func(options *anthropicOptions) {\n\t\toptions.shouldThink = fn\n\t}\n}\n"], ["/opencode/internal/lsp/protocol/pattern_interfaces.go", "package protocol\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n)\n\n// PatternInfo is an interface for types that represent glob patterns\ntype PatternInfo interface {\n\tGetPattern() string\n\tGetBasePath() string\n\tisPattern() // marker method\n}\n\n// StringPattern implements PatternInfo for string patterns\ntype StringPattern struct {\n\tPattern string\n}\n\nfunc (p StringPattern) GetPattern() string { return p.Pattern }\nfunc (p StringPattern) GetBasePath() string { return \"\" }\nfunc (p StringPattern) isPattern() {}\n\n// RelativePatternInfo implements PatternInfo for RelativePattern\ntype RelativePatternInfo struct {\n\tRP RelativePattern\n\tBasePath string\n}\n\nfunc (p RelativePatternInfo) GetPattern() string { return string(p.RP.Pattern) }\nfunc (p RelativePatternInfo) GetBasePath() string { return p.BasePath }\nfunc (p RelativePatternInfo) isPattern() {}\n\n// AsPattern converts GlobPattern to a PatternInfo object\nfunc (g *GlobPattern) AsPattern() (PatternInfo, error) {\n\tif g.Value == nil {\n\t\treturn nil, fmt.Errorf(\"nil pattern\")\n\t}\n\n\tswitch v := g.Value.(type) {\n\tcase string:\n\t\treturn StringPattern{Pattern: v}, nil\n\tcase RelativePattern:\n\t\t// Handle BaseURI which could be string or DocumentUri\n\t\tbasePath := \"\"\n\t\tswitch baseURI := v.BaseURI.Value.(type) {\n\t\tcase string:\n\t\t\tbasePath = strings.TrimPrefix(baseURI, \"file://\")\n\t\tcase DocumentUri:\n\t\t\tbasePath = strings.TrimPrefix(string(baseURI), \"file://\")\n\t\tdefault:\n\t\t\treturn nil, fmt.Errorf(\"unknown BaseURI type: %T\", v.BaseURI.Value)\n\t\t}\n\t\treturn RelativePatternInfo{RP: v, BasePath: basePath}, nil\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"unknown pattern type: %T\", g.Value)\n\t}\n}\n"], ["/opencode/internal/lsp/methods.go", "// Generated code. Do not edit\npackage lsp\n\nimport (\n\t\"context\"\n\n\t\"github.com/opencode-ai/opencode/internal/lsp/protocol\"\n)\n\n// Implementation sends a textDocument/implementation request to the LSP server.\n// A request to resolve the implementation locations of a symbol at a given text document position. The request's parameter is of type TextDocumentPositionParams the response is of type Definition or a Thenable that resolves to such.\nfunc (c *Client) Implementation(ctx context.Context, params protocol.ImplementationParams) (protocol.Or_Result_textDocument_implementation, error) {\n\tvar result protocol.Or_Result_textDocument_implementation\n\terr := c.Call(ctx, \"textDocument/implementation\", params, &result)\n\treturn result, err\n}\n\n// TypeDefinition sends a textDocument/typeDefinition request to the LSP server.\n// A request to resolve the type definition locations of a symbol at a given text document position. The request's parameter is of type TextDocumentPositionParams the response is of type Definition or a Thenable that resolves to such.\nfunc (c *Client) TypeDefinition(ctx context.Context, params protocol.TypeDefinitionParams) (protocol.Or_Result_textDocument_typeDefinition, error) {\n\tvar result protocol.Or_Result_textDocument_typeDefinition\n\terr := c.Call(ctx, \"textDocument/typeDefinition\", params, &result)\n\treturn result, err\n}\n\n// DocumentColor sends a textDocument/documentColor request to the LSP server.\n// A request to list all color symbols found in a given text document. The request's parameter is of type DocumentColorParams the response is of type ColorInformation ColorInformation[] or a Thenable that resolves to such.\nfunc (c *Client) DocumentColor(ctx context.Context, params protocol.DocumentColorParams) ([]protocol.ColorInformation, error) {\n\tvar result []protocol.ColorInformation\n\terr := c.Call(ctx, \"textDocument/documentColor\", params, &result)\n\treturn result, err\n}\n\n// ColorPresentation sends a textDocument/colorPresentation request to the LSP server.\n// A request to list all presentation for a color. The request's parameter is of type ColorPresentationParams the response is of type ColorInformation ColorInformation[] or a Thenable that resolves to such.\nfunc (c *Client) ColorPresentation(ctx context.Context, params protocol.ColorPresentationParams) ([]protocol.ColorPresentation, error) {\n\tvar result []protocol.ColorPresentation\n\terr := c.Call(ctx, \"textDocument/colorPresentation\", params, &result)\n\treturn result, err\n}\n\n// FoldingRange sends a textDocument/foldingRange request to the LSP server.\n// A request to provide folding ranges in a document. The request's parameter is of type FoldingRangeParams, the response is of type FoldingRangeList or a Thenable that resolves to such.\nfunc (c *Client) FoldingRange(ctx context.Context, params protocol.FoldingRangeParams) ([]protocol.FoldingRange, error) {\n\tvar result []protocol.FoldingRange\n\terr := c.Call(ctx, \"textDocument/foldingRange\", params, &result)\n\treturn result, err\n}\n\n// Declaration sends a textDocument/declaration request to the LSP server.\n// A request to resolve the type definition locations of a symbol at a given text document position. The request's parameter is of type TextDocumentPositionParams the response is of type Declaration or a typed array of DeclarationLink or a Thenable that resolves to such.\nfunc (c *Client) Declaration(ctx context.Context, params protocol.DeclarationParams) (protocol.Or_Result_textDocument_declaration, error) {\n\tvar result protocol.Or_Result_textDocument_declaration\n\terr := c.Call(ctx, \"textDocument/declaration\", params, &result)\n\treturn result, err\n}\n\n// SelectionRange sends a textDocument/selectionRange request to the LSP server.\n// A request to provide selection ranges in a document. The request's parameter is of type SelectionRangeParams, the response is of type SelectionRange SelectionRange[] or a Thenable that resolves to such.\nfunc (c *Client) SelectionRange(ctx context.Context, params protocol.SelectionRangeParams) ([]protocol.SelectionRange, error) {\n\tvar result []protocol.SelectionRange\n\terr := c.Call(ctx, \"textDocument/selectionRange\", params, &result)\n\treturn result, err\n}\n\n// PrepareCallHierarchy sends a textDocument/prepareCallHierarchy request to the LSP server.\n// A request to result a CallHierarchyItem in a document at a given position. Can be used as an input to an incoming or outgoing call hierarchy. Since 3.16.0\nfunc (c *Client) PrepareCallHierarchy(ctx context.Context, params protocol.CallHierarchyPrepareParams) ([]protocol.CallHierarchyItem, error) {\n\tvar result []protocol.CallHierarchyItem\n\terr := c.Call(ctx, \"textDocument/prepareCallHierarchy\", params, &result)\n\treturn result, err\n}\n\n// IncomingCalls sends a callHierarchy/incomingCalls request to the LSP server.\n// A request to resolve the incoming calls for a given CallHierarchyItem. Since 3.16.0\nfunc (c *Client) IncomingCalls(ctx context.Context, params protocol.CallHierarchyIncomingCallsParams) ([]protocol.CallHierarchyIncomingCall, error) {\n\tvar result []protocol.CallHierarchyIncomingCall\n\terr := c.Call(ctx, \"callHierarchy/incomingCalls\", params, &result)\n\treturn result, err\n}\n\n// OutgoingCalls sends a callHierarchy/outgoingCalls request to the LSP server.\n// A request to resolve the outgoing calls for a given CallHierarchyItem. Since 3.16.0\nfunc (c *Client) OutgoingCalls(ctx context.Context, params protocol.CallHierarchyOutgoingCallsParams) ([]protocol.CallHierarchyOutgoingCall, error) {\n\tvar result []protocol.CallHierarchyOutgoingCall\n\terr := c.Call(ctx, \"callHierarchy/outgoingCalls\", params, &result)\n\treturn result, err\n}\n\n// SemanticTokensFull sends a textDocument/semanticTokens/full request to the LSP server.\n// Since 3.16.0\nfunc (c *Client) SemanticTokensFull(ctx context.Context, params protocol.SemanticTokensParams) (protocol.SemanticTokens, error) {\n\tvar result protocol.SemanticTokens\n\terr := c.Call(ctx, \"textDocument/semanticTokens/full\", params, &result)\n\treturn result, err\n}\n\n// SemanticTokensFullDelta sends a textDocument/semanticTokens/full/delta request to the LSP server.\n// Since 3.16.0\nfunc (c *Client) SemanticTokensFullDelta(ctx context.Context, params protocol.SemanticTokensDeltaParams) (protocol.Or_Result_textDocument_semanticTokens_full_delta, error) {\n\tvar result protocol.Or_Result_textDocument_semanticTokens_full_delta\n\terr := c.Call(ctx, \"textDocument/semanticTokens/full/delta\", params, &result)\n\treturn result, err\n}\n\n// SemanticTokensRange sends a textDocument/semanticTokens/range request to the LSP server.\n// Since 3.16.0\nfunc (c *Client) SemanticTokensRange(ctx context.Context, params protocol.SemanticTokensRangeParams) (protocol.SemanticTokens, error) {\n\tvar result protocol.SemanticTokens\n\terr := c.Call(ctx, \"textDocument/semanticTokens/range\", params, &result)\n\treturn result, err\n}\n\n// LinkedEditingRange sends a textDocument/linkedEditingRange request to the LSP server.\n// A request to provide ranges that can be edited together. Since 3.16.0\nfunc (c *Client) LinkedEditingRange(ctx context.Context, params protocol.LinkedEditingRangeParams) (protocol.LinkedEditingRanges, error) {\n\tvar result protocol.LinkedEditingRanges\n\terr := c.Call(ctx, \"textDocument/linkedEditingRange\", params, &result)\n\treturn result, err\n}\n\n// WillCreateFiles sends a workspace/willCreateFiles request to the LSP server.\n// The will create files request is sent from the client to the server before files are actually created as long as the creation is triggered from within the client. The request can return a WorkspaceEdit which will be applied to workspace before the files are created. Hence the WorkspaceEdit can not manipulate the content of the file to be created. Since 3.16.0\nfunc (c *Client) WillCreateFiles(ctx context.Context, params protocol.CreateFilesParams) (protocol.WorkspaceEdit, error) {\n\tvar result protocol.WorkspaceEdit\n\terr := c.Call(ctx, \"workspace/willCreateFiles\", params, &result)\n\treturn result, err\n}\n\n// WillRenameFiles sends a workspace/willRenameFiles request to the LSP server.\n// The will rename files request is sent from the client to the server before files are actually renamed as long as the rename is triggered from within the client. Since 3.16.0\nfunc (c *Client) WillRenameFiles(ctx context.Context, params protocol.RenameFilesParams) (protocol.WorkspaceEdit, error) {\n\tvar result protocol.WorkspaceEdit\n\terr := c.Call(ctx, \"workspace/willRenameFiles\", params, &result)\n\treturn result, err\n}\n\n// WillDeleteFiles sends a workspace/willDeleteFiles request to the LSP server.\n// The did delete files notification is sent from the client to the server when files were deleted from within the client. Since 3.16.0\nfunc (c *Client) WillDeleteFiles(ctx context.Context, params protocol.DeleteFilesParams) (protocol.WorkspaceEdit, error) {\n\tvar result protocol.WorkspaceEdit\n\terr := c.Call(ctx, \"workspace/willDeleteFiles\", params, &result)\n\treturn result, err\n}\n\n// Moniker sends a textDocument/moniker request to the LSP server.\n// A request to get the moniker of a symbol at a given text document position. The request parameter is of type TextDocumentPositionParams. The response is of type Moniker Moniker[] or null.\nfunc (c *Client) Moniker(ctx context.Context, params protocol.MonikerParams) ([]protocol.Moniker, error) {\n\tvar result []protocol.Moniker\n\terr := c.Call(ctx, \"textDocument/moniker\", params, &result)\n\treturn result, err\n}\n\n// PrepareTypeHierarchy sends a textDocument/prepareTypeHierarchy request to the LSP server.\n// A request to result a TypeHierarchyItem in a document at a given position. Can be used as an input to a subtypes or supertypes type hierarchy. Since 3.17.0\nfunc (c *Client) PrepareTypeHierarchy(ctx context.Context, params protocol.TypeHierarchyPrepareParams) ([]protocol.TypeHierarchyItem, error) {\n\tvar result []protocol.TypeHierarchyItem\n\terr := c.Call(ctx, \"textDocument/prepareTypeHierarchy\", params, &result)\n\treturn result, err\n}\n\n// Supertypes sends a typeHierarchy/supertypes request to the LSP server.\n// A request to resolve the supertypes for a given TypeHierarchyItem. Since 3.17.0\nfunc (c *Client) Supertypes(ctx context.Context, params protocol.TypeHierarchySupertypesParams) ([]protocol.TypeHierarchyItem, error) {\n\tvar result []protocol.TypeHierarchyItem\n\terr := c.Call(ctx, \"typeHierarchy/supertypes\", params, &result)\n\treturn result, err\n}\n\n// Subtypes sends a typeHierarchy/subtypes request to the LSP server.\n// A request to resolve the subtypes for a given TypeHierarchyItem. Since 3.17.0\nfunc (c *Client) Subtypes(ctx context.Context, params protocol.TypeHierarchySubtypesParams) ([]protocol.TypeHierarchyItem, error) {\n\tvar result []protocol.TypeHierarchyItem\n\terr := c.Call(ctx, \"typeHierarchy/subtypes\", params, &result)\n\treturn result, err\n}\n\n// InlineValue sends a textDocument/inlineValue request to the LSP server.\n// A request to provide inline values in a document. The request's parameter is of type InlineValueParams, the response is of type InlineValue InlineValue[] or a Thenable that resolves to such. Since 3.17.0\nfunc (c *Client) InlineValue(ctx context.Context, params protocol.InlineValueParams) ([]protocol.InlineValue, error) {\n\tvar result []protocol.InlineValue\n\terr := c.Call(ctx, \"textDocument/inlineValue\", params, &result)\n\treturn result, err\n}\n\n// InlayHint sends a textDocument/inlayHint request to the LSP server.\n// A request to provide inlay hints in a document. The request's parameter is of type InlayHintsParams, the response is of type InlayHint InlayHint[] or a Thenable that resolves to such. Since 3.17.0\nfunc (c *Client) InlayHint(ctx context.Context, params protocol.InlayHintParams) ([]protocol.InlayHint, error) {\n\tvar result []protocol.InlayHint\n\terr := c.Call(ctx, \"textDocument/inlayHint\", params, &result)\n\treturn result, err\n}\n\n// Resolve sends a inlayHint/resolve request to the LSP server.\n// A request to resolve additional properties for an inlay hint. The request's parameter is of type InlayHint, the response is of type InlayHint or a Thenable that resolves to such. Since 3.17.0\nfunc (c *Client) Resolve(ctx context.Context, params protocol.InlayHint) (protocol.InlayHint, error) {\n\tvar result protocol.InlayHint\n\terr := c.Call(ctx, \"inlayHint/resolve\", params, &result)\n\treturn result, err\n}\n\n// Diagnostic sends a textDocument/diagnostic request to the LSP server.\n// The document diagnostic request definition. Since 3.17.0\nfunc (c *Client) Diagnostic(ctx context.Context, params protocol.DocumentDiagnosticParams) (protocol.DocumentDiagnosticReport, error) {\n\tvar result protocol.DocumentDiagnosticReport\n\terr := c.Call(ctx, \"textDocument/diagnostic\", params, &result)\n\treturn result, err\n}\n\n// DiagnosticWorkspace sends a workspace/diagnostic request to the LSP server.\n// The workspace diagnostic request definition. Since 3.17.0\nfunc (c *Client) DiagnosticWorkspace(ctx context.Context, params protocol.WorkspaceDiagnosticParams) (protocol.WorkspaceDiagnosticReport, error) {\n\tvar result protocol.WorkspaceDiagnosticReport\n\terr := c.Call(ctx, \"workspace/diagnostic\", params, &result)\n\treturn result, err\n}\n\n// InlineCompletion sends a textDocument/inlineCompletion request to the LSP server.\n// A request to provide inline completions in a document. The request's parameter is of type InlineCompletionParams, the response is of type InlineCompletion InlineCompletion[] or a Thenable that resolves to such. Since 3.18.0 PROPOSED\nfunc (c *Client) InlineCompletion(ctx context.Context, params protocol.InlineCompletionParams) (protocol.Or_Result_textDocument_inlineCompletion, error) {\n\tvar result protocol.Or_Result_textDocument_inlineCompletion\n\terr := c.Call(ctx, \"textDocument/inlineCompletion\", params, &result)\n\treturn result, err\n}\n\n// TextDocumentContent sends a workspace/textDocumentContent request to the LSP server.\n// The workspace/textDocumentContent request is sent from the client to the server to request the content of a text document. Since 3.18.0 PROPOSED\nfunc (c *Client) TextDocumentContent(ctx context.Context, params protocol.TextDocumentContentParams) (string, error) {\n\tvar result string\n\terr := c.Call(ctx, \"workspace/textDocumentContent\", params, &result)\n\treturn result, err\n}\n\n// Initialize sends a initialize request to the LSP server.\n// The initialize request is sent from the client to the server. It is sent once as the request after starting up the server. The requests parameter is of type InitializeParams the response if of type InitializeResult of a Thenable that resolves to such.\nfunc (c *Client) Initialize(ctx context.Context, params protocol.ParamInitialize) (protocol.InitializeResult, error) {\n\tvar result protocol.InitializeResult\n\terr := c.Call(ctx, \"initialize\", params, &result)\n\treturn result, err\n}\n\n// Shutdown sends a shutdown request to the LSP server.\n// A shutdown request is sent from the client to the server. It is sent once when the client decides to shutdown the server. The only notification that is sent after a shutdown request is the exit event.\nfunc (c *Client) Shutdown(ctx context.Context) error {\n\treturn c.Call(ctx, \"shutdown\", nil, nil)\n}\n\n// WillSaveWaitUntil sends a textDocument/willSaveWaitUntil request to the LSP server.\n// A document will save request is sent from the client to the server before the document is actually saved. The request can return an array of TextEdits which will be applied to the text document before it is saved. Please note that clients might drop results if computing the text edits took too long or if a server constantly fails on this request. This is done to keep the save fast and reliable.\nfunc (c *Client) WillSaveWaitUntil(ctx context.Context, params protocol.WillSaveTextDocumentParams) ([]protocol.TextEdit, error) {\n\tvar result []protocol.TextEdit\n\terr := c.Call(ctx, \"textDocument/willSaveWaitUntil\", params, &result)\n\treturn result, err\n}\n\n// Completion sends a textDocument/completion request to the LSP server.\n// Request to request completion at a given text document position. The request's parameter is of type TextDocumentPosition the response is of type CompletionItem CompletionItem[] or CompletionList or a Thenable that resolves to such. The request can delay the computation of the CompletionItem.detail detail and CompletionItem.documentation documentation properties to the completionItem/resolve request. However, properties that are needed for the initial sorting and filtering, like sortText, filterText, insertText, and textEdit, must not be changed during resolve.\nfunc (c *Client) Completion(ctx context.Context, params protocol.CompletionParams) (protocol.Or_Result_textDocument_completion, error) {\n\tvar result protocol.Or_Result_textDocument_completion\n\terr := c.Call(ctx, \"textDocument/completion\", params, &result)\n\treturn result, err\n}\n\n// ResolveCompletionItem sends a completionItem/resolve request to the LSP server.\n// Request to resolve additional information for a given completion item.The request's parameter is of type CompletionItem the response is of type CompletionItem or a Thenable that resolves to such.\nfunc (c *Client) ResolveCompletionItem(ctx context.Context, params protocol.CompletionItem) (protocol.CompletionItem, error) {\n\tvar result protocol.CompletionItem\n\terr := c.Call(ctx, \"completionItem/resolve\", params, &result)\n\treturn result, err\n}\n\n// Hover sends a textDocument/hover request to the LSP server.\n// Request to request hover information at a given text document position. The request's parameter is of type TextDocumentPosition the response is of type Hover or a Thenable that resolves to such.\nfunc (c *Client) Hover(ctx context.Context, params protocol.HoverParams) (protocol.Hover, error) {\n\tvar result protocol.Hover\n\terr := c.Call(ctx, \"textDocument/hover\", params, &result)\n\treturn result, err\n}\n\n// SignatureHelp sends a textDocument/signatureHelp request to the LSP server.\nfunc (c *Client) SignatureHelp(ctx context.Context, params protocol.SignatureHelpParams) (protocol.SignatureHelp, error) {\n\tvar result protocol.SignatureHelp\n\terr := c.Call(ctx, \"textDocument/signatureHelp\", params, &result)\n\treturn result, err\n}\n\n// Definition sends a textDocument/definition request to the LSP server.\n// A request to resolve the definition location of a symbol at a given text document position. The request's parameter is of type TextDocumentPosition the response is of either type Definition or a typed array of DefinitionLink or a Thenable that resolves to such.\nfunc (c *Client) Definition(ctx context.Context, params protocol.DefinitionParams) (protocol.Or_Result_textDocument_definition, error) {\n\tvar result protocol.Or_Result_textDocument_definition\n\terr := c.Call(ctx, \"textDocument/definition\", params, &result)\n\treturn result, err\n}\n\n// References sends a textDocument/references request to the LSP server.\n// A request to resolve project-wide references for the symbol denoted by the given text document position. The request's parameter is of type ReferenceParams the response is of type Location Location[] or a Thenable that resolves to such.\nfunc (c *Client) References(ctx context.Context, params protocol.ReferenceParams) ([]protocol.Location, error) {\n\tvar result []protocol.Location\n\terr := c.Call(ctx, \"textDocument/references\", params, &result)\n\treturn result, err\n}\n\n// DocumentHighlight sends a textDocument/documentHighlight request to the LSP server.\n// Request to resolve a DocumentHighlight for a given text document position. The request's parameter is of type TextDocumentPosition the request response is an array of type DocumentHighlight or a Thenable that resolves to such.\nfunc (c *Client) DocumentHighlight(ctx context.Context, params protocol.DocumentHighlightParams) ([]protocol.DocumentHighlight, error) {\n\tvar result []protocol.DocumentHighlight\n\terr := c.Call(ctx, \"textDocument/documentHighlight\", params, &result)\n\treturn result, err\n}\n\n// DocumentSymbol sends a textDocument/documentSymbol request to the LSP server.\n// A request to list all symbols found in a given text document. The request's parameter is of type TextDocumentIdentifier the response is of type SymbolInformation SymbolInformation[] or a Thenable that resolves to such.\nfunc (c *Client) DocumentSymbol(ctx context.Context, params protocol.DocumentSymbolParams) (protocol.Or_Result_textDocument_documentSymbol, error) {\n\tvar result protocol.Or_Result_textDocument_documentSymbol\n\terr := c.Call(ctx, \"textDocument/documentSymbol\", params, &result)\n\treturn result, err\n}\n\n// CodeAction sends a textDocument/codeAction request to the LSP server.\n// A request to provide commands for the given text document and range.\nfunc (c *Client) CodeAction(ctx context.Context, params protocol.CodeActionParams) ([]protocol.Or_Result_textDocument_codeAction_Item0_Elem, error) {\n\tvar result []protocol.Or_Result_textDocument_codeAction_Item0_Elem\n\terr := c.Call(ctx, \"textDocument/codeAction\", params, &result)\n\treturn result, err\n}\n\n// ResolveCodeAction sends a codeAction/resolve request to the LSP server.\n// Request to resolve additional information for a given code action.The request's parameter is of type CodeAction the response is of type CodeAction or a Thenable that resolves to such.\nfunc (c *Client) ResolveCodeAction(ctx context.Context, params protocol.CodeAction) (protocol.CodeAction, error) {\n\tvar result protocol.CodeAction\n\terr := c.Call(ctx, \"codeAction/resolve\", params, &result)\n\treturn result, err\n}\n\n// Symbol sends a workspace/symbol request to the LSP server.\n// A request to list project-wide symbols matching the query string given by the WorkspaceSymbolParams. The response is of type SymbolInformation SymbolInformation[] or a Thenable that resolves to such. Since 3.17.0 - support for WorkspaceSymbol in the returned data. Clients need to advertise support for WorkspaceSymbols via the client capability workspace.symbol.resolveSupport.\nfunc (c *Client) Symbol(ctx context.Context, params protocol.WorkspaceSymbolParams) (protocol.Or_Result_workspace_symbol, error) {\n\tvar result protocol.Or_Result_workspace_symbol\n\terr := c.Call(ctx, \"workspace/symbol\", params, &result)\n\treturn result, err\n}\n\n// ResolveWorkspaceSymbol sends a workspaceSymbol/resolve request to the LSP server.\n// A request to resolve the range inside the workspace symbol's location. Since 3.17.0\nfunc (c *Client) ResolveWorkspaceSymbol(ctx context.Context, params protocol.WorkspaceSymbol) (protocol.WorkspaceSymbol, error) {\n\tvar result protocol.WorkspaceSymbol\n\terr := c.Call(ctx, \"workspaceSymbol/resolve\", params, &result)\n\treturn result, err\n}\n\n// CodeLens sends a textDocument/codeLens request to the LSP server.\n// A request to provide code lens for the given text document.\nfunc (c *Client) CodeLens(ctx context.Context, params protocol.CodeLensParams) ([]protocol.CodeLens, error) {\n\tvar result []protocol.CodeLens\n\terr := c.Call(ctx, \"textDocument/codeLens\", params, &result)\n\treturn result, err\n}\n\n// ResolveCodeLens sends a codeLens/resolve request to the LSP server.\n// A request to resolve a command for a given code lens.\nfunc (c *Client) ResolveCodeLens(ctx context.Context, params protocol.CodeLens) (protocol.CodeLens, error) {\n\tvar result protocol.CodeLens\n\terr := c.Call(ctx, \"codeLens/resolve\", params, &result)\n\treturn result, err\n}\n\n// DocumentLink sends a textDocument/documentLink request to the LSP server.\n// A request to provide document links\nfunc (c *Client) DocumentLink(ctx context.Context, params protocol.DocumentLinkParams) ([]protocol.DocumentLink, error) {\n\tvar result []protocol.DocumentLink\n\terr := c.Call(ctx, \"textDocument/documentLink\", params, &result)\n\treturn result, err\n}\n\n// ResolveDocumentLink sends a documentLink/resolve request to the LSP server.\n// Request to resolve additional information for a given document link. The request's parameter is of type DocumentLink the response is of type DocumentLink or a Thenable that resolves to such.\nfunc (c *Client) ResolveDocumentLink(ctx context.Context, params protocol.DocumentLink) (protocol.DocumentLink, error) {\n\tvar result protocol.DocumentLink\n\terr := c.Call(ctx, \"documentLink/resolve\", params, &result)\n\treturn result, err\n}\n\n// Formatting sends a textDocument/formatting request to the LSP server.\n// A request to format a whole document.\nfunc (c *Client) Formatting(ctx context.Context, params protocol.DocumentFormattingParams) ([]protocol.TextEdit, error) {\n\tvar result []protocol.TextEdit\n\terr := c.Call(ctx, \"textDocument/formatting\", params, &result)\n\treturn result, err\n}\n\n// RangeFormatting sends a textDocument/rangeFormatting request to the LSP server.\n// A request to format a range in a document.\nfunc (c *Client) RangeFormatting(ctx context.Context, params protocol.DocumentRangeFormattingParams) ([]protocol.TextEdit, error) {\n\tvar result []protocol.TextEdit\n\terr := c.Call(ctx, \"textDocument/rangeFormatting\", params, &result)\n\treturn result, err\n}\n\n// RangesFormatting sends a textDocument/rangesFormatting request to the LSP server.\n// A request to format ranges in a document. Since 3.18.0 PROPOSED\nfunc (c *Client) RangesFormatting(ctx context.Context, params protocol.DocumentRangesFormattingParams) ([]protocol.TextEdit, error) {\n\tvar result []protocol.TextEdit\n\terr := c.Call(ctx, \"textDocument/rangesFormatting\", params, &result)\n\treturn result, err\n}\n\n// OnTypeFormatting sends a textDocument/onTypeFormatting request to the LSP server.\n// A request to format a document on type.\nfunc (c *Client) OnTypeFormatting(ctx context.Context, params protocol.DocumentOnTypeFormattingParams) ([]protocol.TextEdit, error) {\n\tvar result []protocol.TextEdit\n\terr := c.Call(ctx, \"textDocument/onTypeFormatting\", params, &result)\n\treturn result, err\n}\n\n// Rename sends a textDocument/rename request to the LSP server.\n// A request to rename a symbol.\nfunc (c *Client) Rename(ctx context.Context, params protocol.RenameParams) (protocol.WorkspaceEdit, error) {\n\tvar result protocol.WorkspaceEdit\n\terr := c.Call(ctx, \"textDocument/rename\", params, &result)\n\treturn result, err\n}\n\n// PrepareRename sends a textDocument/prepareRename request to the LSP server.\n// A request to test and perform the setup necessary for a rename. Since 3.16 - support for default behavior\nfunc (c *Client) PrepareRename(ctx context.Context, params protocol.PrepareRenameParams) (protocol.PrepareRenameResult, error) {\n\tvar result protocol.PrepareRenameResult\n\terr := c.Call(ctx, \"textDocument/prepareRename\", params, &result)\n\treturn result, err\n}\n\n// ExecuteCommand sends a workspace/executeCommand request to the LSP server.\n// A request send from the client to the server to execute a command. The request might return a workspace edit which the client will apply to the workspace.\nfunc (c *Client) ExecuteCommand(ctx context.Context, params protocol.ExecuteCommandParams) (any, error) {\n\tvar result any\n\terr := c.Call(ctx, \"workspace/executeCommand\", params, &result)\n\treturn result, err\n}\n\n// DidChangeWorkspaceFolders sends a workspace/didChangeWorkspaceFolders notification to the LSP server.\n// The workspace/didChangeWorkspaceFolders notification is sent from the client to the server when the workspace folder configuration changes.\nfunc (c *Client) DidChangeWorkspaceFolders(ctx context.Context, params protocol.DidChangeWorkspaceFoldersParams) error {\n\treturn c.Notify(ctx, \"workspace/didChangeWorkspaceFolders\", params)\n}\n\n// WorkDoneProgressCancel sends a window/workDoneProgress/cancel notification to the LSP server.\n// The window/workDoneProgress/cancel notification is sent from the client to the server to cancel a progress initiated on the server side.\nfunc (c *Client) WorkDoneProgressCancel(ctx context.Context, params protocol.WorkDoneProgressCancelParams) error {\n\treturn c.Notify(ctx, \"window/workDoneProgress/cancel\", params)\n}\n\n// DidCreateFiles sends a workspace/didCreateFiles notification to the LSP server.\n// The did create files notification is sent from the client to the server when files were created from within the client. Since 3.16.0\nfunc (c *Client) DidCreateFiles(ctx context.Context, params protocol.CreateFilesParams) error {\n\treturn c.Notify(ctx, \"workspace/didCreateFiles\", params)\n}\n\n// DidRenameFiles sends a workspace/didRenameFiles notification to the LSP server.\n// The did rename files notification is sent from the client to the server when files were renamed from within the client. Since 3.16.0\nfunc (c *Client) DidRenameFiles(ctx context.Context, params protocol.RenameFilesParams) error {\n\treturn c.Notify(ctx, \"workspace/didRenameFiles\", params)\n}\n\n// DidDeleteFiles sends a workspace/didDeleteFiles notification to the LSP server.\n// The will delete files request is sent from the client to the server before files are actually deleted as long as the deletion is triggered from within the client. Since 3.16.0\nfunc (c *Client) DidDeleteFiles(ctx context.Context, params protocol.DeleteFilesParams) error {\n\treturn c.Notify(ctx, \"workspace/didDeleteFiles\", params)\n}\n\n// DidOpenNotebookDocument sends a notebookDocument/didOpen notification to the LSP server.\n// A notification sent when a notebook opens. Since 3.17.0\nfunc (c *Client) DidOpenNotebookDocument(ctx context.Context, params protocol.DidOpenNotebookDocumentParams) error {\n\treturn c.Notify(ctx, \"notebookDocument/didOpen\", params)\n}\n\n// DidChangeNotebookDocument sends a notebookDocument/didChange notification to the LSP server.\nfunc (c *Client) DidChangeNotebookDocument(ctx context.Context, params protocol.DidChangeNotebookDocumentParams) error {\n\treturn c.Notify(ctx, \"notebookDocument/didChange\", params)\n}\n\n// DidSaveNotebookDocument sends a notebookDocument/didSave notification to the LSP server.\n// A notification sent when a notebook document is saved. Since 3.17.0\nfunc (c *Client) DidSaveNotebookDocument(ctx context.Context, params protocol.DidSaveNotebookDocumentParams) error {\n\treturn c.Notify(ctx, \"notebookDocument/didSave\", params)\n}\n\n// DidCloseNotebookDocument sends a notebookDocument/didClose notification to the LSP server.\n// A notification sent when a notebook closes. Since 3.17.0\nfunc (c *Client) DidCloseNotebookDocument(ctx context.Context, params protocol.DidCloseNotebookDocumentParams) error {\n\treturn c.Notify(ctx, \"notebookDocument/didClose\", params)\n}\n\n// Initialized sends a initialized notification to the LSP server.\n// The initialized notification is sent from the client to the server after the client is fully initialized and the server is allowed to send requests from the server to the client.\nfunc (c *Client) Initialized(ctx context.Context, params protocol.InitializedParams) error {\n\treturn c.Notify(ctx, \"initialized\", params)\n}\n\n// Exit sends a exit notification to the LSP server.\n// The exit event is sent from the client to the server to ask the server to exit its process.\nfunc (c *Client) Exit(ctx context.Context) error {\n\treturn c.Notify(ctx, \"exit\", nil)\n}\n\n// DidChangeConfiguration sends a workspace/didChangeConfiguration notification to the LSP server.\n// The configuration change notification is sent from the client to the server when the client's configuration has changed. The notification contains the changed configuration as defined by the language client.\nfunc (c *Client) DidChangeConfiguration(ctx context.Context, params protocol.DidChangeConfigurationParams) error {\n\treturn c.Notify(ctx, \"workspace/didChangeConfiguration\", params)\n}\n\n// DidOpen sends a textDocument/didOpen notification to the LSP server.\n// The document open notification is sent from the client to the server to signal newly opened text documents. The document's truth is now managed by the client and the server must not try to read the document's truth using the document's uri. Open in this sense means it is managed by the client. It doesn't necessarily mean that its content is presented in an editor. An open notification must not be sent more than once without a corresponding close notification send before. This means open and close notification must be balanced and the max open count is one.\nfunc (c *Client) DidOpen(ctx context.Context, params protocol.DidOpenTextDocumentParams) error {\n\treturn c.Notify(ctx, \"textDocument/didOpen\", params)\n}\n\n// DidChange sends a textDocument/didChange notification to the LSP server.\n// The document change notification is sent from the client to the server to signal changes to a text document.\nfunc (c *Client) DidChange(ctx context.Context, params protocol.DidChangeTextDocumentParams) error {\n\treturn c.Notify(ctx, \"textDocument/didChange\", params)\n}\n\n// DidClose sends a textDocument/didClose notification to the LSP server.\n// The document close notification is sent from the client to the server when the document got closed in the client. The document's truth now exists where the document's uri points to (e.g. if the document's uri is a file uri the truth now exists on disk). As with the open notification the close notification is about managing the document's content. Receiving a close notification doesn't mean that the document was open in an editor before. A close notification requires a previous open notification to be sent.\nfunc (c *Client) DidClose(ctx context.Context, params protocol.DidCloseTextDocumentParams) error {\n\treturn c.Notify(ctx, \"textDocument/didClose\", params)\n}\n\n// DidSave sends a textDocument/didSave notification to the LSP server.\n// The document save notification is sent from the client to the server when the document got saved in the client.\nfunc (c *Client) DidSave(ctx context.Context, params protocol.DidSaveTextDocumentParams) error {\n\treturn c.Notify(ctx, \"textDocument/didSave\", params)\n}\n\n// WillSave sends a textDocument/willSave notification to the LSP server.\n// A document will save notification is sent from the client to the server before the document is actually saved.\nfunc (c *Client) WillSave(ctx context.Context, params protocol.WillSaveTextDocumentParams) error {\n\treturn c.Notify(ctx, \"textDocument/willSave\", params)\n}\n\n// DidChangeWatchedFiles sends a workspace/didChangeWatchedFiles notification to the LSP server.\n// The watched files notification is sent from the client to the server when the client detects changes to file watched by the language client.\nfunc (c *Client) DidChangeWatchedFiles(ctx context.Context, params protocol.DidChangeWatchedFilesParams) error {\n\treturn c.Notify(ctx, \"workspace/didChangeWatchedFiles\", params)\n}\n\n// SetTrace sends a $/setTrace notification to the LSP server.\nfunc (c *Client) SetTrace(ctx context.Context, params protocol.SetTraceParams) error {\n\treturn c.Notify(ctx, \"$/setTrace\", params)\n}\n\n// Progress sends a $/progress notification to the LSP server.\nfunc (c *Client) Progress(ctx context.Context, params protocol.ProgressParams) error {\n\treturn c.Notify(ctx, \"$/progress\", params)\n}\n"], ["/opencode/internal/lsp/util/edit.go", "package util\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"os\"\n\t\"sort\"\n\t\"strings\"\n\n\t\"github.com/opencode-ai/opencode/internal/lsp/protocol\"\n)\n\nfunc applyTextEdits(uri protocol.DocumentUri, edits []protocol.TextEdit) error {\n\tpath := strings.TrimPrefix(string(uri), \"file://\")\n\n\t// Read the file content\n\tcontent, err := os.ReadFile(path)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to read file: %w\", err)\n\t}\n\n\t// Detect line ending style\n\tvar lineEnding string\n\tif bytes.Contains(content, []byte(\"\\r\\n\")) {\n\t\tlineEnding = \"\\r\\n\"\n\t} else {\n\t\tlineEnding = \"\\n\"\n\t}\n\n\t// Track if file ends with a newline\n\tendsWithNewline := len(content) > 0 && bytes.HasSuffix(content, []byte(lineEnding))\n\n\t// Split into lines without the endings\n\tlines := strings.Split(string(content), lineEnding)\n\n\t// Check for overlapping edits\n\tfor i, edit1 := range edits {\n\t\tfor j := i + 1; j < len(edits); j++ {\n\t\t\tif rangesOverlap(edit1.Range, edits[j].Range) {\n\t\t\t\treturn fmt.Errorf(\"overlapping edits detected between edit %d and %d\", i, j)\n\t\t\t}\n\t\t}\n\t}\n\n\t// Sort edits in reverse order\n\tsortedEdits := make([]protocol.TextEdit, len(edits))\n\tcopy(sortedEdits, edits)\n\tsort.Slice(sortedEdits, func(i, j int) bool {\n\t\tif sortedEdits[i].Range.Start.Line != sortedEdits[j].Range.Start.Line {\n\t\t\treturn sortedEdits[i].Range.Start.Line > sortedEdits[j].Range.Start.Line\n\t\t}\n\t\treturn sortedEdits[i].Range.Start.Character > sortedEdits[j].Range.Start.Character\n\t})\n\n\t// Apply each edit\n\tfor _, edit := range sortedEdits {\n\t\tnewLines, err := applyTextEdit(lines, edit)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to apply edit: %w\", err)\n\t\t}\n\t\tlines = newLines\n\t}\n\n\t// Join lines with proper line endings\n\tvar newContent strings.Builder\n\tfor i, line := range lines {\n\t\tif i > 0 {\n\t\t\tnewContent.WriteString(lineEnding)\n\t\t}\n\t\tnewContent.WriteString(line)\n\t}\n\n\t// Only add a newline if the original file had one and we haven't already added it\n\tif endsWithNewline && !strings.HasSuffix(newContent.String(), lineEnding) {\n\t\tnewContent.WriteString(lineEnding)\n\t}\n\n\tif err := os.WriteFile(path, []byte(newContent.String()), 0o644); err != nil {\n\t\treturn fmt.Errorf(\"failed to write file: %w\", err)\n\t}\n\n\treturn nil\n}\n\nfunc applyTextEdit(lines []string, edit protocol.TextEdit) ([]string, error) {\n\tstartLine := int(edit.Range.Start.Line)\n\tendLine := int(edit.Range.End.Line)\n\tstartChar := int(edit.Range.Start.Character)\n\tendChar := int(edit.Range.End.Character)\n\n\t// Validate positions\n\tif startLine < 0 || startLine >= len(lines) {\n\t\treturn nil, fmt.Errorf(\"invalid start line: %d\", startLine)\n\t}\n\tif endLine < 0 || endLine >= len(lines) {\n\t\tendLine = len(lines) - 1\n\t}\n\n\t// Create result slice with initial capacity\n\tresult := make([]string, 0, len(lines))\n\n\t// Copy lines before edit\n\tresult = append(result, lines[:startLine]...)\n\n\t// Get the prefix of the start line\n\tstartLineContent := lines[startLine]\n\tif startChar < 0 || startChar > len(startLineContent) {\n\t\tstartChar = len(startLineContent)\n\t}\n\tprefix := startLineContent[:startChar]\n\n\t// Get the suffix of the end line\n\tendLineContent := lines[endLine]\n\tif endChar < 0 || endChar > len(endLineContent) {\n\t\tendChar = len(endLineContent)\n\t}\n\tsuffix := endLineContent[endChar:]\n\n\t// Handle the edit\n\tif edit.NewText == \"\" {\n\t\tif prefix+suffix != \"\" {\n\t\t\tresult = append(result, prefix+suffix)\n\t\t}\n\t} else {\n\t\t// Split new text into lines, being careful not to add extra newlines\n\t\t// newLines := strings.Split(strings.TrimRight(edit.NewText, \"\\n\"), \"\\n\")\n\t\tnewLines := strings.Split(edit.NewText, \"\\n\")\n\n\t\tif len(newLines) == 1 {\n\t\t\t// Single line change\n\t\t\tresult = append(result, prefix+newLines[0]+suffix)\n\t\t} else {\n\t\t\t// Multi-line change\n\t\t\tresult = append(result, prefix+newLines[0])\n\t\t\tresult = append(result, newLines[1:len(newLines)-1]...)\n\t\t\tresult = append(result, newLines[len(newLines)-1]+suffix)\n\t\t}\n\t}\n\n\t// Add remaining lines\n\tif endLine+1 < len(lines) {\n\t\tresult = append(result, lines[endLine+1:]...)\n\t}\n\n\treturn result, nil\n}\n\n// applyDocumentChange applies a DocumentChange (create/rename/delete operations)\nfunc applyDocumentChange(change protocol.DocumentChange) error {\n\tif change.CreateFile != nil {\n\t\tpath := strings.TrimPrefix(string(change.CreateFile.URI), \"file://\")\n\t\tif change.CreateFile.Options != nil {\n\t\t\tif change.CreateFile.Options.Overwrite {\n\t\t\t\t// Proceed with overwrite\n\t\t\t} else if change.CreateFile.Options.IgnoreIfExists {\n\t\t\t\tif _, err := os.Stat(path); err == nil {\n\t\t\t\t\treturn nil // File exists and we're ignoring it\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif err := os.WriteFile(path, []byte(\"\"), 0o644); err != nil {\n\t\t\treturn fmt.Errorf(\"failed to create file: %w\", err)\n\t\t}\n\t}\n\n\tif change.DeleteFile != nil {\n\t\tpath := strings.TrimPrefix(string(change.DeleteFile.URI), \"file://\")\n\t\tif change.DeleteFile.Options != nil && change.DeleteFile.Options.Recursive {\n\t\t\tif err := os.RemoveAll(path); err != nil {\n\t\t\t\treturn fmt.Errorf(\"failed to delete directory recursively: %w\", err)\n\t\t\t}\n\t\t} else {\n\t\t\tif err := os.Remove(path); err != nil {\n\t\t\t\treturn fmt.Errorf(\"failed to delete file: %w\", err)\n\t\t\t}\n\t\t}\n\t}\n\n\tif change.RenameFile != nil {\n\t\toldPath := strings.TrimPrefix(string(change.RenameFile.OldURI), \"file://\")\n\t\tnewPath := strings.TrimPrefix(string(change.RenameFile.NewURI), \"file://\")\n\t\tif change.RenameFile.Options != nil {\n\t\t\tif !change.RenameFile.Options.Overwrite {\n\t\t\t\tif _, err := os.Stat(newPath); err == nil {\n\t\t\t\t\treturn fmt.Errorf(\"target file already exists and overwrite is not allowed: %s\", newPath)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif err := os.Rename(oldPath, newPath); err != nil {\n\t\t\treturn fmt.Errorf(\"failed to rename file: %w\", err)\n\t\t}\n\t}\n\n\tif change.TextDocumentEdit != nil {\n\t\ttextEdits := make([]protocol.TextEdit, len(change.TextDocumentEdit.Edits))\n\t\tfor i, edit := range change.TextDocumentEdit.Edits {\n\t\t\tvar err error\n\t\t\ttextEdits[i], err = edit.AsTextEdit()\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"invalid edit type: %w\", err)\n\t\t\t}\n\t\t}\n\t\treturn applyTextEdits(change.TextDocumentEdit.TextDocument.URI, textEdits)\n\t}\n\n\treturn nil\n}\n\n// ApplyWorkspaceEdit applies the given WorkspaceEdit to the filesystem\nfunc ApplyWorkspaceEdit(edit protocol.WorkspaceEdit) error {\n\t// Handle Changes field\n\tfor uri, textEdits := range edit.Changes {\n\t\tif err := applyTextEdits(uri, textEdits); err != nil {\n\t\t\treturn fmt.Errorf(\"failed to apply text edits: %w\", err)\n\t\t}\n\t}\n\n\t// Handle DocumentChanges field\n\tfor _, change := range edit.DocumentChanges {\n\t\tif err := applyDocumentChange(change); err != nil {\n\t\t\treturn fmt.Errorf(\"failed to apply document change: %w\", err)\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc rangesOverlap(r1, r2 protocol.Range) bool {\n\tif r1.Start.Line > r2.End.Line || r2.Start.Line > r1.End.Line {\n\t\treturn false\n\t}\n\tif r1.Start.Line == r2.End.Line && r1.Start.Character > r2.End.Character {\n\t\treturn false\n\t}\n\tif r2.Start.Line == r1.End.Line && r2.Start.Character > r1.End.Character {\n\t\treturn false\n\t}\n\treturn true\n}\n"], ["/opencode/internal/config/config.go", "// Package config manages application configuration from various sources.\npackage config\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"log/slog\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"runtime\"\n\t\"strings\"\n\n\t\"github.com/opencode-ai/opencode/internal/llm/models\"\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n\t\"github.com/spf13/viper\"\n)\n\n// MCPType defines the type of MCP (Model Control Protocol) server.\ntype MCPType string\n\n// Supported MCP types\nconst (\n\tMCPStdio MCPType = \"stdio\"\n\tMCPSse MCPType = \"sse\"\n)\n\n// MCPServer defines the configuration for a Model Control Protocol server.\ntype MCPServer struct {\n\tCommand string `json:\"command\"`\n\tEnv []string `json:\"env\"`\n\tArgs []string `json:\"args\"`\n\tType MCPType `json:\"type\"`\n\tURL string `json:\"url\"`\n\tHeaders map[string]string `json:\"headers\"`\n}\n\ntype AgentName string\n\nconst (\n\tAgentCoder AgentName = \"coder\"\n\tAgentSummarizer AgentName = \"summarizer\"\n\tAgentTask AgentName = \"task\"\n\tAgentTitle AgentName = \"title\"\n)\n\n// Agent defines configuration for different LLM models and their token limits.\ntype Agent struct {\n\tModel models.ModelID `json:\"model\"`\n\tMaxTokens int64 `json:\"maxTokens\"`\n\tReasoningEffort string `json:\"reasoningEffort\"` // For openai models low,medium,heigh\n}\n\n// Provider defines configuration for an LLM provider.\ntype Provider struct {\n\tAPIKey string `json:\"apiKey\"`\n\tDisabled bool `json:\"disabled\"`\n}\n\n// Data defines storage configuration.\ntype Data struct {\n\tDirectory string `json:\"directory,omitempty\"`\n}\n\n// LSPConfig defines configuration for Language Server Protocol integration.\ntype LSPConfig struct {\n\tDisabled bool `json:\"enabled\"`\n\tCommand string `json:\"command\"`\n\tArgs []string `json:\"args\"`\n\tOptions any `json:\"options\"`\n}\n\n// TUIConfig defines the configuration for the Terminal User Interface.\ntype TUIConfig struct {\n\tTheme string `json:\"theme,omitempty\"`\n}\n\n// ShellConfig defines the configuration for the shell used by the bash tool.\ntype ShellConfig struct {\n\tPath string `json:\"path,omitempty\"`\n\tArgs []string `json:\"args,omitempty\"`\n}\n\n// Config is the main configuration structure for the application.\ntype Config struct {\n\tData Data `json:\"data\"`\n\tWorkingDir string `json:\"wd,omitempty\"`\n\tMCPServers map[string]MCPServer `json:\"mcpServers,omitempty\"`\n\tProviders map[models.ModelProvider]Provider `json:\"providers,omitempty\"`\n\tLSP map[string]LSPConfig `json:\"lsp,omitempty\"`\n\tAgents map[AgentName]Agent `json:\"agents,omitempty\"`\n\tDebug bool `json:\"debug,omitempty\"`\n\tDebugLSP bool `json:\"debugLSP,omitempty\"`\n\tContextPaths []string `json:\"contextPaths,omitempty\"`\n\tTUI TUIConfig `json:\"tui\"`\n\tShell ShellConfig `json:\"shell,omitempty\"`\n\tAutoCompact bool `json:\"autoCompact,omitempty\"`\n}\n\n// Application constants\nconst (\n\tdefaultDataDirectory = \".opencode\"\n\tdefaultLogLevel = \"info\"\n\tappName = \"opencode\"\n\n\tMaxTokensFallbackDefault = 4096\n)\n\nvar defaultContextPaths = []string{\n\t\".github/copilot-instructions.md\",\n\t\".cursorrules\",\n\t\".cursor/rules/\",\n\t\"CLAUDE.md\",\n\t\"CLAUDE.local.md\",\n\t\"opencode.md\",\n\t\"opencode.local.md\",\n\t\"OpenCode.md\",\n\t\"OpenCode.local.md\",\n\t\"OPENCODE.md\",\n\t\"OPENCODE.local.md\",\n}\n\n// Global configuration instance\nvar cfg *Config\n\n// Load initializes the configuration from environment variables and config files.\n// If debug is true, debug mode is enabled and log level is set to debug.\n// It returns an error if configuration loading fails.\nfunc Load(workingDir string, debug bool) (*Config, error) {\n\tif cfg != nil {\n\t\treturn cfg, nil\n\t}\n\n\tcfg = &Config{\n\t\tWorkingDir: workingDir,\n\t\tMCPServers: make(map[string]MCPServer),\n\t\tProviders: make(map[models.ModelProvider]Provider),\n\t\tLSP: make(map[string]LSPConfig),\n\t}\n\n\tconfigureViper()\n\tsetDefaults(debug)\n\n\t// Read global config\n\tif err := readConfig(viper.ReadInConfig()); err != nil {\n\t\treturn cfg, err\n\t}\n\n\t// Load and merge local config\n\tmergeLocalConfig(workingDir)\n\n\tsetProviderDefaults()\n\n\t// Apply configuration to the struct\n\tif err := viper.Unmarshal(cfg); err != nil {\n\t\treturn cfg, fmt.Errorf(\"failed to unmarshal config: %w\", err)\n\t}\n\n\tapplyDefaultValues()\n\tdefaultLevel := slog.LevelInfo\n\tif cfg.Debug {\n\t\tdefaultLevel = slog.LevelDebug\n\t}\n\tif os.Getenv(\"OPENCODE_DEV_DEBUG\") == \"true\" {\n\t\tloggingFile := fmt.Sprintf(\"%s/%s\", cfg.Data.Directory, \"debug.log\")\n\t\tmessagesPath := fmt.Sprintf(\"%s/%s\", cfg.Data.Directory, \"messages\")\n\n\t\t// if file does not exist create it\n\t\tif _, err := os.Stat(loggingFile); os.IsNotExist(err) {\n\t\t\tif err := os.MkdirAll(cfg.Data.Directory, 0o755); err != nil {\n\t\t\t\treturn cfg, fmt.Errorf(\"failed to create directory: %w\", err)\n\t\t\t}\n\t\t\tif _, err := os.Create(loggingFile); err != nil {\n\t\t\t\treturn cfg, fmt.Errorf(\"failed to create log file: %w\", err)\n\t\t\t}\n\t\t}\n\n\t\tif _, err := os.Stat(messagesPath); os.IsNotExist(err) {\n\t\t\tif err := os.MkdirAll(messagesPath, 0o756); err != nil {\n\t\t\t\treturn cfg, fmt.Errorf(\"failed to create directory: %w\", err)\n\t\t\t}\n\t\t}\n\t\tlogging.MessageDir = messagesPath\n\n\t\tsloggingFileWriter, err := os.OpenFile(loggingFile, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o666)\n\t\tif err != nil {\n\t\t\treturn cfg, fmt.Errorf(\"failed to open log file: %w\", err)\n\t\t}\n\t\t// Configure logger\n\t\tlogger := slog.New(slog.NewTextHandler(sloggingFileWriter, &slog.HandlerOptions{\n\t\t\tLevel: defaultLevel,\n\t\t}))\n\t\tslog.SetDefault(logger)\n\t} else {\n\t\t// Configure logger\n\t\tlogger := slog.New(slog.NewTextHandler(logging.NewWriter(), &slog.HandlerOptions{\n\t\t\tLevel: defaultLevel,\n\t\t}))\n\t\tslog.SetDefault(logger)\n\t}\n\n\t// Validate configuration\n\tif err := Validate(); err != nil {\n\t\treturn cfg, fmt.Errorf(\"config validation failed: %w\", err)\n\t}\n\n\tif cfg.Agents == nil {\n\t\tcfg.Agents = make(map[AgentName]Agent)\n\t}\n\n\t// Override the max tokens for title agent\n\tcfg.Agents[AgentTitle] = Agent{\n\t\tModel: cfg.Agents[AgentTitle].Model,\n\t\tMaxTokens: 80,\n\t}\n\treturn cfg, nil\n}\n\n// configureViper sets up viper's configuration paths and environment variables.\nfunc configureViper() {\n\tviper.SetConfigName(fmt.Sprintf(\".%s\", appName))\n\tviper.SetConfigType(\"json\")\n\tviper.AddConfigPath(\"$HOME\")\n\tviper.AddConfigPath(fmt.Sprintf(\"$XDG_CONFIG_HOME/%s\", appName))\n\tviper.AddConfigPath(fmt.Sprintf(\"$HOME/.config/%s\", appName))\n\tviper.SetEnvPrefix(strings.ToUpper(appName))\n\tviper.AutomaticEnv()\n}\n\n// setDefaults configures default values for configuration options.\nfunc setDefaults(debug bool) {\n\tviper.SetDefault(\"data.directory\", defaultDataDirectory)\n\tviper.SetDefault(\"contextPaths\", defaultContextPaths)\n\tviper.SetDefault(\"tui.theme\", \"opencode\")\n\tviper.SetDefault(\"autoCompact\", true)\n\n\t// Set default shell from environment or fallback to /bin/bash\n\tshellPath := os.Getenv(\"SHELL\")\n\tif shellPath == \"\" {\n\t\tshellPath = \"/bin/bash\"\n\t}\n\tviper.SetDefault(\"shell.path\", shellPath)\n\tviper.SetDefault(\"shell.args\", []string{\"-l\"})\n\n\tif debug {\n\t\tviper.SetDefault(\"debug\", true)\n\t\tviper.Set(\"log.level\", \"debug\")\n\t} else {\n\t\tviper.SetDefault(\"debug\", false)\n\t\tviper.SetDefault(\"log.level\", defaultLogLevel)\n\t}\n}\n\n// setProviderDefaults configures LLM provider defaults based on provider provided by\n// environment variables and configuration file.\nfunc setProviderDefaults() {\n\t// Set all API keys we can find in the environment\n\t// Note: Viper does not default if the json apiKey is \"\"\n\tif apiKey := os.Getenv(\"ANTHROPIC_API_KEY\"); apiKey != \"\" {\n\t\tviper.SetDefault(\"providers.anthropic.apiKey\", apiKey)\n\t}\n\tif apiKey := os.Getenv(\"OPENAI_API_KEY\"); apiKey != \"\" {\n\t\tviper.SetDefault(\"providers.openai.apiKey\", apiKey)\n\t}\n\tif apiKey := os.Getenv(\"GEMINI_API_KEY\"); apiKey != \"\" {\n\t\tviper.SetDefault(\"providers.gemini.apiKey\", apiKey)\n\t}\n\tif apiKey := os.Getenv(\"GROQ_API_KEY\"); apiKey != \"\" {\n\t\tviper.SetDefault(\"providers.groq.apiKey\", apiKey)\n\t}\n\tif apiKey := os.Getenv(\"OPENROUTER_API_KEY\"); apiKey != \"\" {\n\t\tviper.SetDefault(\"providers.openrouter.apiKey\", apiKey)\n\t}\n\tif apiKey := os.Getenv(\"XAI_API_KEY\"); apiKey != \"\" {\n\t\tviper.SetDefault(\"providers.xai.apiKey\", apiKey)\n\t}\n\tif apiKey := os.Getenv(\"AZURE_OPENAI_ENDPOINT\"); apiKey != \"\" {\n\t\t// api-key may be empty when using Entra ID credentials – that's okay\n\t\tviper.SetDefault(\"providers.azure.apiKey\", os.Getenv(\"AZURE_OPENAI_API_KEY\"))\n\t}\n\tif apiKey, err := LoadGitHubToken(); err == nil && apiKey != \"\" {\n\t\tviper.SetDefault(\"providers.copilot.apiKey\", apiKey)\n\t\tif viper.GetString(\"providers.copilot.apiKey\") == \"\" {\n\t\t\tviper.Set(\"providers.copilot.apiKey\", apiKey)\n\t\t}\n\t}\n\n\t// Use this order to set the default models\n\t// 1. Copilot\n\t// 2. Anthropic\n\t// 3. OpenAI\n\t// 4. Google Gemini\n\t// 5. Groq\n\t// 6. OpenRouter\n\t// 7. AWS Bedrock\n\t// 8. Azure\n\t// 9. Google Cloud VertexAI\n\n\t// copilot configuration\n\tif key := viper.GetString(\"providers.copilot.apiKey\"); strings.TrimSpace(key) != \"\" {\n\t\tviper.SetDefault(\"agents.coder.model\", models.CopilotGPT4o)\n\t\tviper.SetDefault(\"agents.summarizer.model\", models.CopilotGPT4o)\n\t\tviper.SetDefault(\"agents.task.model\", models.CopilotGPT4o)\n\t\tviper.SetDefault(\"agents.title.model\", models.CopilotGPT4o)\n\t\treturn\n\t}\n\n\t// Anthropic configuration\n\tif key := viper.GetString(\"providers.anthropic.apiKey\"); strings.TrimSpace(key) != \"\" {\n\t\tviper.SetDefault(\"agents.coder.model\", models.Claude4Sonnet)\n\t\tviper.SetDefault(\"agents.summarizer.model\", models.Claude4Sonnet)\n\t\tviper.SetDefault(\"agents.task.model\", models.Claude4Sonnet)\n\t\tviper.SetDefault(\"agents.title.model\", models.Claude4Sonnet)\n\t\treturn\n\t}\n\n\t// OpenAI configuration\n\tif key := viper.GetString(\"providers.openai.apiKey\"); strings.TrimSpace(key) != \"\" {\n\t\tviper.SetDefault(\"agents.coder.model\", models.GPT41)\n\t\tviper.SetDefault(\"agents.summarizer.model\", models.GPT41)\n\t\tviper.SetDefault(\"agents.task.model\", models.GPT41Mini)\n\t\tviper.SetDefault(\"agents.title.model\", models.GPT41Mini)\n\t\treturn\n\t}\n\n\t// Google Gemini configuration\n\tif key := viper.GetString(\"providers.gemini.apiKey\"); strings.TrimSpace(key) != \"\" {\n\t\tviper.SetDefault(\"agents.coder.model\", models.Gemini25)\n\t\tviper.SetDefault(\"agents.summarizer.model\", models.Gemini25)\n\t\tviper.SetDefault(\"agents.task.model\", models.Gemini25Flash)\n\t\tviper.SetDefault(\"agents.title.model\", models.Gemini25Flash)\n\t\treturn\n\t}\n\n\t// Groq configuration\n\tif key := viper.GetString(\"providers.groq.apiKey\"); strings.TrimSpace(key) != \"\" {\n\t\tviper.SetDefault(\"agents.coder.model\", models.QWENQwq)\n\t\tviper.SetDefault(\"agents.summarizer.model\", models.QWENQwq)\n\t\tviper.SetDefault(\"agents.task.model\", models.QWENQwq)\n\t\tviper.SetDefault(\"agents.title.model\", models.QWENQwq)\n\t\treturn\n\t}\n\n\t// OpenRouter configuration\n\tif key := viper.GetString(\"providers.openrouter.apiKey\"); strings.TrimSpace(key) != \"\" {\n\t\tviper.SetDefault(\"agents.coder.model\", models.OpenRouterClaude37Sonnet)\n\t\tviper.SetDefault(\"agents.summarizer.model\", models.OpenRouterClaude37Sonnet)\n\t\tviper.SetDefault(\"agents.task.model\", models.OpenRouterClaude37Sonnet)\n\t\tviper.SetDefault(\"agents.title.model\", models.OpenRouterClaude35Haiku)\n\t\treturn\n\t}\n\n\t// XAI configuration\n\tif key := viper.GetString(\"providers.xai.apiKey\"); strings.TrimSpace(key) != \"\" {\n\t\tviper.SetDefault(\"agents.coder.model\", models.XAIGrok3Beta)\n\t\tviper.SetDefault(\"agents.summarizer.model\", models.XAIGrok3Beta)\n\t\tviper.SetDefault(\"agents.task.model\", models.XAIGrok3Beta)\n\t\tviper.SetDefault(\"agents.title.model\", models.XAiGrok3MiniFastBeta)\n\t\treturn\n\t}\n\n\t// AWS Bedrock configuration\n\tif hasAWSCredentials() {\n\t\tviper.SetDefault(\"agents.coder.model\", models.BedrockClaude37Sonnet)\n\t\tviper.SetDefault(\"agents.summarizer.model\", models.BedrockClaude37Sonnet)\n\t\tviper.SetDefault(\"agents.task.model\", models.BedrockClaude37Sonnet)\n\t\tviper.SetDefault(\"agents.title.model\", models.BedrockClaude37Sonnet)\n\t\treturn\n\t}\n\n\t// Azure OpenAI configuration\n\tif os.Getenv(\"AZURE_OPENAI_ENDPOINT\") != \"\" {\n\t\tviper.SetDefault(\"agents.coder.model\", models.AzureGPT41)\n\t\tviper.SetDefault(\"agents.summarizer.model\", models.AzureGPT41)\n\t\tviper.SetDefault(\"agents.task.model\", models.AzureGPT41Mini)\n\t\tviper.SetDefault(\"agents.title.model\", models.AzureGPT41Mini)\n\t\treturn\n\t}\n\n\t// Google Cloud VertexAI configuration\n\tif hasVertexAICredentials() {\n\t\tviper.SetDefault(\"agents.coder.model\", models.VertexAIGemini25)\n\t\tviper.SetDefault(\"agents.summarizer.model\", models.VertexAIGemini25)\n\t\tviper.SetDefault(\"agents.task.model\", models.VertexAIGemini25Flash)\n\t\tviper.SetDefault(\"agents.title.model\", models.VertexAIGemini25Flash)\n\t\treturn\n\t}\n}\n\n// hasAWSCredentials checks if AWS credentials are available in the environment.\nfunc hasAWSCredentials() bool {\n\t// Check for explicit AWS credentials\n\tif os.Getenv(\"AWS_ACCESS_KEY_ID\") != \"\" && os.Getenv(\"AWS_SECRET_ACCESS_KEY\") != \"\" {\n\t\treturn true\n\t}\n\n\t// Check for AWS profile\n\tif os.Getenv(\"AWS_PROFILE\") != \"\" || os.Getenv(\"AWS_DEFAULT_PROFILE\") != \"\" {\n\t\treturn true\n\t}\n\n\t// Check for AWS region\n\tif os.Getenv(\"AWS_REGION\") != \"\" || os.Getenv(\"AWS_DEFAULT_REGION\") != \"\" {\n\t\treturn true\n\t}\n\n\t// Check if running on EC2 with instance profile\n\tif os.Getenv(\"AWS_CONTAINER_CREDENTIALS_RELATIVE_URI\") != \"\" ||\n\t\tos.Getenv(\"AWS_CONTAINER_CREDENTIALS_FULL_URI\") != \"\" {\n\t\treturn true\n\t}\n\n\treturn false\n}\n\n// hasVertexAICredentials checks if VertexAI credentials are available in the environment.\nfunc hasVertexAICredentials() bool {\n\t// Check for explicit VertexAI parameters\n\tif os.Getenv(\"VERTEXAI_PROJECT\") != \"\" && os.Getenv(\"VERTEXAI_LOCATION\") != \"\" {\n\t\treturn true\n\t}\n\t// Check for Google Cloud project and location\n\tif os.Getenv(\"GOOGLE_CLOUD_PROJECT\") != \"\" && (os.Getenv(\"GOOGLE_CLOUD_REGION\") != \"\" || os.Getenv(\"GOOGLE_CLOUD_LOCATION\") != \"\") {\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc hasCopilotCredentials() bool {\n\t// Check for explicit Copilot parameters\n\tif token, _ := LoadGitHubToken(); token != \"\" {\n\t\treturn true\n\t}\n\treturn false\n}\n\n// readConfig handles the result of reading a configuration file.\nfunc readConfig(err error) error {\n\tif err == nil {\n\t\treturn nil\n\t}\n\n\t// It's okay if the config file doesn't exist\n\tif _, ok := err.(viper.ConfigFileNotFoundError); ok {\n\t\treturn nil\n\t}\n\n\treturn fmt.Errorf(\"failed to read config: %w\", err)\n}\n\n// mergeLocalConfig loads and merges configuration from the local directory.\nfunc mergeLocalConfig(workingDir string) {\n\tlocal := viper.New()\n\tlocal.SetConfigName(fmt.Sprintf(\".%s\", appName))\n\tlocal.SetConfigType(\"json\")\n\tlocal.AddConfigPath(workingDir)\n\n\t// Merge local config if it exists\n\tif err := local.ReadInConfig(); err == nil {\n\t\tviper.MergeConfigMap(local.AllSettings())\n\t}\n}\n\n// applyDefaultValues sets default values for configuration fields that need processing.\nfunc applyDefaultValues() {\n\t// Set default MCP type if not specified\n\tfor k, v := range cfg.MCPServers {\n\t\tif v.Type == \"\" {\n\t\t\tv.Type = MCPStdio\n\t\t\tcfg.MCPServers[k] = v\n\t\t}\n\t}\n}\n\n// It validates model IDs and providers, ensuring they are supported.\nfunc validateAgent(cfg *Config, name AgentName, agent Agent) error {\n\t// Check if model exists\n\t// TODO:\tIf a copilot model is specified, but model is not found,\n\t// \t\t \tit might be new model. The https://api.githubcopilot.com/models\n\t// \t\t \tendpoint should be queried to validate if the model is supported.\n\tmodel, modelExists := models.SupportedModels[agent.Model]\n\tif !modelExists {\n\t\tlogging.Warn(\"unsupported model configured, reverting to default\",\n\t\t\t\"agent\", name,\n\t\t\t\"configured_model\", agent.Model)\n\n\t\t// Set default model based on available providers\n\t\tif setDefaultModelForAgent(name) {\n\t\t\tlogging.Info(\"set default model for agent\", \"agent\", name, \"model\", cfg.Agents[name].Model)\n\t\t} else {\n\t\t\treturn fmt.Errorf(\"no valid provider available for agent %s\", name)\n\t\t}\n\t\treturn nil\n\t}\n\n\t// Check if provider for the model is configured\n\tprovider := model.Provider\n\tproviderCfg, providerExists := cfg.Providers[provider]\n\n\tif !providerExists {\n\t\t// Provider not configured, check if we have environment variables\n\t\tapiKey := getProviderAPIKey(provider)\n\t\tif apiKey == \"\" {\n\t\t\tlogging.Warn(\"provider not configured for model, reverting to default\",\n\t\t\t\t\"agent\", name,\n\t\t\t\t\"model\", agent.Model,\n\t\t\t\t\"provider\", provider)\n\n\t\t\t// Set default model based on available providers\n\t\t\tif setDefaultModelForAgent(name) {\n\t\t\t\tlogging.Info(\"set default model for agent\", \"agent\", name, \"model\", cfg.Agents[name].Model)\n\t\t\t} else {\n\t\t\t\treturn fmt.Errorf(\"no valid provider available for agent %s\", name)\n\t\t\t}\n\t\t} else {\n\t\t\t// Add provider with API key from environment\n\t\t\tcfg.Providers[provider] = Provider{\n\t\t\t\tAPIKey: apiKey,\n\t\t\t}\n\t\t\tlogging.Info(\"added provider from environment\", \"provider\", provider)\n\t\t}\n\t} else if providerCfg.Disabled || providerCfg.APIKey == \"\" {\n\t\t// Provider is disabled or has no API key\n\t\tlogging.Warn(\"provider is disabled or has no API key, reverting to default\",\n\t\t\t\"agent\", name,\n\t\t\t\"model\", agent.Model,\n\t\t\t\"provider\", provider)\n\n\t\t// Set default model based on available providers\n\t\tif setDefaultModelForAgent(name) {\n\t\t\tlogging.Info(\"set default model for agent\", \"agent\", name, \"model\", cfg.Agents[name].Model)\n\t\t} else {\n\t\t\treturn fmt.Errorf(\"no valid provider available for agent %s\", name)\n\t\t}\n\t}\n\n\t// Validate max tokens\n\tif agent.MaxTokens <= 0 {\n\t\tlogging.Warn(\"invalid max tokens, setting to default\",\n\t\t\t\"agent\", name,\n\t\t\t\"model\", agent.Model,\n\t\t\t\"max_tokens\", agent.MaxTokens)\n\n\t\t// Update the agent with default max tokens\n\t\tupdatedAgent := cfg.Agents[name]\n\t\tif model.DefaultMaxTokens > 0 {\n\t\t\tupdatedAgent.MaxTokens = model.DefaultMaxTokens\n\t\t} else {\n\t\t\tupdatedAgent.MaxTokens = MaxTokensFallbackDefault\n\t\t}\n\t\tcfg.Agents[name] = updatedAgent\n\t} else if model.ContextWindow > 0 && agent.MaxTokens > model.ContextWindow/2 {\n\t\t// Ensure max tokens doesn't exceed half the context window (reasonable limit)\n\t\tlogging.Warn(\"max tokens exceeds half the context window, adjusting\",\n\t\t\t\"agent\", name,\n\t\t\t\"model\", agent.Model,\n\t\t\t\"max_tokens\", agent.MaxTokens,\n\t\t\t\"context_window\", model.ContextWindow)\n\n\t\t// Update the agent with adjusted max tokens\n\t\tupdatedAgent := cfg.Agents[name]\n\t\tupdatedAgent.MaxTokens = model.ContextWindow / 2\n\t\tcfg.Agents[name] = updatedAgent\n\t}\n\n\t// Validate reasoning effort for models that support reasoning\n\tif model.CanReason && provider == models.ProviderOpenAI || provider == models.ProviderLocal {\n\t\tif agent.ReasoningEffort == \"\" {\n\t\t\t// Set default reasoning effort for models that support it\n\t\t\tlogging.Info(\"setting default reasoning effort for model that supports reasoning\",\n\t\t\t\t\"agent\", name,\n\t\t\t\t\"model\", agent.Model)\n\n\t\t\t// Update the agent with default reasoning effort\n\t\t\tupdatedAgent := cfg.Agents[name]\n\t\t\tupdatedAgent.ReasoningEffort = \"medium\"\n\t\t\tcfg.Agents[name] = updatedAgent\n\t\t} else {\n\t\t\t// Check if reasoning effort is valid (low, medium, high)\n\t\t\teffort := strings.ToLower(agent.ReasoningEffort)\n\t\t\tif effort != \"low\" && effort != \"medium\" && effort != \"high\" {\n\t\t\t\tlogging.Warn(\"invalid reasoning effort, setting to medium\",\n\t\t\t\t\t\"agent\", name,\n\t\t\t\t\t\"model\", agent.Model,\n\t\t\t\t\t\"reasoning_effort\", agent.ReasoningEffort)\n\n\t\t\t\t// Update the agent with valid reasoning effort\n\t\t\t\tupdatedAgent := cfg.Agents[name]\n\t\t\t\tupdatedAgent.ReasoningEffort = \"medium\"\n\t\t\t\tcfg.Agents[name] = updatedAgent\n\t\t\t}\n\t\t}\n\t} else if !model.CanReason && agent.ReasoningEffort != \"\" {\n\t\t// Model doesn't support reasoning but reasoning effort is set\n\t\tlogging.Warn(\"model doesn't support reasoning but reasoning effort is set, ignoring\",\n\t\t\t\"agent\", name,\n\t\t\t\"model\", agent.Model,\n\t\t\t\"reasoning_effort\", agent.ReasoningEffort)\n\n\t\t// Update the agent to remove reasoning effort\n\t\tupdatedAgent := cfg.Agents[name]\n\t\tupdatedAgent.ReasoningEffort = \"\"\n\t\tcfg.Agents[name] = updatedAgent\n\t}\n\n\treturn nil\n}\n\n// Validate checks if the configuration is valid and applies defaults where needed.\nfunc Validate() error {\n\tif cfg == nil {\n\t\treturn fmt.Errorf(\"config not loaded\")\n\t}\n\n\t// Validate agent models\n\tfor name, agent := range cfg.Agents {\n\t\tif err := validateAgent(cfg, name, agent); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// Validate providers\n\tfor provider, providerCfg := range cfg.Providers {\n\t\tif providerCfg.APIKey == \"\" && !providerCfg.Disabled {\n\t\t\tfmt.Printf(\"provider has no API key, marking as disabled %s\", provider)\n\t\t\tlogging.Warn(\"provider has no API key, marking as disabled\", \"provider\", provider)\n\t\t\tproviderCfg.Disabled = true\n\t\t\tcfg.Providers[provider] = providerCfg\n\t\t}\n\t}\n\n\t// Validate LSP configurations\n\tfor language, lspConfig := range cfg.LSP {\n\t\tif lspConfig.Command == \"\" && !lspConfig.Disabled {\n\t\t\tlogging.Warn(\"LSP configuration has no command, marking as disabled\", \"language\", language)\n\t\t\tlspConfig.Disabled = true\n\t\t\tcfg.LSP[language] = lspConfig\n\t\t}\n\t}\n\n\treturn nil\n}\n\n// getProviderAPIKey gets the API key for a provider from environment variables\nfunc getProviderAPIKey(provider models.ModelProvider) string {\n\tswitch provider {\n\tcase models.ProviderAnthropic:\n\t\treturn os.Getenv(\"ANTHROPIC_API_KEY\")\n\tcase models.ProviderOpenAI:\n\t\treturn os.Getenv(\"OPENAI_API_KEY\")\n\tcase models.ProviderGemini:\n\t\treturn os.Getenv(\"GEMINI_API_KEY\")\n\tcase models.ProviderGROQ:\n\t\treturn os.Getenv(\"GROQ_API_KEY\")\n\tcase models.ProviderAzure:\n\t\treturn os.Getenv(\"AZURE_OPENAI_API_KEY\")\n\tcase models.ProviderOpenRouter:\n\t\treturn os.Getenv(\"OPENROUTER_API_KEY\")\n\tcase models.ProviderBedrock:\n\t\tif hasAWSCredentials() {\n\t\t\treturn \"aws-credentials-available\"\n\t\t}\n\tcase models.ProviderVertexAI:\n\t\tif hasVertexAICredentials() {\n\t\t\treturn \"vertex-ai-credentials-available\"\n\t\t}\n\t}\n\treturn \"\"\n}\n\n// setDefaultModelForAgent sets a default model for an agent based on available providers\nfunc setDefaultModelForAgent(agent AgentName) bool {\n\tif hasCopilotCredentials() {\n\t\tmaxTokens := int64(5000)\n\t\tif agent == AgentTitle {\n\t\t\tmaxTokens = 80\n\t\t}\n\n\t\tcfg.Agents[agent] = Agent{\n\t\t\tModel: models.CopilotGPT4o,\n\t\t\tMaxTokens: maxTokens,\n\t\t}\n\t\treturn true\n\t}\n\t// Check providers in order of preference\n\tif apiKey := os.Getenv(\"ANTHROPIC_API_KEY\"); apiKey != \"\" {\n\t\tmaxTokens := int64(5000)\n\t\tif agent == AgentTitle {\n\t\t\tmaxTokens = 80\n\t\t}\n\t\tcfg.Agents[agent] = Agent{\n\t\t\tModel: models.Claude37Sonnet,\n\t\t\tMaxTokens: maxTokens,\n\t\t}\n\t\treturn true\n\t}\n\n\tif apiKey := os.Getenv(\"OPENAI_API_KEY\"); apiKey != \"\" {\n\t\tvar model models.ModelID\n\t\tmaxTokens := int64(5000)\n\t\treasoningEffort := \"\"\n\n\t\tswitch agent {\n\t\tcase AgentTitle:\n\t\t\tmodel = models.GPT41Mini\n\t\t\tmaxTokens = 80\n\t\tcase AgentTask:\n\t\t\tmodel = models.GPT41Mini\n\t\tdefault:\n\t\t\tmodel = models.GPT41\n\t\t}\n\n\t\t// Check if model supports reasoning\n\t\tif modelInfo, ok := models.SupportedModels[model]; ok && modelInfo.CanReason {\n\t\t\treasoningEffort = \"medium\"\n\t\t}\n\n\t\tcfg.Agents[agent] = Agent{\n\t\t\tModel: model,\n\t\t\tMaxTokens: maxTokens,\n\t\t\tReasoningEffort: reasoningEffort,\n\t\t}\n\t\treturn true\n\t}\n\n\tif apiKey := os.Getenv(\"OPENROUTER_API_KEY\"); apiKey != \"\" {\n\t\tvar model models.ModelID\n\t\tmaxTokens := int64(5000)\n\t\treasoningEffort := \"\"\n\n\t\tswitch agent {\n\t\tcase AgentTitle:\n\t\t\tmodel = models.OpenRouterClaude35Haiku\n\t\t\tmaxTokens = 80\n\t\tcase AgentTask:\n\t\t\tmodel = models.OpenRouterClaude37Sonnet\n\t\tdefault:\n\t\t\tmodel = models.OpenRouterClaude37Sonnet\n\t\t}\n\n\t\t// Check if model supports reasoning\n\t\tif modelInfo, ok := models.SupportedModels[model]; ok && modelInfo.CanReason {\n\t\t\treasoningEffort = \"medium\"\n\t\t}\n\n\t\tcfg.Agents[agent] = Agent{\n\t\t\tModel: model,\n\t\t\tMaxTokens: maxTokens,\n\t\t\tReasoningEffort: reasoningEffort,\n\t\t}\n\t\treturn true\n\t}\n\n\tif apiKey := os.Getenv(\"GEMINI_API_KEY\"); apiKey != \"\" {\n\t\tvar model models.ModelID\n\t\tmaxTokens := int64(5000)\n\n\t\tif agent == AgentTitle {\n\t\t\tmodel = models.Gemini25Flash\n\t\t\tmaxTokens = 80\n\t\t} else {\n\t\t\tmodel = models.Gemini25\n\t\t}\n\n\t\tcfg.Agents[agent] = Agent{\n\t\t\tModel: model,\n\t\t\tMaxTokens: maxTokens,\n\t\t}\n\t\treturn true\n\t}\n\n\tif apiKey := os.Getenv(\"GROQ_API_KEY\"); apiKey != \"\" {\n\t\tmaxTokens := int64(5000)\n\t\tif agent == AgentTitle {\n\t\t\tmaxTokens = 80\n\t\t}\n\n\t\tcfg.Agents[agent] = Agent{\n\t\t\tModel: models.QWENQwq,\n\t\t\tMaxTokens: maxTokens,\n\t\t}\n\t\treturn true\n\t}\n\n\tif hasAWSCredentials() {\n\t\tmaxTokens := int64(5000)\n\t\tif agent == AgentTitle {\n\t\t\tmaxTokens = 80\n\t\t}\n\n\t\tcfg.Agents[agent] = Agent{\n\t\t\tModel: models.BedrockClaude37Sonnet,\n\t\t\tMaxTokens: maxTokens,\n\t\t\tReasoningEffort: \"medium\", // Claude models support reasoning\n\t\t}\n\t\treturn true\n\t}\n\n\tif hasVertexAICredentials() {\n\t\tvar model models.ModelID\n\t\tmaxTokens := int64(5000)\n\n\t\tif agent == AgentTitle {\n\t\t\tmodel = models.VertexAIGemini25Flash\n\t\t\tmaxTokens = 80\n\t\t} else {\n\t\t\tmodel = models.VertexAIGemini25\n\t\t}\n\n\t\tcfg.Agents[agent] = Agent{\n\t\t\tModel: model,\n\t\t\tMaxTokens: maxTokens,\n\t\t}\n\t\treturn true\n\t}\n\n\treturn false\n}\n\nfunc updateCfgFile(updateCfg func(config *Config)) error {\n\tif cfg == nil {\n\t\treturn fmt.Errorf(\"config not loaded\")\n\t}\n\n\t// Get the config file path\n\tconfigFile := viper.ConfigFileUsed()\n\tvar configData []byte\n\tif configFile == \"\" {\n\t\thomeDir, err := os.UserHomeDir()\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to get home directory: %w\", err)\n\t\t}\n\t\tconfigFile = filepath.Join(homeDir, fmt.Sprintf(\".%s.json\", appName))\n\t\tlogging.Info(\"config file not found, creating new one\", \"path\", configFile)\n\t\tconfigData = []byte(`{}`)\n\t} else {\n\t\t// Read the existing config file\n\t\tdata, err := os.ReadFile(configFile)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to read config file: %w\", err)\n\t\t}\n\t\tconfigData = data\n\t}\n\n\t// Parse the JSON\n\tvar userCfg *Config\n\tif err := json.Unmarshal(configData, &userCfg); err != nil {\n\t\treturn fmt.Errorf(\"failed to parse config file: %w\", err)\n\t}\n\n\tupdateCfg(userCfg)\n\n\t// Write the updated config back to file\n\tupdatedData, err := json.MarshalIndent(userCfg, \"\", \" \")\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to marshal config: %w\", err)\n\t}\n\n\tif err := os.WriteFile(configFile, updatedData, 0o644); err != nil {\n\t\treturn fmt.Errorf(\"failed to write config file: %w\", err)\n\t}\n\n\treturn nil\n}\n\n// Get returns the current configuration.\n// It's safe to call this function multiple times.\nfunc Get() *Config {\n\treturn cfg\n}\n\n// WorkingDirectory returns the current working directory from the configuration.\nfunc WorkingDirectory() string {\n\tif cfg == nil {\n\t\tpanic(\"config not loaded\")\n\t}\n\treturn cfg.WorkingDir\n}\n\nfunc UpdateAgentModel(agentName AgentName, modelID models.ModelID) error {\n\tif cfg == nil {\n\t\tpanic(\"config not loaded\")\n\t}\n\n\texistingAgentCfg := cfg.Agents[agentName]\n\n\tmodel, ok := models.SupportedModels[modelID]\n\tif !ok {\n\t\treturn fmt.Errorf(\"model %s not supported\", modelID)\n\t}\n\n\tmaxTokens := existingAgentCfg.MaxTokens\n\tif model.DefaultMaxTokens > 0 {\n\t\tmaxTokens = model.DefaultMaxTokens\n\t}\n\n\tnewAgentCfg := Agent{\n\t\tModel: modelID,\n\t\tMaxTokens: maxTokens,\n\t\tReasoningEffort: existingAgentCfg.ReasoningEffort,\n\t}\n\tcfg.Agents[agentName] = newAgentCfg\n\n\tif err := validateAgent(cfg, agentName, newAgentCfg); err != nil {\n\t\t// revert config update on failure\n\t\tcfg.Agents[agentName] = existingAgentCfg\n\t\treturn fmt.Errorf(\"failed to update agent model: %w\", err)\n\t}\n\n\treturn updateCfgFile(func(config *Config) {\n\t\tif config.Agents == nil {\n\t\t\tconfig.Agents = make(map[AgentName]Agent)\n\t\t}\n\t\tconfig.Agents[agentName] = newAgentCfg\n\t})\n}\n\n// UpdateTheme updates the theme in the configuration and writes it to the config file.\nfunc UpdateTheme(themeName string) error {\n\tif cfg == nil {\n\t\treturn fmt.Errorf(\"config not loaded\")\n\t}\n\n\t// Update the in-memory config\n\tcfg.TUI.Theme = themeName\n\n\t// Update the file config\n\treturn updateCfgFile(func(config *Config) {\n\t\tconfig.TUI.Theme = themeName\n\t})\n}\n\n// Tries to load Github token from all possible locations\nfunc LoadGitHubToken() (string, error) {\n\t// First check environment variable\n\tif token := os.Getenv(\"GITHUB_TOKEN\"); token != \"\" {\n\t\treturn token, nil\n\t}\n\n\t// Get config directory\n\tvar configDir string\n\tif xdgConfig := os.Getenv(\"XDG_CONFIG_HOME\"); xdgConfig != \"\" {\n\t\tconfigDir = xdgConfig\n\t} else if runtime.GOOS == \"windows\" {\n\t\tif localAppData := os.Getenv(\"LOCALAPPDATA\"); localAppData != \"\" {\n\t\t\tconfigDir = localAppData\n\t\t} else {\n\t\t\tconfigDir = filepath.Join(os.Getenv(\"HOME\"), \"AppData\", \"Local\")\n\t\t}\n\t} else {\n\t\tconfigDir = filepath.Join(os.Getenv(\"HOME\"), \".config\")\n\t}\n\n\t// Try both hosts.json and apps.json files\n\tfilePaths := []string{\n\t\tfilepath.Join(configDir, \"github-copilot\", \"hosts.json\"),\n\t\tfilepath.Join(configDir, \"github-copilot\", \"apps.json\"),\n\t}\n\n\tfor _, filePath := range filePaths {\n\t\tdata, err := os.ReadFile(filePath)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tvar config map[string]map[string]interface{}\n\t\tif err := json.Unmarshal(data, &config); err != nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tfor key, value := range config {\n\t\t\tif strings.Contains(key, \"github.com\") {\n\t\t\t\tif oauthToken, ok := value[\"oauth_token\"].(string); ok {\n\t\t\t\t\treturn oauthToken, nil\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn \"\", fmt.Errorf(\"GitHub token not found in standard locations\")\n}\n"], ["/opencode/internal/lsp/protocol/interface.go", "package protocol\n\nimport \"fmt\"\n\n// TextEditResult is an interface for types that represent workspace symbols\ntype WorkspaceSymbolResult interface {\n\tGetName() string\n\tGetLocation() Location\n\tisWorkspaceSymbol() // marker method\n}\n\nfunc (ws *WorkspaceSymbol) GetName() string { return ws.Name }\nfunc (ws *WorkspaceSymbol) GetLocation() Location {\n\tswitch v := ws.Location.Value.(type) {\n\tcase Location:\n\t\treturn v\n\tcase LocationUriOnly:\n\t\treturn Location{URI: v.URI}\n\t}\n\treturn Location{}\n}\nfunc (ws *WorkspaceSymbol) isWorkspaceSymbol() {}\n\nfunc (si *SymbolInformation) GetName() string { return si.Name }\nfunc (si *SymbolInformation) GetLocation() Location { return si.Location }\nfunc (si *SymbolInformation) isWorkspaceSymbol() {}\n\n// Results converts the Value to a slice of WorkspaceSymbolResult\nfunc (r Or_Result_workspace_symbol) Results() ([]WorkspaceSymbolResult, error) {\n\tif r.Value == nil {\n\t\treturn make([]WorkspaceSymbolResult, 0), nil\n\t}\n\tswitch v := r.Value.(type) {\n\tcase []WorkspaceSymbol:\n\t\tresults := make([]WorkspaceSymbolResult, len(v))\n\t\tfor i := range v {\n\t\t\tresults[i] = &v[i]\n\t\t}\n\t\treturn results, nil\n\tcase []SymbolInformation:\n\t\tresults := make([]WorkspaceSymbolResult, len(v))\n\t\tfor i := range v {\n\t\t\tresults[i] = &v[i]\n\t\t}\n\t\treturn results, nil\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"unknown symbol type: %T\", r.Value)\n\t}\n}\n\n// TextEditResult is an interface for types that represent document symbols\ntype DocumentSymbolResult interface {\n\tGetRange() Range\n\tGetName() string\n\tisDocumentSymbol() // marker method\n}\n\nfunc (ds *DocumentSymbol) GetRange() Range { return ds.Range }\nfunc (ds *DocumentSymbol) GetName() string { return ds.Name }\nfunc (ds *DocumentSymbol) isDocumentSymbol() {}\n\nfunc (si *SymbolInformation) GetRange() Range { return si.Location.Range }\n\n// Note: SymbolInformation already has GetName() implemented above\nfunc (si *SymbolInformation) isDocumentSymbol() {}\n\n// Results converts the Value to a slice of DocumentSymbolResult\nfunc (r Or_Result_textDocument_documentSymbol) Results() ([]DocumentSymbolResult, error) {\n\tif r.Value == nil {\n\t\treturn make([]DocumentSymbolResult, 0), nil\n\t}\n\tswitch v := r.Value.(type) {\n\tcase []DocumentSymbol:\n\t\tresults := make([]DocumentSymbolResult, len(v))\n\t\tfor i := range v {\n\t\t\tresults[i] = &v[i]\n\t\t}\n\t\treturn results, nil\n\tcase []SymbolInformation:\n\t\tresults := make([]DocumentSymbolResult, len(v))\n\t\tfor i := range v {\n\t\t\tresults[i] = &v[i]\n\t\t}\n\t\treturn results, nil\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"unknown document symbol type: %T\", v)\n\t}\n}\n\n// TextEditResult is an interface for types that can be used as text edits\ntype TextEditResult interface {\n\tGetRange() Range\n\tGetNewText() string\n\tisTextEdit() // marker method\n}\n\nfunc (te *TextEdit) GetRange() Range { return te.Range }\nfunc (te *TextEdit) GetNewText() string { return te.NewText }\nfunc (te *TextEdit) isTextEdit() {}\n\n// Convert Or_TextDocumentEdit_edits_Elem to TextEdit\nfunc (e Or_TextDocumentEdit_edits_Elem) AsTextEdit() (TextEdit, error) {\n\tif e.Value == nil {\n\t\treturn TextEdit{}, fmt.Errorf(\"nil text edit\")\n\t}\n\tswitch v := e.Value.(type) {\n\tcase TextEdit:\n\t\treturn v, nil\n\tcase AnnotatedTextEdit:\n\t\treturn TextEdit{\n\t\t\tRange: v.Range,\n\t\t\tNewText: v.NewText,\n\t\t}, nil\n\tdefault:\n\t\treturn TextEdit{}, fmt.Errorf(\"unknown text edit type: %T\", e.Value)\n\t}\n}\n"], ["/opencode/internal/tui/tui.go", "package tui\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"strings\"\n\n\t\"github.com/charmbracelet/bubbles/key\"\n\ttea \"github.com/charmbracelet/bubbletea\"\n\t\"github.com/charmbracelet/lipgloss\"\n\t\"github.com/opencode-ai/opencode/internal/app\"\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/llm/agent\"\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n\t\"github.com/opencode-ai/opencode/internal/permission\"\n\t\"github.com/opencode-ai/opencode/internal/pubsub\"\n\t\"github.com/opencode-ai/opencode/internal/session\"\n\t\"github.com/opencode-ai/opencode/internal/tui/components/chat\"\n\t\"github.com/opencode-ai/opencode/internal/tui/components/core\"\n\t\"github.com/opencode-ai/opencode/internal/tui/components/dialog\"\n\t\"github.com/opencode-ai/opencode/internal/tui/layout\"\n\t\"github.com/opencode-ai/opencode/internal/tui/page\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n\t\"github.com/opencode-ai/opencode/internal/tui/util\"\n)\n\ntype keyMap struct {\n\tLogs key.Binding\n\tQuit key.Binding\n\tHelp key.Binding\n\tSwitchSession key.Binding\n\tCommands key.Binding\n\tFilepicker key.Binding\n\tModels key.Binding\n\tSwitchTheme key.Binding\n}\n\ntype startCompactSessionMsg struct{}\n\nconst (\n\tquitKey = \"q\"\n)\n\nvar keys = keyMap{\n\tLogs: key.NewBinding(\n\t\tkey.WithKeys(\"ctrl+l\"),\n\t\tkey.WithHelp(\"ctrl+l\", \"logs\"),\n\t),\n\n\tQuit: key.NewBinding(\n\t\tkey.WithKeys(\"ctrl+c\"),\n\t\tkey.WithHelp(\"ctrl+c\", \"quit\"),\n\t),\n\tHelp: key.NewBinding(\n\t\tkey.WithKeys(\"ctrl+_\", \"ctrl+h\"),\n\t\tkey.WithHelp(\"ctrl+?\", \"toggle help\"),\n\t),\n\n\tSwitchSession: key.NewBinding(\n\t\tkey.WithKeys(\"ctrl+s\"),\n\t\tkey.WithHelp(\"ctrl+s\", \"switch session\"),\n\t),\n\n\tCommands: key.NewBinding(\n\t\tkey.WithKeys(\"ctrl+k\"),\n\t\tkey.WithHelp(\"ctrl+k\", \"commands\"),\n\t),\n\tFilepicker: key.NewBinding(\n\t\tkey.WithKeys(\"ctrl+f\"),\n\t\tkey.WithHelp(\"ctrl+f\", \"select files to upload\"),\n\t),\n\tModels: key.NewBinding(\n\t\tkey.WithKeys(\"ctrl+o\"),\n\t\tkey.WithHelp(\"ctrl+o\", \"model selection\"),\n\t),\n\n\tSwitchTheme: key.NewBinding(\n\t\tkey.WithKeys(\"ctrl+t\"),\n\t\tkey.WithHelp(\"ctrl+t\", \"switch theme\"),\n\t),\n}\n\nvar helpEsc = key.NewBinding(\n\tkey.WithKeys(\"?\"),\n\tkey.WithHelp(\"?\", \"toggle help\"),\n)\n\nvar returnKey = key.NewBinding(\n\tkey.WithKeys(\"esc\"),\n\tkey.WithHelp(\"esc\", \"close\"),\n)\n\nvar logsKeyReturnKey = key.NewBinding(\n\tkey.WithKeys(\"esc\", \"backspace\", quitKey),\n\tkey.WithHelp(\"esc/q\", \"go back\"),\n)\n\ntype appModel struct {\n\twidth, height int\n\tcurrentPage page.PageID\n\tpreviousPage page.PageID\n\tpages map[page.PageID]tea.Model\n\tloadedPages map[page.PageID]bool\n\tstatus core.StatusCmp\n\tapp *app.App\n\tselectedSession session.Session\n\n\tshowPermissions bool\n\tpermissions dialog.PermissionDialogCmp\n\n\tshowHelp bool\n\thelp dialog.HelpCmp\n\n\tshowQuit bool\n\tquit dialog.QuitDialog\n\n\tshowSessionDialog bool\n\tsessionDialog dialog.SessionDialog\n\n\tshowCommandDialog bool\n\tcommandDialog dialog.CommandDialog\n\tcommands []dialog.Command\n\n\tshowModelDialog bool\n\tmodelDialog dialog.ModelDialog\n\n\tshowInitDialog bool\n\tinitDialog dialog.InitDialogCmp\n\n\tshowFilepicker bool\n\tfilepicker dialog.FilepickerCmp\n\n\tshowThemeDialog bool\n\tthemeDialog dialog.ThemeDialog\n\n\tshowMultiArgumentsDialog bool\n\tmultiArgumentsDialog dialog.MultiArgumentsDialogCmp\n\n\tisCompacting bool\n\tcompactingMessage string\n}\n\nfunc (a appModel) Init() tea.Cmd {\n\tvar cmds []tea.Cmd\n\tcmd := a.pages[a.currentPage].Init()\n\ta.loadedPages[a.currentPage] = true\n\tcmds = append(cmds, cmd)\n\tcmd = a.status.Init()\n\tcmds = append(cmds, cmd)\n\tcmd = a.quit.Init()\n\tcmds = append(cmds, cmd)\n\tcmd = a.help.Init()\n\tcmds = append(cmds, cmd)\n\tcmd = a.sessionDialog.Init()\n\tcmds = append(cmds, cmd)\n\tcmd = a.commandDialog.Init()\n\tcmds = append(cmds, cmd)\n\tcmd = a.modelDialog.Init()\n\tcmds = append(cmds, cmd)\n\tcmd = a.initDialog.Init()\n\tcmds = append(cmds, cmd)\n\tcmd = a.filepicker.Init()\n\tcmds = append(cmds, cmd)\n\tcmd = a.themeDialog.Init()\n\tcmds = append(cmds, cmd)\n\n\t// Check if we should show the init dialog\n\tcmds = append(cmds, func() tea.Msg {\n\t\tshouldShow, err := config.ShouldShowInitDialog()\n\t\tif err != nil {\n\t\t\treturn util.InfoMsg{\n\t\t\t\tType: util.InfoTypeError,\n\t\t\t\tMsg: \"Failed to check init status: \" + err.Error(),\n\t\t\t}\n\t\t}\n\t\treturn dialog.ShowInitDialogMsg{Show: shouldShow}\n\t})\n\n\treturn tea.Batch(cmds...)\n}\n\nfunc (a appModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {\n\tvar cmds []tea.Cmd\n\tvar cmd tea.Cmd\n\tswitch msg := msg.(type) {\n\tcase tea.WindowSizeMsg:\n\t\tmsg.Height -= 1 // Make space for the status bar\n\t\ta.width, a.height = msg.Width, msg.Height\n\n\t\ts, _ := a.status.Update(msg)\n\t\ta.status = s.(core.StatusCmp)\n\t\ta.pages[a.currentPage], cmd = a.pages[a.currentPage].Update(msg)\n\t\tcmds = append(cmds, cmd)\n\n\t\tprm, permCmd := a.permissions.Update(msg)\n\t\ta.permissions = prm.(dialog.PermissionDialogCmp)\n\t\tcmds = append(cmds, permCmd)\n\n\t\thelp, helpCmd := a.help.Update(msg)\n\t\ta.help = help.(dialog.HelpCmp)\n\t\tcmds = append(cmds, helpCmd)\n\n\t\tsession, sessionCmd := a.sessionDialog.Update(msg)\n\t\ta.sessionDialog = session.(dialog.SessionDialog)\n\t\tcmds = append(cmds, sessionCmd)\n\n\t\tcommand, commandCmd := a.commandDialog.Update(msg)\n\t\ta.commandDialog = command.(dialog.CommandDialog)\n\t\tcmds = append(cmds, commandCmd)\n\n\t\tfilepicker, filepickerCmd := a.filepicker.Update(msg)\n\t\ta.filepicker = filepicker.(dialog.FilepickerCmp)\n\t\tcmds = append(cmds, filepickerCmd)\n\n\t\ta.initDialog.SetSize(msg.Width, msg.Height)\n\n\t\tif a.showMultiArgumentsDialog {\n\t\t\ta.multiArgumentsDialog.SetSize(msg.Width, msg.Height)\n\t\t\targs, argsCmd := a.multiArgumentsDialog.Update(msg)\n\t\t\ta.multiArgumentsDialog = args.(dialog.MultiArgumentsDialogCmp)\n\t\t\tcmds = append(cmds, argsCmd, a.multiArgumentsDialog.Init())\n\t\t}\n\n\t\treturn a, tea.Batch(cmds...)\n\t// Status\n\tcase util.InfoMsg:\n\t\ts, cmd := a.status.Update(msg)\n\t\ta.status = s.(core.StatusCmp)\n\t\tcmds = append(cmds, cmd)\n\t\treturn a, tea.Batch(cmds...)\n\tcase pubsub.Event[logging.LogMessage]:\n\t\tif msg.Payload.Persist {\n\t\t\tswitch msg.Payload.Level {\n\t\t\tcase \"error\":\n\t\t\t\ts, cmd := a.status.Update(util.InfoMsg{\n\t\t\t\t\tType: util.InfoTypeError,\n\t\t\t\t\tMsg: msg.Payload.Message,\n\t\t\t\t\tTTL: msg.Payload.PersistTime,\n\t\t\t\t})\n\t\t\t\ta.status = s.(core.StatusCmp)\n\t\t\t\tcmds = append(cmds, cmd)\n\t\t\tcase \"info\":\n\t\t\t\ts, cmd := a.status.Update(util.InfoMsg{\n\t\t\t\t\tType: util.InfoTypeInfo,\n\t\t\t\t\tMsg: msg.Payload.Message,\n\t\t\t\t\tTTL: msg.Payload.PersistTime,\n\t\t\t\t})\n\t\t\t\ta.status = s.(core.StatusCmp)\n\t\t\t\tcmds = append(cmds, cmd)\n\n\t\t\tcase \"warn\":\n\t\t\t\ts, cmd := a.status.Update(util.InfoMsg{\n\t\t\t\t\tType: util.InfoTypeWarn,\n\t\t\t\t\tMsg: msg.Payload.Message,\n\t\t\t\t\tTTL: msg.Payload.PersistTime,\n\t\t\t\t})\n\n\t\t\t\ta.status = s.(core.StatusCmp)\n\t\t\t\tcmds = append(cmds, cmd)\n\t\t\tdefault:\n\t\t\t\ts, cmd := a.status.Update(util.InfoMsg{\n\t\t\t\t\tType: util.InfoTypeInfo,\n\t\t\t\t\tMsg: msg.Payload.Message,\n\t\t\t\t\tTTL: msg.Payload.PersistTime,\n\t\t\t\t})\n\t\t\t\ta.status = s.(core.StatusCmp)\n\t\t\t\tcmds = append(cmds, cmd)\n\t\t\t}\n\t\t}\n\tcase util.ClearStatusMsg:\n\t\ts, _ := a.status.Update(msg)\n\t\ta.status = s.(core.StatusCmp)\n\n\t// Permission\n\tcase pubsub.Event[permission.PermissionRequest]:\n\t\ta.showPermissions = true\n\t\treturn a, a.permissions.SetPermissions(msg.Payload)\n\tcase dialog.PermissionResponseMsg:\n\t\tvar cmd tea.Cmd\n\t\tswitch msg.Action {\n\t\tcase dialog.PermissionAllow:\n\t\t\ta.app.Permissions.Grant(msg.Permission)\n\t\tcase dialog.PermissionAllowForSession:\n\t\t\ta.app.Permissions.GrantPersistant(msg.Permission)\n\t\tcase dialog.PermissionDeny:\n\t\t\ta.app.Permissions.Deny(msg.Permission)\n\t\t}\n\t\ta.showPermissions = false\n\t\treturn a, cmd\n\n\tcase page.PageChangeMsg:\n\t\treturn a, a.moveToPage(msg.ID)\n\n\tcase dialog.CloseQuitMsg:\n\t\ta.showQuit = false\n\t\treturn a, nil\n\n\tcase dialog.CloseSessionDialogMsg:\n\t\ta.showSessionDialog = false\n\t\treturn a, nil\n\n\tcase dialog.CloseCommandDialogMsg:\n\t\ta.showCommandDialog = false\n\t\treturn a, nil\n\n\tcase startCompactSessionMsg:\n\t\t// Start compacting the current session\n\t\ta.isCompacting = true\n\t\ta.compactingMessage = \"Starting summarization...\"\n\n\t\tif a.selectedSession.ID == \"\" {\n\t\t\ta.isCompacting = false\n\t\t\treturn a, util.ReportWarn(\"No active session to summarize\")\n\t\t}\n\n\t\t// Start the summarization process\n\t\treturn a, func() tea.Msg {\n\t\t\tctx := context.Background()\n\t\t\ta.app.CoderAgent.Summarize(ctx, a.selectedSession.ID)\n\t\t\treturn nil\n\t\t}\n\n\tcase pubsub.Event[agent.AgentEvent]:\n\t\tpayload := msg.Payload\n\t\tif payload.Error != nil {\n\t\t\ta.isCompacting = false\n\t\t\treturn a, util.ReportError(payload.Error)\n\t\t}\n\n\t\ta.compactingMessage = payload.Progress\n\n\t\tif payload.Done && payload.Type == agent.AgentEventTypeSummarize {\n\t\t\ta.isCompacting = false\n\t\t\treturn a, util.ReportInfo(\"Session summarization complete\")\n\t\t} else if payload.Done && payload.Type == agent.AgentEventTypeResponse && a.selectedSession.ID != \"\" {\n\t\t\tmodel := a.app.CoderAgent.Model()\n\t\t\tcontextWindow := model.ContextWindow\n\t\t\ttokens := a.selectedSession.CompletionTokens + a.selectedSession.PromptTokens\n\t\t\tif (tokens >= int64(float64(contextWindow)*0.95)) && config.Get().AutoCompact {\n\t\t\t\treturn a, util.CmdHandler(startCompactSessionMsg{})\n\t\t\t}\n\t\t}\n\t\t// Continue listening for events\n\t\treturn a, nil\n\n\tcase dialog.CloseThemeDialogMsg:\n\t\ta.showThemeDialog = false\n\t\treturn a, nil\n\n\tcase dialog.ThemeChangedMsg:\n\t\ta.pages[a.currentPage], cmd = a.pages[a.currentPage].Update(msg)\n\t\ta.showThemeDialog = false\n\t\treturn a, tea.Batch(cmd, util.ReportInfo(\"Theme changed to: \"+msg.ThemeName))\n\n\tcase dialog.CloseModelDialogMsg:\n\t\ta.showModelDialog = false\n\t\treturn a, nil\n\n\tcase dialog.ModelSelectedMsg:\n\t\ta.showModelDialog = false\n\n\t\tmodel, err := a.app.CoderAgent.Update(config.AgentCoder, msg.Model.ID)\n\t\tif err != nil {\n\t\t\treturn a, util.ReportError(err)\n\t\t}\n\n\t\treturn a, util.ReportInfo(fmt.Sprintf(\"Model changed to %s\", model.Name))\n\n\tcase dialog.ShowInitDialogMsg:\n\t\ta.showInitDialog = msg.Show\n\t\treturn a, nil\n\n\tcase dialog.CloseInitDialogMsg:\n\t\ta.showInitDialog = false\n\t\tif msg.Initialize {\n\t\t\t// Run the initialization command\n\t\t\tfor _, cmd := range a.commands {\n\t\t\t\tif cmd.ID == \"init\" {\n\t\t\t\t\t// Mark the project as initialized\n\t\t\t\t\tif err := config.MarkProjectInitialized(); err != nil {\n\t\t\t\t\t\treturn a, util.ReportError(err)\n\t\t\t\t\t}\n\t\t\t\t\treturn a, cmd.Handler(cmd)\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\t// Mark the project as initialized without running the command\n\t\t\tif err := config.MarkProjectInitialized(); err != nil {\n\t\t\t\treturn a, util.ReportError(err)\n\t\t\t}\n\t\t}\n\t\treturn a, nil\n\n\tcase chat.SessionSelectedMsg:\n\t\ta.selectedSession = msg\n\t\ta.sessionDialog.SetSelectedSession(msg.ID)\n\n\tcase pubsub.Event[session.Session]:\n\t\tif msg.Type == pubsub.UpdatedEvent && msg.Payload.ID == a.selectedSession.ID {\n\t\t\ta.selectedSession = msg.Payload\n\t\t}\n\tcase dialog.SessionSelectedMsg:\n\t\ta.showSessionDialog = false\n\t\tif a.currentPage == page.ChatPage {\n\t\t\treturn a, util.CmdHandler(chat.SessionSelectedMsg(msg.Session))\n\t\t}\n\t\treturn a, nil\n\n\tcase dialog.CommandSelectedMsg:\n\t\ta.showCommandDialog = false\n\t\t// Execute the command handler if available\n\t\tif msg.Command.Handler != nil {\n\t\t\treturn a, msg.Command.Handler(msg.Command)\n\t\t}\n\t\treturn a, util.ReportInfo(\"Command selected: \" + msg.Command.Title)\n\n\tcase dialog.ShowMultiArgumentsDialogMsg:\n\t\t// Show multi-arguments dialog\n\t\ta.multiArgumentsDialog = dialog.NewMultiArgumentsDialogCmp(msg.CommandID, msg.Content, msg.ArgNames)\n\t\ta.showMultiArgumentsDialog = true\n\t\treturn a, a.multiArgumentsDialog.Init()\n\n\tcase dialog.CloseMultiArgumentsDialogMsg:\n\t\t// Close multi-arguments dialog\n\t\ta.showMultiArgumentsDialog = false\n\n\t\t// If submitted, replace all named arguments and run the command\n\t\tif msg.Submit {\n\t\t\tcontent := msg.Content\n\n\t\t\t// Replace each named argument with its value\n\t\t\tfor name, value := range msg.Args {\n\t\t\t\tplaceholder := \"$\" + name\n\t\t\t\tcontent = strings.ReplaceAll(content, placeholder, value)\n\t\t\t}\n\n\t\t\t// Execute the command with arguments\n\t\t\treturn a, util.CmdHandler(dialog.CommandRunCustomMsg{\n\t\t\t\tContent: content,\n\t\t\t\tArgs: msg.Args,\n\t\t\t})\n\t\t}\n\t\treturn a, nil\n\n\tcase tea.KeyMsg:\n\t\t// If multi-arguments dialog is open, let it handle the key press first\n\t\tif a.showMultiArgumentsDialog {\n\t\t\targs, cmd := a.multiArgumentsDialog.Update(msg)\n\t\t\ta.multiArgumentsDialog = args.(dialog.MultiArgumentsDialogCmp)\n\t\t\treturn a, cmd\n\t\t}\n\n\t\tswitch {\n\n\t\tcase key.Matches(msg, keys.Quit):\n\t\t\ta.showQuit = !a.showQuit\n\t\t\tif a.showHelp {\n\t\t\t\ta.showHelp = false\n\t\t\t}\n\t\t\tif a.showSessionDialog {\n\t\t\t\ta.showSessionDialog = false\n\t\t\t}\n\t\t\tif a.showCommandDialog {\n\t\t\t\ta.showCommandDialog = false\n\t\t\t}\n\t\t\tif a.showFilepicker {\n\t\t\t\ta.showFilepicker = false\n\t\t\t\ta.filepicker.ToggleFilepicker(a.showFilepicker)\n\t\t\t}\n\t\t\tif a.showModelDialog {\n\t\t\t\ta.showModelDialog = false\n\t\t\t}\n\t\t\tif a.showMultiArgumentsDialog {\n\t\t\t\ta.showMultiArgumentsDialog = false\n\t\t\t}\n\t\t\treturn a, nil\n\t\tcase key.Matches(msg, keys.SwitchSession):\n\t\t\tif a.currentPage == page.ChatPage && !a.showQuit && !a.showPermissions && !a.showCommandDialog {\n\t\t\t\t// Load sessions and show the dialog\n\t\t\t\tsessions, err := a.app.Sessions.List(context.Background())\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn a, util.ReportError(err)\n\t\t\t\t}\n\t\t\t\tif len(sessions) == 0 {\n\t\t\t\t\treturn a, util.ReportWarn(\"No sessions available\")\n\t\t\t\t}\n\t\t\t\ta.sessionDialog.SetSessions(sessions)\n\t\t\t\ta.showSessionDialog = true\n\t\t\t\treturn a, nil\n\t\t\t}\n\t\t\treturn a, nil\n\t\tcase key.Matches(msg, keys.Commands):\n\t\t\tif a.currentPage == page.ChatPage && !a.showQuit && !a.showPermissions && !a.showSessionDialog && !a.showThemeDialog && !a.showFilepicker {\n\t\t\t\t// Show commands dialog\n\t\t\t\tif len(a.commands) == 0 {\n\t\t\t\t\treturn a, util.ReportWarn(\"No commands available\")\n\t\t\t\t}\n\t\t\t\ta.commandDialog.SetCommands(a.commands)\n\t\t\t\ta.showCommandDialog = true\n\t\t\t\treturn a, nil\n\t\t\t}\n\t\t\treturn a, nil\n\t\tcase key.Matches(msg, keys.Models):\n\t\t\tif a.showModelDialog {\n\t\t\t\ta.showModelDialog = false\n\t\t\t\treturn a, nil\n\t\t\t}\n\t\t\tif a.currentPage == page.ChatPage && !a.showQuit && !a.showPermissions && !a.showSessionDialog && !a.showCommandDialog {\n\t\t\t\ta.showModelDialog = true\n\t\t\t\treturn a, nil\n\t\t\t}\n\t\t\treturn a, nil\n\t\tcase key.Matches(msg, keys.SwitchTheme):\n\t\t\tif !a.showQuit && !a.showPermissions && !a.showSessionDialog && !a.showCommandDialog {\n\t\t\t\t// Show theme switcher dialog\n\t\t\t\ta.showThemeDialog = true\n\t\t\t\t// Theme list is dynamically loaded by the dialog component\n\t\t\t\treturn a, a.themeDialog.Init()\n\t\t\t}\n\t\t\treturn a, nil\n\t\tcase key.Matches(msg, returnKey) || key.Matches(msg):\n\t\t\tif msg.String() == quitKey {\n\t\t\t\tif a.currentPage == page.LogsPage {\n\t\t\t\t\treturn a, a.moveToPage(page.ChatPage)\n\t\t\t\t}\n\t\t\t} else if !a.filepicker.IsCWDFocused() {\n\t\t\t\tif a.showQuit {\n\t\t\t\t\ta.showQuit = !a.showQuit\n\t\t\t\t\treturn a, nil\n\t\t\t\t}\n\t\t\t\tif a.showHelp {\n\t\t\t\t\ta.showHelp = !a.showHelp\n\t\t\t\t\treturn a, nil\n\t\t\t\t}\n\t\t\t\tif a.showInitDialog {\n\t\t\t\t\ta.showInitDialog = false\n\t\t\t\t\t// Mark the project as initialized without running the command\n\t\t\t\t\tif err := config.MarkProjectInitialized(); err != nil {\n\t\t\t\t\t\treturn a, util.ReportError(err)\n\t\t\t\t\t}\n\t\t\t\t\treturn a, nil\n\t\t\t\t}\n\t\t\t\tif a.showFilepicker {\n\t\t\t\t\ta.showFilepicker = false\n\t\t\t\t\ta.filepicker.ToggleFilepicker(a.showFilepicker)\n\t\t\t\t\treturn a, nil\n\t\t\t\t}\n\t\t\t\tif a.currentPage == page.LogsPage {\n\t\t\t\t\treturn a, a.moveToPage(page.ChatPage)\n\t\t\t\t}\n\t\t\t}\n\t\tcase key.Matches(msg, keys.Logs):\n\t\t\treturn a, a.moveToPage(page.LogsPage)\n\t\tcase key.Matches(msg, keys.Help):\n\t\t\tif a.showQuit {\n\t\t\t\treturn a, nil\n\t\t\t}\n\t\t\ta.showHelp = !a.showHelp\n\t\t\treturn a, nil\n\t\tcase key.Matches(msg, helpEsc):\n\t\t\tif a.app.CoderAgent.IsBusy() {\n\t\t\t\tif a.showQuit {\n\t\t\t\t\treturn a, nil\n\t\t\t\t}\n\t\t\t\ta.showHelp = !a.showHelp\n\t\t\t\treturn a, nil\n\t\t\t}\n\t\tcase key.Matches(msg, keys.Filepicker):\n\t\t\ta.showFilepicker = !a.showFilepicker\n\t\t\ta.filepicker.ToggleFilepicker(a.showFilepicker)\n\t\t\treturn a, nil\n\t\t}\n\tdefault:\n\t\tf, filepickerCmd := a.filepicker.Update(msg)\n\t\ta.filepicker = f.(dialog.FilepickerCmp)\n\t\tcmds = append(cmds, filepickerCmd)\n\n\t}\n\n\tif a.showFilepicker {\n\t\tf, filepickerCmd := a.filepicker.Update(msg)\n\t\ta.filepicker = f.(dialog.FilepickerCmp)\n\t\tcmds = append(cmds, filepickerCmd)\n\t\t// Only block key messages send all other messages down\n\t\tif _, ok := msg.(tea.KeyMsg); ok {\n\t\t\treturn a, tea.Batch(cmds...)\n\t\t}\n\t}\n\n\tif a.showQuit {\n\t\tq, quitCmd := a.quit.Update(msg)\n\t\ta.quit = q.(dialog.QuitDialog)\n\t\tcmds = append(cmds, quitCmd)\n\t\t// Only block key messages send all other messages down\n\t\tif _, ok := msg.(tea.KeyMsg); ok {\n\t\t\treturn a, tea.Batch(cmds...)\n\t\t}\n\t}\n\tif a.showPermissions {\n\t\td, permissionsCmd := a.permissions.Update(msg)\n\t\ta.permissions = d.(dialog.PermissionDialogCmp)\n\t\tcmds = append(cmds, permissionsCmd)\n\t\t// Only block key messages send all other messages down\n\t\tif _, ok := msg.(tea.KeyMsg); ok {\n\t\t\treturn a, tea.Batch(cmds...)\n\t\t}\n\t}\n\n\tif a.showSessionDialog {\n\t\td, sessionCmd := a.sessionDialog.Update(msg)\n\t\ta.sessionDialog = d.(dialog.SessionDialog)\n\t\tcmds = append(cmds, sessionCmd)\n\t\t// Only block key messages send all other messages down\n\t\tif _, ok := msg.(tea.KeyMsg); ok {\n\t\t\treturn a, tea.Batch(cmds...)\n\t\t}\n\t}\n\n\tif a.showCommandDialog {\n\t\td, commandCmd := a.commandDialog.Update(msg)\n\t\ta.commandDialog = d.(dialog.CommandDialog)\n\t\tcmds = append(cmds, commandCmd)\n\t\t// Only block key messages send all other messages down\n\t\tif _, ok := msg.(tea.KeyMsg); ok {\n\t\t\treturn a, tea.Batch(cmds...)\n\t\t}\n\t}\n\n\tif a.showModelDialog {\n\t\td, modelCmd := a.modelDialog.Update(msg)\n\t\ta.modelDialog = d.(dialog.ModelDialog)\n\t\tcmds = append(cmds, modelCmd)\n\t\t// Only block key messages send all other messages down\n\t\tif _, ok := msg.(tea.KeyMsg); ok {\n\t\t\treturn a, tea.Batch(cmds...)\n\t\t}\n\t}\n\n\tif a.showInitDialog {\n\t\td, initCmd := a.initDialog.Update(msg)\n\t\ta.initDialog = d.(dialog.InitDialogCmp)\n\t\tcmds = append(cmds, initCmd)\n\t\t// Only block key messages send all other messages down\n\t\tif _, ok := msg.(tea.KeyMsg); ok {\n\t\t\treturn a, tea.Batch(cmds...)\n\t\t}\n\t}\n\n\tif a.showThemeDialog {\n\t\td, themeCmd := a.themeDialog.Update(msg)\n\t\ta.themeDialog = d.(dialog.ThemeDialog)\n\t\tcmds = append(cmds, themeCmd)\n\t\t// Only block key messages send all other messages down\n\t\tif _, ok := msg.(tea.KeyMsg); ok {\n\t\t\treturn a, tea.Batch(cmds...)\n\t\t}\n\t}\n\n\ts, _ := a.status.Update(msg)\n\ta.status = s.(core.StatusCmp)\n\ta.pages[a.currentPage], cmd = a.pages[a.currentPage].Update(msg)\n\tcmds = append(cmds, cmd)\n\treturn a, tea.Batch(cmds...)\n}\n\n// RegisterCommand adds a command to the command dialog\nfunc (a *appModel) RegisterCommand(cmd dialog.Command) {\n\ta.commands = append(a.commands, cmd)\n}\n\nfunc (a *appModel) findCommand(id string) (dialog.Command, bool) {\n\tfor _, cmd := range a.commands {\n\t\tif cmd.ID == id {\n\t\t\treturn cmd, true\n\t\t}\n\t}\n\treturn dialog.Command{}, false\n}\n\nfunc (a *appModel) moveToPage(pageID page.PageID) tea.Cmd {\n\tif a.app.CoderAgent.IsBusy() {\n\t\t// For now we don't move to any page if the agent is busy\n\t\treturn util.ReportWarn(\"Agent is busy, please wait...\")\n\t}\n\n\tvar cmds []tea.Cmd\n\tif _, ok := a.loadedPages[pageID]; !ok {\n\t\tcmd := a.pages[pageID].Init()\n\t\tcmds = append(cmds, cmd)\n\t\ta.loadedPages[pageID] = true\n\t}\n\ta.previousPage = a.currentPage\n\ta.currentPage = pageID\n\tif sizable, ok := a.pages[a.currentPage].(layout.Sizeable); ok {\n\t\tcmd := sizable.SetSize(a.width, a.height)\n\t\tcmds = append(cmds, cmd)\n\t}\n\n\treturn tea.Batch(cmds...)\n}\n\nfunc (a appModel) View() string {\n\tcomponents := []string{\n\t\ta.pages[a.currentPage].View(),\n\t}\n\n\tcomponents = append(components, a.status.View())\n\n\tappView := lipgloss.JoinVertical(lipgloss.Top, components...)\n\n\tif a.showPermissions {\n\t\toverlay := a.permissions.View()\n\t\trow := lipgloss.Height(appView) / 2\n\t\trow -= lipgloss.Height(overlay) / 2\n\t\tcol := lipgloss.Width(appView) / 2\n\t\tcol -= lipgloss.Width(overlay) / 2\n\t\tappView = layout.PlaceOverlay(\n\t\t\tcol,\n\t\t\trow,\n\t\t\toverlay,\n\t\t\tappView,\n\t\t\ttrue,\n\t\t)\n\t}\n\n\tif a.showFilepicker {\n\t\toverlay := a.filepicker.View()\n\t\trow := lipgloss.Height(appView) / 2\n\t\trow -= lipgloss.Height(overlay) / 2\n\t\tcol := lipgloss.Width(appView) / 2\n\t\tcol -= lipgloss.Width(overlay) / 2\n\t\tappView = layout.PlaceOverlay(\n\t\t\tcol,\n\t\t\trow,\n\t\t\toverlay,\n\t\t\tappView,\n\t\t\ttrue,\n\t\t)\n\n\t}\n\n\t// Show compacting status overlay\n\tif a.isCompacting {\n\t\tt := theme.CurrentTheme()\n\t\tstyle := lipgloss.NewStyle().\n\t\t\tBorder(lipgloss.RoundedBorder()).\n\t\t\tBorderForeground(t.BorderFocused()).\n\t\t\tBorderBackground(t.Background()).\n\t\t\tPadding(1, 2).\n\t\t\tBackground(t.Background()).\n\t\t\tForeground(t.Text())\n\n\t\toverlay := style.Render(\"Summarizing\\n\" + a.compactingMessage)\n\t\trow := lipgloss.Height(appView) / 2\n\t\trow -= lipgloss.Height(overlay) / 2\n\t\tcol := lipgloss.Width(appView) / 2\n\t\tcol -= lipgloss.Width(overlay) / 2\n\t\tappView = layout.PlaceOverlay(\n\t\t\tcol,\n\t\t\trow,\n\t\t\toverlay,\n\t\t\tappView,\n\t\t\ttrue,\n\t\t)\n\t}\n\n\tif a.showHelp {\n\t\tbindings := layout.KeyMapToSlice(keys)\n\t\tif p, ok := a.pages[a.currentPage].(layout.Bindings); ok {\n\t\t\tbindings = append(bindings, p.BindingKeys()...)\n\t\t}\n\t\tif a.showPermissions {\n\t\t\tbindings = append(bindings, a.permissions.BindingKeys()...)\n\t\t}\n\t\tif a.currentPage == page.LogsPage {\n\t\t\tbindings = append(bindings, logsKeyReturnKey)\n\t\t}\n\t\tif !a.app.CoderAgent.IsBusy() {\n\t\t\tbindings = append(bindings, helpEsc)\n\t\t}\n\t\ta.help.SetBindings(bindings)\n\n\t\toverlay := a.help.View()\n\t\trow := lipgloss.Height(appView) / 2\n\t\trow -= lipgloss.Height(overlay) / 2\n\t\tcol := lipgloss.Width(appView) / 2\n\t\tcol -= lipgloss.Width(overlay) / 2\n\t\tappView = layout.PlaceOverlay(\n\t\t\tcol,\n\t\t\trow,\n\t\t\toverlay,\n\t\t\tappView,\n\t\t\ttrue,\n\t\t)\n\t}\n\n\tif a.showQuit {\n\t\toverlay := a.quit.View()\n\t\trow := lipgloss.Height(appView) / 2\n\t\trow -= lipgloss.Height(overlay) / 2\n\t\tcol := lipgloss.Width(appView) / 2\n\t\tcol -= lipgloss.Width(overlay) / 2\n\t\tappView = layout.PlaceOverlay(\n\t\t\tcol,\n\t\t\trow,\n\t\t\toverlay,\n\t\t\tappView,\n\t\t\ttrue,\n\t\t)\n\t}\n\n\tif a.showSessionDialog {\n\t\toverlay := a.sessionDialog.View()\n\t\trow := lipgloss.Height(appView) / 2\n\t\trow -= lipgloss.Height(overlay) / 2\n\t\tcol := lipgloss.Width(appView) / 2\n\t\tcol -= lipgloss.Width(overlay) / 2\n\t\tappView = layout.PlaceOverlay(\n\t\t\tcol,\n\t\t\trow,\n\t\t\toverlay,\n\t\t\tappView,\n\t\t\ttrue,\n\t\t)\n\t}\n\n\tif a.showModelDialog {\n\t\toverlay := a.modelDialog.View()\n\t\trow := lipgloss.Height(appView) / 2\n\t\trow -= lipgloss.Height(overlay) / 2\n\t\tcol := lipgloss.Width(appView) / 2\n\t\tcol -= lipgloss.Width(overlay) / 2\n\t\tappView = layout.PlaceOverlay(\n\t\t\tcol,\n\t\t\trow,\n\t\t\toverlay,\n\t\t\tappView,\n\t\t\ttrue,\n\t\t)\n\t}\n\n\tif a.showCommandDialog {\n\t\toverlay := a.commandDialog.View()\n\t\trow := lipgloss.Height(appView) / 2\n\t\trow -= lipgloss.Height(overlay) / 2\n\t\tcol := lipgloss.Width(appView) / 2\n\t\tcol -= lipgloss.Width(overlay) / 2\n\t\tappView = layout.PlaceOverlay(\n\t\t\tcol,\n\t\t\trow,\n\t\t\toverlay,\n\t\t\tappView,\n\t\t\ttrue,\n\t\t)\n\t}\n\n\tif a.showInitDialog {\n\t\toverlay := a.initDialog.View()\n\t\tappView = layout.PlaceOverlay(\n\t\t\ta.width/2-lipgloss.Width(overlay)/2,\n\t\t\ta.height/2-lipgloss.Height(overlay)/2,\n\t\t\toverlay,\n\t\t\tappView,\n\t\t\ttrue,\n\t\t)\n\t}\n\n\tif a.showThemeDialog {\n\t\toverlay := a.themeDialog.View()\n\t\trow := lipgloss.Height(appView) / 2\n\t\trow -= lipgloss.Height(overlay) / 2\n\t\tcol := lipgloss.Width(appView) / 2\n\t\tcol -= lipgloss.Width(overlay) / 2\n\t\tappView = layout.PlaceOverlay(\n\t\t\tcol,\n\t\t\trow,\n\t\t\toverlay,\n\t\t\tappView,\n\t\t\ttrue,\n\t\t)\n\t}\n\n\tif a.showMultiArgumentsDialog {\n\t\toverlay := a.multiArgumentsDialog.View()\n\t\trow := lipgloss.Height(appView) / 2\n\t\trow -= lipgloss.Height(overlay) / 2\n\t\tcol := lipgloss.Width(appView) / 2\n\t\tcol -= lipgloss.Width(overlay) / 2\n\t\tappView = layout.PlaceOverlay(\n\t\t\tcol,\n\t\t\trow,\n\t\t\toverlay,\n\t\t\tappView,\n\t\t\ttrue,\n\t\t)\n\t}\n\n\treturn appView\n}\n\nfunc New(app *app.App) tea.Model {\n\tstartPage := page.ChatPage\n\tmodel := &appModel{\n\t\tcurrentPage: startPage,\n\t\tloadedPages: make(map[page.PageID]bool),\n\t\tstatus: core.NewStatusCmp(app.LSPClients),\n\t\thelp: dialog.NewHelpCmp(),\n\t\tquit: dialog.NewQuitCmp(),\n\t\tsessionDialog: dialog.NewSessionDialogCmp(),\n\t\tcommandDialog: dialog.NewCommandDialogCmp(),\n\t\tmodelDialog: dialog.NewModelDialogCmp(),\n\t\tpermissions: dialog.NewPermissionDialogCmp(),\n\t\tinitDialog: dialog.NewInitDialogCmp(),\n\t\tthemeDialog: dialog.NewThemeDialogCmp(),\n\t\tapp: app,\n\t\tcommands: []dialog.Command{},\n\t\tpages: map[page.PageID]tea.Model{\n\t\t\tpage.ChatPage: page.NewChatPage(app),\n\t\t\tpage.LogsPage: page.NewLogsPage(),\n\t\t},\n\t\tfilepicker: dialog.NewFilepickerCmp(app),\n\t}\n\n\tmodel.RegisterCommand(dialog.Command{\n\t\tID: \"init\",\n\t\tTitle: \"Initialize Project\",\n\t\tDescription: \"Create/Update the OpenCode.md memory file\",\n\t\tHandler: func(cmd dialog.Command) tea.Cmd {\n\t\t\tprompt := `Please analyze this codebase and create a OpenCode.md file containing:\n1. Build/lint/test commands - especially for running a single test\n2. Code style guidelines including imports, formatting, types, naming conventions, error handling, etc.\n\nThe file you create will be given to agentic coding agents (such as yourself) that operate in this repository. Make it about 20 lines long.\nIf there's already a opencode.md, improve it.\nIf there are Cursor rules (in .cursor/rules/ or .cursorrules) or Copilot rules (in .github/copilot-instructions.md), make sure to include them.`\n\t\t\treturn tea.Batch(\n\t\t\t\tutil.CmdHandler(chat.SendMsg{\n\t\t\t\t\tText: prompt,\n\t\t\t\t}),\n\t\t\t)\n\t\t},\n\t})\n\n\tmodel.RegisterCommand(dialog.Command{\n\t\tID: \"compact\",\n\t\tTitle: \"Compact Session\",\n\t\tDescription: \"Summarize the current session and create a new one with the summary\",\n\t\tHandler: func(cmd dialog.Command) tea.Cmd {\n\t\t\treturn func() tea.Msg {\n\t\t\t\treturn startCompactSessionMsg{}\n\t\t\t}\n\t\t},\n\t})\n\t// Load custom commands\n\tcustomCommands, err := dialog.LoadCustomCommands()\n\tif err != nil {\n\t\tlogging.Warn(\"Failed to load custom commands\", \"error\", err)\n\t} else {\n\t\tfor _, cmd := range customCommands {\n\t\t\tmodel.RegisterCommand(cmd)\n\t\t}\n\t}\n\n\treturn model\n}\n"], ["/opencode/internal/diff/patch.go", "package diff\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"strings\"\n)\n\ntype ActionType string\n\nconst (\n\tActionAdd ActionType = \"add\"\n\tActionDelete ActionType = \"delete\"\n\tActionUpdate ActionType = \"update\"\n)\n\ntype FileChange struct {\n\tType ActionType\n\tOldContent *string\n\tNewContent *string\n\tMovePath *string\n}\n\ntype Commit struct {\n\tChanges map[string]FileChange\n}\n\ntype Chunk struct {\n\tOrigIndex int // line index of the first line in the original file\n\tDelLines []string // lines to delete\n\tInsLines []string // lines to insert\n}\n\ntype PatchAction struct {\n\tType ActionType\n\tNewFile *string\n\tChunks []Chunk\n\tMovePath *string\n}\n\ntype Patch struct {\n\tActions map[string]PatchAction\n}\n\ntype DiffError struct {\n\tmessage string\n}\n\nfunc (e DiffError) Error() string {\n\treturn e.message\n}\n\n// Helper functions for error handling\nfunc NewDiffError(message string) DiffError {\n\treturn DiffError{message: message}\n}\n\nfunc fileError(action, reason, path string) DiffError {\n\treturn NewDiffError(fmt.Sprintf(\"%s File Error: %s: %s\", action, reason, path))\n}\n\nfunc contextError(index int, context string, isEOF bool) DiffError {\n\tprefix := \"Invalid Context\"\n\tif isEOF {\n\t\tprefix = \"Invalid EOF Context\"\n\t}\n\treturn NewDiffError(fmt.Sprintf(\"%s %d:\\n%s\", prefix, index, context))\n}\n\ntype Parser struct {\n\tcurrentFiles map[string]string\n\tlines []string\n\tindex int\n\tpatch Patch\n\tfuzz int\n}\n\nfunc NewParser(currentFiles map[string]string, lines []string) *Parser {\n\treturn &Parser{\n\t\tcurrentFiles: currentFiles,\n\t\tlines: lines,\n\t\tindex: 0,\n\t\tpatch: Patch{Actions: make(map[string]PatchAction, len(currentFiles))},\n\t\tfuzz: 0,\n\t}\n}\n\nfunc (p *Parser) isDone(prefixes []string) bool {\n\tif p.index >= len(p.lines) {\n\t\treturn true\n\t}\n\tfor _, prefix := range prefixes {\n\t\tif strings.HasPrefix(p.lines[p.index], prefix) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc (p *Parser) startsWith(prefix any) bool {\n\tvar prefixes []string\n\tswitch v := prefix.(type) {\n\tcase string:\n\t\tprefixes = []string{v}\n\tcase []string:\n\t\tprefixes = v\n\t}\n\n\tfor _, pfx := range prefixes {\n\t\tif strings.HasPrefix(p.lines[p.index], pfx) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc (p *Parser) readStr(prefix string, returnEverything bool) string {\n\tif p.index >= len(p.lines) {\n\t\treturn \"\" // Changed from panic to return empty string for safer operation\n\t}\n\tif strings.HasPrefix(p.lines[p.index], prefix) {\n\t\tvar text string\n\t\tif returnEverything {\n\t\t\ttext = p.lines[p.index]\n\t\t} else {\n\t\t\ttext = p.lines[p.index][len(prefix):]\n\t\t}\n\t\tp.index++\n\t\treturn text\n\t}\n\treturn \"\"\n}\n\nfunc (p *Parser) Parse() error {\n\tendPatchPrefixes := []string{\"*** End Patch\"}\n\n\tfor !p.isDone(endPatchPrefixes) {\n\t\tpath := p.readStr(\"*** Update File: \", false)\n\t\tif path != \"\" {\n\t\t\tif _, exists := p.patch.Actions[path]; exists {\n\t\t\t\treturn fileError(\"Update\", \"Duplicate Path\", path)\n\t\t\t}\n\t\t\tmoveTo := p.readStr(\"*** Move to: \", false)\n\t\t\tif _, exists := p.currentFiles[path]; !exists {\n\t\t\t\treturn fileError(\"Update\", \"Missing File\", path)\n\t\t\t}\n\t\t\ttext := p.currentFiles[path]\n\t\t\taction, err := p.parseUpdateFile(text)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif moveTo != \"\" {\n\t\t\t\taction.MovePath = &moveTo\n\t\t\t}\n\t\t\tp.patch.Actions[path] = action\n\t\t\tcontinue\n\t\t}\n\n\t\tpath = p.readStr(\"*** Delete File: \", false)\n\t\tif path != \"\" {\n\t\t\tif _, exists := p.patch.Actions[path]; exists {\n\t\t\t\treturn fileError(\"Delete\", \"Duplicate Path\", path)\n\t\t\t}\n\t\t\tif _, exists := p.currentFiles[path]; !exists {\n\t\t\t\treturn fileError(\"Delete\", \"Missing File\", path)\n\t\t\t}\n\t\t\tp.patch.Actions[path] = PatchAction{Type: ActionDelete, Chunks: []Chunk{}}\n\t\t\tcontinue\n\t\t}\n\n\t\tpath = p.readStr(\"*** Add File: \", false)\n\t\tif path != \"\" {\n\t\t\tif _, exists := p.patch.Actions[path]; exists {\n\t\t\t\treturn fileError(\"Add\", \"Duplicate Path\", path)\n\t\t\t}\n\t\t\tif _, exists := p.currentFiles[path]; exists {\n\t\t\t\treturn fileError(\"Add\", \"File already exists\", path)\n\t\t\t}\n\t\t\taction, err := p.parseAddFile()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tp.patch.Actions[path] = action\n\t\t\tcontinue\n\t\t}\n\n\t\treturn NewDiffError(fmt.Sprintf(\"Unknown Line: %s\", p.lines[p.index]))\n\t}\n\n\tif !p.startsWith(\"*** End Patch\") {\n\t\treturn NewDiffError(\"Missing End Patch\")\n\t}\n\tp.index++\n\n\treturn nil\n}\n\nfunc (p *Parser) parseUpdateFile(text string) (PatchAction, error) {\n\taction := PatchAction{Type: ActionUpdate, Chunks: []Chunk{}}\n\tfileLines := strings.Split(text, \"\\n\")\n\tindex := 0\n\n\tendPrefixes := []string{\n\t\t\"*** End Patch\",\n\t\t\"*** Update File:\",\n\t\t\"*** Delete File:\",\n\t\t\"*** Add File:\",\n\t\t\"*** End of File\",\n\t}\n\n\tfor !p.isDone(endPrefixes) {\n\t\tdefStr := p.readStr(\"@@ \", false)\n\t\tsectionStr := \"\"\n\t\tif defStr == \"\" && p.index < len(p.lines) && p.lines[p.index] == \"@@\" {\n\t\t\tsectionStr = p.lines[p.index]\n\t\t\tp.index++\n\t\t}\n\t\tif defStr == \"\" && sectionStr == \"\" && index != 0 {\n\t\t\treturn action, NewDiffError(fmt.Sprintf(\"Invalid Line:\\n%s\", p.lines[p.index]))\n\t\t}\n\t\tif strings.TrimSpace(defStr) != \"\" {\n\t\t\tfound := false\n\t\t\tfor i := range fileLines[:index] {\n\t\t\t\tif fileLines[i] == defStr {\n\t\t\t\t\tfound = true\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif !found {\n\t\t\t\tfor i := index; i < len(fileLines); i++ {\n\t\t\t\t\tif fileLines[i] == defStr {\n\t\t\t\t\t\tindex = i + 1\n\t\t\t\t\t\tfound = true\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif !found {\n\t\t\t\tfor i := range fileLines[:index] {\n\t\t\t\t\tif strings.TrimSpace(fileLines[i]) == strings.TrimSpace(defStr) {\n\t\t\t\t\t\tfound = true\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif !found {\n\t\t\t\tfor i := index; i < len(fileLines); i++ {\n\t\t\t\t\tif strings.TrimSpace(fileLines[i]) == strings.TrimSpace(defStr) {\n\t\t\t\t\t\tindex = i + 1\n\t\t\t\t\t\tp.fuzz++\n\t\t\t\t\t\tfound = true\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tnextChunkContext, chunks, endPatchIndex, eof := peekNextSection(p.lines, p.index)\n\t\tnewIndex, fuzz := findContext(fileLines, nextChunkContext, index, eof)\n\t\tif newIndex == -1 {\n\t\t\tctxText := strings.Join(nextChunkContext, \"\\n\")\n\t\t\treturn action, contextError(index, ctxText, eof)\n\t\t}\n\t\tp.fuzz += fuzz\n\n\t\tfor _, ch := range chunks {\n\t\t\tch.OrigIndex += newIndex\n\t\t\taction.Chunks = append(action.Chunks, ch)\n\t\t}\n\t\tindex = newIndex + len(nextChunkContext)\n\t\tp.index = endPatchIndex\n\t}\n\treturn action, nil\n}\n\nfunc (p *Parser) parseAddFile() (PatchAction, error) {\n\tlines := make([]string, 0, 16) // Preallocate space for better performance\n\tendPrefixes := []string{\n\t\t\"*** End Patch\",\n\t\t\"*** Update File:\",\n\t\t\"*** Delete File:\",\n\t\t\"*** Add File:\",\n\t}\n\n\tfor !p.isDone(endPrefixes) {\n\t\ts := p.readStr(\"\", true)\n\t\tif !strings.HasPrefix(s, \"+\") {\n\t\t\treturn PatchAction{}, NewDiffError(fmt.Sprintf(\"Invalid Add File Line: %s\", s))\n\t\t}\n\t\tlines = append(lines, s[1:])\n\t}\n\n\tnewFile := strings.Join(lines, \"\\n\")\n\treturn PatchAction{\n\t\tType: ActionAdd,\n\t\tNewFile: &newFile,\n\t\tChunks: []Chunk{},\n\t}, nil\n}\n\n// Refactored to use a matcher function for each comparison type\nfunc findContextCore(lines []string, context []string, start int) (int, int) {\n\tif len(context) == 0 {\n\t\treturn start, 0\n\t}\n\n\t// Try exact match\n\tif idx, fuzz := tryFindMatch(lines, context, start, func(a, b string) bool {\n\t\treturn a == b\n\t}); idx >= 0 {\n\t\treturn idx, fuzz\n\t}\n\n\t// Try trimming right whitespace\n\tif idx, fuzz := tryFindMatch(lines, context, start, func(a, b string) bool {\n\t\treturn strings.TrimRight(a, \" \\t\") == strings.TrimRight(b, \" \\t\")\n\t}); idx >= 0 {\n\t\treturn idx, fuzz\n\t}\n\n\t// Try trimming all whitespace\n\tif idx, fuzz := tryFindMatch(lines, context, start, func(a, b string) bool {\n\t\treturn strings.TrimSpace(a) == strings.TrimSpace(b)\n\t}); idx >= 0 {\n\t\treturn idx, fuzz\n\t}\n\n\treturn -1, 0\n}\n\n// Helper function to DRY up the match logic\nfunc tryFindMatch(lines []string, context []string, start int,\n\tcompareFunc func(string, string) bool,\n) (int, int) {\n\tfor i := start; i < len(lines); i++ {\n\t\tif i+len(context) <= len(lines) {\n\t\t\tmatch := true\n\t\t\tfor j := range context {\n\t\t\t\tif !compareFunc(lines[i+j], context[j]) {\n\t\t\t\t\tmatch = false\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\tif match {\n\t\t\t\t// Return fuzz level: 0 for exact, 1 for trimRight, 100 for trimSpace\n\t\t\t\tvar fuzz int\n\t\t\t\tif compareFunc(\"a \", \"a\") && !compareFunc(\"a\", \"b\") {\n\t\t\t\t\tfuzz = 1\n\t\t\t\t} else if compareFunc(\"a \", \"a\") {\n\t\t\t\t\tfuzz = 100\n\t\t\t\t}\n\t\t\t\treturn i, fuzz\n\t\t\t}\n\t\t}\n\t}\n\treturn -1, 0\n}\n\nfunc findContext(lines []string, context []string, start int, eof bool) (int, int) {\n\tif eof {\n\t\tnewIndex, fuzz := findContextCore(lines, context, len(lines)-len(context))\n\t\tif newIndex != -1 {\n\t\t\treturn newIndex, fuzz\n\t\t}\n\t\tnewIndex, fuzz = findContextCore(lines, context, start)\n\t\treturn newIndex, fuzz + 10000\n\t}\n\treturn findContextCore(lines, context, start)\n}\n\nfunc peekNextSection(lines []string, initialIndex int) ([]string, []Chunk, int, bool) {\n\tindex := initialIndex\n\told := make([]string, 0, 32) // Preallocate for better performance\n\tdelLines := make([]string, 0, 8)\n\tinsLines := make([]string, 0, 8)\n\tchunks := make([]Chunk, 0, 4)\n\tmode := \"keep\"\n\n\t// End conditions for the section\n\tendSectionConditions := func(s string) bool {\n\t\treturn strings.HasPrefix(s, \"@@\") ||\n\t\t\tstrings.HasPrefix(s, \"*** End Patch\") ||\n\t\t\tstrings.HasPrefix(s, \"*** Update File:\") ||\n\t\t\tstrings.HasPrefix(s, \"*** Delete File:\") ||\n\t\t\tstrings.HasPrefix(s, \"*** Add File:\") ||\n\t\t\tstrings.HasPrefix(s, \"*** End of File\") ||\n\t\t\ts == \"***\" ||\n\t\t\tstrings.HasPrefix(s, \"***\")\n\t}\n\n\tfor index < len(lines) {\n\t\ts := lines[index]\n\t\tif endSectionConditions(s) {\n\t\t\tbreak\n\t\t}\n\t\tindex++\n\t\tlastMode := mode\n\t\tline := s\n\n\t\tif len(line) > 0 {\n\t\t\tswitch line[0] {\n\t\t\tcase '+':\n\t\t\t\tmode = \"add\"\n\t\t\tcase '-':\n\t\t\t\tmode = \"delete\"\n\t\t\tcase ' ':\n\t\t\t\tmode = \"keep\"\n\t\t\tdefault:\n\t\t\t\tmode = \"keep\"\n\t\t\t\tline = \" \" + line\n\t\t\t}\n\t\t} else {\n\t\t\tmode = \"keep\"\n\t\t\tline = \" \"\n\t\t}\n\n\t\tline = line[1:]\n\t\tif mode == \"keep\" && lastMode != mode {\n\t\t\tif len(insLines) > 0 || len(delLines) > 0 {\n\t\t\t\tchunks = append(chunks, Chunk{\n\t\t\t\t\tOrigIndex: len(old) - len(delLines),\n\t\t\t\t\tDelLines: delLines,\n\t\t\t\t\tInsLines: insLines,\n\t\t\t\t})\n\t\t\t}\n\t\t\tdelLines = make([]string, 0, 8)\n\t\t\tinsLines = make([]string, 0, 8)\n\t\t}\n\t\tswitch mode {\n\t\tcase \"delete\":\n\t\t\tdelLines = append(delLines, line)\n\t\t\told = append(old, line)\n\t\tcase \"add\":\n\t\t\tinsLines = append(insLines, line)\n\t\tdefault:\n\t\t\told = append(old, line)\n\t\t}\n\t}\n\n\tif len(insLines) > 0 || len(delLines) > 0 {\n\t\tchunks = append(chunks, Chunk{\n\t\t\tOrigIndex: len(old) - len(delLines),\n\t\t\tDelLines: delLines,\n\t\t\tInsLines: insLines,\n\t\t})\n\t}\n\n\tif index < len(lines) && lines[index] == \"*** End of File\" {\n\t\tindex++\n\t\treturn old, chunks, index, true\n\t}\n\treturn old, chunks, index, false\n}\n\nfunc TextToPatch(text string, orig map[string]string) (Patch, int, error) {\n\ttext = strings.TrimSpace(text)\n\tlines := strings.Split(text, \"\\n\")\n\tif len(lines) < 2 || !strings.HasPrefix(lines[0], \"*** Begin Patch\") || lines[len(lines)-1] != \"*** End Patch\" {\n\t\treturn Patch{}, 0, NewDiffError(\"Invalid patch text\")\n\t}\n\tparser := NewParser(orig, lines)\n\tparser.index = 1\n\tif err := parser.Parse(); err != nil {\n\t\treturn Patch{}, 0, err\n\t}\n\treturn parser.patch, parser.fuzz, nil\n}\n\nfunc IdentifyFilesNeeded(text string) []string {\n\ttext = strings.TrimSpace(text)\n\tlines := strings.Split(text, \"\\n\")\n\tresult := make(map[string]bool)\n\n\tfor _, line := range lines {\n\t\tif strings.HasPrefix(line, \"*** Update File: \") {\n\t\t\tresult[line[len(\"*** Update File: \"):]] = true\n\t\t}\n\t\tif strings.HasPrefix(line, \"*** Delete File: \") {\n\t\t\tresult[line[len(\"*** Delete File: \"):]] = true\n\t\t}\n\t}\n\n\tfiles := make([]string, 0, len(result))\n\tfor file := range result {\n\t\tfiles = append(files, file)\n\t}\n\treturn files\n}\n\nfunc IdentifyFilesAdded(text string) []string {\n\ttext = strings.TrimSpace(text)\n\tlines := strings.Split(text, \"\\n\")\n\tresult := make(map[string]bool)\n\n\tfor _, line := range lines {\n\t\tif strings.HasPrefix(line, \"*** Add File: \") {\n\t\t\tresult[line[len(\"*** Add File: \"):]] = true\n\t\t}\n\t}\n\n\tfiles := make([]string, 0, len(result))\n\tfor file := range result {\n\t\tfiles = append(files, file)\n\t}\n\treturn files\n}\n\nfunc getUpdatedFile(text string, action PatchAction, path string) (string, error) {\n\tif action.Type != ActionUpdate {\n\t\treturn \"\", errors.New(\"expected UPDATE action\")\n\t}\n\torigLines := strings.Split(text, \"\\n\")\n\tdestLines := make([]string, 0, len(origLines)) // Preallocate with capacity\n\torigIndex := 0\n\n\tfor _, chunk := range action.Chunks {\n\t\tif chunk.OrigIndex > len(origLines) {\n\t\t\treturn \"\", NewDiffError(fmt.Sprintf(\"%s: chunk.orig_index %d > len(lines) %d\", path, chunk.OrigIndex, len(origLines)))\n\t\t}\n\t\tif origIndex > chunk.OrigIndex {\n\t\t\treturn \"\", NewDiffError(fmt.Sprintf(\"%s: orig_index %d > chunk.orig_index %d\", path, origIndex, chunk.OrigIndex))\n\t\t}\n\t\tdestLines = append(destLines, origLines[origIndex:chunk.OrigIndex]...)\n\t\tdelta := chunk.OrigIndex - origIndex\n\t\torigIndex += delta\n\n\t\tif len(chunk.InsLines) > 0 {\n\t\t\tdestLines = append(destLines, chunk.InsLines...)\n\t\t}\n\t\torigIndex += len(chunk.DelLines)\n\t}\n\n\tdestLines = append(destLines, origLines[origIndex:]...)\n\treturn strings.Join(destLines, \"\\n\"), nil\n}\n\nfunc PatchToCommit(patch Patch, orig map[string]string) (Commit, error) {\n\tcommit := Commit{Changes: make(map[string]FileChange, len(patch.Actions))}\n\tfor pathKey, action := range patch.Actions {\n\t\tswitch action.Type {\n\t\tcase ActionDelete:\n\t\t\toldContent := orig[pathKey]\n\t\t\tcommit.Changes[pathKey] = FileChange{\n\t\t\t\tType: ActionDelete,\n\t\t\t\tOldContent: &oldContent,\n\t\t\t}\n\t\tcase ActionAdd:\n\t\t\tcommit.Changes[pathKey] = FileChange{\n\t\t\t\tType: ActionAdd,\n\t\t\t\tNewContent: action.NewFile,\n\t\t\t}\n\t\tcase ActionUpdate:\n\t\t\tnewContent, err := getUpdatedFile(orig[pathKey], action, pathKey)\n\t\t\tif err != nil {\n\t\t\t\treturn Commit{}, err\n\t\t\t}\n\t\t\toldContent := orig[pathKey]\n\t\t\tfileChange := FileChange{\n\t\t\t\tType: ActionUpdate,\n\t\t\t\tOldContent: &oldContent,\n\t\t\t\tNewContent: &newContent,\n\t\t\t}\n\t\t\tif action.MovePath != nil {\n\t\t\t\tfileChange.MovePath = action.MovePath\n\t\t\t}\n\t\t\tcommit.Changes[pathKey] = fileChange\n\t\t}\n\t}\n\treturn commit, nil\n}\n\nfunc AssembleChanges(orig map[string]string, updatedFiles map[string]string) Commit {\n\tcommit := Commit{Changes: make(map[string]FileChange, len(updatedFiles))}\n\tfor p, newContent := range updatedFiles {\n\t\toldContent, exists := orig[p]\n\t\tif exists && oldContent == newContent {\n\t\t\tcontinue\n\t\t}\n\n\t\tif exists && newContent != \"\" {\n\t\t\tcommit.Changes[p] = FileChange{\n\t\t\t\tType: ActionUpdate,\n\t\t\t\tOldContent: &oldContent,\n\t\t\t\tNewContent: &newContent,\n\t\t\t}\n\t\t} else if newContent != \"\" {\n\t\t\tcommit.Changes[p] = FileChange{\n\t\t\t\tType: ActionAdd,\n\t\t\t\tNewContent: &newContent,\n\t\t\t}\n\t\t} else if exists {\n\t\t\tcommit.Changes[p] = FileChange{\n\t\t\t\tType: ActionDelete,\n\t\t\t\tOldContent: &oldContent,\n\t\t\t}\n\t\t} else {\n\t\t\treturn commit // Changed from panic to simply return current commit\n\t\t}\n\t}\n\treturn commit\n}\n\nfunc LoadFiles(paths []string, openFn func(string) (string, error)) (map[string]string, error) {\n\torig := make(map[string]string, len(paths))\n\tfor _, p := range paths {\n\t\tcontent, err := openFn(p)\n\t\tif err != nil {\n\t\t\treturn nil, fileError(\"Open\", \"File not found\", p)\n\t\t}\n\t\torig[p] = content\n\t}\n\treturn orig, nil\n}\n\nfunc ApplyCommit(commit Commit, writeFn func(string, string) error, removeFn func(string) error) error {\n\tfor p, change := range commit.Changes {\n\t\tswitch change.Type {\n\t\tcase ActionDelete:\n\t\t\tif err := removeFn(p); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\tcase ActionAdd:\n\t\t\tif change.NewContent == nil {\n\t\t\t\treturn NewDiffError(fmt.Sprintf(\"Add action for %s has nil new_content\", p))\n\t\t\t}\n\t\t\tif err := writeFn(p, *change.NewContent); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\tcase ActionUpdate:\n\t\t\tif change.NewContent == nil {\n\t\t\t\treturn NewDiffError(fmt.Sprintf(\"Update action for %s has nil new_content\", p))\n\t\t\t}\n\t\t\tif change.MovePath != nil {\n\t\t\t\tif err := writeFn(*change.MovePath, *change.NewContent); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tif err := removeFn(p); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif err := writeFn(p, *change.NewContent); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc ProcessPatch(text string, openFn func(string) (string, error), writeFn func(string, string) error, removeFn func(string) error) (string, error) {\n\tif !strings.HasPrefix(text, \"*** Begin Patch\") {\n\t\treturn \"\", NewDiffError(\"Patch must start with *** Begin Patch\")\n\t}\n\tpaths := IdentifyFilesNeeded(text)\n\torig, err := LoadFiles(paths, openFn)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tpatch, fuzz, err := TextToPatch(text, orig)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif fuzz > 0 {\n\t\treturn \"\", NewDiffError(fmt.Sprintf(\"Patch contains fuzzy matches (fuzz level: %d)\", fuzz))\n\t}\n\n\tcommit, err := PatchToCommit(patch, orig)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif err := ApplyCommit(commit, writeFn, removeFn); err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn \"Patch applied successfully\", nil\n}\n\nfunc OpenFile(p string) (string, error) {\n\tdata, err := os.ReadFile(p)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn string(data), nil\n}\n\nfunc WriteFile(p string, content string) error {\n\tif filepath.IsAbs(p) {\n\t\treturn NewDiffError(\"We do not support absolute paths.\")\n\t}\n\n\tdir := filepath.Dir(p)\n\tif dir != \".\" {\n\t\tif err := os.MkdirAll(dir, 0o755); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn os.WriteFile(p, []byte(content), 0o644)\n}\n\nfunc RemoveFile(p string) error {\n\treturn os.Remove(p)\n}\n\nfunc ValidatePatch(patchText string, files map[string]string) (bool, string, error) {\n\tif !strings.HasPrefix(patchText, \"*** Begin Patch\") {\n\t\treturn false, \"Patch must start with *** Begin Patch\", nil\n\t}\n\n\tneededFiles := IdentifyFilesNeeded(patchText)\n\tfor _, filePath := range neededFiles {\n\t\tif _, exists := files[filePath]; !exists {\n\t\t\treturn false, fmt.Sprintf(\"File not found: %s\", filePath), nil\n\t\t}\n\t}\n\n\tpatch, fuzz, err := TextToPatch(patchText, files)\n\tif err != nil {\n\t\treturn false, err.Error(), nil\n\t}\n\n\tif fuzz > 0 {\n\t\treturn false, fmt.Sprintf(\"Patch contains fuzzy matches (fuzz level: %d)\", fuzz), nil\n\t}\n\n\t_, err = PatchToCommit(patch, files)\n\tif err != nil {\n\t\treturn false, err.Error(), nil\n\t}\n\n\treturn true, \"Patch is valid\", nil\n}\n"], ["/opencode/internal/llm/prompt/coder.go", "package prompt\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"runtime\"\n\t\"time\"\n\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/llm/models\"\n\t\"github.com/opencode-ai/opencode/internal/llm/tools\"\n)\n\nfunc CoderPrompt(provider models.ModelProvider) string {\n\tbasePrompt := baseAnthropicCoderPrompt\n\tswitch provider {\n\tcase models.ProviderOpenAI:\n\t\tbasePrompt = baseOpenAICoderPrompt\n\t}\n\tenvInfo := getEnvironmentInfo()\n\n\treturn fmt.Sprintf(\"%s\\n\\n%s\\n%s\", basePrompt, envInfo, lspInformation())\n}\n\nconst baseOpenAICoderPrompt = `\nYou are operating as and within the OpenCode CLI, a terminal-based agentic coding assistant built by OpenAI. It wraps OpenAI models to enable natural language interaction with a local codebase. You are expected to be precise, safe, and helpful.\n\nYou can:\n- Receive user prompts, project context, and files.\n- Stream responses and emit function calls (e.g., shell commands, code edits).\n- Apply patches, run commands, and manage user approvals based on policy.\n- Work inside a sandboxed, git-backed workspace with rollback support.\n- Log telemetry so sessions can be replayed or inspected later.\n- More details on your functionality are available at \"opencode --help\"\n\n\nYou are an agent - please keep going until the user's query is completely resolved, before ending your turn and yielding back to the user. Only terminate your turn when you are sure that the problem is solved. If you are not sure about file content or codebase structure pertaining to the user's request, use your tools to read files and gather the relevant information: do NOT guess or make up an answer.\n\nPlease resolve the user's task by editing and testing the code files in your current code execution session. You are a deployed coding agent. Your session allows for you to modify and run code. The repo(s) are already cloned in your working directory, and you must fully solve the problem for your answer to be considered correct.\n\nYou MUST adhere to the following criteria when executing the task:\n- Working on the repo(s) in the current environment is allowed, even if they are proprietary.\n- Analyzing code for vulnerabilities is allowed.\n- Showing user code and tool call details is allowed.\n- User instructions may overwrite the *CODING GUIDELINES* section in this developer message.\n- If completing the user's task requires writing or modifying files:\n - Your code and final answer should follow these *CODING GUIDELINES*:\n - Fix the problem at the root cause rather than applying surface-level patches, when possible.\n - Avoid unneeded complexity in your solution.\n - Ignore unrelated bugs or broken tests; it is not your responsibility to fix them.\n - Update documentation as necessary.\n - Keep changes consistent with the style of the existing codebase. Changes should be minimal and focused on the task.\n - Use \"git log\" and \"git blame\" to search the history of the codebase if additional context is required; internet access is disabled.\n - NEVER add copyright or license headers unless specifically requested.\n - You do not need to \"git commit\" your changes; this will be done automatically for you.\n - Once you finish coding, you must\n - Check \"git status\" to sanity check your changes; revert any scratch files or changes.\n - Remove all inline comments you added as much as possible, even if they look normal. Check using \"git diff\". Inline comments must be generally avoided, unless active maintainers of the repo, after long careful study of the code and the issue, will still misinterpret the code without the comments.\n - Check if you accidentally add copyright or license headers. If so, remove them.\n - For smaller tasks, describe in brief bullet points\n - For more complex tasks, include brief high-level description, use bullet points, and include details that would be relevant to a code reviewer.\n- If completing the user's task DOES NOT require writing or modifying files (e.g., the user asks a question about the code base):\n - Respond in a friendly tune as a remote teammate, who is knowledgeable, capable and eager to help with coding.\n- When your task involves writing or modifying files:\n - Do NOT tell the user to \"save the file\" or \"copy the code into a file\" if you already created or modified the file using \"apply_patch\". Instead, reference the file as already saved.\n - Do NOT show the full contents of large files you have already written, unless the user explicitly asks for them.\n- When doing things with paths, always use use the full path, if the working directory is /abc/xyz and you want to edit the file abc.go in the working dir refer to it as /abc/xyz/abc.go.\n- If you send a path not including the working dir, the working dir will be prepended to it.\n- Remember the user does not see the full output of tools\n`\n\nconst baseAnthropicCoderPrompt = `You are OpenCode, an interactive CLI tool that helps users with software engineering tasks. Use the instructions below and the tools available to you to assist the user.\n\nIMPORTANT: Before you begin work, think about what the code you're editing is supposed to do based on the filenames directory structure.\n\n# Memory\nIf the current working directory contains a file called OpenCode.md, it will be automatically added to your context. This file serves multiple purposes:\n1. Storing frequently used bash commands (build, test, lint, etc.) so you can use them without searching each time\n2. Recording the user's code style preferences (naming conventions, preferred libraries, etc.)\n3. Maintaining useful information about the codebase structure and organization\n\nWhen you spend time searching for commands to typecheck, lint, build, or test, you should ask the user if it's okay to add those commands to OpenCode.md. Similarly, when learning about code style preferences or important codebase information, ask if it's okay to add that to OpenCode.md so you can remember it for next time.\n\n# Tone and style\nYou should be concise, direct, and to the point. When you run a non-trivial bash command, you should explain what the command does and why you are running it, to make sure the user understands what you are doing (this is especially important when you are running a command that will make changes to the user's system).\nRemember that your output will be displayed on a command line interface. Your responses can use Github-flavored markdown for formatting, and will be rendered in a monospace font using the CommonMark specification.\nOutput text to communicate with the user; all text you output outside of tool use is displayed to the user. Only use tools to complete tasks. Never use tools like Bash or code comments as means to communicate with the user during the session.\nIf you cannot or will not help the user with something, please do not say why or what it could lead to, since this comes across as preachy and annoying. Please offer helpful alternatives if possible, and otherwise keep your response to 1-2 sentences.\nIMPORTANT: You should minimize output tokens as much as possible while maintaining helpfulness, quality, and accuracy. Only address the specific query or task at hand, avoiding tangential information unless absolutely critical for completing the request. If you can answer in 1-3 sentences or a short paragraph, please do.\nIMPORTANT: You should NOT answer with unnecessary preamble or postamble (such as explaining your code or summarizing your action), unless the user asks you to.\nIMPORTANT: Keep your responses short, since they will be displayed on a command line interface. You MUST answer concisely with fewer than 4 lines (not including tool use or code generation), unless user asks for detail. Answer the user's question directly, without elaboration, explanation, or details. One word answers are best. Avoid introductions, conclusions, and explanations. You MUST avoid text before/after your response, such as \"The answer is .\", \"Here is the content of the file...\" or \"Based on the information provided, the answer is...\" or \"Here is what I will do next...\". Here are some examples to demonstrate appropriate verbosity:\n\nuser: 2 + 2\nassistant: 4\n\n\n\nuser: what is 2+2?\nassistant: 4\n\n\n\nuser: is 11 a prime number?\nassistant: true\n\n\n\nuser: what command should I run to list files in the current directory?\nassistant: ls\n\n\n\nuser: what command should I run to watch files in the current directory?\nassistant: [use the ls tool to list the files in the current directory, then read docs/commands in the relevant file to find out how to watch files]\nnpm run dev\n\n\n\nuser: How many golf balls fit inside a jetta?\nassistant: 150000\n\n\n\nuser: what files are in the directory src/?\nassistant: [runs ls and sees foo.c, bar.c, baz.c]\nuser: which file contains the implementation of foo?\nassistant: src/foo.c\n\n\n\nuser: write tests for new feature\nassistant: [uses grep and glob search tools to find where similar tests are defined, uses concurrent read file tool use blocks in one tool call to read relevant files at the same time, uses edit/patch file tool to write new tests]\n\n\n# Proactiveness\nYou are allowed to be proactive, but only when the user asks you to do something. You should strive to strike a balance between:\n1. Doing the right thing when asked, including taking actions and follow-up actions\n2. Not surprising the user with actions you take without asking\nFor example, if the user asks you how to approach something, you should do your best to answer their question first, and not immediately jump into taking actions.\n3. Do not add additional code explanation summary unless requested by the user. After working on a file, just stop, rather than providing an explanation of what you did.\n\n# Following conventions\nWhen making changes to files, first understand the file's code conventions. Mimic code style, use existing libraries and utilities, and follow existing patterns.\n- NEVER assume that a given library is available, even if it is well known. Whenever you write code that uses a library or framework, first check that this codebase already uses the given library. For example, you might look at neighboring files, or check the package.json (or cargo.toml, and so on depending on the language).\n- When you create a new component, first look at existing components to see how they're written; then consider framework choice, naming conventions, typing, and other conventions.\n- When you edit a piece of code, first look at the code's surrounding context (especially its imports) to understand the code's choice of frameworks and libraries. Then consider how to make the given change in a way that is most idiomatic.\n- Always follow security best practices. Never introduce code that exposes or logs secrets and keys. Never commit secrets or keys to the repository.\n\n# Code style\n- Do not add comments to the code you write, unless the user asks you to, or the code is complex and requires additional context.\n\n# Doing tasks\nThe user will primarily request you perform software engineering tasks. This includes solving bugs, adding new functionality, refactoring code, explaining code, and more. For these tasks the following steps are recommended:\n1. Use the available search tools to understand the codebase and the user's query. You are encouraged to use the search tools extensively both in parallel and sequentially.\n2. Implement the solution using all tools available to you\n3. Verify the solution if possible with tests. NEVER assume specific test framework or test script. Check the README or search codebase to determine the testing approach.\n4. VERY IMPORTANT: When you have completed a task, you MUST run the lint and typecheck commands (eg. npm run lint, npm run typecheck, ruff, etc.) if they were provided to you to ensure your code is correct. If you are unable to find the correct command, ask the user for the command to run and if they supply it, proactively suggest writing it to opencode.md so that you will know to run it next time.\n\nNEVER commit changes unless the user explicitly asks you to. It is VERY IMPORTANT to only commit when explicitly asked, otherwise the user will feel that you are being too proactive.\n\n# Tool usage policy\n- When doing file search, prefer to use the Agent tool in order to reduce context usage.\n- If you intend to call multiple tools and there are no dependencies between the calls, make all of the independent calls in the same function_calls block.\n- IMPORTANT: The user does not see the full output of the tool responses, so if you need the output of the tool for the response make sure to summarize it for the user.\n\nYou MUST answer concisely with fewer than 4 lines of text (not including tool use or code generation), unless user asks for detail.`\n\nfunc getEnvironmentInfo() string {\n\tcwd := config.WorkingDirectory()\n\tisGit := isGitRepo(cwd)\n\tplatform := runtime.GOOS\n\tdate := time.Now().Format(\"1/2/2006\")\n\tls := tools.NewLsTool()\n\tr, _ := ls.Run(context.Background(), tools.ToolCall{\n\t\tInput: `{\"path\":\".\"}`,\n\t})\n\treturn fmt.Sprintf(`Here is useful information about the environment you are running in:\n\nWorking directory: %s\nIs directory a git repo: %s\nPlatform: %s\nToday's date: %s\n\n\n%s\n\n\t\t`, cwd, boolToYesNo(isGit), platform, date, r.Content)\n}\n\nfunc isGitRepo(dir string) bool {\n\t_, err := os.Stat(filepath.Join(dir, \".git\"))\n\treturn err == nil\n}\n\nfunc lspInformation() string {\n\tcfg := config.Get()\n\thasLSP := false\n\tfor _, v := range cfg.LSP {\n\t\tif !v.Disabled {\n\t\t\thasLSP = true\n\t\t\tbreak\n\t\t}\n\t}\n\tif !hasLSP {\n\t\treturn \"\"\n\t}\n\treturn `# LSP Information\nTools that support it will also include useful diagnostics such as linting and typechecking.\n- These diagnostics will be automatically enabled when you run the tool, and will be displayed in the output at the bottom within the and tags.\n- Take necessary actions to fix the issues.\n- You should ignore diagnostics of files that you did not change or are not related or caused by your changes unless the user explicitly asks you to fix them.\n`\n}\n\nfunc boolToYesNo(b bool) string {\n\tif b {\n\t\treturn \"Yes\"\n\t}\n\treturn \"No\"\n}\n"], ["/opencode/internal/lsp/protocol/uri.go", "// Copyright 2023 The Go Authors. All rights reserved.\n// Use of this source code is governed by a BSD-style\n// license that can be found in the LICENSE file.\n\npackage protocol\n\n// This file declares URI, DocumentUri, and its methods.\n//\n// For the LSP definition of these types, see\n// https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#uri\n\nimport (\n\t\"fmt\"\n\t\"net/url\"\n\t\"path/filepath\"\n\t\"strings\"\n\t\"unicode\"\n)\n\n// A DocumentUri is the URI of a client editor document.\n//\n// According to the LSP specification:\n//\n//\tCare should be taken to handle encoding in URIs. For\n//\texample, some clients (such as VS Code) may encode colons\n//\tin drive letters while others do not. The URIs below are\n//\tboth valid, but clients and servers should be consistent\n//\twith the form they use themselves to ensure the other party\n//\tdoesn’t interpret them as distinct URIs. Clients and\n//\tservers should not assume that each other are encoding the\n//\tsame way (for example a client encoding colons in drive\n//\tletters cannot assume server responses will have encoded\n//\tcolons). The same applies to casing of drive letters - one\n//\tparty should not assume the other party will return paths\n//\twith drive letters cased the same as it.\n//\n//\tfile:///c:/project/readme.md\n//\tfile:///C%3A/project/readme.md\n//\n// This is done during JSON unmarshalling;\n// see [DocumentUri.UnmarshalText] for details.\ntype DocumentUri string\n\n// A URI is an arbitrary URL (e.g. https), not necessarily a file.\ntype URI = string\n\n// UnmarshalText implements decoding of DocumentUri values.\n//\n// In particular, it implements a systematic correction of various odd\n// features of the definition of DocumentUri in the LSP spec that\n// appear to be workarounds for bugs in VS Code. For example, it may\n// URI-encode the URI itself, so that colon becomes %3A, and it may\n// send file://foo.go URIs that have two slashes (not three) and no\n// hostname.\n//\n// We use UnmarshalText, not UnmarshalJSON, because it is called even\n// for non-addressable values such as keys and values of map[K]V,\n// where there is no pointer of type *K or *V on which to call\n// UnmarshalJSON. (See Go issue #28189 for more detail.)\n//\n// Non-empty DocumentUris are valid \"file\"-scheme URIs.\n// The empty DocumentUri is valid.\nfunc (uri *DocumentUri) UnmarshalText(data []byte) (err error) {\n\t*uri, err = ParseDocumentUri(string(data))\n\treturn\n}\n\n// Path returns the file path for the given URI.\n//\n// DocumentUri(\"\").Path() returns the empty string.\n//\n// Path panics if called on a URI that is not a valid filename.\nfunc (uri DocumentUri) Path() string {\n\tfilename, err := filename(uri)\n\tif err != nil {\n\t\t// e.g. ParseRequestURI failed.\n\t\t//\n\t\t// This can only affect DocumentUris created by\n\t\t// direct string manipulation; all DocumentUris\n\t\t// received from the client pass through\n\t\t// ParseRequestURI, which ensures validity.\n\t\tpanic(err)\n\t}\n\treturn filepath.FromSlash(filename)\n}\n\n// Dir returns the URI for the directory containing the receiver.\nfunc (uri DocumentUri) Dir() DocumentUri {\n\t// This function could be more efficiently implemented by avoiding any call\n\t// to Path(), but at least consolidates URI manipulation.\n\treturn URIFromPath(uri.DirPath())\n}\n\n// DirPath returns the file path to the directory containing this URI, which\n// must be a file URI.\nfunc (uri DocumentUri) DirPath() string {\n\treturn filepath.Dir(uri.Path())\n}\n\nfunc filename(uri DocumentUri) (string, error) {\n\tif uri == \"\" {\n\t\treturn \"\", nil\n\t}\n\n\t// This conservative check for the common case\n\t// of a simple non-empty absolute POSIX filename\n\t// avoids the allocation of a net.URL.\n\tif strings.HasPrefix(string(uri), \"file:///\") {\n\t\trest := string(uri)[len(\"file://\"):] // leave one slash\n\t\tfor i := range len(rest) {\n\t\t\tb := rest[i]\n\t\t\t// Reject these cases:\n\t\t\tif b < ' ' || b == 0x7f || // control character\n\t\t\t\tb == '%' || b == '+' || // URI escape\n\t\t\t\tb == ':' || // Windows drive letter\n\t\t\t\tb == '@' || b == '&' || b == '?' { // authority or query\n\t\t\t\tgoto slow\n\t\t\t}\n\t\t}\n\t\treturn rest, nil\n\t}\nslow:\n\n\tu, err := url.ParseRequestURI(string(uri))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tif u.Scheme != fileScheme {\n\t\treturn \"\", fmt.Errorf(\"only file URIs are supported, got %q from %q\", u.Scheme, uri)\n\t}\n\t// If the URI is a Windows URI, we trim the leading \"/\" and uppercase\n\t// the drive letter, which will never be case sensitive.\n\tif isWindowsDriveURIPath(u.Path) {\n\t\tu.Path = strings.ToUpper(string(u.Path[1])) + u.Path[2:]\n\t}\n\n\treturn u.Path, nil\n}\n\n// ParseDocumentUri interprets a string as a DocumentUri, applying VS\n// Code workarounds; see [DocumentUri.UnmarshalText] for details.\nfunc ParseDocumentUri(s string) (DocumentUri, error) {\n\tif s == \"\" {\n\t\treturn \"\", nil\n\t}\n\n\tif !strings.HasPrefix(s, \"file://\") {\n\t\treturn \"\", fmt.Errorf(\"DocumentUri scheme is not 'file': %s\", s)\n\t}\n\n\t// VS Code sends URLs with only two slashes,\n\t// which are invalid. golang/go#39789.\n\tif !strings.HasPrefix(s, \"file:///\") {\n\t\ts = \"file:///\" + s[len(\"file://\"):]\n\t}\n\n\t// Even though the input is a URI, it may not be in canonical form. VS Code\n\t// in particular over-escapes :, @, etc. Unescape and re-encode to canonicalize.\n\tpath, err := url.PathUnescape(s[len(\"file://\"):])\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t// File URIs from Windows may have lowercase drive letters.\n\t// Since drive letters are guaranteed to be case insensitive,\n\t// we change them to uppercase to remain consistent.\n\t// For example, file:///c:/x/y/z becomes file:///C:/x/y/z.\n\tif isWindowsDriveURIPath(path) {\n\t\tpath = path[:1] + strings.ToUpper(string(path[1])) + path[2:]\n\t}\n\tu := url.URL{Scheme: fileScheme, Path: path}\n\treturn DocumentUri(u.String()), nil\n}\n\n// URIFromPath returns DocumentUri for the supplied file path.\n// Given \"\", it returns \"\".\nfunc URIFromPath(path string) DocumentUri {\n\tif path == \"\" {\n\t\treturn \"\"\n\t}\n\tif !isWindowsDrivePath(path) {\n\t\tif abs, err := filepath.Abs(path); err == nil {\n\t\t\tpath = abs\n\t\t}\n\t}\n\t// Check the file path again, in case it became absolute.\n\tif isWindowsDrivePath(path) {\n\t\tpath = \"/\" + strings.ToUpper(string(path[0])) + path[1:]\n\t}\n\tpath = filepath.ToSlash(path)\n\tu := url.URL{\n\t\tScheme: fileScheme,\n\t\tPath: path,\n\t}\n\treturn DocumentUri(u.String())\n}\n\nconst fileScheme = \"file\"\n\n// isWindowsDrivePath returns true if the file path is of the form used by\n// Windows. We check if the path begins with a drive letter, followed by a \":\".\n// For example: C:/x/y/z.\nfunc isWindowsDrivePath(path string) bool {\n\tif len(path) < 3 {\n\t\treturn false\n\t}\n\treturn unicode.IsLetter(rune(path[0])) && path[1] == ':'\n}\n\n// isWindowsDriveURIPath returns true if the file URI is of the format used by\n// Windows URIs. The url.Parse package does not specially handle Windows paths\n// (see golang/go#6027), so we check if the URI path has a drive prefix (e.g. \"/C:\").\nfunc isWindowsDriveURIPath(uri string) bool {\n\tif len(uri) < 4 {\n\t\treturn false\n\t}\n\treturn uri[0] == '/' && unicode.IsLetter(rune(uri[1])) && uri[2] == ':'\n}\n"], ["/opencode/cmd/schema/main.go", "package main\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"os\"\n\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/llm/models\"\n)\n\n// JSONSchemaType represents a JSON Schema type\ntype JSONSchemaType struct {\n\tType string `json:\"type,omitempty\"`\n\tDescription string `json:\"description,omitempty\"`\n\tProperties map[string]any `json:\"properties,omitempty\"`\n\tRequired []string `json:\"required,omitempty\"`\n\tAdditionalProperties any `json:\"additionalProperties,omitempty\"`\n\tEnum []any `json:\"enum,omitempty\"`\n\tItems map[string]any `json:\"items,omitempty\"`\n\tOneOf []map[string]any `json:\"oneOf,omitempty\"`\n\tAnyOf []map[string]any `json:\"anyOf,omitempty\"`\n\tDefault any `json:\"default,omitempty\"`\n}\n\nfunc main() {\n\tschema := generateSchema()\n\n\t// Pretty print the schema\n\tencoder := json.NewEncoder(os.Stdout)\n\tencoder.SetIndent(\"\", \" \")\n\tif err := encoder.Encode(schema); err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"Error encoding schema: %v\\n\", err)\n\t\tos.Exit(1)\n\t}\n}\n\nfunc generateSchema() map[string]any {\n\tschema := map[string]any{\n\t\t\"$schema\": \"http://json-schema.org/draft-07/schema#\",\n\t\t\"title\": \"OpenCode Configuration\",\n\t\t\"description\": \"Configuration schema for the OpenCode application\",\n\t\t\"type\": \"object\",\n\t\t\"properties\": map[string]any{},\n\t}\n\n\t// Add Data configuration\n\tschema[\"properties\"].(map[string]any)[\"data\"] = map[string]any{\n\t\t\"type\": \"object\",\n\t\t\"description\": \"Storage configuration\",\n\t\t\"properties\": map[string]any{\n\t\t\t\"directory\": map[string]any{\n\t\t\t\t\"type\": \"string\",\n\t\t\t\t\"description\": \"Directory where application data is stored\",\n\t\t\t\t\"default\": \".opencode\",\n\t\t\t},\n\t\t},\n\t\t\"required\": []string{\"directory\"},\n\t}\n\n\t// Add working directory\n\tschema[\"properties\"].(map[string]any)[\"wd\"] = map[string]any{\n\t\t\"type\": \"string\",\n\t\t\"description\": \"Working directory for the application\",\n\t}\n\n\t// Add debug flags\n\tschema[\"properties\"].(map[string]any)[\"debug\"] = map[string]any{\n\t\t\"type\": \"boolean\",\n\t\t\"description\": \"Enable debug mode\",\n\t\t\"default\": false,\n\t}\n\n\tschema[\"properties\"].(map[string]any)[\"debugLSP\"] = map[string]any{\n\t\t\"type\": \"boolean\",\n\t\t\"description\": \"Enable LSP debug mode\",\n\t\t\"default\": false,\n\t}\n\n\tschema[\"properties\"].(map[string]any)[\"contextPaths\"] = map[string]any{\n\t\t\"type\": \"array\",\n\t\t\"description\": \"Context paths for the application\",\n\t\t\"items\": map[string]any{\n\t\t\t\"type\": \"string\",\n\t\t},\n\t\t\"default\": []string{\n\t\t\t\".github/copilot-instructions.md\",\n\t\t\t\".cursorrules\",\n\t\t\t\".cursor/rules/\",\n\t\t\t\"CLAUDE.md\",\n\t\t\t\"CLAUDE.local.md\",\n\t\t\t\"opencode.md\",\n\t\t\t\"opencode.local.md\",\n\t\t\t\"OpenCode.md\",\n\t\t\t\"OpenCode.local.md\",\n\t\t\t\"OPENCODE.md\",\n\t\t\t\"OPENCODE.local.md\",\n\t\t},\n\t}\n\n\tschema[\"properties\"].(map[string]any)[\"tui\"] = map[string]any{\n\t\t\"type\": \"object\",\n\t\t\"description\": \"Terminal User Interface configuration\",\n\t\t\"properties\": map[string]any{\n\t\t\t\"theme\": map[string]any{\n\t\t\t\t\"type\": \"string\",\n\t\t\t\t\"description\": \"TUI theme name\",\n\t\t\t\t\"default\": \"opencode\",\n\t\t\t\t\"enum\": []string{\n\t\t\t\t\t\"opencode\",\n\t\t\t\t\t\"catppuccin\",\n\t\t\t\t\t\"dracula\",\n\t\t\t\t\t\"flexoki\",\n\t\t\t\t\t\"gruvbox\",\n\t\t\t\t\t\"monokai\",\n\t\t\t\t\t\"onedark\",\n\t\t\t\t\t\"tokyonight\",\n\t\t\t\t\t\"tron\",\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\t// Add MCP servers\n\tschema[\"properties\"].(map[string]any)[\"mcpServers\"] = map[string]any{\n\t\t\"type\": \"object\",\n\t\t\"description\": \"Model Control Protocol server configurations\",\n\t\t\"additionalProperties\": map[string]any{\n\t\t\t\"type\": \"object\",\n\t\t\t\"description\": \"MCP server configuration\",\n\t\t\t\"properties\": map[string]any{\n\t\t\t\t\"command\": map[string]any{\n\t\t\t\t\t\"type\": \"string\",\n\t\t\t\t\t\"description\": \"Command to execute for the MCP server\",\n\t\t\t\t},\n\t\t\t\t\"env\": map[string]any{\n\t\t\t\t\t\"type\": \"array\",\n\t\t\t\t\t\"description\": \"Environment variables for the MCP server\",\n\t\t\t\t\t\"items\": map[string]any{\n\t\t\t\t\t\t\"type\": \"string\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t\"args\": map[string]any{\n\t\t\t\t\t\"type\": \"array\",\n\t\t\t\t\t\"description\": \"Command arguments for the MCP server\",\n\t\t\t\t\t\"items\": map[string]any{\n\t\t\t\t\t\t\"type\": \"string\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t\"type\": map[string]any{\n\t\t\t\t\t\"type\": \"string\",\n\t\t\t\t\t\"description\": \"Type of MCP server\",\n\t\t\t\t\t\"enum\": []string{\"stdio\", \"sse\"},\n\t\t\t\t\t\"default\": \"stdio\",\n\t\t\t\t},\n\t\t\t\t\"url\": map[string]any{\n\t\t\t\t\t\"type\": \"string\",\n\t\t\t\t\t\"description\": \"URL for SSE type MCP servers\",\n\t\t\t\t},\n\t\t\t\t\"headers\": map[string]any{\n\t\t\t\t\t\"type\": \"object\",\n\t\t\t\t\t\"description\": \"HTTP headers for SSE type MCP servers\",\n\t\t\t\t\t\"additionalProperties\": map[string]any{\n\t\t\t\t\t\t\"type\": \"string\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\t\"required\": []string{\"command\"},\n\t\t},\n\t}\n\n\t// Add providers\n\tproviderSchema := map[string]any{\n\t\t\"type\": \"object\",\n\t\t\"description\": \"LLM provider configurations\",\n\t\t\"additionalProperties\": map[string]any{\n\t\t\t\"type\": \"object\",\n\t\t\t\"description\": \"Provider configuration\",\n\t\t\t\"properties\": map[string]any{\n\t\t\t\t\"apiKey\": map[string]any{\n\t\t\t\t\t\"type\": \"string\",\n\t\t\t\t\t\"description\": \"API key for the provider\",\n\t\t\t\t},\n\t\t\t\t\"disabled\": map[string]any{\n\t\t\t\t\t\"type\": \"boolean\",\n\t\t\t\t\t\"description\": \"Whether the provider is disabled\",\n\t\t\t\t\t\"default\": false,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\t// Add known providers\n\tknownProviders := []string{\n\t\tstring(models.ProviderAnthropic),\n\t\tstring(models.ProviderOpenAI),\n\t\tstring(models.ProviderGemini),\n\t\tstring(models.ProviderGROQ),\n\t\tstring(models.ProviderOpenRouter),\n\t\tstring(models.ProviderBedrock),\n\t\tstring(models.ProviderAzure),\n\t\tstring(models.ProviderVertexAI),\n\t}\n\n\tproviderSchema[\"additionalProperties\"].(map[string]any)[\"properties\"].(map[string]any)[\"provider\"] = map[string]any{\n\t\t\"type\": \"string\",\n\t\t\"description\": \"Provider type\",\n\t\t\"enum\": knownProviders,\n\t}\n\n\tschema[\"properties\"].(map[string]any)[\"providers\"] = providerSchema\n\n\t// Add agents\n\tagentSchema := map[string]any{\n\t\t\"type\": \"object\",\n\t\t\"description\": \"Agent configurations\",\n\t\t\"additionalProperties\": map[string]any{\n\t\t\t\"type\": \"object\",\n\t\t\t\"description\": \"Agent configuration\",\n\t\t\t\"properties\": map[string]any{\n\t\t\t\t\"model\": map[string]any{\n\t\t\t\t\t\"type\": \"string\",\n\t\t\t\t\t\"description\": \"Model ID for the agent\",\n\t\t\t\t},\n\t\t\t\t\"maxTokens\": map[string]any{\n\t\t\t\t\t\"type\": \"integer\",\n\t\t\t\t\t\"description\": \"Maximum tokens for the agent\",\n\t\t\t\t\t\"minimum\": 1,\n\t\t\t\t},\n\t\t\t\t\"reasoningEffort\": map[string]any{\n\t\t\t\t\t\"type\": \"string\",\n\t\t\t\t\t\"description\": \"Reasoning effort for models that support it (OpenAI, Anthropic)\",\n\t\t\t\t\t\"enum\": []string{\"low\", \"medium\", \"high\"},\n\t\t\t\t},\n\t\t\t},\n\t\t\t\"required\": []string{\"model\"},\n\t\t},\n\t}\n\n\t// Add model enum\n\tmodelEnum := []string{}\n\tfor modelID := range models.SupportedModels {\n\t\tmodelEnum = append(modelEnum, string(modelID))\n\t}\n\tagentSchema[\"additionalProperties\"].(map[string]any)[\"properties\"].(map[string]any)[\"model\"].(map[string]any)[\"enum\"] = modelEnum\n\n\t// Add specific agent properties\n\tagentProperties := map[string]any{}\n\tknownAgents := []string{\n\t\tstring(config.AgentCoder),\n\t\tstring(config.AgentTask),\n\t\tstring(config.AgentTitle),\n\t}\n\n\tfor _, agentName := range knownAgents {\n\t\tagentProperties[agentName] = map[string]any{\n\t\t\t\"$ref\": \"#/definitions/agent\",\n\t\t}\n\t}\n\n\t// Create a combined schema that allows both specific agents and additional ones\n\tcombinedAgentSchema := map[string]any{\n\t\t\"type\": \"object\",\n\t\t\"description\": \"Agent configurations\",\n\t\t\"properties\": agentProperties,\n\t\t\"additionalProperties\": agentSchema[\"additionalProperties\"],\n\t}\n\n\tschema[\"properties\"].(map[string]any)[\"agents\"] = combinedAgentSchema\n\tschema[\"definitions\"] = map[string]any{\n\t\t\"agent\": agentSchema[\"additionalProperties\"],\n\t}\n\n\t// Add LSP configuration\n\tschema[\"properties\"].(map[string]any)[\"lsp\"] = map[string]any{\n\t\t\"type\": \"object\",\n\t\t\"description\": \"Language Server Protocol configurations\",\n\t\t\"additionalProperties\": map[string]any{\n\t\t\t\"type\": \"object\",\n\t\t\t\"description\": \"LSP configuration for a language\",\n\t\t\t\"properties\": map[string]any{\n\t\t\t\t\"disabled\": map[string]any{\n\t\t\t\t\t\"type\": \"boolean\",\n\t\t\t\t\t\"description\": \"Whether the LSP is disabled\",\n\t\t\t\t\t\"default\": false,\n\t\t\t\t},\n\t\t\t\t\"command\": map[string]any{\n\t\t\t\t\t\"type\": \"string\",\n\t\t\t\t\t\"description\": \"Command to execute for the LSP server\",\n\t\t\t\t},\n\t\t\t\t\"args\": map[string]any{\n\t\t\t\t\t\"type\": \"array\",\n\t\t\t\t\t\"description\": \"Command arguments for the LSP server\",\n\t\t\t\t\t\"items\": map[string]any{\n\t\t\t\t\t\t\"type\": \"string\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t\"options\": map[string]any{\n\t\t\t\t\t\"type\": \"object\",\n\t\t\t\t\t\"description\": \"Additional options for the LSP server\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t\"required\": []string{\"command\"},\n\t\t},\n\t}\n\n\treturn schema\n}\n"], ["/opencode/internal/lsp/protocol/tsjson.go", "// Copyright 2023 The Go Authors. All rights reserved.\n// Use of this source code is governed by a BSD-style\n// license that can be found in the LICENSE file.\n\n// Code generated for LSP. DO NOT EDIT.\n\npackage protocol\n\n// Code generated from protocol/metaModel.json at ref release/protocol/3.17.6-next.9 (hash c94395b5da53729e6dff931293b051009ccaaaa4).\n// https://github.com/microsoft/vscode-languageserver-node/blob/release/protocol/3.17.6-next.9/protocol/metaModel.json\n// LSP metaData.version = 3.17.0.\n\nimport \"bytes\"\nimport \"encoding/json\"\n\nimport \"fmt\"\n\n// UnmarshalError indicates that a JSON value did not conform to\n// one of the expected cases of an LSP union type.\ntype UnmarshalError struct {\n\tmsg string\n}\n\nfunc (e UnmarshalError) Error() string {\n\treturn e.msg\n}\nfunc (t Or_CancelParams_id) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase int32:\n\t\treturn json.Marshal(x)\n\tcase string:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [int32 string]\", t)\n}\n\nfunc (t *Or_CancelParams_id) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder41 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder41.DisallowUnknownFields()\n\tvar int32Val int32\n\tif err := decoder41.Decode(&int32Val); err == nil {\n\t\tt.Value = int32Val\n\t\treturn nil\n\t}\n\tdecoder42 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder42.DisallowUnknownFields()\n\tvar stringVal string\n\tif err := decoder42.Decode(&stringVal); err == nil {\n\t\tt.Value = stringVal\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [int32 string]\"}\n}\n\nfunc (t Or_ClientSemanticTokensRequestOptions_full) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase ClientSemanticTokensRequestFullDelta:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [ClientSemanticTokensRequestFullDelta bool]\", t)\n}\n\nfunc (t *Or_ClientSemanticTokensRequestOptions_full) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder220 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder220.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder220.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder221 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder221.DisallowUnknownFields()\n\tvar h221 ClientSemanticTokensRequestFullDelta\n\tif err := decoder221.Decode(&h221); err == nil {\n\t\tt.Value = h221\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [ClientSemanticTokensRequestFullDelta bool]\"}\n}\n\nfunc (t Or_ClientSemanticTokensRequestOptions_range) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase Lit_ClientSemanticTokensRequestOptions_range_Item1:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [Lit_ClientSemanticTokensRequestOptions_range_Item1 bool]\", t)\n}\n\nfunc (t *Or_ClientSemanticTokensRequestOptions_range) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder217 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder217.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder217.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder218 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder218.DisallowUnknownFields()\n\tvar h218 Lit_ClientSemanticTokensRequestOptions_range_Item1\n\tif err := decoder218.Decode(&h218); err == nil {\n\t\tt.Value = h218\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [Lit_ClientSemanticTokensRequestOptions_range_Item1 bool]\"}\n}\n\nfunc (t Or_CompletionItemDefaults_editRange) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase EditRangeWithInsertReplace:\n\t\treturn json.Marshal(x)\n\tcase Range:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [EditRangeWithInsertReplace Range]\", t)\n}\n\nfunc (t *Or_CompletionItemDefaults_editRange) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder183 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder183.DisallowUnknownFields()\n\tvar h183 EditRangeWithInsertReplace\n\tif err := decoder183.Decode(&h183); err == nil {\n\t\tt.Value = h183\n\t\treturn nil\n\t}\n\tdecoder184 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder184.DisallowUnknownFields()\n\tvar h184 Range\n\tif err := decoder184.Decode(&h184); err == nil {\n\t\tt.Value = h184\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [EditRangeWithInsertReplace Range]\"}\n}\n\nfunc (t Or_CompletionItem_documentation) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase MarkupContent:\n\t\treturn json.Marshal(x)\n\tcase string:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [MarkupContent string]\", t)\n}\n\nfunc (t *Or_CompletionItem_documentation) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder25 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder25.DisallowUnknownFields()\n\tvar stringVal string\n\tif err := decoder25.Decode(&stringVal); err == nil {\n\t\tt.Value = stringVal\n\t\treturn nil\n\t}\n\tdecoder26 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder26.DisallowUnknownFields()\n\tvar h26 MarkupContent\n\tif err := decoder26.Decode(&h26); err == nil {\n\t\tt.Value = h26\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [MarkupContent string]\"}\n}\n\nfunc (t Or_CompletionItem_textEdit) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase InsertReplaceEdit:\n\t\treturn json.Marshal(x)\n\tcase TextEdit:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [InsertReplaceEdit TextEdit]\", t)\n}\n\nfunc (t *Or_CompletionItem_textEdit) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder29 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder29.DisallowUnknownFields()\n\tvar h29 InsertReplaceEdit\n\tif err := decoder29.Decode(&h29); err == nil {\n\t\tt.Value = h29\n\t\treturn nil\n\t}\n\tdecoder30 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder30.DisallowUnknownFields()\n\tvar h30 TextEdit\n\tif err := decoder30.Decode(&h30); err == nil {\n\t\tt.Value = h30\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [InsertReplaceEdit TextEdit]\"}\n}\n\nfunc (t Or_Declaration) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase Location:\n\t\treturn json.Marshal(x)\n\tcase []Location:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [Location []Location]\", t)\n}\n\nfunc (t *Or_Declaration) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder237 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder237.DisallowUnknownFields()\n\tvar h237 Location\n\tif err := decoder237.Decode(&h237); err == nil {\n\t\tt.Value = h237\n\t\treturn nil\n\t}\n\tdecoder238 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder238.DisallowUnknownFields()\n\tvar h238 []Location\n\tif err := decoder238.Decode(&h238); err == nil {\n\t\tt.Value = h238\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [Location []Location]\"}\n}\n\nfunc (t Or_Definition) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase Location:\n\t\treturn json.Marshal(x)\n\tcase []Location:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [Location []Location]\", t)\n}\n\nfunc (t *Or_Definition) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder224 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder224.DisallowUnknownFields()\n\tvar h224 Location\n\tif err := decoder224.Decode(&h224); err == nil {\n\t\tt.Value = h224\n\t\treturn nil\n\t}\n\tdecoder225 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder225.DisallowUnknownFields()\n\tvar h225 []Location\n\tif err := decoder225.Decode(&h225); err == nil {\n\t\tt.Value = h225\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [Location []Location]\"}\n}\n\nfunc (t Or_Diagnostic_code) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase int32:\n\t\treturn json.Marshal(x)\n\tcase string:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [int32 string]\", t)\n}\n\nfunc (t *Or_Diagnostic_code) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder179 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder179.DisallowUnknownFields()\n\tvar int32Val int32\n\tif err := decoder179.Decode(&int32Val); err == nil {\n\t\tt.Value = int32Val\n\t\treturn nil\n\t}\n\tdecoder180 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder180.DisallowUnknownFields()\n\tvar stringVal string\n\tif err := decoder180.Decode(&stringVal); err == nil {\n\t\tt.Value = stringVal\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [int32 string]\"}\n}\n\nfunc (t Or_DidChangeConfigurationRegistrationOptions_section) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase []string:\n\t\treturn json.Marshal(x)\n\tcase string:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [[]string string]\", t)\n}\n\nfunc (t *Or_DidChangeConfigurationRegistrationOptions_section) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder22 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder22.DisallowUnknownFields()\n\tvar stringVal string\n\tif err := decoder22.Decode(&stringVal); err == nil {\n\t\tt.Value = stringVal\n\t\treturn nil\n\t}\n\tdecoder23 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder23.DisallowUnknownFields()\n\tvar h23 []string\n\tif err := decoder23.Decode(&h23); err == nil {\n\t\tt.Value = h23\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [[]string string]\"}\n}\n\nfunc (t Or_DocumentDiagnosticReport) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase RelatedFullDocumentDiagnosticReport:\n\t\treturn json.Marshal(x)\n\tcase RelatedUnchangedDocumentDiagnosticReport:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [RelatedFullDocumentDiagnosticReport RelatedUnchangedDocumentDiagnosticReport]\", t)\n}\n\nfunc (t *Or_DocumentDiagnosticReport) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder247 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder247.DisallowUnknownFields()\n\tvar h247 RelatedFullDocumentDiagnosticReport\n\tif err := decoder247.Decode(&h247); err == nil {\n\t\tt.Value = h247\n\t\treturn nil\n\t}\n\tdecoder248 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder248.DisallowUnknownFields()\n\tvar h248 RelatedUnchangedDocumentDiagnosticReport\n\tif err := decoder248.Decode(&h248); err == nil {\n\t\tt.Value = h248\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [RelatedFullDocumentDiagnosticReport RelatedUnchangedDocumentDiagnosticReport]\"}\n}\n\nfunc (t Or_DocumentDiagnosticReportPartialResult_relatedDocuments_Value) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase FullDocumentDiagnosticReport:\n\t\treturn json.Marshal(x)\n\tcase UnchangedDocumentDiagnosticReport:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [FullDocumentDiagnosticReport UnchangedDocumentDiagnosticReport]\", t)\n}\n\nfunc (t *Or_DocumentDiagnosticReportPartialResult_relatedDocuments_Value) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder16 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder16.DisallowUnknownFields()\n\tvar h16 FullDocumentDiagnosticReport\n\tif err := decoder16.Decode(&h16); err == nil {\n\t\tt.Value = h16\n\t\treturn nil\n\t}\n\tdecoder17 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder17.DisallowUnknownFields()\n\tvar h17 UnchangedDocumentDiagnosticReport\n\tif err := decoder17.Decode(&h17); err == nil {\n\t\tt.Value = h17\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [FullDocumentDiagnosticReport UnchangedDocumentDiagnosticReport]\"}\n}\n\nfunc (t Or_DocumentFilter) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase NotebookCellTextDocumentFilter:\n\t\treturn json.Marshal(x)\n\tcase TextDocumentFilter:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [NotebookCellTextDocumentFilter TextDocumentFilter]\", t)\n}\n\nfunc (t *Or_DocumentFilter) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder270 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder270.DisallowUnknownFields()\n\tvar h270 NotebookCellTextDocumentFilter\n\tif err := decoder270.Decode(&h270); err == nil {\n\t\tt.Value = h270\n\t\treturn nil\n\t}\n\tdecoder271 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder271.DisallowUnknownFields()\n\tvar h271 TextDocumentFilter\n\tif err := decoder271.Decode(&h271); err == nil {\n\t\tt.Value = h271\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [NotebookCellTextDocumentFilter TextDocumentFilter]\"}\n}\n\nfunc (t Or_GlobPattern) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase Pattern:\n\t\treturn json.Marshal(x)\n\tcase RelativePattern:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [Pattern RelativePattern]\", t)\n}\n\nfunc (t *Or_GlobPattern) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder274 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder274.DisallowUnknownFields()\n\tvar h274 Pattern\n\tif err := decoder274.Decode(&h274); err == nil {\n\t\tt.Value = h274\n\t\treturn nil\n\t}\n\tdecoder275 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder275.DisallowUnknownFields()\n\tvar h275 RelativePattern\n\tif err := decoder275.Decode(&h275); err == nil {\n\t\tt.Value = h275\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [Pattern RelativePattern]\"}\n}\n\nfunc (t Or_Hover_contents) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase MarkedString:\n\t\treturn json.Marshal(x)\n\tcase MarkupContent:\n\t\treturn json.Marshal(x)\n\tcase []MarkedString:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [MarkedString MarkupContent []MarkedString]\", t)\n}\n\nfunc (t *Or_Hover_contents) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder34 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder34.DisallowUnknownFields()\n\tvar h34 MarkedString\n\tif err := decoder34.Decode(&h34); err == nil {\n\t\tt.Value = h34\n\t\treturn nil\n\t}\n\tdecoder35 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder35.DisallowUnknownFields()\n\tvar h35 MarkupContent\n\tif err := decoder35.Decode(&h35); err == nil {\n\t\tt.Value = h35\n\t\treturn nil\n\t}\n\tdecoder36 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder36.DisallowUnknownFields()\n\tvar h36 []MarkedString\n\tif err := decoder36.Decode(&h36); err == nil {\n\t\tt.Value = h36\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [MarkedString MarkupContent []MarkedString]\"}\n}\n\nfunc (t Or_InlayHintLabelPart_tooltip) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase MarkupContent:\n\t\treturn json.Marshal(x)\n\tcase string:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [MarkupContent string]\", t)\n}\n\nfunc (t *Or_InlayHintLabelPart_tooltip) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder56 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder56.DisallowUnknownFields()\n\tvar stringVal string\n\tif err := decoder56.Decode(&stringVal); err == nil {\n\t\tt.Value = stringVal\n\t\treturn nil\n\t}\n\tdecoder57 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder57.DisallowUnknownFields()\n\tvar h57 MarkupContent\n\tif err := decoder57.Decode(&h57); err == nil {\n\t\tt.Value = h57\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [MarkupContent string]\"}\n}\n\nfunc (t Or_InlayHint_label) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase []InlayHintLabelPart:\n\t\treturn json.Marshal(x)\n\tcase string:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [[]InlayHintLabelPart string]\", t)\n}\n\nfunc (t *Or_InlayHint_label) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder9 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder9.DisallowUnknownFields()\n\tvar stringVal string\n\tif err := decoder9.Decode(&stringVal); err == nil {\n\t\tt.Value = stringVal\n\t\treturn nil\n\t}\n\tdecoder10 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder10.DisallowUnknownFields()\n\tvar h10 []InlayHintLabelPart\n\tif err := decoder10.Decode(&h10); err == nil {\n\t\tt.Value = h10\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [[]InlayHintLabelPart string]\"}\n}\n\nfunc (t Or_InlayHint_tooltip) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase MarkupContent:\n\t\treturn json.Marshal(x)\n\tcase string:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [MarkupContent string]\", t)\n}\n\nfunc (t *Or_InlayHint_tooltip) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder12 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder12.DisallowUnknownFields()\n\tvar stringVal string\n\tif err := decoder12.Decode(&stringVal); err == nil {\n\t\tt.Value = stringVal\n\t\treturn nil\n\t}\n\tdecoder13 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder13.DisallowUnknownFields()\n\tvar h13 MarkupContent\n\tif err := decoder13.Decode(&h13); err == nil {\n\t\tt.Value = h13\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [MarkupContent string]\"}\n}\n\nfunc (t Or_InlineCompletionItem_insertText) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase StringValue:\n\t\treturn json.Marshal(x)\n\tcase string:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [StringValue string]\", t)\n}\n\nfunc (t *Or_InlineCompletionItem_insertText) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder19 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder19.DisallowUnknownFields()\n\tvar stringVal string\n\tif err := decoder19.Decode(&stringVal); err == nil {\n\t\tt.Value = stringVal\n\t\treturn nil\n\t}\n\tdecoder20 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder20.DisallowUnknownFields()\n\tvar h20 StringValue\n\tif err := decoder20.Decode(&h20); err == nil {\n\t\tt.Value = h20\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [StringValue string]\"}\n}\n\nfunc (t Or_InlineValue) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase InlineValueEvaluatableExpression:\n\t\treturn json.Marshal(x)\n\tcase InlineValueText:\n\t\treturn json.Marshal(x)\n\tcase InlineValueVariableLookup:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [InlineValueEvaluatableExpression InlineValueText InlineValueVariableLookup]\", t)\n}\n\nfunc (t *Or_InlineValue) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder242 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder242.DisallowUnknownFields()\n\tvar h242 InlineValueEvaluatableExpression\n\tif err := decoder242.Decode(&h242); err == nil {\n\t\tt.Value = h242\n\t\treturn nil\n\t}\n\tdecoder243 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder243.DisallowUnknownFields()\n\tvar h243 InlineValueText\n\tif err := decoder243.Decode(&h243); err == nil {\n\t\tt.Value = h243\n\t\treturn nil\n\t}\n\tdecoder244 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder244.DisallowUnknownFields()\n\tvar h244 InlineValueVariableLookup\n\tif err := decoder244.Decode(&h244); err == nil {\n\t\tt.Value = h244\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [InlineValueEvaluatableExpression InlineValueText InlineValueVariableLookup]\"}\n}\n\nfunc (t Or_LSPAny) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase LSPArray:\n\t\treturn json.Marshal(x)\n\tcase LSPObject:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase float64:\n\t\treturn json.Marshal(x)\n\tcase int32:\n\t\treturn json.Marshal(x)\n\tcase string:\n\t\treturn json.Marshal(x)\n\tcase uint32:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [LSPArray LSPObject bool float64 int32 string uint32]\", t)\n}\n\nfunc (t *Or_LSPAny) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder228 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder228.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder228.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder229 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder229.DisallowUnknownFields()\n\tvar float64Val float64\n\tif err := decoder229.Decode(&float64Val); err == nil {\n\t\tt.Value = float64Val\n\t\treturn nil\n\t}\n\tdecoder230 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder230.DisallowUnknownFields()\n\tvar int32Val int32\n\tif err := decoder230.Decode(&int32Val); err == nil {\n\t\tt.Value = int32Val\n\t\treturn nil\n\t}\n\tdecoder231 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder231.DisallowUnknownFields()\n\tvar stringVal string\n\tif err := decoder231.Decode(&stringVal); err == nil {\n\t\tt.Value = stringVal\n\t\treturn nil\n\t}\n\tdecoder232 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder232.DisallowUnknownFields()\n\tvar uint32Val uint32\n\tif err := decoder232.Decode(&uint32Val); err == nil {\n\t\tt.Value = uint32Val\n\t\treturn nil\n\t}\n\tdecoder233 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder233.DisallowUnknownFields()\n\tvar h233 LSPArray\n\tif err := decoder233.Decode(&h233); err == nil {\n\t\tt.Value = h233\n\t\treturn nil\n\t}\n\tdecoder234 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder234.DisallowUnknownFields()\n\tvar h234 LSPObject\n\tif err := decoder234.Decode(&h234); err == nil {\n\t\tt.Value = h234\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [LSPArray LSPObject bool float64 int32 string uint32]\"}\n}\n\nfunc (t Or_MarkedString) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase MarkedStringWithLanguage:\n\t\treturn json.Marshal(x)\n\tcase string:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [MarkedStringWithLanguage string]\", t)\n}\n\nfunc (t *Or_MarkedString) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder266 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder266.DisallowUnknownFields()\n\tvar stringVal string\n\tif err := decoder266.Decode(&stringVal); err == nil {\n\t\tt.Value = stringVal\n\t\treturn nil\n\t}\n\tdecoder267 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder267.DisallowUnknownFields()\n\tvar h267 MarkedStringWithLanguage\n\tif err := decoder267.Decode(&h267); err == nil {\n\t\tt.Value = h267\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [MarkedStringWithLanguage string]\"}\n}\n\nfunc (t Or_NotebookCellTextDocumentFilter_notebook) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase NotebookDocumentFilter:\n\t\treturn json.Marshal(x)\n\tcase string:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [NotebookDocumentFilter string]\", t)\n}\n\nfunc (t *Or_NotebookCellTextDocumentFilter_notebook) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder208 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder208.DisallowUnknownFields()\n\tvar stringVal string\n\tif err := decoder208.Decode(&stringVal); err == nil {\n\t\tt.Value = stringVal\n\t\treturn nil\n\t}\n\tdecoder209 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder209.DisallowUnknownFields()\n\tvar h209 NotebookDocumentFilter\n\tif err := decoder209.Decode(&h209); err == nil {\n\t\tt.Value = h209\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [NotebookDocumentFilter string]\"}\n}\n\nfunc (t Or_NotebookDocumentFilter) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase NotebookDocumentFilterNotebookType:\n\t\treturn json.Marshal(x)\n\tcase NotebookDocumentFilterPattern:\n\t\treturn json.Marshal(x)\n\tcase NotebookDocumentFilterScheme:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [NotebookDocumentFilterNotebookType NotebookDocumentFilterPattern NotebookDocumentFilterScheme]\", t)\n}\n\nfunc (t *Or_NotebookDocumentFilter) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder285 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder285.DisallowUnknownFields()\n\tvar h285 NotebookDocumentFilterNotebookType\n\tif err := decoder285.Decode(&h285); err == nil {\n\t\tt.Value = h285\n\t\treturn nil\n\t}\n\tdecoder286 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder286.DisallowUnknownFields()\n\tvar h286 NotebookDocumentFilterPattern\n\tif err := decoder286.Decode(&h286); err == nil {\n\t\tt.Value = h286\n\t\treturn nil\n\t}\n\tdecoder287 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder287.DisallowUnknownFields()\n\tvar h287 NotebookDocumentFilterScheme\n\tif err := decoder287.Decode(&h287); err == nil {\n\t\tt.Value = h287\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [NotebookDocumentFilterNotebookType NotebookDocumentFilterPattern NotebookDocumentFilterScheme]\"}\n}\n\nfunc (t Or_NotebookDocumentFilterWithCells_notebook) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase NotebookDocumentFilter:\n\t\treturn json.Marshal(x)\n\tcase string:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [NotebookDocumentFilter string]\", t)\n}\n\nfunc (t *Or_NotebookDocumentFilterWithCells_notebook) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder192 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder192.DisallowUnknownFields()\n\tvar stringVal string\n\tif err := decoder192.Decode(&stringVal); err == nil {\n\t\tt.Value = stringVal\n\t\treturn nil\n\t}\n\tdecoder193 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder193.DisallowUnknownFields()\n\tvar h193 NotebookDocumentFilter\n\tif err := decoder193.Decode(&h193); err == nil {\n\t\tt.Value = h193\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [NotebookDocumentFilter string]\"}\n}\n\nfunc (t Or_NotebookDocumentFilterWithNotebook_notebook) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase NotebookDocumentFilter:\n\t\treturn json.Marshal(x)\n\tcase string:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [NotebookDocumentFilter string]\", t)\n}\n\nfunc (t *Or_NotebookDocumentFilterWithNotebook_notebook) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder189 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder189.DisallowUnknownFields()\n\tvar stringVal string\n\tif err := decoder189.Decode(&stringVal); err == nil {\n\t\tt.Value = stringVal\n\t\treturn nil\n\t}\n\tdecoder190 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder190.DisallowUnknownFields()\n\tvar h190 NotebookDocumentFilter\n\tif err := decoder190.Decode(&h190); err == nil {\n\t\tt.Value = h190\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [NotebookDocumentFilter string]\"}\n}\n\nfunc (t Or_NotebookDocumentSyncOptions_notebookSelector_Elem) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase NotebookDocumentFilterWithCells:\n\t\treturn json.Marshal(x)\n\tcase NotebookDocumentFilterWithNotebook:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [NotebookDocumentFilterWithCells NotebookDocumentFilterWithNotebook]\", t)\n}\n\nfunc (t *Or_NotebookDocumentSyncOptions_notebookSelector_Elem) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder68 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder68.DisallowUnknownFields()\n\tvar h68 NotebookDocumentFilterWithCells\n\tif err := decoder68.Decode(&h68); err == nil {\n\t\tt.Value = h68\n\t\treturn nil\n\t}\n\tdecoder69 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder69.DisallowUnknownFields()\n\tvar h69 NotebookDocumentFilterWithNotebook\n\tif err := decoder69.Decode(&h69); err == nil {\n\t\tt.Value = h69\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [NotebookDocumentFilterWithCells NotebookDocumentFilterWithNotebook]\"}\n}\n\nfunc (t Or_ParameterInformation_documentation) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase MarkupContent:\n\t\treturn json.Marshal(x)\n\tcase string:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [MarkupContent string]\", t)\n}\n\nfunc (t *Or_ParameterInformation_documentation) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder205 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder205.DisallowUnknownFields()\n\tvar stringVal string\n\tif err := decoder205.Decode(&stringVal); err == nil {\n\t\tt.Value = stringVal\n\t\treturn nil\n\t}\n\tdecoder206 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder206.DisallowUnknownFields()\n\tvar h206 MarkupContent\n\tif err := decoder206.Decode(&h206); err == nil {\n\t\tt.Value = h206\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [MarkupContent string]\"}\n}\n\nfunc (t Or_ParameterInformation_label) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase Tuple_ParameterInformation_label_Item1:\n\t\treturn json.Marshal(x)\n\tcase string:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [Tuple_ParameterInformation_label_Item1 string]\", t)\n}\n\nfunc (t *Or_ParameterInformation_label) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder202 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder202.DisallowUnknownFields()\n\tvar stringVal string\n\tif err := decoder202.Decode(&stringVal); err == nil {\n\t\tt.Value = stringVal\n\t\treturn nil\n\t}\n\tdecoder203 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder203.DisallowUnknownFields()\n\tvar h203 Tuple_ParameterInformation_label_Item1\n\tif err := decoder203.Decode(&h203); err == nil {\n\t\tt.Value = h203\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [Tuple_ParameterInformation_label_Item1 string]\"}\n}\n\nfunc (t Or_PrepareRenameResult) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase PrepareRenameDefaultBehavior:\n\t\treturn json.Marshal(x)\n\tcase PrepareRenamePlaceholder:\n\t\treturn json.Marshal(x)\n\tcase Range:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [PrepareRenameDefaultBehavior PrepareRenamePlaceholder Range]\", t)\n}\n\nfunc (t *Or_PrepareRenameResult) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder252 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder252.DisallowUnknownFields()\n\tvar h252 PrepareRenameDefaultBehavior\n\tif err := decoder252.Decode(&h252); err == nil {\n\t\tt.Value = h252\n\t\treturn nil\n\t}\n\tdecoder253 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder253.DisallowUnknownFields()\n\tvar h253 PrepareRenamePlaceholder\n\tif err := decoder253.Decode(&h253); err == nil {\n\t\tt.Value = h253\n\t\treturn nil\n\t}\n\tdecoder254 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder254.DisallowUnknownFields()\n\tvar h254 Range\n\tif err := decoder254.Decode(&h254); err == nil {\n\t\tt.Value = h254\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [PrepareRenameDefaultBehavior PrepareRenamePlaceholder Range]\"}\n}\n\nfunc (t Or_ProgressToken) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase int32:\n\t\treturn json.Marshal(x)\n\tcase string:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [int32 string]\", t)\n}\n\nfunc (t *Or_ProgressToken) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder255 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder255.DisallowUnknownFields()\n\tvar int32Val int32\n\tif err := decoder255.Decode(&int32Val); err == nil {\n\t\tt.Value = int32Val\n\t\treturn nil\n\t}\n\tdecoder256 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder256.DisallowUnknownFields()\n\tvar stringVal string\n\tif err := decoder256.Decode(&stringVal); err == nil {\n\t\tt.Value = stringVal\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [int32 string]\"}\n}\n\nfunc (t Or_RelatedFullDocumentDiagnosticReport_relatedDocuments_Value) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase FullDocumentDiagnosticReport:\n\t\treturn json.Marshal(x)\n\tcase UnchangedDocumentDiagnosticReport:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [FullDocumentDiagnosticReport UnchangedDocumentDiagnosticReport]\", t)\n}\n\nfunc (t *Or_RelatedFullDocumentDiagnosticReport_relatedDocuments_Value) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder60 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder60.DisallowUnknownFields()\n\tvar h60 FullDocumentDiagnosticReport\n\tif err := decoder60.Decode(&h60); err == nil {\n\t\tt.Value = h60\n\t\treturn nil\n\t}\n\tdecoder61 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder61.DisallowUnknownFields()\n\tvar h61 UnchangedDocumentDiagnosticReport\n\tif err := decoder61.Decode(&h61); err == nil {\n\t\tt.Value = h61\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [FullDocumentDiagnosticReport UnchangedDocumentDiagnosticReport]\"}\n}\n\nfunc (t Or_RelatedUnchangedDocumentDiagnosticReport_relatedDocuments_Value) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase FullDocumentDiagnosticReport:\n\t\treturn json.Marshal(x)\n\tcase UnchangedDocumentDiagnosticReport:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [FullDocumentDiagnosticReport UnchangedDocumentDiagnosticReport]\", t)\n}\n\nfunc (t *Or_RelatedUnchangedDocumentDiagnosticReport_relatedDocuments_Value) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder64 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder64.DisallowUnknownFields()\n\tvar h64 FullDocumentDiagnosticReport\n\tif err := decoder64.Decode(&h64); err == nil {\n\t\tt.Value = h64\n\t\treturn nil\n\t}\n\tdecoder65 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder65.DisallowUnknownFields()\n\tvar h65 UnchangedDocumentDiagnosticReport\n\tif err := decoder65.Decode(&h65); err == nil {\n\t\tt.Value = h65\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [FullDocumentDiagnosticReport UnchangedDocumentDiagnosticReport]\"}\n}\n\nfunc (t Or_RelativePattern_baseUri) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase URI:\n\t\treturn json.Marshal(x)\n\tcase WorkspaceFolder:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [URI WorkspaceFolder]\", t)\n}\n\nfunc (t *Or_RelativePattern_baseUri) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder214 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder214.DisallowUnknownFields()\n\tvar h214 URI\n\tif err := decoder214.Decode(&h214); err == nil {\n\t\tt.Value = h214\n\t\treturn nil\n\t}\n\tdecoder215 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder215.DisallowUnknownFields()\n\tvar h215 WorkspaceFolder\n\tif err := decoder215.Decode(&h215); err == nil {\n\t\tt.Value = h215\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [URI WorkspaceFolder]\"}\n}\n\nfunc (t Or_Result_textDocument_codeAction_Item0_Elem) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase CodeAction:\n\t\treturn json.Marshal(x)\n\tcase Command:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [CodeAction Command]\", t)\n}\n\nfunc (t *Or_Result_textDocument_codeAction_Item0_Elem) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder322 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder322.DisallowUnknownFields()\n\tvar h322 CodeAction\n\tif err := decoder322.Decode(&h322); err == nil {\n\t\tt.Value = h322\n\t\treturn nil\n\t}\n\tdecoder323 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder323.DisallowUnknownFields()\n\tvar h323 Command\n\tif err := decoder323.Decode(&h323); err == nil {\n\t\tt.Value = h323\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [CodeAction Command]\"}\n}\n\nfunc (t Or_Result_textDocument_completion) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase CompletionList:\n\t\treturn json.Marshal(x)\n\tcase []CompletionItem:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [CompletionList []CompletionItem]\", t)\n}\n\nfunc (t *Or_Result_textDocument_completion) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder310 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder310.DisallowUnknownFields()\n\tvar h310 CompletionList\n\tif err := decoder310.Decode(&h310); err == nil {\n\t\tt.Value = h310\n\t\treturn nil\n\t}\n\tdecoder311 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder311.DisallowUnknownFields()\n\tvar h311 []CompletionItem\n\tif err := decoder311.Decode(&h311); err == nil {\n\t\tt.Value = h311\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [CompletionList []CompletionItem]\"}\n}\n\nfunc (t Or_Result_textDocument_declaration) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase Declaration:\n\t\treturn json.Marshal(x)\n\tcase []DeclarationLink:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [Declaration []DeclarationLink]\", t)\n}\n\nfunc (t *Or_Result_textDocument_declaration) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder298 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder298.DisallowUnknownFields()\n\tvar h298 Declaration\n\tif err := decoder298.Decode(&h298); err == nil {\n\t\tt.Value = h298\n\t\treturn nil\n\t}\n\tdecoder299 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder299.DisallowUnknownFields()\n\tvar h299 []DeclarationLink\n\tif err := decoder299.Decode(&h299); err == nil {\n\t\tt.Value = h299\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [Declaration []DeclarationLink]\"}\n}\n\nfunc (t Or_Result_textDocument_definition) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase Definition:\n\t\treturn json.Marshal(x)\n\tcase []DefinitionLink:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [Definition []DefinitionLink]\", t)\n}\n\nfunc (t *Or_Result_textDocument_definition) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder314 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder314.DisallowUnknownFields()\n\tvar h314 Definition\n\tif err := decoder314.Decode(&h314); err == nil {\n\t\tt.Value = h314\n\t\treturn nil\n\t}\n\tdecoder315 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder315.DisallowUnknownFields()\n\tvar h315 []DefinitionLink\n\tif err := decoder315.Decode(&h315); err == nil {\n\t\tt.Value = h315\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [Definition []DefinitionLink]\"}\n}\n\nfunc (t Or_Result_textDocument_documentSymbol) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase []DocumentSymbol:\n\t\treturn json.Marshal(x)\n\tcase []SymbolInformation:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [[]DocumentSymbol []SymbolInformation]\", t)\n}\n\nfunc (t *Or_Result_textDocument_documentSymbol) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder318 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder318.DisallowUnknownFields()\n\tvar h318 []DocumentSymbol\n\tif err := decoder318.Decode(&h318); err == nil {\n\t\tt.Value = h318\n\t\treturn nil\n\t}\n\tdecoder319 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder319.DisallowUnknownFields()\n\tvar h319 []SymbolInformation\n\tif err := decoder319.Decode(&h319); err == nil {\n\t\tt.Value = h319\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [[]DocumentSymbol []SymbolInformation]\"}\n}\n\nfunc (t Or_Result_textDocument_implementation) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase Definition:\n\t\treturn json.Marshal(x)\n\tcase []DefinitionLink:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [Definition []DefinitionLink]\", t)\n}\n\nfunc (t *Or_Result_textDocument_implementation) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder290 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder290.DisallowUnknownFields()\n\tvar h290 Definition\n\tif err := decoder290.Decode(&h290); err == nil {\n\t\tt.Value = h290\n\t\treturn nil\n\t}\n\tdecoder291 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder291.DisallowUnknownFields()\n\tvar h291 []DefinitionLink\n\tif err := decoder291.Decode(&h291); err == nil {\n\t\tt.Value = h291\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [Definition []DefinitionLink]\"}\n}\n\nfunc (t Or_Result_textDocument_inlineCompletion) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase InlineCompletionList:\n\t\treturn json.Marshal(x)\n\tcase []InlineCompletionItem:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [InlineCompletionList []InlineCompletionItem]\", t)\n}\n\nfunc (t *Or_Result_textDocument_inlineCompletion) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder306 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder306.DisallowUnknownFields()\n\tvar h306 InlineCompletionList\n\tif err := decoder306.Decode(&h306); err == nil {\n\t\tt.Value = h306\n\t\treturn nil\n\t}\n\tdecoder307 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder307.DisallowUnknownFields()\n\tvar h307 []InlineCompletionItem\n\tif err := decoder307.Decode(&h307); err == nil {\n\t\tt.Value = h307\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [InlineCompletionList []InlineCompletionItem]\"}\n}\n\nfunc (t Or_Result_textDocument_semanticTokens_full_delta) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase SemanticTokens:\n\t\treturn json.Marshal(x)\n\tcase SemanticTokensDelta:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [SemanticTokens SemanticTokensDelta]\", t)\n}\n\nfunc (t *Or_Result_textDocument_semanticTokens_full_delta) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder302 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder302.DisallowUnknownFields()\n\tvar h302 SemanticTokens\n\tif err := decoder302.Decode(&h302); err == nil {\n\t\tt.Value = h302\n\t\treturn nil\n\t}\n\tdecoder303 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder303.DisallowUnknownFields()\n\tvar h303 SemanticTokensDelta\n\tif err := decoder303.Decode(&h303); err == nil {\n\t\tt.Value = h303\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [SemanticTokens SemanticTokensDelta]\"}\n}\n\nfunc (t Or_Result_textDocument_typeDefinition) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase Definition:\n\t\treturn json.Marshal(x)\n\tcase []DefinitionLink:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [Definition []DefinitionLink]\", t)\n}\n\nfunc (t *Or_Result_textDocument_typeDefinition) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder294 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder294.DisallowUnknownFields()\n\tvar h294 Definition\n\tif err := decoder294.Decode(&h294); err == nil {\n\t\tt.Value = h294\n\t\treturn nil\n\t}\n\tdecoder295 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder295.DisallowUnknownFields()\n\tvar h295 []DefinitionLink\n\tif err := decoder295.Decode(&h295); err == nil {\n\t\tt.Value = h295\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [Definition []DefinitionLink]\"}\n}\n\nfunc (t Or_Result_workspace_symbol) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase []SymbolInformation:\n\t\treturn json.Marshal(x)\n\tcase []WorkspaceSymbol:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [[]SymbolInformation []WorkspaceSymbol]\", t)\n}\n\nfunc (t *Or_Result_workspace_symbol) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder326 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder326.DisallowUnknownFields()\n\tvar h326 []SymbolInformation\n\tif err := decoder326.Decode(&h326); err == nil {\n\t\tt.Value = h326\n\t\treturn nil\n\t}\n\tdecoder327 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder327.DisallowUnknownFields()\n\tvar h327 []WorkspaceSymbol\n\tif err := decoder327.Decode(&h327); err == nil {\n\t\tt.Value = h327\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [[]SymbolInformation []WorkspaceSymbol]\"}\n}\n\nfunc (t Or_SemanticTokensOptions_full) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase SemanticTokensFullDelta:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [SemanticTokensFullDelta bool]\", t)\n}\n\nfunc (t *Or_SemanticTokensOptions_full) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder47 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder47.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder47.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder48 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder48.DisallowUnknownFields()\n\tvar h48 SemanticTokensFullDelta\n\tif err := decoder48.Decode(&h48); err == nil {\n\t\tt.Value = h48\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [SemanticTokensFullDelta bool]\"}\n}\n\nfunc (t Or_SemanticTokensOptions_range) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase Lit_SemanticTokensOptions_range_Item1:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [Lit_SemanticTokensOptions_range_Item1 bool]\", t)\n}\n\nfunc (t *Or_SemanticTokensOptions_range) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder44 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder44.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder44.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder45 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder45.DisallowUnknownFields()\n\tvar h45 Lit_SemanticTokensOptions_range_Item1\n\tif err := decoder45.Decode(&h45); err == nil {\n\t\tt.Value = h45\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [Lit_SemanticTokensOptions_range_Item1 bool]\"}\n}\n\nfunc (t Or_ServerCapabilities_callHierarchyProvider) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase CallHierarchyOptions:\n\t\treturn json.Marshal(x)\n\tcase CallHierarchyRegistrationOptions:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [CallHierarchyOptions CallHierarchyRegistrationOptions bool]\", t)\n}\n\nfunc (t *Or_ServerCapabilities_callHierarchyProvider) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder140 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder140.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder140.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder141 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder141.DisallowUnknownFields()\n\tvar h141 CallHierarchyOptions\n\tif err := decoder141.Decode(&h141); err == nil {\n\t\tt.Value = h141\n\t\treturn nil\n\t}\n\tdecoder142 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder142.DisallowUnknownFields()\n\tvar h142 CallHierarchyRegistrationOptions\n\tif err := decoder142.Decode(&h142); err == nil {\n\t\tt.Value = h142\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [CallHierarchyOptions CallHierarchyRegistrationOptions bool]\"}\n}\n\nfunc (t Or_ServerCapabilities_codeActionProvider) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase CodeActionOptions:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [CodeActionOptions bool]\", t)\n}\n\nfunc (t *Or_ServerCapabilities_codeActionProvider) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder109 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder109.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder109.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder110 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder110.DisallowUnknownFields()\n\tvar h110 CodeActionOptions\n\tif err := decoder110.Decode(&h110); err == nil {\n\t\tt.Value = h110\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [CodeActionOptions bool]\"}\n}\n\nfunc (t Or_ServerCapabilities_colorProvider) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase DocumentColorOptions:\n\t\treturn json.Marshal(x)\n\tcase DocumentColorRegistrationOptions:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [DocumentColorOptions DocumentColorRegistrationOptions bool]\", t)\n}\n\nfunc (t *Or_ServerCapabilities_colorProvider) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder113 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder113.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder113.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder114 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder114.DisallowUnknownFields()\n\tvar h114 DocumentColorOptions\n\tif err := decoder114.Decode(&h114); err == nil {\n\t\tt.Value = h114\n\t\treturn nil\n\t}\n\tdecoder115 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder115.DisallowUnknownFields()\n\tvar h115 DocumentColorRegistrationOptions\n\tif err := decoder115.Decode(&h115); err == nil {\n\t\tt.Value = h115\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [DocumentColorOptions DocumentColorRegistrationOptions bool]\"}\n}\n\nfunc (t Or_ServerCapabilities_declarationProvider) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase DeclarationOptions:\n\t\treturn json.Marshal(x)\n\tcase DeclarationRegistrationOptions:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [DeclarationOptions DeclarationRegistrationOptions bool]\", t)\n}\n\nfunc (t *Or_ServerCapabilities_declarationProvider) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder83 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder83.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder83.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder84 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder84.DisallowUnknownFields()\n\tvar h84 DeclarationOptions\n\tif err := decoder84.Decode(&h84); err == nil {\n\t\tt.Value = h84\n\t\treturn nil\n\t}\n\tdecoder85 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder85.DisallowUnknownFields()\n\tvar h85 DeclarationRegistrationOptions\n\tif err := decoder85.Decode(&h85); err == nil {\n\t\tt.Value = h85\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [DeclarationOptions DeclarationRegistrationOptions bool]\"}\n}\n\nfunc (t Or_ServerCapabilities_definitionProvider) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase DefinitionOptions:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [DefinitionOptions bool]\", t)\n}\n\nfunc (t *Or_ServerCapabilities_definitionProvider) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder87 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder87.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder87.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder88 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder88.DisallowUnknownFields()\n\tvar h88 DefinitionOptions\n\tif err := decoder88.Decode(&h88); err == nil {\n\t\tt.Value = h88\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [DefinitionOptions bool]\"}\n}\n\nfunc (t Or_ServerCapabilities_diagnosticProvider) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase DiagnosticOptions:\n\t\treturn json.Marshal(x)\n\tcase DiagnosticRegistrationOptions:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [DiagnosticOptions DiagnosticRegistrationOptions]\", t)\n}\n\nfunc (t *Or_ServerCapabilities_diagnosticProvider) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder174 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder174.DisallowUnknownFields()\n\tvar h174 DiagnosticOptions\n\tif err := decoder174.Decode(&h174); err == nil {\n\t\tt.Value = h174\n\t\treturn nil\n\t}\n\tdecoder175 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder175.DisallowUnknownFields()\n\tvar h175 DiagnosticRegistrationOptions\n\tif err := decoder175.Decode(&h175); err == nil {\n\t\tt.Value = h175\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [DiagnosticOptions DiagnosticRegistrationOptions]\"}\n}\n\nfunc (t Or_ServerCapabilities_documentFormattingProvider) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase DocumentFormattingOptions:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [DocumentFormattingOptions bool]\", t)\n}\n\nfunc (t *Or_ServerCapabilities_documentFormattingProvider) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder120 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder120.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder120.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder121 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder121.DisallowUnknownFields()\n\tvar h121 DocumentFormattingOptions\n\tif err := decoder121.Decode(&h121); err == nil {\n\t\tt.Value = h121\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [DocumentFormattingOptions bool]\"}\n}\n\nfunc (t Or_ServerCapabilities_documentHighlightProvider) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase DocumentHighlightOptions:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [DocumentHighlightOptions bool]\", t)\n}\n\nfunc (t *Or_ServerCapabilities_documentHighlightProvider) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder103 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder103.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder103.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder104 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder104.DisallowUnknownFields()\n\tvar h104 DocumentHighlightOptions\n\tif err := decoder104.Decode(&h104); err == nil {\n\t\tt.Value = h104\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [DocumentHighlightOptions bool]\"}\n}\n\nfunc (t Or_ServerCapabilities_documentRangeFormattingProvider) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase DocumentRangeFormattingOptions:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [DocumentRangeFormattingOptions bool]\", t)\n}\n\nfunc (t *Or_ServerCapabilities_documentRangeFormattingProvider) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder123 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder123.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder123.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder124 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder124.DisallowUnknownFields()\n\tvar h124 DocumentRangeFormattingOptions\n\tif err := decoder124.Decode(&h124); err == nil {\n\t\tt.Value = h124\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [DocumentRangeFormattingOptions bool]\"}\n}\n\nfunc (t Or_ServerCapabilities_documentSymbolProvider) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase DocumentSymbolOptions:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [DocumentSymbolOptions bool]\", t)\n}\n\nfunc (t *Or_ServerCapabilities_documentSymbolProvider) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder106 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder106.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder106.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder107 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder107.DisallowUnknownFields()\n\tvar h107 DocumentSymbolOptions\n\tif err := decoder107.Decode(&h107); err == nil {\n\t\tt.Value = h107\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [DocumentSymbolOptions bool]\"}\n}\n\nfunc (t Or_ServerCapabilities_foldingRangeProvider) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase FoldingRangeOptions:\n\t\treturn json.Marshal(x)\n\tcase FoldingRangeRegistrationOptions:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [FoldingRangeOptions FoldingRangeRegistrationOptions bool]\", t)\n}\n\nfunc (t *Or_ServerCapabilities_foldingRangeProvider) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder130 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder130.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder130.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder131 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder131.DisallowUnknownFields()\n\tvar h131 FoldingRangeOptions\n\tif err := decoder131.Decode(&h131); err == nil {\n\t\tt.Value = h131\n\t\treturn nil\n\t}\n\tdecoder132 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder132.DisallowUnknownFields()\n\tvar h132 FoldingRangeRegistrationOptions\n\tif err := decoder132.Decode(&h132); err == nil {\n\t\tt.Value = h132\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [FoldingRangeOptions FoldingRangeRegistrationOptions bool]\"}\n}\n\nfunc (t Or_ServerCapabilities_hoverProvider) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase HoverOptions:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [HoverOptions bool]\", t)\n}\n\nfunc (t *Or_ServerCapabilities_hoverProvider) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder79 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder79.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder79.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder80 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder80.DisallowUnknownFields()\n\tvar h80 HoverOptions\n\tif err := decoder80.Decode(&h80); err == nil {\n\t\tt.Value = h80\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [HoverOptions bool]\"}\n}\n\nfunc (t Or_ServerCapabilities_implementationProvider) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase ImplementationOptions:\n\t\treturn json.Marshal(x)\n\tcase ImplementationRegistrationOptions:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [ImplementationOptions ImplementationRegistrationOptions bool]\", t)\n}\n\nfunc (t *Or_ServerCapabilities_implementationProvider) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder96 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder96.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder96.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder97 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder97.DisallowUnknownFields()\n\tvar h97 ImplementationOptions\n\tif err := decoder97.Decode(&h97); err == nil {\n\t\tt.Value = h97\n\t\treturn nil\n\t}\n\tdecoder98 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder98.DisallowUnknownFields()\n\tvar h98 ImplementationRegistrationOptions\n\tif err := decoder98.Decode(&h98); err == nil {\n\t\tt.Value = h98\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [ImplementationOptions ImplementationRegistrationOptions bool]\"}\n}\n\nfunc (t Or_ServerCapabilities_inlayHintProvider) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase InlayHintOptions:\n\t\treturn json.Marshal(x)\n\tcase InlayHintRegistrationOptions:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [InlayHintOptions InlayHintRegistrationOptions bool]\", t)\n}\n\nfunc (t *Or_ServerCapabilities_inlayHintProvider) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder169 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder169.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder169.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder170 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder170.DisallowUnknownFields()\n\tvar h170 InlayHintOptions\n\tif err := decoder170.Decode(&h170); err == nil {\n\t\tt.Value = h170\n\t\treturn nil\n\t}\n\tdecoder171 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder171.DisallowUnknownFields()\n\tvar h171 InlayHintRegistrationOptions\n\tif err := decoder171.Decode(&h171); err == nil {\n\t\tt.Value = h171\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [InlayHintOptions InlayHintRegistrationOptions bool]\"}\n}\n\nfunc (t Or_ServerCapabilities_inlineCompletionProvider) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase InlineCompletionOptions:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [InlineCompletionOptions bool]\", t)\n}\n\nfunc (t *Or_ServerCapabilities_inlineCompletionProvider) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder177 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder177.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder177.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder178 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder178.DisallowUnknownFields()\n\tvar h178 InlineCompletionOptions\n\tif err := decoder178.Decode(&h178); err == nil {\n\t\tt.Value = h178\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [InlineCompletionOptions bool]\"}\n}\n\nfunc (t Or_ServerCapabilities_inlineValueProvider) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase InlineValueOptions:\n\t\treturn json.Marshal(x)\n\tcase InlineValueRegistrationOptions:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [InlineValueOptions InlineValueRegistrationOptions bool]\", t)\n}\n\nfunc (t *Or_ServerCapabilities_inlineValueProvider) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder164 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder164.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder164.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder165 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder165.DisallowUnknownFields()\n\tvar h165 InlineValueOptions\n\tif err := decoder165.Decode(&h165); err == nil {\n\t\tt.Value = h165\n\t\treturn nil\n\t}\n\tdecoder166 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder166.DisallowUnknownFields()\n\tvar h166 InlineValueRegistrationOptions\n\tif err := decoder166.Decode(&h166); err == nil {\n\t\tt.Value = h166\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [InlineValueOptions InlineValueRegistrationOptions bool]\"}\n}\n\nfunc (t Or_ServerCapabilities_linkedEditingRangeProvider) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase LinkedEditingRangeOptions:\n\t\treturn json.Marshal(x)\n\tcase LinkedEditingRangeRegistrationOptions:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [LinkedEditingRangeOptions LinkedEditingRangeRegistrationOptions bool]\", t)\n}\n\nfunc (t *Or_ServerCapabilities_linkedEditingRangeProvider) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder145 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder145.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder145.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder146 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder146.DisallowUnknownFields()\n\tvar h146 LinkedEditingRangeOptions\n\tif err := decoder146.Decode(&h146); err == nil {\n\t\tt.Value = h146\n\t\treturn nil\n\t}\n\tdecoder147 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder147.DisallowUnknownFields()\n\tvar h147 LinkedEditingRangeRegistrationOptions\n\tif err := decoder147.Decode(&h147); err == nil {\n\t\tt.Value = h147\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [LinkedEditingRangeOptions LinkedEditingRangeRegistrationOptions bool]\"}\n}\n\nfunc (t Or_ServerCapabilities_monikerProvider) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase MonikerOptions:\n\t\treturn json.Marshal(x)\n\tcase MonikerRegistrationOptions:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [MonikerOptions MonikerRegistrationOptions bool]\", t)\n}\n\nfunc (t *Or_ServerCapabilities_monikerProvider) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder154 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder154.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder154.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder155 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder155.DisallowUnknownFields()\n\tvar h155 MonikerOptions\n\tif err := decoder155.Decode(&h155); err == nil {\n\t\tt.Value = h155\n\t\treturn nil\n\t}\n\tdecoder156 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder156.DisallowUnknownFields()\n\tvar h156 MonikerRegistrationOptions\n\tif err := decoder156.Decode(&h156); err == nil {\n\t\tt.Value = h156\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [MonikerOptions MonikerRegistrationOptions bool]\"}\n}\n\nfunc (t Or_ServerCapabilities_notebookDocumentSync) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase NotebookDocumentSyncOptions:\n\t\treturn json.Marshal(x)\n\tcase NotebookDocumentSyncRegistrationOptions:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [NotebookDocumentSyncOptions NotebookDocumentSyncRegistrationOptions]\", t)\n}\n\nfunc (t *Or_ServerCapabilities_notebookDocumentSync) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder76 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder76.DisallowUnknownFields()\n\tvar h76 NotebookDocumentSyncOptions\n\tif err := decoder76.Decode(&h76); err == nil {\n\t\tt.Value = h76\n\t\treturn nil\n\t}\n\tdecoder77 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder77.DisallowUnknownFields()\n\tvar h77 NotebookDocumentSyncRegistrationOptions\n\tif err := decoder77.Decode(&h77); err == nil {\n\t\tt.Value = h77\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [NotebookDocumentSyncOptions NotebookDocumentSyncRegistrationOptions]\"}\n}\n\nfunc (t Or_ServerCapabilities_referencesProvider) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase ReferenceOptions:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [ReferenceOptions bool]\", t)\n}\n\nfunc (t *Or_ServerCapabilities_referencesProvider) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder100 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder100.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder100.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder101 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder101.DisallowUnknownFields()\n\tvar h101 ReferenceOptions\n\tif err := decoder101.Decode(&h101); err == nil {\n\t\tt.Value = h101\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [ReferenceOptions bool]\"}\n}\n\nfunc (t Or_ServerCapabilities_renameProvider) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase RenameOptions:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [RenameOptions bool]\", t)\n}\n\nfunc (t *Or_ServerCapabilities_renameProvider) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder126 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder126.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder126.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder127 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder127.DisallowUnknownFields()\n\tvar h127 RenameOptions\n\tif err := decoder127.Decode(&h127); err == nil {\n\t\tt.Value = h127\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [RenameOptions bool]\"}\n}\n\nfunc (t Or_ServerCapabilities_selectionRangeProvider) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase SelectionRangeOptions:\n\t\treturn json.Marshal(x)\n\tcase SelectionRangeRegistrationOptions:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [SelectionRangeOptions SelectionRangeRegistrationOptions bool]\", t)\n}\n\nfunc (t *Or_ServerCapabilities_selectionRangeProvider) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder135 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder135.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder135.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder136 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder136.DisallowUnknownFields()\n\tvar h136 SelectionRangeOptions\n\tif err := decoder136.Decode(&h136); err == nil {\n\t\tt.Value = h136\n\t\treturn nil\n\t}\n\tdecoder137 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder137.DisallowUnknownFields()\n\tvar h137 SelectionRangeRegistrationOptions\n\tif err := decoder137.Decode(&h137); err == nil {\n\t\tt.Value = h137\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [SelectionRangeOptions SelectionRangeRegistrationOptions bool]\"}\n}\n\nfunc (t Or_ServerCapabilities_semanticTokensProvider) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase SemanticTokensOptions:\n\t\treturn json.Marshal(x)\n\tcase SemanticTokensRegistrationOptions:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [SemanticTokensOptions SemanticTokensRegistrationOptions]\", t)\n}\n\nfunc (t *Or_ServerCapabilities_semanticTokensProvider) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder150 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder150.DisallowUnknownFields()\n\tvar h150 SemanticTokensOptions\n\tif err := decoder150.Decode(&h150); err == nil {\n\t\tt.Value = h150\n\t\treturn nil\n\t}\n\tdecoder151 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder151.DisallowUnknownFields()\n\tvar h151 SemanticTokensRegistrationOptions\n\tif err := decoder151.Decode(&h151); err == nil {\n\t\tt.Value = h151\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [SemanticTokensOptions SemanticTokensRegistrationOptions]\"}\n}\n\nfunc (t Or_ServerCapabilities_textDocumentSync) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase TextDocumentSyncKind:\n\t\treturn json.Marshal(x)\n\tcase TextDocumentSyncOptions:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [TextDocumentSyncKind TextDocumentSyncOptions]\", t)\n}\n\nfunc (t *Or_ServerCapabilities_textDocumentSync) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder72 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder72.DisallowUnknownFields()\n\tvar h72 TextDocumentSyncKind\n\tif err := decoder72.Decode(&h72); err == nil {\n\t\tt.Value = h72\n\t\treturn nil\n\t}\n\tdecoder73 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder73.DisallowUnknownFields()\n\tvar h73 TextDocumentSyncOptions\n\tif err := decoder73.Decode(&h73); err == nil {\n\t\tt.Value = h73\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [TextDocumentSyncKind TextDocumentSyncOptions]\"}\n}\n\nfunc (t Or_ServerCapabilities_typeDefinitionProvider) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase TypeDefinitionOptions:\n\t\treturn json.Marshal(x)\n\tcase TypeDefinitionRegistrationOptions:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [TypeDefinitionOptions TypeDefinitionRegistrationOptions bool]\", t)\n}\n\nfunc (t *Or_ServerCapabilities_typeDefinitionProvider) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder91 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder91.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder91.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder92 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder92.DisallowUnknownFields()\n\tvar h92 TypeDefinitionOptions\n\tif err := decoder92.Decode(&h92); err == nil {\n\t\tt.Value = h92\n\t\treturn nil\n\t}\n\tdecoder93 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder93.DisallowUnknownFields()\n\tvar h93 TypeDefinitionRegistrationOptions\n\tif err := decoder93.Decode(&h93); err == nil {\n\t\tt.Value = h93\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [TypeDefinitionOptions TypeDefinitionRegistrationOptions bool]\"}\n}\n\nfunc (t Or_ServerCapabilities_typeHierarchyProvider) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase TypeHierarchyOptions:\n\t\treturn json.Marshal(x)\n\tcase TypeHierarchyRegistrationOptions:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [TypeHierarchyOptions TypeHierarchyRegistrationOptions bool]\", t)\n}\n\nfunc (t *Or_ServerCapabilities_typeHierarchyProvider) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder159 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder159.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder159.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder160 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder160.DisallowUnknownFields()\n\tvar h160 TypeHierarchyOptions\n\tif err := decoder160.Decode(&h160); err == nil {\n\t\tt.Value = h160\n\t\treturn nil\n\t}\n\tdecoder161 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder161.DisallowUnknownFields()\n\tvar h161 TypeHierarchyRegistrationOptions\n\tif err := decoder161.Decode(&h161); err == nil {\n\t\tt.Value = h161\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [TypeHierarchyOptions TypeHierarchyRegistrationOptions bool]\"}\n}\n\nfunc (t Or_ServerCapabilities_workspaceSymbolProvider) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase WorkspaceSymbolOptions:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [WorkspaceSymbolOptions bool]\", t)\n}\n\nfunc (t *Or_ServerCapabilities_workspaceSymbolProvider) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder117 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder117.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder117.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder118 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder118.DisallowUnknownFields()\n\tvar h118 WorkspaceSymbolOptions\n\tif err := decoder118.Decode(&h118); err == nil {\n\t\tt.Value = h118\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [WorkspaceSymbolOptions bool]\"}\n}\n\nfunc (t Or_SignatureInformation_documentation) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase MarkupContent:\n\t\treturn json.Marshal(x)\n\tcase string:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [MarkupContent string]\", t)\n}\n\nfunc (t *Or_SignatureInformation_documentation) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder186 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder186.DisallowUnknownFields()\n\tvar stringVal string\n\tif err := decoder186.Decode(&stringVal); err == nil {\n\t\tt.Value = stringVal\n\t\treturn nil\n\t}\n\tdecoder187 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder187.DisallowUnknownFields()\n\tvar h187 MarkupContent\n\tif err := decoder187.Decode(&h187); err == nil {\n\t\tt.Value = h187\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [MarkupContent string]\"}\n}\n\nfunc (t Or_TextDocumentContentChangeEvent) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase TextDocumentContentChangePartial:\n\t\treturn json.Marshal(x)\n\tcase TextDocumentContentChangeWholeDocument:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [TextDocumentContentChangePartial TextDocumentContentChangeWholeDocument]\", t)\n}\n\nfunc (t *Or_TextDocumentContentChangeEvent) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder263 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder263.DisallowUnknownFields()\n\tvar h263 TextDocumentContentChangePartial\n\tif err := decoder263.Decode(&h263); err == nil {\n\t\tt.Value = h263\n\t\treturn nil\n\t}\n\tdecoder264 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder264.DisallowUnknownFields()\n\tvar h264 TextDocumentContentChangeWholeDocument\n\tif err := decoder264.Decode(&h264); err == nil {\n\t\tt.Value = h264\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [TextDocumentContentChangePartial TextDocumentContentChangeWholeDocument]\"}\n}\n\nfunc (t Or_TextDocumentEdit_edits_Elem) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase AnnotatedTextEdit:\n\t\treturn json.Marshal(x)\n\tcase SnippetTextEdit:\n\t\treturn json.Marshal(x)\n\tcase TextEdit:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [AnnotatedTextEdit SnippetTextEdit TextEdit]\", t)\n}\n\nfunc (t *Or_TextDocumentEdit_edits_Elem) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder52 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder52.DisallowUnknownFields()\n\tvar h52 AnnotatedTextEdit\n\tif err := decoder52.Decode(&h52); err == nil {\n\t\tt.Value = h52\n\t\treturn nil\n\t}\n\tdecoder53 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder53.DisallowUnknownFields()\n\tvar h53 SnippetTextEdit\n\tif err := decoder53.Decode(&h53); err == nil {\n\t\tt.Value = h53\n\t\treturn nil\n\t}\n\tdecoder54 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder54.DisallowUnknownFields()\n\tvar h54 TextEdit\n\tif err := decoder54.Decode(&h54); err == nil {\n\t\tt.Value = h54\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [AnnotatedTextEdit SnippetTextEdit TextEdit]\"}\n}\n\nfunc (t Or_TextDocumentFilter) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase TextDocumentFilterLanguage:\n\t\treturn json.Marshal(x)\n\tcase TextDocumentFilterPattern:\n\t\treturn json.Marshal(x)\n\tcase TextDocumentFilterScheme:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [TextDocumentFilterLanguage TextDocumentFilterPattern TextDocumentFilterScheme]\", t)\n}\n\nfunc (t *Or_TextDocumentFilter) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder279 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder279.DisallowUnknownFields()\n\tvar h279 TextDocumentFilterLanguage\n\tif err := decoder279.Decode(&h279); err == nil {\n\t\tt.Value = h279\n\t\treturn nil\n\t}\n\tdecoder280 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder280.DisallowUnknownFields()\n\tvar h280 TextDocumentFilterPattern\n\tif err := decoder280.Decode(&h280); err == nil {\n\t\tt.Value = h280\n\t\treturn nil\n\t}\n\tdecoder281 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder281.DisallowUnknownFields()\n\tvar h281 TextDocumentFilterScheme\n\tif err := decoder281.Decode(&h281); err == nil {\n\t\tt.Value = h281\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [TextDocumentFilterLanguage TextDocumentFilterPattern TextDocumentFilterScheme]\"}\n}\n\nfunc (t Or_TextDocumentSyncOptions_save) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase SaveOptions:\n\t\treturn json.Marshal(x)\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [SaveOptions bool]\", t)\n}\n\nfunc (t *Or_TextDocumentSyncOptions_save) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder195 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder195.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder195.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder196 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder196.DisallowUnknownFields()\n\tvar h196 SaveOptions\n\tif err := decoder196.Decode(&h196); err == nil {\n\t\tt.Value = h196\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [SaveOptions bool]\"}\n}\n\nfunc (t Or_WorkspaceDocumentDiagnosticReport) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase WorkspaceFullDocumentDiagnosticReport:\n\t\treturn json.Marshal(x)\n\tcase WorkspaceUnchangedDocumentDiagnosticReport:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [WorkspaceFullDocumentDiagnosticReport WorkspaceUnchangedDocumentDiagnosticReport]\", t)\n}\n\nfunc (t *Or_WorkspaceDocumentDiagnosticReport) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder259 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder259.DisallowUnknownFields()\n\tvar h259 WorkspaceFullDocumentDiagnosticReport\n\tif err := decoder259.Decode(&h259); err == nil {\n\t\tt.Value = h259\n\t\treturn nil\n\t}\n\tdecoder260 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder260.DisallowUnknownFields()\n\tvar h260 WorkspaceUnchangedDocumentDiagnosticReport\n\tif err := decoder260.Decode(&h260); err == nil {\n\t\tt.Value = h260\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [WorkspaceFullDocumentDiagnosticReport WorkspaceUnchangedDocumentDiagnosticReport]\"}\n}\n\nfunc (t Or_WorkspaceEdit_documentChanges_Elem) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase CreateFile:\n\t\treturn json.Marshal(x)\n\tcase DeleteFile:\n\t\treturn json.Marshal(x)\n\tcase RenameFile:\n\t\treturn json.Marshal(x)\n\tcase TextDocumentEdit:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [CreateFile DeleteFile RenameFile TextDocumentEdit]\", t)\n}\n\nfunc (t *Or_WorkspaceEdit_documentChanges_Elem) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder4 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder4.DisallowUnknownFields()\n\tvar h4 CreateFile\n\tif err := decoder4.Decode(&h4); err == nil {\n\t\tt.Value = h4\n\t\treturn nil\n\t}\n\tdecoder5 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder5.DisallowUnknownFields()\n\tvar h5 DeleteFile\n\tif err := decoder5.Decode(&h5); err == nil {\n\t\tt.Value = h5\n\t\treturn nil\n\t}\n\tdecoder6 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder6.DisallowUnknownFields()\n\tvar h6 RenameFile\n\tif err := decoder6.Decode(&h6); err == nil {\n\t\tt.Value = h6\n\t\treturn nil\n\t}\n\tdecoder7 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder7.DisallowUnknownFields()\n\tvar h7 TextDocumentEdit\n\tif err := decoder7.Decode(&h7); err == nil {\n\t\tt.Value = h7\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [CreateFile DeleteFile RenameFile TextDocumentEdit]\"}\n}\n\nfunc (t Or_WorkspaceFoldersServerCapabilities_changeNotifications) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase bool:\n\t\treturn json.Marshal(x)\n\tcase string:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [bool string]\", t)\n}\n\nfunc (t *Or_WorkspaceFoldersServerCapabilities_changeNotifications) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder210 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder210.DisallowUnknownFields()\n\tvar boolVal bool\n\tif err := decoder210.Decode(&boolVal); err == nil {\n\t\tt.Value = boolVal\n\t\treturn nil\n\t}\n\tdecoder211 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder211.DisallowUnknownFields()\n\tvar stringVal string\n\tif err := decoder211.Decode(&stringVal); err == nil {\n\t\tt.Value = stringVal\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [bool string]\"}\n}\n\nfunc (t Or_WorkspaceOptions_textDocumentContent) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase TextDocumentContentOptions:\n\t\treturn json.Marshal(x)\n\tcase TextDocumentContentRegistrationOptions:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [TextDocumentContentOptions TextDocumentContentRegistrationOptions]\", t)\n}\n\nfunc (t *Or_WorkspaceOptions_textDocumentContent) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder199 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder199.DisallowUnknownFields()\n\tvar h199 TextDocumentContentOptions\n\tif err := decoder199.Decode(&h199); err == nil {\n\t\tt.Value = h199\n\t\treturn nil\n\t}\n\tdecoder200 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder200.DisallowUnknownFields()\n\tvar h200 TextDocumentContentRegistrationOptions\n\tif err := decoder200.Decode(&h200); err == nil {\n\t\tt.Value = h200\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [TextDocumentContentOptions TextDocumentContentRegistrationOptions]\"}\n}\n\nfunc (t Or_WorkspaceSymbol_location) MarshalJSON() ([]byte, error) {\n\tswitch x := t.Value.(type) {\n\tcase Location:\n\t\treturn json.Marshal(x)\n\tcase LocationUriOnly:\n\t\treturn json.Marshal(x)\n\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn nil, fmt.Errorf(\"type %T not one of [Location LocationUriOnly]\", t)\n}\n\nfunc (t *Or_WorkspaceSymbol_location) UnmarshalJSON(x []byte) error {\n\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\treturn nil\n\t}\n\tdecoder39 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder39.DisallowUnknownFields()\n\tvar h39 Location\n\tif err := decoder39.Decode(&h39); err == nil {\n\t\tt.Value = h39\n\t\treturn nil\n\t}\n\tdecoder40 := json.NewDecoder(bytes.NewReader(x))\n\tdecoder40.DisallowUnknownFields()\n\tvar h40 LocationUriOnly\n\tif err := decoder40.Decode(&h40); err == nil {\n\t\tt.Value = h40\n\t\treturn nil\n\t}\n\treturn &UnmarshalError{\"unmarshal failed to match one of [Location LocationUriOnly]\"}\n}\n"], ["/opencode/internal/tui/components/dialog/permission.go", "package dialog\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\n\t\"github.com/charmbracelet/bubbles/key\"\n\t\"github.com/charmbracelet/bubbles/viewport\"\n\ttea \"github.com/charmbracelet/bubbletea\"\n\t\"github.com/charmbracelet/lipgloss\"\n\t\"github.com/opencode-ai/opencode/internal/diff\"\n\t\"github.com/opencode-ai/opencode/internal/llm/tools\"\n\t\"github.com/opencode-ai/opencode/internal/permission\"\n\t\"github.com/opencode-ai/opencode/internal/tui/layout\"\n\t\"github.com/opencode-ai/opencode/internal/tui/styles\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n\t\"github.com/opencode-ai/opencode/internal/tui/util\"\n)\n\ntype PermissionAction string\n\n// Permission responses\nconst (\n\tPermissionAllow PermissionAction = \"allow\"\n\tPermissionAllowForSession PermissionAction = \"allow_session\"\n\tPermissionDeny PermissionAction = \"deny\"\n)\n\n// PermissionResponseMsg represents the user's response to a permission request\ntype PermissionResponseMsg struct {\n\tPermission permission.PermissionRequest\n\tAction PermissionAction\n}\n\n// PermissionDialogCmp interface for permission dialog component\ntype PermissionDialogCmp interface {\n\ttea.Model\n\tlayout.Bindings\n\tSetPermissions(permission permission.PermissionRequest) tea.Cmd\n}\n\ntype permissionsMapping struct {\n\tLeft key.Binding\n\tRight key.Binding\n\tEnterSpace key.Binding\n\tAllow key.Binding\n\tAllowSession key.Binding\n\tDeny key.Binding\n\tTab key.Binding\n}\n\nvar permissionsKeys = permissionsMapping{\n\tLeft: key.NewBinding(\n\t\tkey.WithKeys(\"left\"),\n\t\tkey.WithHelp(\"←\", \"switch options\"),\n\t),\n\tRight: key.NewBinding(\n\t\tkey.WithKeys(\"right\"),\n\t\tkey.WithHelp(\"→\", \"switch options\"),\n\t),\n\tEnterSpace: key.NewBinding(\n\t\tkey.WithKeys(\"enter\", \" \"),\n\t\tkey.WithHelp(\"enter/space\", \"confirm\"),\n\t),\n\tAllow: key.NewBinding(\n\t\tkey.WithKeys(\"a\"),\n\t\tkey.WithHelp(\"a\", \"allow\"),\n\t),\n\tAllowSession: key.NewBinding(\n\t\tkey.WithKeys(\"s\"),\n\t\tkey.WithHelp(\"s\", \"allow for session\"),\n\t),\n\tDeny: key.NewBinding(\n\t\tkey.WithKeys(\"d\"),\n\t\tkey.WithHelp(\"d\", \"deny\"),\n\t),\n\tTab: key.NewBinding(\n\t\tkey.WithKeys(\"tab\"),\n\t\tkey.WithHelp(\"tab\", \"switch options\"),\n\t),\n}\n\n// permissionDialogCmp is the implementation of PermissionDialog\ntype permissionDialogCmp struct {\n\twidth int\n\theight int\n\tpermission permission.PermissionRequest\n\twindowSize tea.WindowSizeMsg\n\tcontentViewPort viewport.Model\n\tselectedOption int // 0: Allow, 1: Allow for session, 2: Deny\n\n\tdiffCache map[string]string\n\tmarkdownCache map[string]string\n}\n\nfunc (p *permissionDialogCmp) Init() tea.Cmd {\n\treturn p.contentViewPort.Init()\n}\n\nfunc (p *permissionDialogCmp) Update(msg tea.Msg) (tea.Model, tea.Cmd) {\n\tvar cmds []tea.Cmd\n\n\tswitch msg := msg.(type) {\n\tcase tea.WindowSizeMsg:\n\t\tp.windowSize = msg\n\t\tcmd := p.SetSize()\n\t\tcmds = append(cmds, cmd)\n\t\tp.markdownCache = make(map[string]string)\n\t\tp.diffCache = make(map[string]string)\n\tcase tea.KeyMsg:\n\t\tswitch {\n\t\tcase key.Matches(msg, permissionsKeys.Right) || key.Matches(msg, permissionsKeys.Tab):\n\t\t\tp.selectedOption = (p.selectedOption + 1) % 3\n\t\t\treturn p, nil\n\t\tcase key.Matches(msg, permissionsKeys.Left):\n\t\t\tp.selectedOption = (p.selectedOption + 2) % 3\n\t\tcase key.Matches(msg, permissionsKeys.EnterSpace):\n\t\t\treturn p, p.selectCurrentOption()\n\t\tcase key.Matches(msg, permissionsKeys.Allow):\n\t\t\treturn p, util.CmdHandler(PermissionResponseMsg{Action: PermissionAllow, Permission: p.permission})\n\t\tcase key.Matches(msg, permissionsKeys.AllowSession):\n\t\t\treturn p, util.CmdHandler(PermissionResponseMsg{Action: PermissionAllowForSession, Permission: p.permission})\n\t\tcase key.Matches(msg, permissionsKeys.Deny):\n\t\t\treturn p, util.CmdHandler(PermissionResponseMsg{Action: PermissionDeny, Permission: p.permission})\n\t\tdefault:\n\t\t\t// Pass other keys to viewport\n\t\t\tviewPort, cmd := p.contentViewPort.Update(msg)\n\t\t\tp.contentViewPort = viewPort\n\t\t\tcmds = append(cmds, cmd)\n\t\t}\n\t}\n\n\treturn p, tea.Batch(cmds...)\n}\n\nfunc (p *permissionDialogCmp) selectCurrentOption() tea.Cmd {\n\tvar action PermissionAction\n\n\tswitch p.selectedOption {\n\tcase 0:\n\t\taction = PermissionAllow\n\tcase 1:\n\t\taction = PermissionAllowForSession\n\tcase 2:\n\t\taction = PermissionDeny\n\t}\n\n\treturn util.CmdHandler(PermissionResponseMsg{Action: action, Permission: p.permission})\n}\n\nfunc (p *permissionDialogCmp) renderButtons() string {\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\n\tallowStyle := baseStyle\n\tallowSessionStyle := baseStyle\n\tdenyStyle := baseStyle\n\tspacerStyle := baseStyle.Background(t.Background())\n\n\t// Style the selected button\n\tswitch p.selectedOption {\n\tcase 0:\n\t\tallowStyle = allowStyle.Background(t.Primary()).Foreground(t.Background())\n\t\tallowSessionStyle = allowSessionStyle.Background(t.Background()).Foreground(t.Primary())\n\t\tdenyStyle = denyStyle.Background(t.Background()).Foreground(t.Primary())\n\tcase 1:\n\t\tallowStyle = allowStyle.Background(t.Background()).Foreground(t.Primary())\n\t\tallowSessionStyle = allowSessionStyle.Background(t.Primary()).Foreground(t.Background())\n\t\tdenyStyle = denyStyle.Background(t.Background()).Foreground(t.Primary())\n\tcase 2:\n\t\tallowStyle = allowStyle.Background(t.Background()).Foreground(t.Primary())\n\t\tallowSessionStyle = allowSessionStyle.Background(t.Background()).Foreground(t.Primary())\n\t\tdenyStyle = denyStyle.Background(t.Primary()).Foreground(t.Background())\n\t}\n\n\tallowButton := allowStyle.Padding(0, 1).Render(\"Allow (a)\")\n\tallowSessionButton := allowSessionStyle.Padding(0, 1).Render(\"Allow for session (s)\")\n\tdenyButton := denyStyle.Padding(0, 1).Render(\"Deny (d)\")\n\n\tcontent := lipgloss.JoinHorizontal(\n\t\tlipgloss.Left,\n\t\tallowButton,\n\t\tspacerStyle.Render(\" \"),\n\t\tallowSessionButton,\n\t\tspacerStyle.Render(\" \"),\n\t\tdenyButton,\n\t\tspacerStyle.Render(\" \"),\n\t)\n\n\tremainingWidth := p.width - lipgloss.Width(content)\n\tif remainingWidth > 0 {\n\t\tcontent = spacerStyle.Render(strings.Repeat(\" \", remainingWidth)) + content\n\t}\n\treturn content\n}\n\nfunc (p *permissionDialogCmp) renderHeader() string {\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\n\ttoolKey := baseStyle.Foreground(t.TextMuted()).Bold(true).Render(\"Tool\")\n\ttoolValue := baseStyle.\n\t\tForeground(t.Text()).\n\t\tWidth(p.width - lipgloss.Width(toolKey)).\n\t\tRender(fmt.Sprintf(\": %s\", p.permission.ToolName))\n\n\tpathKey := baseStyle.Foreground(t.TextMuted()).Bold(true).Render(\"Path\")\n\tpathValue := baseStyle.\n\t\tForeground(t.Text()).\n\t\tWidth(p.width - lipgloss.Width(pathKey)).\n\t\tRender(fmt.Sprintf(\": %s\", p.permission.Path))\n\n\theaderParts := []string{\n\t\tlipgloss.JoinHorizontal(\n\t\t\tlipgloss.Left,\n\t\t\ttoolKey,\n\t\t\ttoolValue,\n\t\t),\n\t\tbaseStyle.Render(strings.Repeat(\" \", p.width)),\n\t\tlipgloss.JoinHorizontal(\n\t\t\tlipgloss.Left,\n\t\t\tpathKey,\n\t\t\tpathValue,\n\t\t),\n\t\tbaseStyle.Render(strings.Repeat(\" \", p.width)),\n\t}\n\n\t// Add tool-specific header information\n\tswitch p.permission.ToolName {\n\tcase tools.BashToolName:\n\t\theaderParts = append(headerParts, baseStyle.Foreground(t.TextMuted()).Width(p.width).Bold(true).Render(\"Command\"))\n\tcase tools.EditToolName:\n\t\tparams := p.permission.Params.(tools.EditPermissionsParams)\n\t\tfileKey := baseStyle.Foreground(t.TextMuted()).Bold(true).Render(\"File\")\n\t\tfilePath := baseStyle.\n\t\t\tForeground(t.Text()).\n\t\t\tWidth(p.width - lipgloss.Width(fileKey)).\n\t\t\tRender(fmt.Sprintf(\": %s\", params.FilePath))\n\t\theaderParts = append(headerParts,\n\t\t\tlipgloss.JoinHorizontal(\n\t\t\t\tlipgloss.Left,\n\t\t\t\tfileKey,\n\t\t\t\tfilePath,\n\t\t\t),\n\t\t\tbaseStyle.Render(strings.Repeat(\" \", p.width)),\n\t\t)\n\n\tcase tools.WriteToolName:\n\t\tparams := p.permission.Params.(tools.WritePermissionsParams)\n\t\tfileKey := baseStyle.Foreground(t.TextMuted()).Bold(true).Render(\"File\")\n\t\tfilePath := baseStyle.\n\t\t\tForeground(t.Text()).\n\t\t\tWidth(p.width - lipgloss.Width(fileKey)).\n\t\t\tRender(fmt.Sprintf(\": %s\", params.FilePath))\n\t\theaderParts = append(headerParts,\n\t\t\tlipgloss.JoinHorizontal(\n\t\t\t\tlipgloss.Left,\n\t\t\t\tfileKey,\n\t\t\t\tfilePath,\n\t\t\t),\n\t\t\tbaseStyle.Render(strings.Repeat(\" \", p.width)),\n\t\t)\n\tcase tools.FetchToolName:\n\t\theaderParts = append(headerParts, baseStyle.Foreground(t.TextMuted()).Width(p.width).Bold(true).Render(\"URL\"))\n\t}\n\n\treturn lipgloss.NewStyle().Background(t.Background()).Render(lipgloss.JoinVertical(lipgloss.Left, headerParts...))\n}\n\nfunc (p *permissionDialogCmp) renderBashContent() string {\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\n\tif pr, ok := p.permission.Params.(tools.BashPermissionsParams); ok {\n\t\tcontent := fmt.Sprintf(\"```bash\\n%s\\n```\", pr.Command)\n\n\t\t// Use the cache for markdown rendering\n\t\trenderedContent := p.GetOrSetMarkdown(p.permission.ID, func() (string, error) {\n\t\t\tr := styles.GetMarkdownRenderer(p.width - 10)\n\t\t\ts, err := r.Render(content)\n\t\t\treturn styles.ForceReplaceBackgroundWithLipgloss(s, t.Background()), err\n\t\t})\n\n\t\tfinalContent := baseStyle.\n\t\t\tWidth(p.contentViewPort.Width).\n\t\t\tRender(renderedContent)\n\t\tp.contentViewPort.SetContent(finalContent)\n\t\treturn p.styleViewport()\n\t}\n\treturn \"\"\n}\n\nfunc (p *permissionDialogCmp) renderEditContent() string {\n\tif pr, ok := p.permission.Params.(tools.EditPermissionsParams); ok {\n\t\tdiff := p.GetOrSetDiff(p.permission.ID, func() (string, error) {\n\t\t\treturn diff.FormatDiff(pr.Diff, diff.WithTotalWidth(p.contentViewPort.Width))\n\t\t})\n\n\t\tp.contentViewPort.SetContent(diff)\n\t\treturn p.styleViewport()\n\t}\n\treturn \"\"\n}\n\nfunc (p *permissionDialogCmp) renderPatchContent() string {\n\tif pr, ok := p.permission.Params.(tools.EditPermissionsParams); ok {\n\t\tdiff := p.GetOrSetDiff(p.permission.ID, func() (string, error) {\n\t\t\treturn diff.FormatDiff(pr.Diff, diff.WithTotalWidth(p.contentViewPort.Width))\n\t\t})\n\n\t\tp.contentViewPort.SetContent(diff)\n\t\treturn p.styleViewport()\n\t}\n\treturn \"\"\n}\n\nfunc (p *permissionDialogCmp) renderWriteContent() string {\n\tif pr, ok := p.permission.Params.(tools.WritePermissionsParams); ok {\n\t\t// Use the cache for diff rendering\n\t\tdiff := p.GetOrSetDiff(p.permission.ID, func() (string, error) {\n\t\t\treturn diff.FormatDiff(pr.Diff, diff.WithTotalWidth(p.contentViewPort.Width))\n\t\t})\n\n\t\tp.contentViewPort.SetContent(diff)\n\t\treturn p.styleViewport()\n\t}\n\treturn \"\"\n}\n\nfunc (p *permissionDialogCmp) renderFetchContent() string {\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\n\tif pr, ok := p.permission.Params.(tools.FetchPermissionsParams); ok {\n\t\tcontent := fmt.Sprintf(\"```bash\\n%s\\n```\", pr.URL)\n\n\t\t// Use the cache for markdown rendering\n\t\trenderedContent := p.GetOrSetMarkdown(p.permission.ID, func() (string, error) {\n\t\t\tr := styles.GetMarkdownRenderer(p.width - 10)\n\t\t\ts, err := r.Render(content)\n\t\t\treturn styles.ForceReplaceBackgroundWithLipgloss(s, t.Background()), err\n\t\t})\n\n\t\tfinalContent := baseStyle.\n\t\t\tWidth(p.contentViewPort.Width).\n\t\t\tRender(renderedContent)\n\t\tp.contentViewPort.SetContent(finalContent)\n\t\treturn p.styleViewport()\n\t}\n\treturn \"\"\n}\n\nfunc (p *permissionDialogCmp) renderDefaultContent() string {\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\n\tcontent := p.permission.Description\n\n\t// Use the cache for markdown rendering\n\trenderedContent := p.GetOrSetMarkdown(p.permission.ID, func() (string, error) {\n\t\tr := styles.GetMarkdownRenderer(p.width - 10)\n\t\ts, err := r.Render(content)\n\t\treturn styles.ForceReplaceBackgroundWithLipgloss(s, t.Background()), err\n\t})\n\n\tfinalContent := baseStyle.\n\t\tWidth(p.contentViewPort.Width).\n\t\tRender(renderedContent)\n\tp.contentViewPort.SetContent(finalContent)\n\n\tif renderedContent == \"\" {\n\t\treturn \"\"\n\t}\n\n\treturn p.styleViewport()\n}\n\nfunc (p *permissionDialogCmp) styleViewport() string {\n\tt := theme.CurrentTheme()\n\tcontentStyle := lipgloss.NewStyle().\n\t\tBackground(t.Background())\n\n\treturn contentStyle.Render(p.contentViewPort.View())\n}\n\nfunc (p *permissionDialogCmp) render() string {\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\n\ttitle := baseStyle.\n\t\tBold(true).\n\t\tWidth(p.width - 4).\n\t\tForeground(t.Primary()).\n\t\tRender(\"Permission Required\")\n\t// Render header\n\theaderContent := p.renderHeader()\n\t// Render buttons\n\tbuttons := p.renderButtons()\n\n\t// Calculate content height dynamically based on window size\n\tp.contentViewPort.Height = p.height - lipgloss.Height(headerContent) - lipgloss.Height(buttons) - 2 - lipgloss.Height(title)\n\tp.contentViewPort.Width = p.width - 4\n\n\t// Render content based on tool type\n\tvar contentFinal string\n\tswitch p.permission.ToolName {\n\tcase tools.BashToolName:\n\t\tcontentFinal = p.renderBashContent()\n\tcase tools.EditToolName:\n\t\tcontentFinal = p.renderEditContent()\n\tcase tools.PatchToolName:\n\t\tcontentFinal = p.renderPatchContent()\n\tcase tools.WriteToolName:\n\t\tcontentFinal = p.renderWriteContent()\n\tcase tools.FetchToolName:\n\t\tcontentFinal = p.renderFetchContent()\n\tdefault:\n\t\tcontentFinal = p.renderDefaultContent()\n\t}\n\n\tcontent := lipgloss.JoinVertical(\n\t\tlipgloss.Top,\n\t\ttitle,\n\t\tbaseStyle.Render(strings.Repeat(\" \", lipgloss.Width(title))),\n\t\theaderContent,\n\t\tcontentFinal,\n\t\tbuttons,\n\t\tbaseStyle.Render(strings.Repeat(\" \", p.width-4)),\n\t)\n\n\treturn baseStyle.\n\t\tPadding(1, 0, 0, 1).\n\t\tBorder(lipgloss.RoundedBorder()).\n\t\tBorderBackground(t.Background()).\n\t\tBorderForeground(t.TextMuted()).\n\t\tWidth(p.width).\n\t\tHeight(p.height).\n\t\tRender(\n\t\t\tcontent,\n\t\t)\n}\n\nfunc (p *permissionDialogCmp) View() string {\n\treturn p.render()\n}\n\nfunc (p *permissionDialogCmp) BindingKeys() []key.Binding {\n\treturn layout.KeyMapToSlice(permissionsKeys)\n}\n\nfunc (p *permissionDialogCmp) SetSize() tea.Cmd {\n\tif p.permission.ID == \"\" {\n\t\treturn nil\n\t}\n\tswitch p.permission.ToolName {\n\tcase tools.BashToolName:\n\t\tp.width = int(float64(p.windowSize.Width) * 0.4)\n\t\tp.height = int(float64(p.windowSize.Height) * 0.3)\n\tcase tools.EditToolName:\n\t\tp.width = int(float64(p.windowSize.Width) * 0.8)\n\t\tp.height = int(float64(p.windowSize.Height) * 0.8)\n\tcase tools.WriteToolName:\n\t\tp.width = int(float64(p.windowSize.Width) * 0.8)\n\t\tp.height = int(float64(p.windowSize.Height) * 0.8)\n\tcase tools.FetchToolName:\n\t\tp.width = int(float64(p.windowSize.Width) * 0.4)\n\t\tp.height = int(float64(p.windowSize.Height) * 0.3)\n\tdefault:\n\t\tp.width = int(float64(p.windowSize.Width) * 0.7)\n\t\tp.height = int(float64(p.windowSize.Height) * 0.5)\n\t}\n\treturn nil\n}\n\nfunc (p *permissionDialogCmp) SetPermissions(permission permission.PermissionRequest) tea.Cmd {\n\tp.permission = permission\n\treturn p.SetSize()\n}\n\n// Helper to get or set cached diff content\nfunc (c *permissionDialogCmp) GetOrSetDiff(key string, generator func() (string, error)) string {\n\tif cached, ok := c.diffCache[key]; ok {\n\t\treturn cached\n\t}\n\n\tcontent, err := generator()\n\tif err != nil {\n\t\treturn fmt.Sprintf(\"Error formatting diff: %v\", err)\n\t}\n\n\tc.diffCache[key] = content\n\n\treturn content\n}\n\n// Helper to get or set cached markdown content\nfunc (c *permissionDialogCmp) GetOrSetMarkdown(key string, generator func() (string, error)) string {\n\tif cached, ok := c.markdownCache[key]; ok {\n\t\treturn cached\n\t}\n\n\tcontent, err := generator()\n\tif err != nil {\n\t\treturn fmt.Sprintf(\"Error rendering markdown: %v\", err)\n\t}\n\n\tc.markdownCache[key] = content\n\n\treturn content\n}\n\nfunc NewPermissionDialogCmp() PermissionDialogCmp {\n\t// Create viewport for content\n\tcontentViewport := viewport.New(0, 0)\n\n\treturn &permissionDialogCmp{\n\t\tcontentViewPort: contentViewport,\n\t\tselectedOption: 0, // Default to \"Allow\"\n\t\tdiffCache: make(map[string]string),\n\t\tmarkdownCache: make(map[string]string),\n\t}\n}\n"], ["/opencode/internal/diff/diff.go", "package diff\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\"\n\t\"regexp\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"github.com/alecthomas/chroma/v2\"\n\t\"github.com/alecthomas/chroma/v2/formatters\"\n\t\"github.com/alecthomas/chroma/v2/lexers\"\n\t\"github.com/alecthomas/chroma/v2/styles\"\n\t\"github.com/aymanbagabas/go-udiff\"\n\t\"github.com/charmbracelet/lipgloss\"\n\t\"github.com/charmbracelet/x/ansi\"\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n\t\"github.com/sergi/go-diff/diffmatchpatch\"\n)\n\n// -------------------------------------------------------------------------\n// Core Types\n// -------------------------------------------------------------------------\n\n// LineType represents the kind of line in a diff.\ntype LineType int\n\nconst (\n\tLineContext LineType = iota // Line exists in both files\n\tLineAdded // Line added in the new file\n\tLineRemoved // Line removed from the old file\n)\n\n// Segment represents a portion of a line for intra-line highlighting\ntype Segment struct {\n\tStart int\n\tEnd int\n\tType LineType\n\tText string\n}\n\n// DiffLine represents a single line in a diff\ntype DiffLine struct {\n\tOldLineNo int // Line number in old file (0 for added lines)\n\tNewLineNo int // Line number in new file (0 for removed lines)\n\tKind LineType // Type of line (added, removed, context)\n\tContent string // Content of the line\n\tSegments []Segment // Segments for intraline highlighting\n}\n\n// Hunk represents a section of changes in a diff\ntype Hunk struct {\n\tHeader string\n\tLines []DiffLine\n}\n\n// DiffResult contains the parsed result of a diff\ntype DiffResult struct {\n\tOldFile string\n\tNewFile string\n\tHunks []Hunk\n}\n\n// linePair represents a pair of lines for side-by-side display\ntype linePair struct {\n\tleft *DiffLine\n\tright *DiffLine\n}\n\n// -------------------------------------------------------------------------\n// Parse Configuration\n// -------------------------------------------------------------------------\n\n// ParseConfig configures the behavior of diff parsing\ntype ParseConfig struct {\n\tContextSize int // Number of context lines to include\n}\n\n// ParseOption modifies a ParseConfig\ntype ParseOption func(*ParseConfig)\n\n// WithContextSize sets the number of context lines to include\nfunc WithContextSize(size int) ParseOption {\n\treturn func(p *ParseConfig) {\n\t\tif size >= 0 {\n\t\t\tp.ContextSize = size\n\t\t}\n\t}\n}\n\n// -------------------------------------------------------------------------\n// Side-by-Side Configuration\n// -------------------------------------------------------------------------\n\n// SideBySideConfig configures the rendering of side-by-side diffs\ntype SideBySideConfig struct {\n\tTotalWidth int\n}\n\n// SideBySideOption modifies a SideBySideConfig\ntype SideBySideOption func(*SideBySideConfig)\n\n// NewSideBySideConfig creates a SideBySideConfig with default values\nfunc NewSideBySideConfig(opts ...SideBySideOption) SideBySideConfig {\n\tconfig := SideBySideConfig{\n\t\tTotalWidth: 160, // Default width for side-by-side view\n\t}\n\n\tfor _, opt := range opts {\n\t\topt(&config)\n\t}\n\n\treturn config\n}\n\n// WithTotalWidth sets the total width for side-by-side view\nfunc WithTotalWidth(width int) SideBySideOption {\n\treturn func(s *SideBySideConfig) {\n\t\tif width > 0 {\n\t\t\ts.TotalWidth = width\n\t\t}\n\t}\n}\n\n// -------------------------------------------------------------------------\n// Diff Parsing\n// -------------------------------------------------------------------------\n\n// ParseUnifiedDiff parses a unified diff format string into structured data\nfunc ParseUnifiedDiff(diff string) (DiffResult, error) {\n\tvar result DiffResult\n\tvar currentHunk *Hunk\n\n\thunkHeaderRe := regexp.MustCompile(`^@@ -(\\d+),?(\\d*) \\+(\\d+),?(\\d*) @@`)\n\tlines := strings.Split(diff, \"\\n\")\n\n\tvar oldLine, newLine int\n\tinFileHeader := true\n\n\tfor _, line := range lines {\n\t\t// Parse file headers\n\t\tif inFileHeader {\n\t\t\tif strings.HasPrefix(line, \"--- a/\") {\n\t\t\t\tresult.OldFile = strings.TrimPrefix(line, \"--- a/\")\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif strings.HasPrefix(line, \"+++ b/\") {\n\t\t\t\tresult.NewFile = strings.TrimPrefix(line, \"+++ b/\")\n\t\t\t\tinFileHeader = false\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\n\t\t// Parse hunk headers\n\t\tif matches := hunkHeaderRe.FindStringSubmatch(line); matches != nil {\n\t\t\tif currentHunk != nil {\n\t\t\t\tresult.Hunks = append(result.Hunks, *currentHunk)\n\t\t\t}\n\t\t\tcurrentHunk = &Hunk{\n\t\t\t\tHeader: line,\n\t\t\t\tLines: []DiffLine{},\n\t\t\t}\n\n\t\t\toldStart, _ := strconv.Atoi(matches[1])\n\t\t\tnewStart, _ := strconv.Atoi(matches[3])\n\t\t\toldLine = oldStart\n\t\t\tnewLine = newStart\n\t\t\tcontinue\n\t\t}\n\n\t\t// Ignore \"No newline at end of file\" markers\n\t\tif strings.HasPrefix(line, \"\\\\ No newline at end of file\") {\n\t\t\tcontinue\n\t\t}\n\n\t\tif currentHunk == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\t// Process the line based on its prefix\n\t\tif len(line) > 0 {\n\t\t\tswitch line[0] {\n\t\t\tcase '+':\n\t\t\t\tcurrentHunk.Lines = append(currentHunk.Lines, DiffLine{\n\t\t\t\t\tOldLineNo: 0,\n\t\t\t\t\tNewLineNo: newLine,\n\t\t\t\t\tKind: LineAdded,\n\t\t\t\t\tContent: line[1:],\n\t\t\t\t})\n\t\t\t\tnewLine++\n\t\t\tcase '-':\n\t\t\t\tcurrentHunk.Lines = append(currentHunk.Lines, DiffLine{\n\t\t\t\t\tOldLineNo: oldLine,\n\t\t\t\t\tNewLineNo: 0,\n\t\t\t\t\tKind: LineRemoved,\n\t\t\t\t\tContent: line[1:],\n\t\t\t\t})\n\t\t\t\toldLine++\n\t\t\tdefault:\n\t\t\t\tcurrentHunk.Lines = append(currentHunk.Lines, DiffLine{\n\t\t\t\t\tOldLineNo: oldLine,\n\t\t\t\t\tNewLineNo: newLine,\n\t\t\t\t\tKind: LineContext,\n\t\t\t\t\tContent: line,\n\t\t\t\t})\n\t\t\t\toldLine++\n\t\t\t\tnewLine++\n\t\t\t}\n\t\t} else {\n\t\t\t// Handle empty lines\n\t\t\tcurrentHunk.Lines = append(currentHunk.Lines, DiffLine{\n\t\t\t\tOldLineNo: oldLine,\n\t\t\t\tNewLineNo: newLine,\n\t\t\t\tKind: LineContext,\n\t\t\t\tContent: \"\",\n\t\t\t})\n\t\t\toldLine++\n\t\t\tnewLine++\n\t\t}\n\t}\n\n\t// Add the last hunk if there is one\n\tif currentHunk != nil {\n\t\tresult.Hunks = append(result.Hunks, *currentHunk)\n\t}\n\n\treturn result, nil\n}\n\n// HighlightIntralineChanges updates lines in a hunk to show character-level differences\nfunc HighlightIntralineChanges(h *Hunk) {\n\tvar updated []DiffLine\n\tdmp := diffmatchpatch.New()\n\n\tfor i := 0; i < len(h.Lines); i++ {\n\t\t// Look for removed line followed by added line\n\t\tif i+1 < len(h.Lines) &&\n\t\t\th.Lines[i].Kind == LineRemoved &&\n\t\t\th.Lines[i+1].Kind == LineAdded {\n\n\t\t\toldLine := h.Lines[i]\n\t\t\tnewLine := h.Lines[i+1]\n\n\t\t\t// Find character-level differences\n\t\t\tpatches := dmp.DiffMain(oldLine.Content, newLine.Content, false)\n\t\t\tpatches = dmp.DiffCleanupSemantic(patches)\n\t\t\tpatches = dmp.DiffCleanupMerge(patches)\n\t\t\tpatches = dmp.DiffCleanupEfficiency(patches)\n\n\t\t\tsegments := make([]Segment, 0)\n\n\t\t\tremoveStart := 0\n\t\t\taddStart := 0\n\t\t\tfor _, patch := range patches {\n\t\t\t\tswitch patch.Type {\n\t\t\t\tcase diffmatchpatch.DiffDelete:\n\t\t\t\t\tsegments = append(segments, Segment{\n\t\t\t\t\t\tStart: removeStart,\n\t\t\t\t\t\tEnd: removeStart + len(patch.Text),\n\t\t\t\t\t\tType: LineRemoved,\n\t\t\t\t\t\tText: patch.Text,\n\t\t\t\t\t})\n\t\t\t\t\tremoveStart += len(patch.Text)\n\t\t\t\tcase diffmatchpatch.DiffInsert:\n\t\t\t\t\tsegments = append(segments, Segment{\n\t\t\t\t\t\tStart: addStart,\n\t\t\t\t\t\tEnd: addStart + len(patch.Text),\n\t\t\t\t\t\tType: LineAdded,\n\t\t\t\t\t\tText: patch.Text,\n\t\t\t\t\t})\n\t\t\t\t\taddStart += len(patch.Text)\n\t\t\t\tdefault:\n\t\t\t\t\t// Context text, no highlighting needed\n\t\t\t\t\tremoveStart += len(patch.Text)\n\t\t\t\t\taddStart += len(patch.Text)\n\t\t\t\t}\n\t\t\t}\n\t\t\toldLine.Segments = segments\n\t\t\tnewLine.Segments = segments\n\n\t\t\tupdated = append(updated, oldLine, newLine)\n\t\t\ti++ // Skip the next line as we've already processed it\n\t\t} else {\n\t\t\tupdated = append(updated, h.Lines[i])\n\t\t}\n\t}\n\n\th.Lines = updated\n}\n\n// pairLines converts a flat list of diff lines to pairs for side-by-side display\nfunc pairLines(lines []DiffLine) []linePair {\n\tvar pairs []linePair\n\ti := 0\n\n\tfor i < len(lines) {\n\t\tswitch lines[i].Kind {\n\t\tcase LineRemoved:\n\t\t\t// Check if the next line is an addition, if so pair them\n\t\t\tif i+1 < len(lines) && lines[i+1].Kind == LineAdded {\n\t\t\t\tpairs = append(pairs, linePair{left: &lines[i], right: &lines[i+1]})\n\t\t\t\ti += 2\n\t\t\t} else {\n\t\t\t\tpairs = append(pairs, linePair{left: &lines[i], right: nil})\n\t\t\t\ti++\n\t\t\t}\n\t\tcase LineAdded:\n\t\t\tpairs = append(pairs, linePair{left: nil, right: &lines[i]})\n\t\t\ti++\n\t\tcase LineContext:\n\t\t\tpairs = append(pairs, linePair{left: &lines[i], right: &lines[i]})\n\t\t\ti++\n\t\t}\n\t}\n\n\treturn pairs\n}\n\n// -------------------------------------------------------------------------\n// Syntax Highlighting\n// -------------------------------------------------------------------------\n\n// SyntaxHighlight applies syntax highlighting to text based on file extension\nfunc SyntaxHighlight(w io.Writer, source, fileName, formatter string, bg lipgloss.TerminalColor) error {\n\tt := theme.CurrentTheme()\n\n\t// Determine the language lexer to use\n\tl := lexers.Match(fileName)\n\tif l == nil {\n\t\tl = lexers.Analyse(source)\n\t}\n\tif l == nil {\n\t\tl = lexers.Fallback\n\t}\n\tl = chroma.Coalesce(l)\n\n\t// Get the formatter\n\tf := formatters.Get(formatter)\n\tif f == nil {\n\t\tf = formatters.Fallback\n\t}\n\n\t// Dynamic theme based on current theme values\n\tsyntaxThemeXml := fmt.Sprintf(`\n\t\n`,\n\t\tgetColor(t.Background()), // Background\n\t\tgetColor(t.Text()), // Text\n\t\tgetColor(t.Text()), // Other\n\t\tgetColor(t.Error()), // Error\n\n\t\tgetColor(t.SyntaxKeyword()), // Keyword\n\t\tgetColor(t.SyntaxKeyword()), // KeywordConstant\n\t\tgetColor(t.SyntaxKeyword()), // KeywordDeclaration\n\t\tgetColor(t.SyntaxKeyword()), // KeywordNamespace\n\t\tgetColor(t.SyntaxKeyword()), // KeywordPseudo\n\t\tgetColor(t.SyntaxKeyword()), // KeywordReserved\n\t\tgetColor(t.SyntaxType()), // KeywordType\n\n\t\tgetColor(t.Text()), // Name\n\t\tgetColor(t.SyntaxVariable()), // NameAttribute\n\t\tgetColor(t.SyntaxType()), // NameBuiltin\n\t\tgetColor(t.SyntaxVariable()), // NameBuiltinPseudo\n\t\tgetColor(t.SyntaxType()), // NameClass\n\t\tgetColor(t.SyntaxVariable()), // NameConstant\n\t\tgetColor(t.SyntaxFunction()), // NameDecorator\n\t\tgetColor(t.SyntaxVariable()), // NameEntity\n\t\tgetColor(t.SyntaxType()), // NameException\n\t\tgetColor(t.SyntaxFunction()), // NameFunction\n\t\tgetColor(t.Text()), // NameLabel\n\t\tgetColor(t.SyntaxType()), // NameNamespace\n\t\tgetColor(t.SyntaxVariable()), // NameOther\n\t\tgetColor(t.SyntaxKeyword()), // NameTag\n\t\tgetColor(t.SyntaxVariable()), // NameVariable\n\t\tgetColor(t.SyntaxVariable()), // NameVariableClass\n\t\tgetColor(t.SyntaxVariable()), // NameVariableGlobal\n\t\tgetColor(t.SyntaxVariable()), // NameVariableInstance\n\n\t\tgetColor(t.SyntaxString()), // Literal\n\t\tgetColor(t.SyntaxString()), // LiteralDate\n\t\tgetColor(t.SyntaxString()), // LiteralString\n\t\tgetColor(t.SyntaxString()), // LiteralStringBacktick\n\t\tgetColor(t.SyntaxString()), // LiteralStringChar\n\t\tgetColor(t.SyntaxString()), // LiteralStringDoc\n\t\tgetColor(t.SyntaxString()), // LiteralStringDouble\n\t\tgetColor(t.SyntaxString()), // LiteralStringEscape\n\t\tgetColor(t.SyntaxString()), // LiteralStringHeredoc\n\t\tgetColor(t.SyntaxString()), // LiteralStringInterpol\n\t\tgetColor(t.SyntaxString()), // LiteralStringOther\n\t\tgetColor(t.SyntaxString()), // LiteralStringRegex\n\t\tgetColor(t.SyntaxString()), // LiteralStringSingle\n\t\tgetColor(t.SyntaxString()), // LiteralStringSymbol\n\n\t\tgetColor(t.SyntaxNumber()), // LiteralNumber\n\t\tgetColor(t.SyntaxNumber()), // LiteralNumberBin\n\t\tgetColor(t.SyntaxNumber()), // LiteralNumberFloat\n\t\tgetColor(t.SyntaxNumber()), // LiteralNumberHex\n\t\tgetColor(t.SyntaxNumber()), // LiteralNumberInteger\n\t\tgetColor(t.SyntaxNumber()), // LiteralNumberIntegerLong\n\t\tgetColor(t.SyntaxNumber()), // LiteralNumberOct\n\n\t\tgetColor(t.SyntaxOperator()), // Operator\n\t\tgetColor(t.SyntaxKeyword()), // OperatorWord\n\t\tgetColor(t.SyntaxPunctuation()), // Punctuation\n\n\t\tgetColor(t.SyntaxComment()), // Comment\n\t\tgetColor(t.SyntaxComment()), // CommentHashbang\n\t\tgetColor(t.SyntaxComment()), // CommentMultiline\n\t\tgetColor(t.SyntaxComment()), // CommentSingle\n\t\tgetColor(t.SyntaxComment()), // CommentSpecial\n\t\tgetColor(t.SyntaxKeyword()), // CommentPreproc\n\n\t\tgetColor(t.Text()), // Generic\n\t\tgetColor(t.Error()), // GenericDeleted\n\t\tgetColor(t.Text()), // GenericEmph\n\t\tgetColor(t.Error()), // GenericError\n\t\tgetColor(t.Text()), // GenericHeading\n\t\tgetColor(t.Success()), // GenericInserted\n\t\tgetColor(t.TextMuted()), // GenericOutput\n\t\tgetColor(t.Text()), // GenericPrompt\n\t\tgetColor(t.Text()), // GenericStrong\n\t\tgetColor(t.Text()), // GenericSubheading\n\t\tgetColor(t.Error()), // GenericTraceback\n\t\tgetColor(t.Text()), // TextWhitespace\n\t)\n\n\tr := strings.NewReader(syntaxThemeXml)\n\tstyle := chroma.MustNewXMLStyle(r)\n\n\t// Modify the style to use the provided background\n\ts, err := style.Builder().Transform(\n\t\tfunc(t chroma.StyleEntry) chroma.StyleEntry {\n\t\t\tr, g, b, _ := bg.RGBA()\n\t\t\tt.Background = chroma.NewColour(uint8(r>>8), uint8(g>>8), uint8(b>>8))\n\t\t\treturn t\n\t\t},\n\t).Build()\n\tif err != nil {\n\t\ts = styles.Fallback\n\t}\n\n\t// Tokenize and format\n\tit, err := l.Tokenise(nil, source)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn f.Format(w, s, it)\n}\n\n// getColor returns the appropriate hex color string based on terminal background\nfunc getColor(adaptiveColor lipgloss.AdaptiveColor) string {\n\tif lipgloss.HasDarkBackground() {\n\t\treturn adaptiveColor.Dark\n\t}\n\treturn adaptiveColor.Light\n}\n\n// highlightLine applies syntax highlighting to a single line\nfunc highlightLine(fileName string, line string, bg lipgloss.TerminalColor) string {\n\tvar buf bytes.Buffer\n\terr := SyntaxHighlight(&buf, line, fileName, \"terminal16m\", bg)\n\tif err != nil {\n\t\treturn line\n\t}\n\treturn buf.String()\n}\n\n// createStyles generates the lipgloss styles needed for rendering diffs\nfunc createStyles(t theme.Theme) (removedLineStyle, addedLineStyle, contextLineStyle, lineNumberStyle lipgloss.Style) {\n\tremovedLineStyle = lipgloss.NewStyle().Background(t.DiffRemovedBg())\n\taddedLineStyle = lipgloss.NewStyle().Background(t.DiffAddedBg())\n\tcontextLineStyle = lipgloss.NewStyle().Background(t.DiffContextBg())\n\tlineNumberStyle = lipgloss.NewStyle().Foreground(t.DiffLineNumber())\n\n\treturn\n}\n\n// -------------------------------------------------------------------------\n// Rendering Functions\n// -------------------------------------------------------------------------\n\nfunc lipglossToHex(color lipgloss.Color) string {\n\tr, g, b, a := color.RGBA()\n\n\t// Scale uint32 values (0-65535) to uint8 (0-255).\n\tr8 := uint8(r >> 8)\n\tg8 := uint8(g >> 8)\n\tb8 := uint8(b >> 8)\n\ta8 := uint8(a >> 8)\n\n\treturn fmt.Sprintf(\"#%02x%02x%02x%02x\", r8, g8, b8, a8)\n}\n\n// applyHighlighting applies intra-line highlighting to a piece of text\nfunc applyHighlighting(content string, segments []Segment, segmentType LineType, highlightBg lipgloss.AdaptiveColor) string {\n\t// Find all ANSI sequences in the content\n\tansiRegex := regexp.MustCompile(`\\x1b(?:[@-Z\\\\-_]|\\[[0-9?]*(?:;[0-9?]*)*[@-~])`)\n\tansiMatches := ansiRegex.FindAllStringIndex(content, -1)\n\n\t// Build a mapping of visible character positions to their actual indices\n\tvisibleIdx := 0\n\tansiSequences := make(map[int]string)\n\tlastAnsiSeq := \"\\x1b[0m\" // Default reset sequence\n\n\tfor i := 0; i < len(content); {\n\t\tisAnsi := false\n\t\tfor _, match := range ansiMatches {\n\t\t\tif match[0] == i {\n\t\t\t\tansiSequences[visibleIdx] = content[match[0]:match[1]]\n\t\t\t\tlastAnsiSeq = content[match[0]:match[1]]\n\t\t\t\ti = match[1]\n\t\t\t\tisAnsi = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif isAnsi {\n\t\t\tcontinue\n\t\t}\n\n\t\t// For non-ANSI positions, store the last ANSI sequence\n\t\tif _, exists := ansiSequences[visibleIdx]; !exists {\n\t\t\tansiSequences[visibleIdx] = lastAnsiSeq\n\t\t}\n\t\tvisibleIdx++\n\t\ti++\n\t}\n\n\t// Apply highlighting\n\tvar sb strings.Builder\n\tinSelection := false\n\tcurrentPos := 0\n\n\t// Get the appropriate color based on terminal background\n\tbgColor := lipgloss.Color(getColor(highlightBg))\n\tfgColor := lipgloss.Color(getColor(theme.CurrentTheme().Background()))\n\n\tfor i := 0; i < len(content); {\n\t\t// Check if we're at an ANSI sequence\n\t\tisAnsi := false\n\t\tfor _, match := range ansiMatches {\n\t\t\tif match[0] == i {\n\t\t\t\tsb.WriteString(content[match[0]:match[1]]) // Preserve ANSI sequence\n\t\t\t\ti = match[1]\n\t\t\t\tisAnsi = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif isAnsi {\n\t\t\tcontinue\n\t\t}\n\n\t\t// Check for segment boundaries\n\t\tfor _, seg := range segments {\n\t\t\tif seg.Type == segmentType {\n\t\t\t\tif currentPos == seg.Start {\n\t\t\t\t\tinSelection = true\n\t\t\t\t}\n\t\t\t\tif currentPos == seg.End {\n\t\t\t\t\tinSelection = false\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Get current character\n\t\tchar := string(content[i])\n\n\t\tif inSelection {\n\t\t\t// Get the current styling\n\t\t\tcurrentStyle := ansiSequences[currentPos]\n\n\t\t\t// Apply foreground and background highlight\n\t\t\tsb.WriteString(\"\\x1b[38;2;\")\n\t\t\tr, g, b, _ := fgColor.RGBA()\n\t\t\tsb.WriteString(fmt.Sprintf(\"%d;%d;%dm\", r>>8, g>>8, b>>8))\n\t\t\tsb.WriteString(\"\\x1b[48;2;\")\n\t\t\tr, g, b, _ = bgColor.RGBA()\n\t\t\tsb.WriteString(fmt.Sprintf(\"%d;%d;%dm\", r>>8, g>>8, b>>8))\n\t\t\tsb.WriteString(char)\n\t\t\t// Reset foreground and background\n\t\t\tsb.WriteString(\"\\x1b[39m\")\n\n\t\t\t// Reapply the original ANSI sequence\n\t\t\tsb.WriteString(currentStyle)\n\t\t} else {\n\t\t\t// Not in selection, just copy the character\n\t\t\tsb.WriteString(char)\n\t\t}\n\n\t\tcurrentPos++\n\t\ti++\n\t}\n\n\treturn sb.String()\n}\n\n// renderLeftColumn formats the left side of a side-by-side diff\nfunc renderLeftColumn(fileName string, dl *DiffLine, colWidth int) string {\n\tt := theme.CurrentTheme()\n\n\tif dl == nil {\n\t\tcontextLineStyle := lipgloss.NewStyle().Background(t.DiffContextBg())\n\t\treturn contextLineStyle.Width(colWidth).Render(\"\")\n\t}\n\n\tremovedLineStyle, _, contextLineStyle, lineNumberStyle := createStyles(t)\n\n\t// Determine line style based on line type\n\tvar marker string\n\tvar bgStyle lipgloss.Style\n\tswitch dl.Kind {\n\tcase LineRemoved:\n\t\tmarker = removedLineStyle.Foreground(t.DiffRemoved()).Render(\"-\")\n\t\tbgStyle = removedLineStyle\n\t\tlineNumberStyle = lineNumberStyle.Foreground(t.DiffRemoved()).Background(t.DiffRemovedLineNumberBg())\n\tcase LineAdded:\n\t\tmarker = \"?\"\n\t\tbgStyle = contextLineStyle\n\tcase LineContext:\n\t\tmarker = contextLineStyle.Render(\" \")\n\t\tbgStyle = contextLineStyle\n\t}\n\n\t// Format line number\n\tlineNum := \"\"\n\tif dl.OldLineNo > 0 {\n\t\tlineNum = fmt.Sprintf(\"%6d\", dl.OldLineNo)\n\t}\n\n\t// Create the line prefix\n\tprefix := lineNumberStyle.Render(lineNum + \" \" + marker)\n\n\t// Apply syntax highlighting\n\tcontent := highlightLine(fileName, dl.Content, bgStyle.GetBackground())\n\n\t// Apply intra-line highlighting for removed lines\n\tif dl.Kind == LineRemoved && len(dl.Segments) > 0 {\n\t\tcontent = applyHighlighting(content, dl.Segments, LineRemoved, t.DiffHighlightRemoved())\n\t}\n\n\t// Add a padding space for removed lines\n\tif dl.Kind == LineRemoved {\n\t\tcontent = bgStyle.Render(\" \") + content\n\t}\n\n\t// Create the final line and truncate if needed\n\tlineText := prefix + content\n\treturn bgStyle.MaxHeight(1).Width(colWidth).Render(\n\t\tansi.Truncate(\n\t\t\tlineText,\n\t\t\tcolWidth,\n\t\t\tlipgloss.NewStyle().Background(bgStyle.GetBackground()).Foreground(t.TextMuted()).Render(\"...\"),\n\t\t),\n\t)\n}\n\n// renderRightColumn formats the right side of a side-by-side diff\nfunc renderRightColumn(fileName string, dl *DiffLine, colWidth int) string {\n\tt := theme.CurrentTheme()\n\n\tif dl == nil {\n\t\tcontextLineStyle := lipgloss.NewStyle().Background(t.DiffContextBg())\n\t\treturn contextLineStyle.Width(colWidth).Render(\"\")\n\t}\n\n\t_, addedLineStyle, contextLineStyle, lineNumberStyle := createStyles(t)\n\n\t// Determine line style based on line type\n\tvar marker string\n\tvar bgStyle lipgloss.Style\n\tswitch dl.Kind {\n\tcase LineAdded:\n\t\tmarker = addedLineStyle.Foreground(t.DiffAdded()).Render(\"+\")\n\t\tbgStyle = addedLineStyle\n\t\tlineNumberStyle = lineNumberStyle.Foreground(t.DiffAdded()).Background(t.DiffAddedLineNumberBg())\n\tcase LineRemoved:\n\t\tmarker = \"?\"\n\t\tbgStyle = contextLineStyle\n\tcase LineContext:\n\t\tmarker = contextLineStyle.Render(\" \")\n\t\tbgStyle = contextLineStyle\n\t}\n\n\t// Format line number\n\tlineNum := \"\"\n\tif dl.NewLineNo > 0 {\n\t\tlineNum = fmt.Sprintf(\"%6d\", dl.NewLineNo)\n\t}\n\n\t// Create the line prefix\n\tprefix := lineNumberStyle.Render(lineNum + \" \" + marker)\n\n\t// Apply syntax highlighting\n\tcontent := highlightLine(fileName, dl.Content, bgStyle.GetBackground())\n\n\t// Apply intra-line highlighting for added lines\n\tif dl.Kind == LineAdded && len(dl.Segments) > 0 {\n\t\tcontent = applyHighlighting(content, dl.Segments, LineAdded, t.DiffHighlightAdded())\n\t}\n\n\t// Add a padding space for added lines\n\tif dl.Kind == LineAdded {\n\t\tcontent = bgStyle.Render(\" \") + content\n\t}\n\n\t// Create the final line and truncate if needed\n\tlineText := prefix + content\n\treturn bgStyle.MaxHeight(1).Width(colWidth).Render(\n\t\tansi.Truncate(\n\t\t\tlineText,\n\t\t\tcolWidth,\n\t\t\tlipgloss.NewStyle().Background(bgStyle.GetBackground()).Foreground(t.TextMuted()).Render(\"...\"),\n\t\t),\n\t)\n}\n\n// -------------------------------------------------------------------------\n// Public API\n// -------------------------------------------------------------------------\n\n// RenderSideBySideHunk formats a hunk for side-by-side display\nfunc RenderSideBySideHunk(fileName string, h Hunk, opts ...SideBySideOption) string {\n\t// Apply options to create the configuration\n\tconfig := NewSideBySideConfig(opts...)\n\n\t// Make a copy of the hunk so we don't modify the original\n\thunkCopy := Hunk{Lines: make([]DiffLine, len(h.Lines))}\n\tcopy(hunkCopy.Lines, h.Lines)\n\n\t// Highlight changes within lines\n\tHighlightIntralineChanges(&hunkCopy)\n\n\t// Pair lines for side-by-side display\n\tpairs := pairLines(hunkCopy.Lines)\n\n\t// Calculate column width\n\tcolWidth := config.TotalWidth / 2\n\n\tleftWidth := colWidth\n\trightWidth := config.TotalWidth - colWidth\n\tvar sb strings.Builder\n\tfor _, p := range pairs {\n\t\tleftStr := renderLeftColumn(fileName, p.left, leftWidth)\n\t\trightStr := renderRightColumn(fileName, p.right, rightWidth)\n\t\tsb.WriteString(leftStr + rightStr + \"\\n\")\n\t}\n\n\treturn sb.String()\n}\n\n// FormatDiff creates a side-by-side formatted view of a diff\nfunc FormatDiff(diffText string, opts ...SideBySideOption) (string, error) {\n\tdiffResult, err := ParseUnifiedDiff(diffText)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tvar sb strings.Builder\n\tfor _, h := range diffResult.Hunks {\n\t\tsb.WriteString(RenderSideBySideHunk(diffResult.OldFile, h, opts...))\n\t}\n\n\treturn sb.String(), nil\n}\n\n// GenerateDiff creates a unified diff from two file contents\nfunc GenerateDiff(beforeContent, afterContent, fileName string) (string, int, int) {\n\t// remove the cwd prefix and ensure consistent path format\n\t// this prevents issues with absolute paths in different environments\n\tcwd := config.WorkingDirectory()\n\tfileName = strings.TrimPrefix(fileName, cwd)\n\tfileName = strings.TrimPrefix(fileName, \"/\")\n\n\tvar (\n\t\tunified = udiff.Unified(\"a/\"+fileName, \"b/\"+fileName, beforeContent, afterContent)\n\t\tadditions = 0\n\t\tremovals = 0\n\t)\n\n\tlines := strings.SplitSeq(unified, \"\\n\")\n\tfor line := range lines {\n\t\tif strings.HasPrefix(line, \"+\") && !strings.HasPrefix(line, \"+++\") {\n\t\t\tadditions++\n\t\t} else if strings.HasPrefix(line, \"-\") && !strings.HasPrefix(line, \"---\") {\n\t\t\tremovals++\n\t\t}\n\t}\n\n\treturn unified, additions, removals\n}\n"], ["/opencode/internal/tui/components/chat/list.go", "package chat\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"math\"\n\n\t\"github.com/charmbracelet/bubbles/key\"\n\t\"github.com/charmbracelet/bubbles/spinner\"\n\t\"github.com/charmbracelet/bubbles/viewport\"\n\ttea \"github.com/charmbracelet/bubbletea\"\n\t\"github.com/charmbracelet/lipgloss\"\n\t\"github.com/opencode-ai/opencode/internal/app\"\n\t\"github.com/opencode-ai/opencode/internal/message\"\n\t\"github.com/opencode-ai/opencode/internal/pubsub\"\n\t\"github.com/opencode-ai/opencode/internal/session\"\n\t\"github.com/opencode-ai/opencode/internal/tui/components/dialog\"\n\t\"github.com/opencode-ai/opencode/internal/tui/styles\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n\t\"github.com/opencode-ai/opencode/internal/tui/util\"\n)\n\ntype cacheItem struct {\n\twidth int\n\tcontent []uiMessage\n}\ntype messagesCmp struct {\n\tapp *app.App\n\twidth, height int\n\tviewport viewport.Model\n\tsession session.Session\n\tmessages []message.Message\n\tuiMessages []uiMessage\n\tcurrentMsgID string\n\tcachedContent map[string]cacheItem\n\tspinner spinner.Model\n\trendering bool\n\tattachments viewport.Model\n}\ntype renderFinishedMsg struct{}\n\ntype MessageKeys struct {\n\tPageDown key.Binding\n\tPageUp key.Binding\n\tHalfPageUp key.Binding\n\tHalfPageDown key.Binding\n}\n\nvar messageKeys = MessageKeys{\n\tPageDown: key.NewBinding(\n\t\tkey.WithKeys(\"pgdown\"),\n\t\tkey.WithHelp(\"f/pgdn\", \"page down\"),\n\t),\n\tPageUp: key.NewBinding(\n\t\tkey.WithKeys(\"pgup\"),\n\t\tkey.WithHelp(\"b/pgup\", \"page up\"),\n\t),\n\tHalfPageUp: key.NewBinding(\n\t\tkey.WithKeys(\"ctrl+u\"),\n\t\tkey.WithHelp(\"ctrl+u\", \"½ page up\"),\n\t),\n\tHalfPageDown: key.NewBinding(\n\t\tkey.WithKeys(\"ctrl+d\", \"ctrl+d\"),\n\t\tkey.WithHelp(\"ctrl+d\", \"½ page down\"),\n\t),\n}\n\nfunc (m *messagesCmp) Init() tea.Cmd {\n\treturn tea.Batch(m.viewport.Init(), m.spinner.Tick)\n}\n\nfunc (m *messagesCmp) Update(msg tea.Msg) (tea.Model, tea.Cmd) {\n\tvar cmds []tea.Cmd\n\tswitch msg := msg.(type) {\n\tcase dialog.ThemeChangedMsg:\n\t\tm.rerender()\n\t\treturn m, nil\n\tcase SessionSelectedMsg:\n\t\tif msg.ID != m.session.ID {\n\t\t\tcmd := m.SetSession(msg)\n\t\t\treturn m, cmd\n\t\t}\n\t\treturn m, nil\n\tcase SessionClearedMsg:\n\t\tm.session = session.Session{}\n\t\tm.messages = make([]message.Message, 0)\n\t\tm.currentMsgID = \"\"\n\t\tm.rendering = false\n\t\treturn m, nil\n\n\tcase tea.KeyMsg:\n\t\tif key.Matches(msg, messageKeys.PageUp) || key.Matches(msg, messageKeys.PageDown) ||\n\t\t\tkey.Matches(msg, messageKeys.HalfPageUp) || key.Matches(msg, messageKeys.HalfPageDown) {\n\t\t\tu, cmd := m.viewport.Update(msg)\n\t\t\tm.viewport = u\n\t\t\tcmds = append(cmds, cmd)\n\t\t}\n\n\tcase renderFinishedMsg:\n\t\tm.rendering = false\n\t\tm.viewport.GotoBottom()\n\tcase pubsub.Event[session.Session]:\n\t\tif msg.Type == pubsub.UpdatedEvent && msg.Payload.ID == m.session.ID {\n\t\t\tm.session = msg.Payload\n\t\t\tif m.session.SummaryMessageID == m.currentMsgID {\n\t\t\t\tdelete(m.cachedContent, m.currentMsgID)\n\t\t\t\tm.renderView()\n\t\t\t}\n\t\t}\n\tcase pubsub.Event[message.Message]:\n\t\tneedsRerender := false\n\t\tif msg.Type == pubsub.CreatedEvent {\n\t\t\tif msg.Payload.SessionID == m.session.ID {\n\n\t\t\t\tmessageExists := false\n\t\t\t\tfor _, v := range m.messages {\n\t\t\t\t\tif v.ID == msg.Payload.ID {\n\t\t\t\t\t\tmessageExists = true\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif !messageExists {\n\t\t\t\t\tif len(m.messages) > 0 {\n\t\t\t\t\t\tlastMsgID := m.messages[len(m.messages)-1].ID\n\t\t\t\t\t\tdelete(m.cachedContent, lastMsgID)\n\t\t\t\t\t}\n\n\t\t\t\t\tm.messages = append(m.messages, msg.Payload)\n\t\t\t\t\tdelete(m.cachedContent, m.currentMsgID)\n\t\t\t\t\tm.currentMsgID = msg.Payload.ID\n\t\t\t\t\tneedsRerender = true\n\t\t\t\t}\n\t\t\t}\n\t\t\t// There are tool calls from the child task\n\t\t\tfor _, v := range m.messages {\n\t\t\t\tfor _, c := range v.ToolCalls() {\n\t\t\t\t\tif c.ID == msg.Payload.SessionID {\n\t\t\t\t\t\tdelete(m.cachedContent, v.ID)\n\t\t\t\t\t\tneedsRerender = true\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t} else if msg.Type == pubsub.UpdatedEvent && msg.Payload.SessionID == m.session.ID {\n\t\t\tfor i, v := range m.messages {\n\t\t\t\tif v.ID == msg.Payload.ID {\n\t\t\t\t\tm.messages[i] = msg.Payload\n\t\t\t\t\tdelete(m.cachedContent, msg.Payload.ID)\n\t\t\t\t\tneedsRerender = true\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif needsRerender {\n\t\t\tm.renderView()\n\t\t\tif len(m.messages) > 0 {\n\t\t\t\tif (msg.Type == pubsub.CreatedEvent) ||\n\t\t\t\t\t(msg.Type == pubsub.UpdatedEvent && msg.Payload.ID == m.messages[len(m.messages)-1].ID) {\n\t\t\t\t\tm.viewport.GotoBottom()\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tspinner, cmd := m.spinner.Update(msg)\n\tm.spinner = spinner\n\tcmds = append(cmds, cmd)\n\treturn m, tea.Batch(cmds...)\n}\n\nfunc (m *messagesCmp) IsAgentWorking() bool {\n\treturn m.app.CoderAgent.IsSessionBusy(m.session.ID)\n}\n\nfunc formatTimeDifference(unixTime1, unixTime2 int64) string {\n\tdiffSeconds := float64(math.Abs(float64(unixTime2 - unixTime1)))\n\n\tif diffSeconds < 60 {\n\t\treturn fmt.Sprintf(\"%.1fs\", diffSeconds)\n\t}\n\n\tminutes := int(diffSeconds / 60)\n\tseconds := int(diffSeconds) % 60\n\treturn fmt.Sprintf(\"%dm%ds\", minutes, seconds)\n}\n\nfunc (m *messagesCmp) renderView() {\n\tm.uiMessages = make([]uiMessage, 0)\n\tpos := 0\n\tbaseStyle := styles.BaseStyle()\n\n\tif m.width == 0 {\n\t\treturn\n\t}\n\tfor inx, msg := range m.messages {\n\t\tswitch msg.Role {\n\t\tcase message.User:\n\t\t\tif cache, ok := m.cachedContent[msg.ID]; ok && cache.width == m.width {\n\t\t\t\tm.uiMessages = append(m.uiMessages, cache.content...)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tuserMsg := renderUserMessage(\n\t\t\t\tmsg,\n\t\t\t\tmsg.ID == m.currentMsgID,\n\t\t\t\tm.width,\n\t\t\t\tpos,\n\t\t\t)\n\t\t\tm.uiMessages = append(m.uiMessages, userMsg)\n\t\t\tm.cachedContent[msg.ID] = cacheItem{\n\t\t\t\twidth: m.width,\n\t\t\t\tcontent: []uiMessage{userMsg},\n\t\t\t}\n\t\t\tpos += userMsg.height + 1 // + 1 for spacing\n\t\tcase message.Assistant:\n\t\t\tif cache, ok := m.cachedContent[msg.ID]; ok && cache.width == m.width {\n\t\t\t\tm.uiMessages = append(m.uiMessages, cache.content...)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tisSummary := m.session.SummaryMessageID == msg.ID\n\n\t\t\tassistantMessages := renderAssistantMessage(\n\t\t\t\tmsg,\n\t\t\t\tinx,\n\t\t\t\tm.messages,\n\t\t\t\tm.app.Messages,\n\t\t\t\tm.currentMsgID,\n\t\t\t\tisSummary,\n\t\t\t\tm.width,\n\t\t\t\tpos,\n\t\t\t)\n\t\t\tfor _, msg := range assistantMessages {\n\t\t\t\tm.uiMessages = append(m.uiMessages, msg)\n\t\t\t\tpos += msg.height + 1 // + 1 for spacing\n\t\t\t}\n\t\t\tm.cachedContent[msg.ID] = cacheItem{\n\t\t\t\twidth: m.width,\n\t\t\t\tcontent: assistantMessages,\n\t\t\t}\n\t\t}\n\t}\n\n\tmessages := make([]string, 0)\n\tfor _, v := range m.uiMessages {\n\t\tmessages = append(messages, lipgloss.JoinVertical(lipgloss.Left, v.content),\n\t\t\tbaseStyle.\n\t\t\t\tWidth(m.width).\n\t\t\t\tRender(\n\t\t\t\t\t\"\",\n\t\t\t\t),\n\t\t)\n\t}\n\n\tm.viewport.SetContent(\n\t\tbaseStyle.\n\t\t\tWidth(m.width).\n\t\t\tRender(\n\t\t\t\tlipgloss.JoinVertical(\n\t\t\t\t\tlipgloss.Top,\n\t\t\t\t\tmessages...,\n\t\t\t\t),\n\t\t\t),\n\t)\n}\n\nfunc (m *messagesCmp) View() string {\n\tbaseStyle := styles.BaseStyle()\n\n\tif m.rendering {\n\t\treturn baseStyle.\n\t\t\tWidth(m.width).\n\t\t\tRender(\n\t\t\t\tlipgloss.JoinVertical(\n\t\t\t\t\tlipgloss.Top,\n\t\t\t\t\t\"Loading...\",\n\t\t\t\t\tm.working(),\n\t\t\t\t\tm.help(),\n\t\t\t\t),\n\t\t\t)\n\t}\n\tif len(m.messages) == 0 {\n\t\tcontent := baseStyle.\n\t\t\tWidth(m.width).\n\t\t\tHeight(m.height - 1).\n\t\t\tRender(\n\t\t\t\tm.initialScreen(),\n\t\t\t)\n\n\t\treturn baseStyle.\n\t\t\tWidth(m.width).\n\t\t\tRender(\n\t\t\t\tlipgloss.JoinVertical(\n\t\t\t\t\tlipgloss.Top,\n\t\t\t\t\tcontent,\n\t\t\t\t\t\"\",\n\t\t\t\t\tm.help(),\n\t\t\t\t),\n\t\t\t)\n\t}\n\n\treturn baseStyle.\n\t\tWidth(m.width).\n\t\tRender(\n\t\t\tlipgloss.JoinVertical(\n\t\t\t\tlipgloss.Top,\n\t\t\t\tm.viewport.View(),\n\t\t\t\tm.working(),\n\t\t\t\tm.help(),\n\t\t\t),\n\t\t)\n}\n\nfunc hasToolsWithoutResponse(messages []message.Message) bool {\n\ttoolCalls := make([]message.ToolCall, 0)\n\ttoolResults := make([]message.ToolResult, 0)\n\tfor _, m := range messages {\n\t\ttoolCalls = append(toolCalls, m.ToolCalls()...)\n\t\ttoolResults = append(toolResults, m.ToolResults()...)\n\t}\n\n\tfor _, v := range toolCalls {\n\t\tfound := false\n\t\tfor _, r := range toolResults {\n\t\t\tif v.ID == r.ToolCallID {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif !found && v.Finished {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc hasUnfinishedToolCalls(messages []message.Message) bool {\n\ttoolCalls := make([]message.ToolCall, 0)\n\tfor _, m := range messages {\n\t\ttoolCalls = append(toolCalls, m.ToolCalls()...)\n\t}\n\tfor _, v := range toolCalls {\n\t\tif !v.Finished {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc (m *messagesCmp) working() string {\n\ttext := \"\"\n\tif m.IsAgentWorking() && len(m.messages) > 0 {\n\t\tt := theme.CurrentTheme()\n\t\tbaseStyle := styles.BaseStyle()\n\n\t\ttask := \"Thinking...\"\n\t\tlastMessage := m.messages[len(m.messages)-1]\n\t\tif hasToolsWithoutResponse(m.messages) {\n\t\t\ttask = \"Waiting for tool response...\"\n\t\t} else if hasUnfinishedToolCalls(m.messages) {\n\t\t\ttask = \"Building tool call...\"\n\t\t} else if !lastMessage.IsFinished() {\n\t\t\ttask = \"Generating...\"\n\t\t}\n\t\tif task != \"\" {\n\t\t\ttext += baseStyle.\n\t\t\t\tWidth(m.width).\n\t\t\t\tForeground(t.Primary()).\n\t\t\t\tBold(true).\n\t\t\t\tRender(fmt.Sprintf(\"%s %s \", m.spinner.View(), task))\n\t\t}\n\t}\n\treturn text\n}\n\nfunc (m *messagesCmp) help() string {\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\n\ttext := \"\"\n\n\tif m.app.CoderAgent.IsBusy() {\n\t\ttext += lipgloss.JoinHorizontal(\n\t\t\tlipgloss.Left,\n\t\t\tbaseStyle.Foreground(t.TextMuted()).Bold(true).Render(\"press \"),\n\t\t\tbaseStyle.Foreground(t.Text()).Bold(true).Render(\"esc\"),\n\t\t\tbaseStyle.Foreground(t.TextMuted()).Bold(true).Render(\" to exit cancel\"),\n\t\t)\n\t} else {\n\t\ttext += lipgloss.JoinHorizontal(\n\t\t\tlipgloss.Left,\n\t\t\tbaseStyle.Foreground(t.TextMuted()).Bold(true).Render(\"press \"),\n\t\t\tbaseStyle.Foreground(t.Text()).Bold(true).Render(\"enter\"),\n\t\t\tbaseStyle.Foreground(t.TextMuted()).Bold(true).Render(\" to send the message,\"),\n\t\t\tbaseStyle.Foreground(t.TextMuted()).Bold(true).Render(\" write\"),\n\t\t\tbaseStyle.Foreground(t.Text()).Bold(true).Render(\" \\\\\"),\n\t\t\tbaseStyle.Foreground(t.TextMuted()).Bold(true).Render(\" and enter to add a new line\"),\n\t\t)\n\t}\n\treturn baseStyle.\n\t\tWidth(m.width).\n\t\tRender(text)\n}\n\nfunc (m *messagesCmp) initialScreen() string {\n\tbaseStyle := styles.BaseStyle()\n\n\treturn baseStyle.Width(m.width).Render(\n\t\tlipgloss.JoinVertical(\n\t\t\tlipgloss.Top,\n\t\t\theader(m.width),\n\t\t\t\"\",\n\t\t\tlspsConfigured(m.width),\n\t\t),\n\t)\n}\n\nfunc (m *messagesCmp) rerender() {\n\tfor _, msg := range m.messages {\n\t\tdelete(m.cachedContent, msg.ID)\n\t}\n\tm.renderView()\n}\n\nfunc (m *messagesCmp) SetSize(width, height int) tea.Cmd {\n\tif m.width == width && m.height == height {\n\t\treturn nil\n\t}\n\tm.width = width\n\tm.height = height\n\tm.viewport.Width = width\n\tm.viewport.Height = height - 2\n\tm.attachments.Width = width + 40\n\tm.attachments.Height = 3\n\tm.rerender()\n\treturn nil\n}\n\nfunc (m *messagesCmp) GetSize() (int, int) {\n\treturn m.width, m.height\n}\n\nfunc (m *messagesCmp) SetSession(session session.Session) tea.Cmd {\n\tif m.session.ID == session.ID {\n\t\treturn nil\n\t}\n\tm.session = session\n\tmessages, err := m.app.Messages.List(context.Background(), session.ID)\n\tif err != nil {\n\t\treturn util.ReportError(err)\n\t}\n\tm.messages = messages\n\tif len(m.messages) > 0 {\n\t\tm.currentMsgID = m.messages[len(m.messages)-1].ID\n\t}\n\tdelete(m.cachedContent, m.currentMsgID)\n\tm.rendering = true\n\treturn func() tea.Msg {\n\t\tm.renderView()\n\t\treturn renderFinishedMsg{}\n\t}\n}\n\nfunc (m *messagesCmp) BindingKeys() []key.Binding {\n\treturn []key.Binding{\n\t\tm.viewport.KeyMap.PageDown,\n\t\tm.viewport.KeyMap.PageUp,\n\t\tm.viewport.KeyMap.HalfPageUp,\n\t\tm.viewport.KeyMap.HalfPageDown,\n\t}\n}\n\nfunc NewMessagesCmp(app *app.App) tea.Model {\n\ts := spinner.New()\n\ts.Spinner = spinner.Pulse\n\tvp := viewport.New(0, 0)\n\tattachmets := viewport.New(0, 0)\n\tvp.KeyMap.PageUp = messageKeys.PageUp\n\tvp.KeyMap.PageDown = messageKeys.PageDown\n\tvp.KeyMap.HalfPageUp = messageKeys.HalfPageUp\n\tvp.KeyMap.HalfPageDown = messageKeys.HalfPageDown\n\treturn &messagesCmp{\n\t\tapp: app,\n\t\tcachedContent: make(map[string]cacheItem),\n\t\tviewport: vp,\n\t\tspinner: s,\n\t\tattachments: attachmets,\n\t}\n}\n"], ["/opencode/internal/tui/styles/markdown.go", "package styles\n\nimport (\n\t\"github.com/charmbracelet/glamour\"\n\t\"github.com/charmbracelet/glamour/ansi\"\n\t\"github.com/charmbracelet/lipgloss\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n)\n\nconst defaultMargin = 1\n\n// Helper functions for style pointers\nfunc boolPtr(b bool) *bool { return &b }\nfunc stringPtr(s string) *string { return &s }\nfunc uintPtr(u uint) *uint { return &u }\n\n// returns a glamour TermRenderer configured with the current theme\nfunc GetMarkdownRenderer(width int) *glamour.TermRenderer {\n\tr, _ := glamour.NewTermRenderer(\n\t\tglamour.WithStyles(generateMarkdownStyleConfig()),\n\t\tglamour.WithWordWrap(width),\n\t)\n\treturn r\n}\n\n// creates an ansi.StyleConfig for markdown rendering\n// using adaptive colors from the provided theme.\nfunc generateMarkdownStyleConfig() ansi.StyleConfig {\n\tt := theme.CurrentTheme()\n\n\treturn ansi.StyleConfig{\n\t\tDocument: ansi.StyleBlock{\n\t\t\tStylePrimitive: ansi.StylePrimitive{\n\t\t\t\tBlockPrefix: \"\",\n\t\t\t\tBlockSuffix: \"\",\n\t\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownText())),\n\t\t\t},\n\t\t\tMargin: uintPtr(defaultMargin),\n\t\t},\n\t\tBlockQuote: ansi.StyleBlock{\n\t\t\tStylePrimitive: ansi.StylePrimitive{\n\t\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownBlockQuote())),\n\t\t\t\tItalic: boolPtr(true),\n\t\t\t\tPrefix: \"┃ \",\n\t\t\t},\n\t\t\tIndent: uintPtr(1),\n\t\t\tIndentToken: stringPtr(BaseStyle().Render(\" \")),\n\t\t},\n\t\tList: ansi.StyleList{\n\t\t\tLevelIndent: defaultMargin,\n\t\t\tStyleBlock: ansi.StyleBlock{\n\t\t\t\tIndentToken: stringPtr(BaseStyle().Render(\" \")),\n\t\t\t\tStylePrimitive: ansi.StylePrimitive{\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownText())),\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\tHeading: ansi.StyleBlock{\n\t\t\tStylePrimitive: ansi.StylePrimitive{\n\t\t\t\tBlockSuffix: \"\\n\",\n\t\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownHeading())),\n\t\t\t\tBold: boolPtr(true),\n\t\t\t},\n\t\t},\n\t\tH1: ansi.StyleBlock{\n\t\t\tStylePrimitive: ansi.StylePrimitive{\n\t\t\t\tPrefix: \"# \",\n\t\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownHeading())),\n\t\t\t\tBold: boolPtr(true),\n\t\t\t},\n\t\t},\n\t\tH2: ansi.StyleBlock{\n\t\t\tStylePrimitive: ansi.StylePrimitive{\n\t\t\t\tPrefix: \"## \",\n\t\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownHeading())),\n\t\t\t\tBold: boolPtr(true),\n\t\t\t},\n\t\t},\n\t\tH3: ansi.StyleBlock{\n\t\t\tStylePrimitive: ansi.StylePrimitive{\n\t\t\t\tPrefix: \"### \",\n\t\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownHeading())),\n\t\t\t\tBold: boolPtr(true),\n\t\t\t},\n\t\t},\n\t\tH4: ansi.StyleBlock{\n\t\t\tStylePrimitive: ansi.StylePrimitive{\n\t\t\t\tPrefix: \"#### \",\n\t\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownHeading())),\n\t\t\t\tBold: boolPtr(true),\n\t\t\t},\n\t\t},\n\t\tH5: ansi.StyleBlock{\n\t\t\tStylePrimitive: ansi.StylePrimitive{\n\t\t\t\tPrefix: \"##### \",\n\t\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownHeading())),\n\t\t\t\tBold: boolPtr(true),\n\t\t\t},\n\t\t},\n\t\tH6: ansi.StyleBlock{\n\t\t\tStylePrimitive: ansi.StylePrimitive{\n\t\t\t\tPrefix: \"###### \",\n\t\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownHeading())),\n\t\t\t\tBold: boolPtr(true),\n\t\t\t},\n\t\t},\n\t\tStrikethrough: ansi.StylePrimitive{\n\t\t\tCrossedOut: boolPtr(true),\n\t\t\tColor: stringPtr(adaptiveColorToString(t.TextMuted())),\n\t\t},\n\t\tEmph: ansi.StylePrimitive{\n\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownEmph())),\n\t\t\tItalic: boolPtr(true),\n\t\t},\n\t\tStrong: ansi.StylePrimitive{\n\t\t\tBold: boolPtr(true),\n\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownStrong())),\n\t\t},\n\t\tHorizontalRule: ansi.StylePrimitive{\n\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownHorizontalRule())),\n\t\t\tFormat: \"\\n─────────────────────────────────────────\\n\",\n\t\t},\n\t\tItem: ansi.StylePrimitive{\n\t\t\tBlockPrefix: \"• \",\n\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownListItem())),\n\t\t},\n\t\tEnumeration: ansi.StylePrimitive{\n\t\t\tBlockPrefix: \". \",\n\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownListEnumeration())),\n\t\t},\n\t\tTask: ansi.StyleTask{\n\t\t\tStylePrimitive: ansi.StylePrimitive{},\n\t\t\tTicked: \"[✓] \",\n\t\t\tUnticked: \"[ ] \",\n\t\t},\n\t\tLink: ansi.StylePrimitive{\n\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownLink())),\n\t\t\tUnderline: boolPtr(true),\n\t\t},\n\t\tLinkText: ansi.StylePrimitive{\n\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownLinkText())),\n\t\t\tBold: boolPtr(true),\n\t\t},\n\t\tImage: ansi.StylePrimitive{\n\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownImage())),\n\t\t\tUnderline: boolPtr(true),\n\t\t\tFormat: \"🖼 {{.text}}\",\n\t\t},\n\t\tImageText: ansi.StylePrimitive{\n\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownImageText())),\n\t\t\tFormat: \"{{.text}}\",\n\t\t},\n\t\tCode: ansi.StyleBlock{\n\t\t\tStylePrimitive: ansi.StylePrimitive{\n\t\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownCode())),\n\t\t\t\tPrefix: \"\",\n\t\t\t\tSuffix: \"\",\n\t\t\t},\n\t\t},\n\t\tCodeBlock: ansi.StyleCodeBlock{\n\t\t\tStyleBlock: ansi.StyleBlock{\n\t\t\t\tStylePrimitive: ansi.StylePrimitive{\n\t\t\t\t\tPrefix: \" \",\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownCodeBlock())),\n\t\t\t\t},\n\t\t\t\tMargin: uintPtr(defaultMargin),\n\t\t\t},\n\t\t\tChroma: &ansi.Chroma{\n\t\t\t\tText: ansi.StylePrimitive{\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownText())),\n\t\t\t\t},\n\t\t\t\tError: ansi.StylePrimitive{\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.Error())),\n\t\t\t\t},\n\t\t\t\tComment: ansi.StylePrimitive{\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.SyntaxComment())),\n\t\t\t\t},\n\t\t\t\tCommentPreproc: ansi.StylePrimitive{\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.SyntaxKeyword())),\n\t\t\t\t},\n\t\t\t\tKeyword: ansi.StylePrimitive{\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.SyntaxKeyword())),\n\t\t\t\t},\n\t\t\t\tKeywordReserved: ansi.StylePrimitive{\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.SyntaxKeyword())),\n\t\t\t\t},\n\t\t\t\tKeywordNamespace: ansi.StylePrimitive{\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.SyntaxKeyword())),\n\t\t\t\t},\n\t\t\t\tKeywordType: ansi.StylePrimitive{\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.SyntaxType())),\n\t\t\t\t},\n\t\t\t\tOperator: ansi.StylePrimitive{\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.SyntaxOperator())),\n\t\t\t\t},\n\t\t\t\tPunctuation: ansi.StylePrimitive{\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.SyntaxPunctuation())),\n\t\t\t\t},\n\t\t\t\tName: ansi.StylePrimitive{\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.SyntaxVariable())),\n\t\t\t\t},\n\t\t\t\tNameBuiltin: ansi.StylePrimitive{\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.SyntaxVariable())),\n\t\t\t\t},\n\t\t\t\tNameTag: ansi.StylePrimitive{\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.SyntaxKeyword())),\n\t\t\t\t},\n\t\t\t\tNameAttribute: ansi.StylePrimitive{\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.SyntaxFunction())),\n\t\t\t\t},\n\t\t\t\tNameClass: ansi.StylePrimitive{\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.SyntaxType())),\n\t\t\t\t},\n\t\t\t\tNameConstant: ansi.StylePrimitive{\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.SyntaxVariable())),\n\t\t\t\t},\n\t\t\t\tNameDecorator: ansi.StylePrimitive{\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.SyntaxFunction())),\n\t\t\t\t},\n\t\t\t\tNameFunction: ansi.StylePrimitive{\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.SyntaxFunction())),\n\t\t\t\t},\n\t\t\t\tLiteralNumber: ansi.StylePrimitive{\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.SyntaxNumber())),\n\t\t\t\t},\n\t\t\t\tLiteralString: ansi.StylePrimitive{\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.SyntaxString())),\n\t\t\t\t},\n\t\t\t\tLiteralStringEscape: ansi.StylePrimitive{\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.SyntaxKeyword())),\n\t\t\t\t},\n\t\t\t\tGenericDeleted: ansi.StylePrimitive{\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.DiffRemoved())),\n\t\t\t\t},\n\t\t\t\tGenericEmph: ansi.StylePrimitive{\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownEmph())),\n\t\t\t\t\tItalic: boolPtr(true),\n\t\t\t\t},\n\t\t\t\tGenericInserted: ansi.StylePrimitive{\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.DiffAdded())),\n\t\t\t\t},\n\t\t\t\tGenericStrong: ansi.StylePrimitive{\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownStrong())),\n\t\t\t\t\tBold: boolPtr(true),\n\t\t\t\t},\n\t\t\t\tGenericSubheading: ansi.StylePrimitive{\n\t\t\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownHeading())),\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\tTable: ansi.StyleTable{\n\t\t\tStyleBlock: ansi.StyleBlock{\n\t\t\t\tStylePrimitive: ansi.StylePrimitive{\n\t\t\t\t\tBlockPrefix: \"\\n\",\n\t\t\t\t\tBlockSuffix: \"\\n\",\n\t\t\t\t},\n\t\t\t},\n\t\t\tCenterSeparator: stringPtr(\"┼\"),\n\t\t\tColumnSeparator: stringPtr(\"│\"),\n\t\t\tRowSeparator: stringPtr(\"─\"),\n\t\t},\n\t\tDefinitionDescription: ansi.StylePrimitive{\n\t\t\tBlockPrefix: \"\\n ❯ \",\n\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownLinkText())),\n\t\t},\n\t\tText: ansi.StylePrimitive{\n\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownText())),\n\t\t},\n\t\tParagraph: ansi.StyleBlock{\n\t\t\tStylePrimitive: ansi.StylePrimitive{\n\t\t\t\tColor: stringPtr(adaptiveColorToString(t.MarkdownText())),\n\t\t\t},\n\t\t},\n\t}\n}\n\n// adaptiveColorToString converts a lipgloss.AdaptiveColor to the appropriate\n// hex color string based on the current terminal background\nfunc adaptiveColorToString(color lipgloss.AdaptiveColor) string {\n\tif lipgloss.HasDarkBackground() {\n\t\treturn color.Dark\n\t}\n\treturn color.Light\n}\n"], ["/opencode/cmd/root.go", "package cmd\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"os\"\n\t\"sync\"\n\t\"time\"\n\n\ttea \"github.com/charmbracelet/bubbletea\"\n\tzone \"github.com/lrstanley/bubblezone\"\n\t\"github.com/opencode-ai/opencode/internal/app\"\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/db\"\n\t\"github.com/opencode-ai/opencode/internal/format\"\n\t\"github.com/opencode-ai/opencode/internal/llm/agent\"\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n\t\"github.com/opencode-ai/opencode/internal/pubsub\"\n\t\"github.com/opencode-ai/opencode/internal/tui\"\n\t\"github.com/opencode-ai/opencode/internal/version\"\n\t\"github.com/spf13/cobra\"\n)\n\nvar rootCmd = &cobra.Command{\n\tUse: \"opencode\",\n\tShort: \"Terminal-based AI assistant for software development\",\n\tLong: `OpenCode is a powerful terminal-based AI assistant that helps with software development tasks.\nIt provides an interactive chat interface with AI capabilities, code analysis, and LSP integration\nto assist developers in writing, debugging, and understanding code directly from the terminal.`,\n\tExample: `\n # Run in interactive mode\n opencode\n\n # Run with debug logging\n opencode -d\n\n # Run with debug logging in a specific directory\n opencode -d -c /path/to/project\n\n # Print version\n opencode -v\n\n # Run a single non-interactive prompt\n opencode -p \"Explain the use of context in Go\"\n\n # Run a single non-interactive prompt with JSON output format\n opencode -p \"Explain the use of context in Go\" -f json\n `,\n\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t// If the help flag is set, show the help message\n\t\tif cmd.Flag(\"help\").Changed {\n\t\t\tcmd.Help()\n\t\t\treturn nil\n\t\t}\n\t\tif cmd.Flag(\"version\").Changed {\n\t\t\tfmt.Println(version.Version)\n\t\t\treturn nil\n\t\t}\n\n\t\t// Load the config\n\t\tdebug, _ := cmd.Flags().GetBool(\"debug\")\n\t\tcwd, _ := cmd.Flags().GetString(\"cwd\")\n\t\tprompt, _ := cmd.Flags().GetString(\"prompt\")\n\t\toutputFormat, _ := cmd.Flags().GetString(\"output-format\")\n\t\tquiet, _ := cmd.Flags().GetBool(\"quiet\")\n\n\t\t// Validate format option\n\t\tif !format.IsValid(outputFormat) {\n\t\t\treturn fmt.Errorf(\"invalid format option: %s\\n%s\", outputFormat, format.GetHelpText())\n\t\t}\n\n\t\tif cwd != \"\" {\n\t\t\terr := os.Chdir(cwd)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"failed to change directory: %v\", err)\n\t\t\t}\n\t\t}\n\t\tif cwd == \"\" {\n\t\t\tc, err := os.Getwd()\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"failed to get current working directory: %v\", err)\n\t\t\t}\n\t\t\tcwd = c\n\t\t}\n\t\t_, err := config.Load(cwd, debug)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Connect DB, this will also run migrations\n\t\tconn, err := db.Connect()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Create main context for the application\n\t\tctx, cancel := context.WithCancel(context.Background())\n\t\tdefer cancel()\n\n\t\tapp, err := app.New(ctx, conn)\n\t\tif err != nil {\n\t\t\tlogging.Error(\"Failed to create app: %v\", err)\n\t\t\treturn err\n\t\t}\n\t\t// Defer shutdown here so it runs for both interactive and non-interactive modes\n\t\tdefer app.Shutdown()\n\n\t\t// Initialize MCP tools early for both modes\n\t\tinitMCPTools(ctx, app)\n\n\t\t// Non-interactive mode\n\t\tif prompt != \"\" {\n\t\t\t// Run non-interactive flow using the App method\n\t\t\treturn app.RunNonInteractive(ctx, prompt, outputFormat, quiet)\n\t\t}\n\n\t\t// Interactive mode\n\t\t// Set up the TUI\n\t\tzone.NewGlobal()\n\t\tprogram := tea.NewProgram(\n\t\t\ttui.New(app),\n\t\t\ttea.WithAltScreen(),\n\t\t)\n\n\t\t// Setup the subscriptions, this will send services events to the TUI\n\t\tch, cancelSubs := setupSubscriptions(app, ctx)\n\n\t\t// Create a context for the TUI message handler\n\t\ttuiCtx, tuiCancel := context.WithCancel(ctx)\n\t\tvar tuiWg sync.WaitGroup\n\t\ttuiWg.Add(1)\n\n\t\t// Set up message handling for the TUI\n\t\tgo func() {\n\t\t\tdefer tuiWg.Done()\n\t\t\tdefer logging.RecoverPanic(\"TUI-message-handler\", func() {\n\t\t\t\tattemptTUIRecovery(program)\n\t\t\t})\n\n\t\t\tfor {\n\t\t\t\tselect {\n\t\t\t\tcase <-tuiCtx.Done():\n\t\t\t\t\tlogging.Info(\"TUI message handler shutting down\")\n\t\t\t\t\treturn\n\t\t\t\tcase msg, ok := <-ch:\n\t\t\t\t\tif !ok {\n\t\t\t\t\t\tlogging.Info(\"TUI message channel closed\")\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\tprogram.Send(msg)\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\n\t\t// Cleanup function for when the program exits\n\t\tcleanup := func() {\n\t\t\t// Shutdown the app\n\t\t\tapp.Shutdown()\n\n\t\t\t// Cancel subscriptions first\n\t\t\tcancelSubs()\n\n\t\t\t// Then cancel TUI message handler\n\t\t\ttuiCancel()\n\n\t\t\t// Wait for TUI message handler to finish\n\t\t\ttuiWg.Wait()\n\n\t\t\tlogging.Info(\"All goroutines cleaned up\")\n\t\t}\n\n\t\t// Run the TUI\n\t\tresult, err := program.Run()\n\t\tcleanup()\n\n\t\tif err != nil {\n\t\t\tlogging.Error(\"TUI error: %v\", err)\n\t\t\treturn fmt.Errorf(\"TUI error: %v\", err)\n\t\t}\n\n\t\tlogging.Info(\"TUI exited with result: %v\", result)\n\t\treturn nil\n\t},\n}\n\n// attemptTUIRecovery tries to recover the TUI after a panic\nfunc attemptTUIRecovery(program *tea.Program) {\n\tlogging.Info(\"Attempting to recover TUI after panic\")\n\n\t// We could try to restart the TUI or gracefully exit\n\t// For now, we'll just quit the program to avoid further issues\n\tprogram.Quit()\n}\n\nfunc initMCPTools(ctx context.Context, app *app.App) {\n\tgo func() {\n\t\tdefer logging.RecoverPanic(\"MCP-goroutine\", nil)\n\n\t\t// Create a context with timeout for the initial MCP tools fetch\n\t\tctxWithTimeout, cancel := context.WithTimeout(ctx, 30*time.Second)\n\t\tdefer cancel()\n\n\t\t// Set this up once with proper error handling\n\t\tagent.GetMcpTools(ctxWithTimeout, app.Permissions)\n\t\tlogging.Info(\"MCP message handling goroutine exiting\")\n\t}()\n}\n\nfunc setupSubscriber[T any](\n\tctx context.Context,\n\twg *sync.WaitGroup,\n\tname string,\n\tsubscriber func(context.Context) <-chan pubsub.Event[T],\n\toutputCh chan<- tea.Msg,\n) {\n\twg.Add(1)\n\tgo func() {\n\t\tdefer wg.Done()\n\t\tdefer logging.RecoverPanic(fmt.Sprintf(\"subscription-%s\", name), nil)\n\n\t\tsubCh := subscriber(ctx)\n\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase event, ok := <-subCh:\n\t\t\t\tif !ok {\n\t\t\t\t\tlogging.Info(\"subscription channel closed\", \"name\", name)\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tvar msg tea.Msg = event\n\n\t\t\t\tselect {\n\t\t\t\tcase outputCh <- msg:\n\t\t\t\tcase <-time.After(2 * time.Second):\n\t\t\t\t\tlogging.Warn(\"message dropped due to slow consumer\", \"name\", name)\n\t\t\t\tcase <-ctx.Done():\n\t\t\t\t\tlogging.Info(\"subscription cancelled\", \"name\", name)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\tcase <-ctx.Done():\n\t\t\t\tlogging.Info(\"subscription cancelled\", \"name\", name)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}()\n}\n\nfunc setupSubscriptions(app *app.App, parentCtx context.Context) (chan tea.Msg, func()) {\n\tch := make(chan tea.Msg, 100)\n\n\twg := sync.WaitGroup{}\n\tctx, cancel := context.WithCancel(parentCtx) // Inherit from parent context\n\n\tsetupSubscriber(ctx, &wg, \"logging\", logging.Subscribe, ch)\n\tsetupSubscriber(ctx, &wg, \"sessions\", app.Sessions.Subscribe, ch)\n\tsetupSubscriber(ctx, &wg, \"messages\", app.Messages.Subscribe, ch)\n\tsetupSubscriber(ctx, &wg, \"permissions\", app.Permissions.Subscribe, ch)\n\tsetupSubscriber(ctx, &wg, \"coderAgent\", app.CoderAgent.Subscribe, ch)\n\n\tcleanupFunc := func() {\n\t\tlogging.Info(\"Cancelling all subscriptions\")\n\t\tcancel() // Signal all goroutines to stop\n\n\t\twaitCh := make(chan struct{})\n\t\tgo func() {\n\t\t\tdefer logging.RecoverPanic(\"subscription-cleanup\", nil)\n\t\t\twg.Wait()\n\t\t\tclose(waitCh)\n\t\t}()\n\n\t\tselect {\n\t\tcase <-waitCh:\n\t\t\tlogging.Info(\"All subscription goroutines completed successfully\")\n\t\t\tclose(ch) // Only close after all writers are confirmed done\n\t\tcase <-time.After(5 * time.Second):\n\t\t\tlogging.Warn(\"Timed out waiting for some subscription goroutines to complete\")\n\t\t\tclose(ch)\n\t\t}\n\t}\n\treturn ch, cleanupFunc\n}\n\nfunc Execute() {\n\terr := rootCmd.Execute()\n\tif err != nil {\n\t\tos.Exit(1)\n\t}\n}\n\nfunc init() {\n\trootCmd.Flags().BoolP(\"help\", \"h\", false, \"Help\")\n\trootCmd.Flags().BoolP(\"version\", \"v\", false, \"Version\")\n\trootCmd.Flags().BoolP(\"debug\", \"d\", false, \"Debug\")\n\trootCmd.Flags().StringP(\"cwd\", \"c\", \"\", \"Current working directory\")\n\trootCmd.Flags().StringP(\"prompt\", \"p\", \"\", \"Prompt to run in non-interactive mode\")\n\n\t// Add format flag with validation logic\n\trootCmd.Flags().StringP(\"output-format\", \"f\", format.Text.String(),\n\t\t\"Output format for non-interactive mode (text, json)\")\n\n\t// Add quiet flag to hide spinner in non-interactive mode\n\trootCmd.Flags().BoolP(\"quiet\", \"q\", false, \"Hide spinner in non-interactive mode\")\n\n\t// Register custom validation for the format flag\n\trootCmd.RegisterFlagCompletionFunc(\"output-format\", func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {\n\t\treturn format.SupportedFormats, cobra.ShellCompDirectiveNoFileComp\n\t})\n}\n"], ["/opencode/internal/lsp/protocol/tsprotocol.go", "// Copyright 2023 The Go Authors. All rights reserved.\n// Use of this source code is governed by a BSD-style\n// license that can be found in the LICENSE file.\n\n// Code generated for LSP. DO NOT EDIT.\n\npackage protocol\n\n// Code generated from protocol/metaModel.json at ref release/protocol/3.17.6-next.9 (hash c94395b5da53729e6dff931293b051009ccaaaa4).\n// https://github.com/microsoft/vscode-languageserver-node/blob/release/protocol/3.17.6-next.9/protocol/metaModel.json\n// LSP metaData.version = 3.17.0.\n\nimport \"encoding/json\"\n\n// created for And\ntype And_RegOpt_textDocument_colorPresentation struct {\n\tWorkDoneProgressOptions\n\tTextDocumentRegistrationOptions\n}\n\n// A special text edit with an additional change annotation.\n//\n// @since 3.16.0.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#annotatedTextEdit\ntype AnnotatedTextEdit struct {\n\t// The actual identifier of the change annotation\n\tAnnotationID *ChangeAnnotationIdentifier `json:\"annotationId,omitempty\"`\n\tTextEdit\n}\n\n// The parameters passed via an apply workspace edit request.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#applyWorkspaceEditParams\ntype ApplyWorkspaceEditParams struct {\n\t// An optional label of the workspace edit. This label is\n\t// presented in the user interface for example on an undo\n\t// stack to undo the workspace edit.\n\tLabel string `json:\"label,omitempty\"`\n\t// The edits to apply.\n\tEdit WorkspaceEdit `json:\"edit\"`\n\t// Additional data about the edit.\n\t//\n\t// @since 3.18.0\n\t// @proposed\n\tMetadata *WorkspaceEditMetadata `json:\"metadata,omitempty\"`\n}\n\n// The result returned from the apply workspace edit request.\n//\n// @since 3.17 renamed from ApplyWorkspaceEditResponse\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#applyWorkspaceEditResult\ntype ApplyWorkspaceEditResult struct {\n\t// Indicates whether the edit was applied or not.\n\tApplied bool `json:\"applied\"`\n\t// An optional textual description for why the edit was not applied.\n\t// This may be used by the server for diagnostic logging or to provide\n\t// a suitable error for a request that triggered the edit.\n\tFailureReason string `json:\"failureReason,omitempty\"`\n\t// Depending on the client's failure handling strategy `failedChange` might\n\t// contain the index of the change that failed. This property is only available\n\t// if the client signals a `failureHandlingStrategy` in its client capabilities.\n\tFailedChange uint32 `json:\"failedChange,omitempty\"`\n}\n\n// A base for all symbol information.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#baseSymbolInformation\ntype BaseSymbolInformation struct {\n\t// The name of this symbol.\n\tName string `json:\"name\"`\n\t// The kind of this symbol.\n\tKind SymbolKind `json:\"kind\"`\n\t// Tags for this symbol.\n\t//\n\t// @since 3.16.0\n\tTags []SymbolTag `json:\"tags,omitempty\"`\n\t// The name of the symbol containing this symbol. This information is for\n\t// user interface purposes (e.g. to render a qualifier in the user interface\n\t// if necessary). It can't be used to re-infer a hierarchy for the document\n\t// symbols.\n\tContainerName string `json:\"containerName,omitempty\"`\n}\n\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#callHierarchyClientCapabilities\ntype CallHierarchyClientCapabilities struct {\n\t// Whether implementation supports dynamic registration. If this is set to `true`\n\t// the client supports the new `(TextDocumentRegistrationOptions & StaticRegistrationOptions)`\n\t// return value for the corresponding server capability as well.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n}\n\n// Represents an incoming call, e.g. a caller of a method or constructor.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#callHierarchyIncomingCall\ntype CallHierarchyIncomingCall struct {\n\t// The item that makes the call.\n\tFrom CallHierarchyItem `json:\"from\"`\n\t// The ranges at which the calls appear. This is relative to the caller\n\t// denoted by {@link CallHierarchyIncomingCall.from `this.from`}.\n\tFromRanges []Range `json:\"fromRanges\"`\n}\n\n// The parameter of a `callHierarchy/incomingCalls` request.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#callHierarchyIncomingCallsParams\ntype CallHierarchyIncomingCallsParams struct {\n\tItem CallHierarchyItem `json:\"item\"`\n\tWorkDoneProgressParams\n\tPartialResultParams\n}\n\n// Represents programming constructs like functions or constructors in the context\n// of call hierarchy.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#callHierarchyItem\ntype CallHierarchyItem struct {\n\t// The name of this item.\n\tName string `json:\"name\"`\n\t// The kind of this item.\n\tKind SymbolKind `json:\"kind\"`\n\t// Tags for this item.\n\tTags []SymbolTag `json:\"tags,omitempty\"`\n\t// More detail for this item, e.g. the signature of a function.\n\tDetail string `json:\"detail,omitempty\"`\n\t// The resource identifier of this item.\n\tURI DocumentUri `json:\"uri\"`\n\t// The range enclosing this symbol not including leading/trailing whitespace but everything else, e.g. comments and code.\n\tRange Range `json:\"range\"`\n\t// The range that should be selected and revealed when this symbol is being picked, e.g. the name of a function.\n\t// Must be contained by the {@link CallHierarchyItem.range `range`}.\n\tSelectionRange Range `json:\"selectionRange\"`\n\t// A data entry field that is preserved between a call hierarchy prepare and\n\t// incoming calls or outgoing calls requests.\n\tData interface{} `json:\"data,omitempty\"`\n}\n\n// Call hierarchy options used during static registration.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#callHierarchyOptions\ntype CallHierarchyOptions struct {\n\tWorkDoneProgressOptions\n}\n\n// Represents an outgoing call, e.g. calling a getter from a method or a method from a constructor etc.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#callHierarchyOutgoingCall\ntype CallHierarchyOutgoingCall struct {\n\t// The item that is called.\n\tTo CallHierarchyItem `json:\"to\"`\n\t// The range at which this item is called. This is the range relative to the caller, e.g the item\n\t// passed to {@link CallHierarchyItemProvider.provideCallHierarchyOutgoingCalls `provideCallHierarchyOutgoingCalls`}\n\t// and not {@link CallHierarchyOutgoingCall.to `this.to`}.\n\tFromRanges []Range `json:\"fromRanges\"`\n}\n\n// The parameter of a `callHierarchy/outgoingCalls` request.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#callHierarchyOutgoingCallsParams\ntype CallHierarchyOutgoingCallsParams struct {\n\tItem CallHierarchyItem `json:\"item\"`\n\tWorkDoneProgressParams\n\tPartialResultParams\n}\n\n// The parameter of a `textDocument/prepareCallHierarchy` request.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#callHierarchyPrepareParams\ntype CallHierarchyPrepareParams struct {\n\tTextDocumentPositionParams\n\tWorkDoneProgressParams\n}\n\n// Call hierarchy options used during static or dynamic registration.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#callHierarchyRegistrationOptions\ntype CallHierarchyRegistrationOptions struct {\n\tTextDocumentRegistrationOptions\n\tCallHierarchyOptions\n\tStaticRegistrationOptions\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#cancelParams\ntype CancelParams struct {\n\t// The request id to cancel.\n\tID interface{} `json:\"id\"`\n}\n\n// Additional information that describes document changes.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#changeAnnotation\ntype ChangeAnnotation struct {\n\t// A human-readable string describing the actual change. The string\n\t// is rendered prominent in the user interface.\n\tLabel string `json:\"label\"`\n\t// A flag which indicates that user confirmation is needed\n\t// before applying the change.\n\tNeedsConfirmation bool `json:\"needsConfirmation,omitempty\"`\n\t// A human-readable string which is rendered less prominent in\n\t// the user interface.\n\tDescription string `json:\"description,omitempty\"`\n}\n\n// An identifier to refer to a change annotation stored with a workspace edit.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#changeAnnotationIdentifier\ntype ChangeAnnotationIdentifier = string // (alias)\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#changeAnnotationsSupportOptions\ntype ChangeAnnotationsSupportOptions struct {\n\t// Whether the client groups edits with equal labels into tree nodes,\n\t// for instance all edits labelled with \"Changes in Strings\" would\n\t// be a tree node.\n\tGroupsOnLabel bool `json:\"groupsOnLabel,omitempty\"`\n}\n\n// Defines the capabilities provided by the client.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#clientCapabilities\ntype ClientCapabilities struct {\n\t// Workspace specific client capabilities.\n\tWorkspace WorkspaceClientCapabilities `json:\"workspace,omitempty\"`\n\t// Text document specific client capabilities.\n\tTextDocument TextDocumentClientCapabilities `json:\"textDocument,omitempty\"`\n\t// Capabilities specific to the notebook document support.\n\t//\n\t// @since 3.17.0\n\tNotebookDocument *NotebookDocumentClientCapabilities `json:\"notebookDocument,omitempty\"`\n\t// Window specific client capabilities.\n\tWindow WindowClientCapabilities `json:\"window,omitempty\"`\n\t// General client capabilities.\n\t//\n\t// @since 3.16.0\n\tGeneral *GeneralClientCapabilities `json:\"general,omitempty\"`\n\t// Experimental client capabilities.\n\tExperimental interface{} `json:\"experimental,omitempty\"`\n}\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#clientCodeActionKindOptions\ntype ClientCodeActionKindOptions struct {\n\t// The code action kind values the client supports. When this\n\t// property exists the client also guarantees that it will\n\t// handle values outside its set gracefully and falls back\n\t// to a default value when unknown.\n\tValueSet []CodeActionKind `json:\"valueSet\"`\n}\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#clientCodeActionLiteralOptions\ntype ClientCodeActionLiteralOptions struct {\n\t// The code action kind is support with the following value\n\t// set.\n\tCodeActionKind ClientCodeActionKindOptions `json:\"codeActionKind\"`\n}\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#clientCodeActionResolveOptions\ntype ClientCodeActionResolveOptions struct {\n\t// The properties that a client can resolve lazily.\n\tProperties []string `json:\"properties\"`\n}\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#clientCodeLensResolveOptions\ntype ClientCodeLensResolveOptions struct {\n\t// The properties that a client can resolve lazily.\n\tProperties []string `json:\"properties\"`\n}\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#clientCompletionItemInsertTextModeOptions\ntype ClientCompletionItemInsertTextModeOptions struct {\n\tValueSet []InsertTextMode `json:\"valueSet\"`\n}\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#clientCompletionItemOptions\ntype ClientCompletionItemOptions struct {\n\t// Client supports snippets as insert text.\n\t//\n\t// A snippet can define tab stops and placeholders with `$1`, `$2`\n\t// and `${3:foo}`. `$0` defines the final tab stop, it defaults to\n\t// the end of the snippet. Placeholders with equal identifiers are linked,\n\t// that is typing in one will update others too.\n\tSnippetSupport bool `json:\"snippetSupport,omitempty\"`\n\t// Client supports commit characters on a completion item.\n\tCommitCharactersSupport bool `json:\"commitCharactersSupport,omitempty\"`\n\t// Client supports the following content formats for the documentation\n\t// property. The order describes the preferred format of the client.\n\tDocumentationFormat []MarkupKind `json:\"documentationFormat,omitempty\"`\n\t// Client supports the deprecated property on a completion item.\n\tDeprecatedSupport bool `json:\"deprecatedSupport,omitempty\"`\n\t// Client supports the preselect property on a completion item.\n\tPreselectSupport bool `json:\"preselectSupport,omitempty\"`\n\t// Client supports the tag property on a completion item. Clients supporting\n\t// tags have to handle unknown tags gracefully. Clients especially need to\n\t// preserve unknown tags when sending a completion item back to the server in\n\t// a resolve call.\n\t//\n\t// @since 3.15.0\n\tTagSupport *CompletionItemTagOptions `json:\"tagSupport,omitempty\"`\n\t// Client support insert replace edit to control different behavior if a\n\t// completion item is inserted in the text or should replace text.\n\t//\n\t// @since 3.16.0\n\tInsertReplaceSupport bool `json:\"insertReplaceSupport,omitempty\"`\n\t// Indicates which properties a client can resolve lazily on a completion\n\t// item. Before version 3.16.0 only the predefined properties `documentation`\n\t// and `details` could be resolved lazily.\n\t//\n\t// @since 3.16.0\n\tResolveSupport *ClientCompletionItemResolveOptions `json:\"resolveSupport,omitempty\"`\n\t// The client supports the `insertTextMode` property on\n\t// a completion item to override the whitespace handling mode\n\t// as defined by the client (see `insertTextMode`).\n\t//\n\t// @since 3.16.0\n\tInsertTextModeSupport *ClientCompletionItemInsertTextModeOptions `json:\"insertTextModeSupport,omitempty\"`\n\t// The client has support for completion item label\n\t// details (see also `CompletionItemLabelDetails`).\n\t//\n\t// @since 3.17.0\n\tLabelDetailsSupport bool `json:\"labelDetailsSupport,omitempty\"`\n}\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#clientCompletionItemOptionsKind\ntype ClientCompletionItemOptionsKind struct {\n\t// The completion item kind values the client supports. When this\n\t// property exists the client also guarantees that it will\n\t// handle values outside its set gracefully and falls back\n\t// to a default value when unknown.\n\t//\n\t// If this property is not present the client only supports\n\t// the completion items kinds from `Text` to `Reference` as defined in\n\t// the initial version of the protocol.\n\tValueSet []CompletionItemKind `json:\"valueSet,omitempty\"`\n}\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#clientCompletionItemResolveOptions\ntype ClientCompletionItemResolveOptions struct {\n\t// The properties that a client can resolve lazily.\n\tProperties []string `json:\"properties\"`\n}\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#clientDiagnosticsTagOptions\ntype ClientDiagnosticsTagOptions struct {\n\t// The tags supported by the client.\n\tValueSet []DiagnosticTag `json:\"valueSet\"`\n}\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#clientFoldingRangeKindOptions\ntype ClientFoldingRangeKindOptions struct {\n\t// The folding range kind values the client supports. When this\n\t// property exists the client also guarantees that it will\n\t// handle values outside its set gracefully and falls back\n\t// to a default value when unknown.\n\tValueSet []FoldingRangeKind `json:\"valueSet,omitempty\"`\n}\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#clientFoldingRangeOptions\ntype ClientFoldingRangeOptions struct {\n\t// If set, the client signals that it supports setting collapsedText on\n\t// folding ranges to display custom labels instead of the default text.\n\t//\n\t// @since 3.17.0\n\tCollapsedText bool `json:\"collapsedText,omitempty\"`\n}\n\n// Information about the client\n//\n// @since 3.15.0\n// @since 3.18.0 ClientInfo type name added.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#clientInfo\ntype ClientInfo struct {\n\t// The name of the client as defined by the client.\n\tName string `json:\"name\"`\n\t// The client's version as defined by the client.\n\tVersion string `json:\"version,omitempty\"`\n}\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#clientInlayHintResolveOptions\ntype ClientInlayHintResolveOptions struct {\n\t// The properties that a client can resolve lazily.\n\tProperties []string `json:\"properties\"`\n}\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#clientSemanticTokensRequestFullDelta\ntype ClientSemanticTokensRequestFullDelta struct {\n\t// The client will send the `textDocument/semanticTokens/full/delta` request if\n\t// the server provides a corresponding handler.\n\tDelta bool `json:\"delta,omitempty\"`\n}\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#clientSemanticTokensRequestOptions\ntype ClientSemanticTokensRequestOptions struct {\n\t// The client will send the `textDocument/semanticTokens/range` request if\n\t// the server provides a corresponding handler.\n\tRange *Or_ClientSemanticTokensRequestOptions_range `json:\"range,omitempty\"`\n\t// The client will send the `textDocument/semanticTokens/full` request if\n\t// the server provides a corresponding handler.\n\tFull *Or_ClientSemanticTokensRequestOptions_full `json:\"full,omitempty\"`\n}\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#clientShowMessageActionItemOptions\ntype ClientShowMessageActionItemOptions struct {\n\t// Whether the client supports additional attributes which\n\t// are preserved and send back to the server in the\n\t// request's response.\n\tAdditionalPropertiesSupport bool `json:\"additionalPropertiesSupport,omitempty\"`\n}\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#clientSignatureInformationOptions\ntype ClientSignatureInformationOptions struct {\n\t// Client supports the following content formats for the documentation\n\t// property. The order describes the preferred format of the client.\n\tDocumentationFormat []MarkupKind `json:\"documentationFormat,omitempty\"`\n\t// Client capabilities specific to parameter information.\n\tParameterInformation *ClientSignatureParameterInformationOptions `json:\"parameterInformation,omitempty\"`\n\t// The client supports the `activeParameter` property on `SignatureInformation`\n\t// literal.\n\t//\n\t// @since 3.16.0\n\tActiveParameterSupport bool `json:\"activeParameterSupport,omitempty\"`\n\t// The client supports the `activeParameter` property on\n\t// `SignatureHelp`/`SignatureInformation` being set to `null` to\n\t// indicate that no parameter should be active.\n\t//\n\t// @since 3.18.0\n\t// @proposed\n\tNoActiveParameterSupport bool `json:\"noActiveParameterSupport,omitempty\"`\n}\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#clientSignatureParameterInformationOptions\ntype ClientSignatureParameterInformationOptions struct {\n\t// The client supports processing label offsets instead of a\n\t// simple label string.\n\t//\n\t// @since 3.14.0\n\tLabelOffsetSupport bool `json:\"labelOffsetSupport,omitempty\"`\n}\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#clientSymbolKindOptions\ntype ClientSymbolKindOptions struct {\n\t// The symbol kind values the client supports. When this\n\t// property exists the client also guarantees that it will\n\t// handle values outside its set gracefully and falls back\n\t// to a default value when unknown.\n\t//\n\t// If this property is not present the client only supports\n\t// the symbol kinds from `File` to `Array` as defined in\n\t// the initial version of the protocol.\n\tValueSet []SymbolKind `json:\"valueSet,omitempty\"`\n}\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#clientSymbolResolveOptions\ntype ClientSymbolResolveOptions struct {\n\t// The properties that a client can resolve lazily. Usually\n\t// `location.range`\n\tProperties []string `json:\"properties\"`\n}\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#clientSymbolTagOptions\ntype ClientSymbolTagOptions struct {\n\t// The tags supported by the client.\n\tValueSet []SymbolTag `json:\"valueSet\"`\n}\n\n// A code action represents a change that can be performed in code, e.g. to fix a problem or\n// to refactor code.\n//\n// A CodeAction must set either `edit` and/or a `command`. If both are supplied, the `edit` is applied first, then the `command` is executed.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#codeAction\ntype CodeAction struct {\n\t// A short, human-readable, title for this code action.\n\tTitle string `json:\"title\"`\n\t// The kind of the code action.\n\t//\n\t// Used to filter code actions.\n\tKind CodeActionKind `json:\"kind,omitempty\"`\n\t// The diagnostics that this code action resolves.\n\tDiagnostics []Diagnostic `json:\"diagnostics,omitempty\"`\n\t// Marks this as a preferred action. Preferred actions are used by the `auto fix` command and can be targeted\n\t// by keybindings.\n\t//\n\t// A quick fix should be marked preferred if it properly addresses the underlying error.\n\t// A refactoring should be marked preferred if it is the most reasonable choice of actions to take.\n\t//\n\t// @since 3.15.0\n\tIsPreferred bool `json:\"isPreferred,omitempty\"`\n\t// Marks that the code action cannot currently be applied.\n\t//\n\t// Clients should follow the following guidelines regarding disabled code actions:\n\t//\n\t// - Disabled code actions are not shown in automatic [lightbulbs](https://code.visualstudio.com/docs/editor/editingevolved#_code-action)\n\t// code action menus.\n\t//\n\t// - Disabled actions are shown as faded out in the code action menu when the user requests a more specific type\n\t// of code action, such as refactorings.\n\t//\n\t// - If the user has a [keybinding](https://code.visualstudio.com/docs/editor/refactoring#_keybindings-for-code-actions)\n\t// that auto applies a code action and only disabled code actions are returned, the client should show the user an\n\t// error message with `reason` in the editor.\n\t//\n\t// @since 3.16.0\n\tDisabled *CodeActionDisabled `json:\"disabled,omitempty\"`\n\t// The workspace edit this code action performs.\n\tEdit *WorkspaceEdit `json:\"edit,omitempty\"`\n\t// A command this code action executes. If a code action\n\t// provides an edit and a command, first the edit is\n\t// executed and then the command.\n\tCommand *Command `json:\"command,omitempty\"`\n\t// A data entry field that is preserved on a code action between\n\t// a `textDocument/codeAction` and a `codeAction/resolve` request.\n\t//\n\t// @since 3.16.0\n\tData *json.RawMessage `json:\"data,omitempty\"`\n}\n\n// The Client Capabilities of a {@link CodeActionRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#codeActionClientCapabilities\ntype CodeActionClientCapabilities struct {\n\t// Whether code action supports dynamic registration.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n\t// The client support code action literals of type `CodeAction` as a valid\n\t// response of the `textDocument/codeAction` request. If the property is not\n\t// set the request can only return `Command` literals.\n\t//\n\t// @since 3.8.0\n\tCodeActionLiteralSupport ClientCodeActionLiteralOptions `json:\"codeActionLiteralSupport,omitempty\"`\n\t// Whether code action supports the `isPreferred` property.\n\t//\n\t// @since 3.15.0\n\tIsPreferredSupport bool `json:\"isPreferredSupport,omitempty\"`\n\t// Whether code action supports the `disabled` property.\n\t//\n\t// @since 3.16.0\n\tDisabledSupport bool `json:\"disabledSupport,omitempty\"`\n\t// Whether code action supports the `data` property which is\n\t// preserved between a `textDocument/codeAction` and a\n\t// `codeAction/resolve` request.\n\t//\n\t// @since 3.16.0\n\tDataSupport bool `json:\"dataSupport,omitempty\"`\n\t// Whether the client supports resolving additional code action\n\t// properties via a separate `codeAction/resolve` request.\n\t//\n\t// @since 3.16.0\n\tResolveSupport *ClientCodeActionResolveOptions `json:\"resolveSupport,omitempty\"`\n\t// Whether the client honors the change annotations in\n\t// text edits and resource operations returned via the\n\t// `CodeAction#edit` property by for example presenting\n\t// the workspace edit in the user interface and asking\n\t// for confirmation.\n\t//\n\t// @since 3.16.0\n\tHonorsChangeAnnotations bool `json:\"honorsChangeAnnotations,omitempty\"`\n\t// Whether the client supports documentation for a class of\n\t// code actions.\n\t//\n\t// @since 3.18.0\n\t// @proposed\n\tDocumentationSupport bool `json:\"documentationSupport,omitempty\"`\n}\n\n// Contains additional diagnostic information about the context in which\n// a {@link CodeActionProvider.provideCodeActions code action} is run.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#codeActionContext\ntype CodeActionContext struct {\n\t// An array of diagnostics known on the client side overlapping the range provided to the\n\t// `textDocument/codeAction` request. They are provided so that the server knows which\n\t// errors are currently presented to the user for the given range. There is no guarantee\n\t// that these accurately reflect the error state of the resource. The primary parameter\n\t// to compute code actions is the provided range.\n\tDiagnostics []Diagnostic `json:\"diagnostics\"`\n\t// Requested kind of actions to return.\n\t//\n\t// Actions not of this kind are filtered out by the client before being shown. So servers\n\t// can omit computing them.\n\tOnly []CodeActionKind `json:\"only,omitempty\"`\n\t// The reason why code actions were requested.\n\t//\n\t// @since 3.17.0\n\tTriggerKind *CodeActionTriggerKind `json:\"triggerKind,omitempty\"`\n}\n\n// Captures why the code action is currently disabled.\n//\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#codeActionDisabled\ntype CodeActionDisabled struct {\n\t// Human readable description of why the code action is currently disabled.\n\t//\n\t// This is displayed in the code actions UI.\n\tReason string `json:\"reason\"`\n}\n\n// A set of predefined code action kinds\ntype CodeActionKind string\n\n// Documentation for a class of code actions.\n//\n// @since 3.18.0\n// @proposed\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#codeActionKindDocumentation\ntype CodeActionKindDocumentation struct {\n\t// The kind of the code action being documented.\n\t//\n\t// If the kind is generic, such as `CodeActionKind.Refactor`, the documentation will be shown whenever any\n\t// refactorings are returned. If the kind if more specific, such as `CodeActionKind.RefactorExtract`, the\n\t// documentation will only be shown when extract refactoring code actions are returned.\n\tKind CodeActionKind `json:\"kind\"`\n\t// Command that is ued to display the documentation to the user.\n\t//\n\t// The title of this documentation code action is taken from {@linkcode Command.title}\n\tCommand Command `json:\"command\"`\n}\n\n// Provider options for a {@link CodeActionRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#codeActionOptions\ntype CodeActionOptions struct {\n\t// CodeActionKinds that this server may return.\n\t//\n\t// The list of kinds may be generic, such as `CodeActionKind.Refactor`, or the server\n\t// may list out every specific kind they provide.\n\tCodeActionKinds []CodeActionKind `json:\"codeActionKinds,omitempty\"`\n\t// Static documentation for a class of code actions.\n\t//\n\t// Documentation from the provider should be shown in the code actions menu if either:\n\t//\n\t//\n\t// - Code actions of `kind` are requested by the editor. In this case, the editor will show the documentation that\n\t// most closely matches the requested code action kind. For example, if a provider has documentation for\n\t// both `Refactor` and `RefactorExtract`, when the user requests code actions for `RefactorExtract`,\n\t// the editor will use the documentation for `RefactorExtract` instead of the documentation for `Refactor`.\n\t//\n\t//\n\t// - Any code actions of `kind` are returned by the provider.\n\t//\n\t// At most one documentation entry should be shown per provider.\n\t//\n\t// @since 3.18.0\n\t// @proposed\n\tDocumentation []CodeActionKindDocumentation `json:\"documentation,omitempty\"`\n\t// The server provides support to resolve additional\n\t// information for a code action.\n\t//\n\t// @since 3.16.0\n\tResolveProvider bool `json:\"resolveProvider,omitempty\"`\n\tWorkDoneProgressOptions\n}\n\n// The parameters of a {@link CodeActionRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#codeActionParams\ntype CodeActionParams struct {\n\t// The document in which the command was invoked.\n\tTextDocument TextDocumentIdentifier `json:\"textDocument\"`\n\t// The range for which the command was invoked.\n\tRange Range `json:\"range\"`\n\t// Context carrying additional information.\n\tContext CodeActionContext `json:\"context\"`\n\tWorkDoneProgressParams\n\tPartialResultParams\n}\n\n// Registration options for a {@link CodeActionRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#codeActionRegistrationOptions\ntype CodeActionRegistrationOptions struct {\n\tTextDocumentRegistrationOptions\n\tCodeActionOptions\n}\n\n// The reason why code actions were requested.\n//\n// @since 3.17.0\ntype CodeActionTriggerKind uint32\n\n// Structure to capture a description for an error code.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#codeDescription\ntype CodeDescription struct {\n\t// An URI to open with more information about the diagnostic error.\n\tHref URI `json:\"href\"`\n}\n\n// A code lens represents a {@link Command command} that should be shown along with\n// source text, like the number of references, a way to run tests, etc.\n//\n// A code lens is _unresolved_ when no command is associated to it. For performance\n// reasons the creation of a code lens and resolving should be done in two stages.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#codeLens\ntype CodeLens struct {\n\t// The range in which this code lens is valid. Should only span a single line.\n\tRange Range `json:\"range\"`\n\t// The command this code lens represents.\n\tCommand *Command `json:\"command,omitempty\"`\n\t// A data entry field that is preserved on a code lens item between\n\t// a {@link CodeLensRequest} and a {@link CodeLensResolveRequest}\n\tData interface{} `json:\"data,omitempty\"`\n}\n\n// The client capabilities of a {@link CodeLensRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#codeLensClientCapabilities\ntype CodeLensClientCapabilities struct {\n\t// Whether code lens supports dynamic registration.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n\t// Whether the client supports resolving additional code lens\n\t// properties via a separate `codeLens/resolve` request.\n\t//\n\t// @since 3.18.0\n\tResolveSupport *ClientCodeLensResolveOptions `json:\"resolveSupport,omitempty\"`\n}\n\n// Code Lens provider options of a {@link CodeLensRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#codeLensOptions\ntype CodeLensOptions struct {\n\t// Code lens has a resolve provider as well.\n\tResolveProvider bool `json:\"resolveProvider,omitempty\"`\n\tWorkDoneProgressOptions\n}\n\n// The parameters of a {@link CodeLensRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#codeLensParams\ntype CodeLensParams struct {\n\t// The document to request code lens for.\n\tTextDocument TextDocumentIdentifier `json:\"textDocument\"`\n\tWorkDoneProgressParams\n\tPartialResultParams\n}\n\n// Registration options for a {@link CodeLensRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#codeLensRegistrationOptions\ntype CodeLensRegistrationOptions struct {\n\tTextDocumentRegistrationOptions\n\tCodeLensOptions\n}\n\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#codeLensWorkspaceClientCapabilities\ntype CodeLensWorkspaceClientCapabilities struct {\n\t// Whether the client implementation supports a refresh request sent from the\n\t// server to the client.\n\t//\n\t// Note that this event is global and will force the client to refresh all\n\t// code lenses currently shown. It should be used with absolute care and is\n\t// useful for situation where a server for example detect a project wide\n\t// change that requires such a calculation.\n\tRefreshSupport bool `json:\"refreshSupport,omitempty\"`\n}\n\n// Represents a color in RGBA space.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#color\ntype Color struct {\n\t// The red component of this color in the range [0-1].\n\tRed float64 `json:\"red\"`\n\t// The green component of this color in the range [0-1].\n\tGreen float64 `json:\"green\"`\n\t// The blue component of this color in the range [0-1].\n\tBlue float64 `json:\"blue\"`\n\t// The alpha component of this color in the range [0-1].\n\tAlpha float64 `json:\"alpha\"`\n}\n\n// Represents a color range from a document.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#colorInformation\ntype ColorInformation struct {\n\t// The range in the document where this color appears.\n\tRange Range `json:\"range\"`\n\t// The actual color value for this color range.\n\tColor Color `json:\"color\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#colorPresentation\ntype ColorPresentation struct {\n\t// The label of this color presentation. It will be shown on the color\n\t// picker header. By default this is also the text that is inserted when selecting\n\t// this color presentation.\n\tLabel string `json:\"label\"`\n\t// An {@link TextEdit edit} which is applied to a document when selecting\n\t// this presentation for the color. When `falsy` the {@link ColorPresentation.label label}\n\t// is used.\n\tTextEdit *TextEdit `json:\"textEdit,omitempty\"`\n\t// An optional array of additional {@link TextEdit text edits} that are applied when\n\t// selecting this color presentation. Edits must not overlap with the main {@link ColorPresentation.textEdit edit} nor with themselves.\n\tAdditionalTextEdits []TextEdit `json:\"additionalTextEdits,omitempty\"`\n}\n\n// Parameters for a {@link ColorPresentationRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#colorPresentationParams\ntype ColorPresentationParams struct {\n\t// The text document.\n\tTextDocument TextDocumentIdentifier `json:\"textDocument\"`\n\t// The color to request presentations for.\n\tColor Color `json:\"color\"`\n\t// The range where the color would be inserted. Serves as a context.\n\tRange Range `json:\"range\"`\n\tWorkDoneProgressParams\n\tPartialResultParams\n}\n\n// Represents a reference to a command. Provides a title which\n// will be used to represent a command in the UI and, optionally,\n// an array of arguments which will be passed to the command handler\n// function when invoked.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#command\ntype Command struct {\n\t// Title of the command, like `save`.\n\tTitle string `json:\"title\"`\n\t// An optional tooltip.\n\t//\n\t// @since 3.18.0\n\t// @proposed\n\tTooltip string `json:\"tooltip,omitempty\"`\n\t// The identifier of the actual command handler.\n\tCommand string `json:\"command\"`\n\t// Arguments that the command handler should be\n\t// invoked with.\n\tArguments []json.RawMessage `json:\"arguments,omitempty\"`\n}\n\n// Completion client capabilities\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#completionClientCapabilities\ntype CompletionClientCapabilities struct {\n\t// Whether completion supports dynamic registration.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n\t// The client supports the following `CompletionItem` specific\n\t// capabilities.\n\tCompletionItem ClientCompletionItemOptions `json:\"completionItem,omitempty\"`\n\tCompletionItemKind *ClientCompletionItemOptionsKind `json:\"completionItemKind,omitempty\"`\n\t// Defines how the client handles whitespace and indentation\n\t// when accepting a completion item that uses multi line\n\t// text in either `insertText` or `textEdit`.\n\t//\n\t// @since 3.17.0\n\tInsertTextMode InsertTextMode `json:\"insertTextMode,omitempty\"`\n\t// The client supports to send additional context information for a\n\t// `textDocument/completion` request.\n\tContextSupport bool `json:\"contextSupport,omitempty\"`\n\t// The client supports the following `CompletionList` specific\n\t// capabilities.\n\t//\n\t// @since 3.17.0\n\tCompletionList *CompletionListCapabilities `json:\"completionList,omitempty\"`\n}\n\n// Contains additional information about the context in which a completion request is triggered.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#completionContext\ntype CompletionContext struct {\n\t// How the completion was triggered.\n\tTriggerKind CompletionTriggerKind `json:\"triggerKind\"`\n\t// The trigger character (a single character) that has trigger code complete.\n\t// Is undefined if `triggerKind !== CompletionTriggerKind.TriggerCharacter`\n\tTriggerCharacter string `json:\"triggerCharacter,omitempty\"`\n}\n\n// A completion item represents a text snippet that is\n// proposed to complete text that is being typed.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#completionItem\ntype CompletionItem struct {\n\t// The label of this completion item.\n\t//\n\t// The label property is also by default the text that\n\t// is inserted when selecting this completion.\n\t//\n\t// If label details are provided the label itself should\n\t// be an unqualified name of the completion item.\n\tLabel string `json:\"label\"`\n\t// Additional details for the label\n\t//\n\t// @since 3.17.0\n\tLabelDetails *CompletionItemLabelDetails `json:\"labelDetails,omitempty\"`\n\t// The kind of this completion item. Based of the kind\n\t// an icon is chosen by the editor.\n\tKind CompletionItemKind `json:\"kind,omitempty\"`\n\t// Tags for this completion item.\n\t//\n\t// @since 3.15.0\n\tTags []CompletionItemTag `json:\"tags,omitempty\"`\n\t// A human-readable string with additional information\n\t// about this item, like type or symbol information.\n\tDetail string `json:\"detail,omitempty\"`\n\t// A human-readable string that represents a doc-comment.\n\tDocumentation *Or_CompletionItem_documentation `json:\"documentation,omitempty\"`\n\t// Indicates if this item is deprecated.\n\t// @deprecated Use `tags` instead.\n\tDeprecated bool `json:\"deprecated,omitempty\"`\n\t// Select this item when showing.\n\t//\n\t// *Note* that only one completion item can be selected and that the\n\t// tool / client decides which item that is. The rule is that the *first*\n\t// item of those that match best is selected.\n\tPreselect bool `json:\"preselect,omitempty\"`\n\t// A string that should be used when comparing this item\n\t// with other items. When `falsy` the {@link CompletionItem.label label}\n\t// is used.\n\tSortText string `json:\"sortText,omitempty\"`\n\t// A string that should be used when filtering a set of\n\t// completion items. When `falsy` the {@link CompletionItem.label label}\n\t// is used.\n\tFilterText string `json:\"filterText,omitempty\"`\n\t// A string that should be inserted into a document when selecting\n\t// this completion. When `falsy` the {@link CompletionItem.label label}\n\t// is used.\n\t//\n\t// The `insertText` is subject to interpretation by the client side.\n\t// Some tools might not take the string literally. For example\n\t// VS Code when code complete is requested in this example\n\t// `con` and a completion item with an `insertText` of\n\t// `console` is provided it will only insert `sole`. Therefore it is\n\t// recommended to use `textEdit` instead since it avoids additional client\n\t// side interpretation.\n\tInsertText string `json:\"insertText,omitempty\"`\n\t// The format of the insert text. The format applies to both the\n\t// `insertText` property and the `newText` property of a provided\n\t// `textEdit`. If omitted defaults to `InsertTextFormat.PlainText`.\n\t//\n\t// Please note that the insertTextFormat doesn't apply to\n\t// `additionalTextEdits`.\n\tInsertTextFormat *InsertTextFormat `json:\"insertTextFormat,omitempty\"`\n\t// How whitespace and indentation is handled during completion\n\t// item insertion. If not provided the clients default value depends on\n\t// the `textDocument.completion.insertTextMode` client capability.\n\t//\n\t// @since 3.16.0\n\tInsertTextMode *InsertTextMode `json:\"insertTextMode,omitempty\"`\n\t// An {@link TextEdit edit} which is applied to a document when selecting\n\t// this completion. When an edit is provided the value of\n\t// {@link CompletionItem.insertText insertText} is ignored.\n\t//\n\t// Most editors support two different operations when accepting a completion\n\t// item. One is to insert a completion text and the other is to replace an\n\t// existing text with a completion text. Since this can usually not be\n\t// predetermined by a server it can report both ranges. Clients need to\n\t// signal support for `InsertReplaceEdits` via the\n\t// `textDocument.completion.insertReplaceSupport` client capability\n\t// property.\n\t//\n\t// *Note 1:* The text edit's range as well as both ranges from an insert\n\t// replace edit must be a [single line] and they must contain the position\n\t// at which completion has been requested.\n\t// *Note 2:* If an `InsertReplaceEdit` is returned the edit's insert range\n\t// must be a prefix of the edit's replace range, that means it must be\n\t// contained and starting at the same position.\n\t//\n\t// @since 3.16.0 additional type `InsertReplaceEdit`\n\tTextEdit *Or_CompletionItem_textEdit `json:\"textEdit,omitempty\"`\n\t// The edit text used if the completion item is part of a CompletionList and\n\t// CompletionList defines an item default for the text edit range.\n\t//\n\t// Clients will only honor this property if they opt into completion list\n\t// item defaults using the capability `completionList.itemDefaults`.\n\t//\n\t// If not provided and a list's default range is provided the label\n\t// property is used as a text.\n\t//\n\t// @since 3.17.0\n\tTextEditText string `json:\"textEditText,omitempty\"`\n\t// An optional array of additional {@link TextEdit text edits} that are applied when\n\t// selecting this completion. Edits must not overlap (including the same insert position)\n\t// with the main {@link CompletionItem.textEdit edit} nor with themselves.\n\t//\n\t// Additional text edits should be used to change text unrelated to the current cursor position\n\t// (for example adding an import statement at the top of the file if the completion item will\n\t// insert an unqualified type).\n\tAdditionalTextEdits []TextEdit `json:\"additionalTextEdits,omitempty\"`\n\t// An optional set of characters that when pressed while this completion is active will accept it first and\n\t// then type that character. *Note* that all commit characters should have `length=1` and that superfluous\n\t// characters will be ignored.\n\tCommitCharacters []string `json:\"commitCharacters,omitempty\"`\n\t// An optional {@link Command command} that is executed *after* inserting this completion. *Note* that\n\t// additional modifications to the current document should be described with the\n\t// {@link CompletionItem.additionalTextEdits additionalTextEdits}-property.\n\tCommand *Command `json:\"command,omitempty\"`\n\t// A data entry field that is preserved on a completion item between a\n\t// {@link CompletionRequest} and a {@link CompletionResolveRequest}.\n\tData interface{} `json:\"data,omitempty\"`\n}\n\n// In many cases the items of an actual completion result share the same\n// value for properties like `commitCharacters` or the range of a text\n// edit. A completion list can therefore define item defaults which will\n// be used if a completion item itself doesn't specify the value.\n//\n// If a completion list specifies a default value and a completion item\n// also specifies a corresponding value the one from the item is used.\n//\n// Servers are only allowed to return default values if the client\n// signals support for this via the `completionList.itemDefaults`\n// capability.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#completionItemDefaults\ntype CompletionItemDefaults struct {\n\t// A default commit character set.\n\t//\n\t// @since 3.17.0\n\tCommitCharacters []string `json:\"commitCharacters,omitempty\"`\n\t// A default edit range.\n\t//\n\t// @since 3.17.0\n\tEditRange *Or_CompletionItemDefaults_editRange `json:\"editRange,omitempty\"`\n\t// A default insert text format.\n\t//\n\t// @since 3.17.0\n\tInsertTextFormat *InsertTextFormat `json:\"insertTextFormat,omitempty\"`\n\t// A default insert text mode.\n\t//\n\t// @since 3.17.0\n\tInsertTextMode *InsertTextMode `json:\"insertTextMode,omitempty\"`\n\t// A default data value.\n\t//\n\t// @since 3.17.0\n\tData interface{} `json:\"data,omitempty\"`\n}\n\n// The kind of a completion entry.\ntype CompletionItemKind uint32\n\n// Additional details for a completion item label.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#completionItemLabelDetails\ntype CompletionItemLabelDetails struct {\n\t// An optional string which is rendered less prominently directly after {@link CompletionItem.label label},\n\t// without any spacing. Should be used for function signatures and type annotations.\n\tDetail string `json:\"detail,omitempty\"`\n\t// An optional string which is rendered less prominently after {@link CompletionItem.detail}. Should be used\n\t// for fully qualified names and file paths.\n\tDescription string `json:\"description,omitempty\"`\n}\n\n// Completion item tags are extra annotations that tweak the rendering of a completion\n// item.\n//\n// @since 3.15.0\ntype CompletionItemTag uint32\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#completionItemTagOptions\ntype CompletionItemTagOptions struct {\n\t// The tags supported by the client.\n\tValueSet []CompletionItemTag `json:\"valueSet\"`\n}\n\n// Represents a collection of {@link CompletionItem completion items} to be presented\n// in the editor.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#completionList\ntype CompletionList struct {\n\t// This list it not complete. Further typing results in recomputing this list.\n\t//\n\t// Recomputed lists have all their items replaced (not appended) in the\n\t// incomplete completion sessions.\n\tIsIncomplete bool `json:\"isIncomplete\"`\n\t// In many cases the items of an actual completion result share the same\n\t// value for properties like `commitCharacters` or the range of a text\n\t// edit. A completion list can therefore define item defaults which will\n\t// be used if a completion item itself doesn't specify the value.\n\t//\n\t// If a completion list specifies a default value and a completion item\n\t// also specifies a corresponding value the one from the item is used.\n\t//\n\t// Servers are only allowed to return default values if the client\n\t// signals support for this via the `completionList.itemDefaults`\n\t// capability.\n\t//\n\t// @since 3.17.0\n\tItemDefaults *CompletionItemDefaults `json:\"itemDefaults,omitempty\"`\n\t// The completion items.\n\tItems []CompletionItem `json:\"items\"`\n}\n\n// The client supports the following `CompletionList` specific\n// capabilities.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#completionListCapabilities\ntype CompletionListCapabilities struct {\n\t// The client supports the following itemDefaults on\n\t// a completion list.\n\t//\n\t// The value lists the supported property names of the\n\t// `CompletionList.itemDefaults` object. If omitted\n\t// no properties are supported.\n\t//\n\t// @since 3.17.0\n\tItemDefaults []string `json:\"itemDefaults,omitempty\"`\n}\n\n// Completion options.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#completionOptions\ntype CompletionOptions struct {\n\t// Most tools trigger completion request automatically without explicitly requesting\n\t// it using a keyboard shortcut (e.g. Ctrl+Space). Typically they do so when the user\n\t// starts to type an identifier. For example if the user types `c` in a JavaScript file\n\t// code complete will automatically pop up present `console` besides others as a\n\t// completion item. Characters that make up identifiers don't need to be listed here.\n\t//\n\t// If code complete should automatically be trigger on characters not being valid inside\n\t// an identifier (for example `.` in JavaScript) list them in `triggerCharacters`.\n\tTriggerCharacters []string `json:\"triggerCharacters,omitempty\"`\n\t// The list of all possible characters that commit a completion. This field can be used\n\t// if clients don't support individual commit characters per completion item. See\n\t// `ClientCapabilities.textDocument.completion.completionItem.commitCharactersSupport`\n\t//\n\t// If a server provides both `allCommitCharacters` and commit characters on an individual\n\t// completion item the ones on the completion item win.\n\t//\n\t// @since 3.2.0\n\tAllCommitCharacters []string `json:\"allCommitCharacters,omitempty\"`\n\t// The server provides support to resolve additional\n\t// information for a completion item.\n\tResolveProvider bool `json:\"resolveProvider,omitempty\"`\n\t// The server supports the following `CompletionItem` specific\n\t// capabilities.\n\t//\n\t// @since 3.17.0\n\tCompletionItem *ServerCompletionItemOptions `json:\"completionItem,omitempty\"`\n\tWorkDoneProgressOptions\n}\n\n// Completion parameters\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#completionParams\ntype CompletionParams struct {\n\t// The completion context. This is only available it the client specifies\n\t// to send this using the client capability `textDocument.completion.contextSupport === true`\n\tContext CompletionContext `json:\"context,omitempty\"`\n\tTextDocumentPositionParams\n\tWorkDoneProgressParams\n\tPartialResultParams\n}\n\n// Registration options for a {@link CompletionRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#completionRegistrationOptions\ntype CompletionRegistrationOptions struct {\n\tTextDocumentRegistrationOptions\n\tCompletionOptions\n}\n\n// How a completion was triggered\ntype CompletionTriggerKind uint32\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#configurationItem\ntype ConfigurationItem struct {\n\t// The scope to get the configuration section for.\n\tScopeURI *URI `json:\"scopeUri,omitempty\"`\n\t// The configuration section asked for.\n\tSection string `json:\"section,omitempty\"`\n}\n\n// The parameters of a configuration request.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#configurationParams\ntype ConfigurationParams struct {\n\tItems []ConfigurationItem `json:\"items\"`\n}\n\n// Create file operation.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#createFile\ntype CreateFile struct {\n\t// A create\n\tKind string `json:\"kind\"`\n\t// The resource to create.\n\tURI DocumentUri `json:\"uri\"`\n\t// Additional options\n\tOptions *CreateFileOptions `json:\"options,omitempty\"`\n\tResourceOperation\n}\n\n// Options to create a file.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#createFileOptions\ntype CreateFileOptions struct {\n\t// Overwrite existing file. Overwrite wins over `ignoreIfExists`\n\tOverwrite bool `json:\"overwrite,omitempty\"`\n\t// Ignore if exists.\n\tIgnoreIfExists bool `json:\"ignoreIfExists,omitempty\"`\n}\n\n// The parameters sent in notifications/requests for user-initiated creation of\n// files.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#createFilesParams\ntype CreateFilesParams struct {\n\t// An array of all files/folders created in this operation.\n\tFiles []FileCreate `json:\"files\"`\n}\n\n// The declaration of a symbol representation as one or many {@link Location locations}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#declaration\ntype Declaration = Or_Declaration // (alias)\n// @since 3.14.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#declarationClientCapabilities\ntype DeclarationClientCapabilities struct {\n\t// Whether declaration supports dynamic registration. If this is set to `true`\n\t// the client supports the new `DeclarationRegistrationOptions` return value\n\t// for the corresponding server capability as well.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n\t// The client supports additional metadata in the form of declaration links.\n\tLinkSupport bool `json:\"linkSupport,omitempty\"`\n}\n\n// Information about where a symbol is declared.\n//\n// Provides additional metadata over normal {@link Location location} declarations, including the range of\n// the declaring symbol.\n//\n// Servers should prefer returning `DeclarationLink` over `Declaration` if supported\n// by the client.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#declarationLink\ntype DeclarationLink = LocationLink // (alias)\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#declarationOptions\ntype DeclarationOptions struct {\n\tWorkDoneProgressOptions\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#declarationParams\ntype DeclarationParams struct {\n\tTextDocumentPositionParams\n\tWorkDoneProgressParams\n\tPartialResultParams\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#declarationRegistrationOptions\ntype DeclarationRegistrationOptions struct {\n\tDeclarationOptions\n\tTextDocumentRegistrationOptions\n\tStaticRegistrationOptions\n}\n\n// The definition of a symbol represented as one or many {@link Location locations}.\n// For most programming languages there is only one location at which a symbol is\n// defined.\n//\n// Servers should prefer returning `DefinitionLink` over `Definition` if supported\n// by the client.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#definition\ntype Definition = Or_Definition // (alias)\n// Client Capabilities for a {@link DefinitionRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#definitionClientCapabilities\ntype DefinitionClientCapabilities struct {\n\t// Whether definition supports dynamic registration.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n\t// The client supports additional metadata in the form of definition links.\n\t//\n\t// @since 3.14.0\n\tLinkSupport bool `json:\"linkSupport,omitempty\"`\n}\n\n// Information about where a symbol is defined.\n//\n// Provides additional metadata over normal {@link Location location} definitions, including the range of\n// the defining symbol\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#definitionLink\ntype DefinitionLink = LocationLink // (alias)\n// Server Capabilities for a {@link DefinitionRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#definitionOptions\ntype DefinitionOptions struct {\n\tWorkDoneProgressOptions\n}\n\n// Parameters for a {@link DefinitionRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#definitionParams\ntype DefinitionParams struct {\n\tTextDocumentPositionParams\n\tWorkDoneProgressParams\n\tPartialResultParams\n}\n\n// Registration options for a {@link DefinitionRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#definitionRegistrationOptions\ntype DefinitionRegistrationOptions struct {\n\tTextDocumentRegistrationOptions\n\tDefinitionOptions\n}\n\n// Delete file operation\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#deleteFile\ntype DeleteFile struct {\n\t// A delete\n\tKind string `json:\"kind\"`\n\t// The file to delete.\n\tURI DocumentUri `json:\"uri\"`\n\t// Delete options.\n\tOptions *DeleteFileOptions `json:\"options,omitempty\"`\n\tResourceOperation\n}\n\n// Delete file options\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#deleteFileOptions\ntype DeleteFileOptions struct {\n\t// Delete the content recursively if a folder is denoted.\n\tRecursive bool `json:\"recursive,omitempty\"`\n\t// Ignore the operation if the file doesn't exist.\n\tIgnoreIfNotExists bool `json:\"ignoreIfNotExists,omitempty\"`\n}\n\n// The parameters sent in notifications/requests for user-initiated deletes of\n// files.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#deleteFilesParams\ntype DeleteFilesParams struct {\n\t// An array of all files/folders deleted in this operation.\n\tFiles []FileDelete `json:\"files\"`\n}\n\n// Represents a diagnostic, such as a compiler error or warning. Diagnostic objects\n// are only valid in the scope of a resource.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#diagnostic\ntype Diagnostic struct {\n\t// The range at which the message applies\n\tRange Range `json:\"range\"`\n\t// The diagnostic's severity. To avoid interpretation mismatches when a\n\t// server is used with different clients it is highly recommended that servers\n\t// always provide a severity value.\n\tSeverity DiagnosticSeverity `json:\"severity,omitempty\"`\n\t// The diagnostic's code, which usually appear in the user interface.\n\tCode interface{} `json:\"code,omitempty\"`\n\t// An optional property to describe the error code.\n\t// Requires the code field (above) to be present/not null.\n\t//\n\t// @since 3.16.0\n\tCodeDescription *CodeDescription `json:\"codeDescription,omitempty\"`\n\t// A human-readable string describing the source of this\n\t// diagnostic, e.g. 'typescript' or 'super lint'. It usually\n\t// appears in the user interface.\n\tSource string `json:\"source,omitempty\"`\n\t// The diagnostic's message. It usually appears in the user interface\n\tMessage string `json:\"message\"`\n\t// Additional metadata about the diagnostic.\n\t//\n\t// @since 3.15.0\n\tTags []DiagnosticTag `json:\"tags,omitempty\"`\n\t// An array of related diagnostic information, e.g. when symbol-names within\n\t// a scope collide all definitions can be marked via this property.\n\tRelatedInformation []DiagnosticRelatedInformation `json:\"relatedInformation,omitempty\"`\n\t// A data entry field that is preserved between a `textDocument/publishDiagnostics`\n\t// notification and `textDocument/codeAction` request.\n\t//\n\t// @since 3.16.0\n\tData *json.RawMessage `json:\"data,omitempty\"`\n}\n\n// Client capabilities specific to diagnostic pull requests.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#diagnosticClientCapabilities\ntype DiagnosticClientCapabilities struct {\n\t// Whether implementation supports dynamic registration. If this is set to `true`\n\t// the client supports the new `(TextDocumentRegistrationOptions & StaticRegistrationOptions)`\n\t// return value for the corresponding server capability as well.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n\t// Whether the clients supports related documents for document diagnostic pulls.\n\tRelatedDocumentSupport bool `json:\"relatedDocumentSupport,omitempty\"`\n\tDiagnosticsCapabilities\n}\n\n// Diagnostic options.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#diagnosticOptions\ntype DiagnosticOptions struct {\n\t// An optional identifier under which the diagnostics are\n\t// managed by the client.\n\tIdentifier string `json:\"identifier,omitempty\"`\n\t// Whether the language has inter file dependencies meaning that\n\t// editing code in one file can result in a different diagnostic\n\t// set in another file. Inter file dependencies are common for\n\t// most programming languages and typically uncommon for linters.\n\tInterFileDependencies bool `json:\"interFileDependencies\"`\n\t// The server provides support for workspace diagnostics as well.\n\tWorkspaceDiagnostics bool `json:\"workspaceDiagnostics\"`\n\tWorkDoneProgressOptions\n}\n\n// Diagnostic registration options.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#diagnosticRegistrationOptions\ntype DiagnosticRegistrationOptions struct {\n\tTextDocumentRegistrationOptions\n\tDiagnosticOptions\n\tStaticRegistrationOptions\n}\n\n// Represents a related message and source code location for a diagnostic. This should be\n// used to point to code locations that cause or related to a diagnostics, e.g when duplicating\n// a symbol in a scope.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#diagnosticRelatedInformation\ntype DiagnosticRelatedInformation struct {\n\t// The location of this related diagnostic information.\n\tLocation Location `json:\"location\"`\n\t// The message of this related diagnostic information.\n\tMessage string `json:\"message\"`\n}\n\n// Cancellation data returned from a diagnostic request.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#diagnosticServerCancellationData\ntype DiagnosticServerCancellationData struct {\n\tRetriggerRequest bool `json:\"retriggerRequest\"`\n}\n\n// The diagnostic's severity.\ntype DiagnosticSeverity uint32\n\n// The diagnostic tags.\n//\n// @since 3.15.0\ntype DiagnosticTag uint32\n\n// Workspace client capabilities specific to diagnostic pull requests.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#diagnosticWorkspaceClientCapabilities\ntype DiagnosticWorkspaceClientCapabilities struct {\n\t// Whether the client implementation supports a refresh request sent from\n\t// the server to the client.\n\t//\n\t// Note that this event is global and will force the client to refresh all\n\t// pulled diagnostics currently shown. It should be used with absolute care and\n\t// is useful for situation where a server for example detects a project wide\n\t// change that requires such a calculation.\n\tRefreshSupport bool `json:\"refreshSupport,omitempty\"`\n}\n\n// General diagnostics capabilities for pull and push model.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#diagnosticsCapabilities\ntype DiagnosticsCapabilities struct {\n\t// Whether the clients accepts diagnostics with related information.\n\tRelatedInformation bool `json:\"relatedInformation,omitempty\"`\n\t// Client supports the tag property to provide meta data about a diagnostic.\n\t// Clients supporting tags have to handle unknown tags gracefully.\n\t//\n\t// @since 3.15.0\n\tTagSupport *ClientDiagnosticsTagOptions `json:\"tagSupport,omitempty\"`\n\t// Client supports a codeDescription property\n\t//\n\t// @since 3.16.0\n\tCodeDescriptionSupport bool `json:\"codeDescriptionSupport,omitempty\"`\n\t// Whether code action supports the `data` property which is\n\t// preserved between a `textDocument/publishDiagnostics` and\n\t// `textDocument/codeAction` request.\n\t//\n\t// @since 3.16.0\n\tDataSupport bool `json:\"dataSupport,omitempty\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#didChangeConfigurationClientCapabilities\ntype DidChangeConfigurationClientCapabilities struct {\n\t// Did change configuration notification supports dynamic registration.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n}\n\n// The parameters of a change configuration notification.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#didChangeConfigurationParams\ntype DidChangeConfigurationParams struct {\n\t// The actual changed settings\n\tSettings interface{} `json:\"settings\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#didChangeConfigurationRegistrationOptions\ntype DidChangeConfigurationRegistrationOptions struct {\n\tSection *Or_DidChangeConfigurationRegistrationOptions_section `json:\"section,omitempty\"`\n}\n\n// The params sent in a change notebook document notification.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#didChangeNotebookDocumentParams\ntype DidChangeNotebookDocumentParams struct {\n\t// The notebook document that did change. The version number points\n\t// to the version after all provided changes have been applied. If\n\t// only the text document content of a cell changes the notebook version\n\t// doesn't necessarily have to change.\n\tNotebookDocument VersionedNotebookDocumentIdentifier `json:\"notebookDocument\"`\n\t// The actual changes to the notebook document.\n\t//\n\t// The changes describe single state changes to the notebook document.\n\t// So if there are two changes c1 (at array index 0) and c2 (at array\n\t// index 1) for a notebook in state S then c1 moves the notebook from\n\t// S to S' and c2 from S' to S''. So c1 is computed on the state S and\n\t// c2 is computed on the state S'.\n\t//\n\t// To mirror the content of a notebook using change events use the following approach:\n\t//\n\t// - start with the same initial content\n\t// - apply the 'notebookDocument/didChange' notifications in the order you receive them.\n\t// - apply the `NotebookChangeEvent`s in a single notification in the order\n\t// you receive them.\n\tChange NotebookDocumentChangeEvent `json:\"change\"`\n}\n\n// The change text document notification's parameters.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#didChangeTextDocumentParams\ntype DidChangeTextDocumentParams struct {\n\t// The document that did change. The version number points\n\t// to the version after all provided content changes have\n\t// been applied.\n\tTextDocument VersionedTextDocumentIdentifier `json:\"textDocument\"`\n\t// The actual content changes. The content changes describe single state changes\n\t// to the document. So if there are two content changes c1 (at array index 0) and\n\t// c2 (at array index 1) for a document in state S then c1 moves the document from\n\t// S to S' and c2 from S' to S''. So c1 is computed on the state S and c2 is computed\n\t// on the state S'.\n\t//\n\t// To mirror the content of a document using change events use the following approach:\n\t//\n\t// - start with the same initial content\n\t// - apply the 'textDocument/didChange' notifications in the order you receive them.\n\t// - apply the `TextDocumentContentChangeEvent`s in a single notification in the order\n\t// you receive them.\n\tContentChanges []TextDocumentContentChangeEvent `json:\"contentChanges\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#didChangeWatchedFilesClientCapabilities\ntype DidChangeWatchedFilesClientCapabilities struct {\n\t// Did change watched files notification supports dynamic registration. Please note\n\t// that the current protocol doesn't support static configuration for file changes\n\t// from the server side.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n\t// Whether the client has support for {@link RelativePattern relative pattern}\n\t// or not.\n\t//\n\t// @since 3.17.0\n\tRelativePatternSupport bool `json:\"relativePatternSupport,omitempty\"`\n}\n\n// The watched files change notification's parameters.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#didChangeWatchedFilesParams\ntype DidChangeWatchedFilesParams struct {\n\t// The actual file events.\n\tChanges []FileEvent `json:\"changes\"`\n}\n\n// Describe options to be used when registered for text document change events.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#didChangeWatchedFilesRegistrationOptions\ntype DidChangeWatchedFilesRegistrationOptions struct {\n\t// The watchers to register.\n\tWatchers []FileSystemWatcher `json:\"watchers\"`\n}\n\n// The parameters of a `workspace/didChangeWorkspaceFolders` notification.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#didChangeWorkspaceFoldersParams\ntype DidChangeWorkspaceFoldersParams struct {\n\t// The actual workspace folder change event.\n\tEvent WorkspaceFoldersChangeEvent `json:\"event\"`\n}\n\n// The params sent in a close notebook document notification.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#didCloseNotebookDocumentParams\ntype DidCloseNotebookDocumentParams struct {\n\t// The notebook document that got closed.\n\tNotebookDocument NotebookDocumentIdentifier `json:\"notebookDocument\"`\n\t// The text documents that represent the content\n\t// of a notebook cell that got closed.\n\tCellTextDocuments []TextDocumentIdentifier `json:\"cellTextDocuments\"`\n}\n\n// The parameters sent in a close text document notification\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#didCloseTextDocumentParams\ntype DidCloseTextDocumentParams struct {\n\t// The document that was closed.\n\tTextDocument TextDocumentIdentifier `json:\"textDocument\"`\n}\n\n// The params sent in an open notebook document notification.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#didOpenNotebookDocumentParams\ntype DidOpenNotebookDocumentParams struct {\n\t// The notebook document that got opened.\n\tNotebookDocument NotebookDocument `json:\"notebookDocument\"`\n\t// The text documents that represent the content\n\t// of a notebook cell.\n\tCellTextDocuments []TextDocumentItem `json:\"cellTextDocuments\"`\n}\n\n// The parameters sent in an open text document notification\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#didOpenTextDocumentParams\ntype DidOpenTextDocumentParams struct {\n\t// The document that was opened.\n\tTextDocument TextDocumentItem `json:\"textDocument\"`\n}\n\n// The params sent in a save notebook document notification.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#didSaveNotebookDocumentParams\ntype DidSaveNotebookDocumentParams struct {\n\t// The notebook document that got saved.\n\tNotebookDocument NotebookDocumentIdentifier `json:\"notebookDocument\"`\n}\n\n// The parameters sent in a save text document notification\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#didSaveTextDocumentParams\ntype DidSaveTextDocumentParams struct {\n\t// The document that was saved.\n\tTextDocument TextDocumentIdentifier `json:\"textDocument\"`\n\t// Optional the content when saved. Depends on the includeText value\n\t// when the save notification was requested.\n\tText *string `json:\"text,omitempty\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentColorClientCapabilities\ntype DocumentColorClientCapabilities struct {\n\t// Whether implementation supports dynamic registration. If this is set to `true`\n\t// the client supports the new `DocumentColorRegistrationOptions` return value\n\t// for the corresponding server capability as well.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentColorOptions\ntype DocumentColorOptions struct {\n\tWorkDoneProgressOptions\n}\n\n// Parameters for a {@link DocumentColorRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentColorParams\ntype DocumentColorParams struct {\n\t// The text document.\n\tTextDocument TextDocumentIdentifier `json:\"textDocument\"`\n\tWorkDoneProgressParams\n\tPartialResultParams\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentColorRegistrationOptions\ntype DocumentColorRegistrationOptions struct {\n\tTextDocumentRegistrationOptions\n\tDocumentColorOptions\n\tStaticRegistrationOptions\n}\n\n// Parameters of the document diagnostic request.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentDiagnosticParams\ntype DocumentDiagnosticParams struct {\n\t// The text document.\n\tTextDocument TextDocumentIdentifier `json:\"textDocument\"`\n\t// The additional identifier provided during registration.\n\tIdentifier string `json:\"identifier,omitempty\"`\n\t// The result id of a previous response if provided.\n\tPreviousResultID string `json:\"previousResultId,omitempty\"`\n\tWorkDoneProgressParams\n\tPartialResultParams\n}\n\n// The result of a document diagnostic pull request. A report can\n// either be a full report containing all diagnostics for the\n// requested document or an unchanged report indicating that nothing\n// has changed in terms of diagnostics in comparison to the last\n// pull request.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentDiagnosticReport\ntype DocumentDiagnosticReport = Or_DocumentDiagnosticReport // (alias)\n// The document diagnostic report kinds.\n//\n// @since 3.17.0\ntype DocumentDiagnosticReportKind string\n\n// A partial result for a document diagnostic report.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentDiagnosticReportPartialResult\ntype DocumentDiagnosticReportPartialResult struct {\n\tRelatedDocuments map[DocumentUri]interface{} `json:\"relatedDocuments\"`\n}\n\n// A document filter describes a top level text document or\n// a notebook cell document.\n//\n// @since 3.17.0 - proposed support for NotebookCellTextDocumentFilter.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentFilter\ntype DocumentFilter = Or_DocumentFilter // (alias)\n// Client capabilities of a {@link DocumentFormattingRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentFormattingClientCapabilities\ntype DocumentFormattingClientCapabilities struct {\n\t// Whether formatting supports dynamic registration.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n}\n\n// Provider options for a {@link DocumentFormattingRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentFormattingOptions\ntype DocumentFormattingOptions struct {\n\tWorkDoneProgressOptions\n}\n\n// The parameters of a {@link DocumentFormattingRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentFormattingParams\ntype DocumentFormattingParams struct {\n\t// The document to format.\n\tTextDocument TextDocumentIdentifier `json:\"textDocument\"`\n\t// The format options.\n\tOptions FormattingOptions `json:\"options\"`\n\tWorkDoneProgressParams\n}\n\n// Registration options for a {@link DocumentFormattingRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentFormattingRegistrationOptions\ntype DocumentFormattingRegistrationOptions struct {\n\tTextDocumentRegistrationOptions\n\tDocumentFormattingOptions\n}\n\n// A document highlight is a range inside a text document which deserves\n// special attention. Usually a document highlight is visualized by changing\n// the background color of its range.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentHighlight\ntype DocumentHighlight struct {\n\t// The range this highlight applies to.\n\tRange Range `json:\"range\"`\n\t// The highlight kind, default is {@link DocumentHighlightKind.Text text}.\n\tKind DocumentHighlightKind `json:\"kind,omitempty\"`\n}\n\n// Client Capabilities for a {@link DocumentHighlightRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentHighlightClientCapabilities\ntype DocumentHighlightClientCapabilities struct {\n\t// Whether document highlight supports dynamic registration.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n}\n\n// A document highlight kind.\ntype DocumentHighlightKind uint32\n\n// Provider options for a {@link DocumentHighlightRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentHighlightOptions\ntype DocumentHighlightOptions struct {\n\tWorkDoneProgressOptions\n}\n\n// Parameters for a {@link DocumentHighlightRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentHighlightParams\ntype DocumentHighlightParams struct {\n\tTextDocumentPositionParams\n\tWorkDoneProgressParams\n\tPartialResultParams\n}\n\n// Registration options for a {@link DocumentHighlightRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentHighlightRegistrationOptions\ntype DocumentHighlightRegistrationOptions struct {\n\tTextDocumentRegistrationOptions\n\tDocumentHighlightOptions\n}\n\n// A document link is a range in a text document that links to an internal or external resource, like another\n// text document or a web site.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentLink\ntype DocumentLink struct {\n\t// The range this link applies to.\n\tRange Range `json:\"range\"`\n\t// The uri this link points to. If missing a resolve request is sent later.\n\tTarget *URI `json:\"target,omitempty\"`\n\t// The tooltip text when you hover over this link.\n\t//\n\t// If a tooltip is provided, is will be displayed in a string that includes instructions on how to\n\t// trigger the link, such as `{0} (ctrl + click)`. The specific instructions vary depending on OS,\n\t// user settings, and localization.\n\t//\n\t// @since 3.15.0\n\tTooltip string `json:\"tooltip,omitempty\"`\n\t// A data entry field that is preserved on a document link between a\n\t// DocumentLinkRequest and a DocumentLinkResolveRequest.\n\tData interface{} `json:\"data,omitempty\"`\n}\n\n// The client capabilities of a {@link DocumentLinkRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentLinkClientCapabilities\ntype DocumentLinkClientCapabilities struct {\n\t// Whether document link supports dynamic registration.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n\t// Whether the client supports the `tooltip` property on `DocumentLink`.\n\t//\n\t// @since 3.15.0\n\tTooltipSupport bool `json:\"tooltipSupport,omitempty\"`\n}\n\n// Provider options for a {@link DocumentLinkRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentLinkOptions\ntype DocumentLinkOptions struct {\n\t// Document links have a resolve provider as well.\n\tResolveProvider bool `json:\"resolveProvider,omitempty\"`\n\tWorkDoneProgressOptions\n}\n\n// The parameters of a {@link DocumentLinkRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentLinkParams\ntype DocumentLinkParams struct {\n\t// The document to provide document links for.\n\tTextDocument TextDocumentIdentifier `json:\"textDocument\"`\n\tWorkDoneProgressParams\n\tPartialResultParams\n}\n\n// Registration options for a {@link DocumentLinkRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentLinkRegistrationOptions\ntype DocumentLinkRegistrationOptions struct {\n\tTextDocumentRegistrationOptions\n\tDocumentLinkOptions\n}\n\n// Client capabilities of a {@link DocumentOnTypeFormattingRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentOnTypeFormattingClientCapabilities\ntype DocumentOnTypeFormattingClientCapabilities struct {\n\t// Whether on type formatting supports dynamic registration.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n}\n\n// Provider options for a {@link DocumentOnTypeFormattingRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentOnTypeFormattingOptions\ntype DocumentOnTypeFormattingOptions struct {\n\t// A character on which formatting should be triggered, like `{`.\n\tFirstTriggerCharacter string `json:\"firstTriggerCharacter\"`\n\t// More trigger characters.\n\tMoreTriggerCharacter []string `json:\"moreTriggerCharacter,omitempty\"`\n}\n\n// The parameters of a {@link DocumentOnTypeFormattingRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentOnTypeFormattingParams\ntype DocumentOnTypeFormattingParams struct {\n\t// The document to format.\n\tTextDocument TextDocumentIdentifier `json:\"textDocument\"`\n\t// The position around which the on type formatting should happen.\n\t// This is not necessarily the exact position where the character denoted\n\t// by the property `ch` got typed.\n\tPosition Position `json:\"position\"`\n\t// The character that has been typed that triggered the formatting\n\t// on type request. That is not necessarily the last character that\n\t// got inserted into the document since the client could auto insert\n\t// characters as well (e.g. like automatic brace completion).\n\tCh string `json:\"ch\"`\n\t// The formatting options.\n\tOptions FormattingOptions `json:\"options\"`\n}\n\n// Registration options for a {@link DocumentOnTypeFormattingRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentOnTypeFormattingRegistrationOptions\ntype DocumentOnTypeFormattingRegistrationOptions struct {\n\tTextDocumentRegistrationOptions\n\tDocumentOnTypeFormattingOptions\n}\n\n// Client capabilities of a {@link DocumentRangeFormattingRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentRangeFormattingClientCapabilities\ntype DocumentRangeFormattingClientCapabilities struct {\n\t// Whether range formatting supports dynamic registration.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n\t// Whether the client supports formatting multiple ranges at once.\n\t//\n\t// @since 3.18.0\n\t// @proposed\n\tRangesSupport bool `json:\"rangesSupport,omitempty\"`\n}\n\n// Provider options for a {@link DocumentRangeFormattingRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentRangeFormattingOptions\ntype DocumentRangeFormattingOptions struct {\n\t// Whether the server supports formatting multiple ranges at once.\n\t//\n\t// @since 3.18.0\n\t// @proposed\n\tRangesSupport bool `json:\"rangesSupport,omitempty\"`\n\tWorkDoneProgressOptions\n}\n\n// The parameters of a {@link DocumentRangeFormattingRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentRangeFormattingParams\ntype DocumentRangeFormattingParams struct {\n\t// The document to format.\n\tTextDocument TextDocumentIdentifier `json:\"textDocument\"`\n\t// The range to format\n\tRange Range `json:\"range\"`\n\t// The format options\n\tOptions FormattingOptions `json:\"options\"`\n\tWorkDoneProgressParams\n}\n\n// Registration options for a {@link DocumentRangeFormattingRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentRangeFormattingRegistrationOptions\ntype DocumentRangeFormattingRegistrationOptions struct {\n\tTextDocumentRegistrationOptions\n\tDocumentRangeFormattingOptions\n}\n\n// The parameters of a {@link DocumentRangesFormattingRequest}.\n//\n// @since 3.18.0\n// @proposed\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentRangesFormattingParams\ntype DocumentRangesFormattingParams struct {\n\t// The document to format.\n\tTextDocument TextDocumentIdentifier `json:\"textDocument\"`\n\t// The ranges to format\n\tRanges []Range `json:\"ranges\"`\n\t// The format options\n\tOptions FormattingOptions `json:\"options\"`\n\tWorkDoneProgressParams\n}\n\n// A document selector is the combination of one or many document filters.\n//\n// @sample `let sel:DocumentSelector = [{ language: 'typescript' }, { language: 'json', pattern: '**∕tsconfig.json' }]`;\n//\n// The use of a string as a document filter is deprecated @since 3.16.0.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentSelector\ntype DocumentSelector = []DocumentFilter // (alias)\n// Represents programming constructs like variables, classes, interfaces etc.\n// that appear in a document. Document symbols can be hierarchical and they\n// have two ranges: one that encloses its definition and one that points to\n// its most interesting range, e.g. the range of an identifier.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentSymbol\ntype DocumentSymbol struct {\n\t// The name of this symbol. Will be displayed in the user interface and therefore must not be\n\t// an empty string or a string only consisting of white spaces.\n\tName string `json:\"name\"`\n\t// More detail for this symbol, e.g the signature of a function.\n\tDetail string `json:\"detail,omitempty\"`\n\t// The kind of this symbol.\n\tKind SymbolKind `json:\"kind\"`\n\t// Tags for this document symbol.\n\t//\n\t// @since 3.16.0\n\tTags []SymbolTag `json:\"tags,omitempty\"`\n\t// Indicates if this symbol is deprecated.\n\t//\n\t// @deprecated Use tags instead\n\tDeprecated bool `json:\"deprecated,omitempty\"`\n\t// The range enclosing this symbol not including leading/trailing whitespace but everything else\n\t// like comments. This information is typically used to determine if the clients cursor is\n\t// inside the symbol to reveal in the symbol in the UI.\n\tRange Range `json:\"range\"`\n\t// The range that should be selected and revealed when this symbol is being picked, e.g the name of a function.\n\t// Must be contained by the `range`.\n\tSelectionRange Range `json:\"selectionRange\"`\n\t// Children of this symbol, e.g. properties of a class.\n\tChildren []DocumentSymbol `json:\"children,omitempty\"`\n}\n\n// Client Capabilities for a {@link DocumentSymbolRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentSymbolClientCapabilities\ntype DocumentSymbolClientCapabilities struct {\n\t// Whether document symbol supports dynamic registration.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n\t// Specific capabilities for the `SymbolKind` in the\n\t// `textDocument/documentSymbol` request.\n\tSymbolKind *ClientSymbolKindOptions `json:\"symbolKind,omitempty\"`\n\t// The client supports hierarchical document symbols.\n\tHierarchicalDocumentSymbolSupport bool `json:\"hierarchicalDocumentSymbolSupport,omitempty\"`\n\t// The client supports tags on `SymbolInformation`. Tags are supported on\n\t// `DocumentSymbol` if `hierarchicalDocumentSymbolSupport` is set to true.\n\t// Clients supporting tags have to handle unknown tags gracefully.\n\t//\n\t// @since 3.16.0\n\tTagSupport *ClientSymbolTagOptions `json:\"tagSupport,omitempty\"`\n\t// The client supports an additional label presented in the UI when\n\t// registering a document symbol provider.\n\t//\n\t// @since 3.16.0\n\tLabelSupport bool `json:\"labelSupport,omitempty\"`\n}\n\n// Provider options for a {@link DocumentSymbolRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentSymbolOptions\ntype DocumentSymbolOptions struct {\n\t// A human-readable string that is shown when multiple outlines trees\n\t// are shown for the same document.\n\t//\n\t// @since 3.16.0\n\tLabel string `json:\"label,omitempty\"`\n\tWorkDoneProgressOptions\n}\n\n// Parameters for a {@link DocumentSymbolRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentSymbolParams\ntype DocumentSymbolParams struct {\n\t// The text document.\n\tTextDocument TextDocumentIdentifier `json:\"textDocument\"`\n\tWorkDoneProgressParams\n\tPartialResultParams\n}\n\n// Registration options for a {@link DocumentSymbolRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#documentSymbolRegistrationOptions\ntype DocumentSymbolRegistrationOptions struct {\n\tTextDocumentRegistrationOptions\n\tDocumentSymbolOptions\n}\n\n// Edit range variant that includes ranges for insert and replace operations.\n//\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#editRangeWithInsertReplace\ntype EditRangeWithInsertReplace struct {\n\tInsert Range `json:\"insert\"`\n\tReplace Range `json:\"replace\"`\n}\n\n// Predefined error codes.\ntype ErrorCodes int32\n\n// The client capabilities of a {@link ExecuteCommandRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#executeCommandClientCapabilities\ntype ExecuteCommandClientCapabilities struct {\n\t// Execute command supports dynamic registration.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n}\n\n// The server capabilities of a {@link ExecuteCommandRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#executeCommandOptions\ntype ExecuteCommandOptions struct {\n\t// The commands to be executed on the server\n\tCommands []string `json:\"commands\"`\n\tWorkDoneProgressOptions\n}\n\n// The parameters of a {@link ExecuteCommandRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#executeCommandParams\ntype ExecuteCommandParams struct {\n\t// The identifier of the actual command handler.\n\tCommand string `json:\"command\"`\n\t// Arguments that the command should be invoked with.\n\tArguments []json.RawMessage `json:\"arguments,omitempty\"`\n\tWorkDoneProgressParams\n}\n\n// Registration options for a {@link ExecuteCommandRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#executeCommandRegistrationOptions\ntype ExecuteCommandRegistrationOptions struct {\n\tExecuteCommandOptions\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#executionSummary\ntype ExecutionSummary struct {\n\t// A strict monotonically increasing value\n\t// indicating the execution order of a cell\n\t// inside a notebook.\n\tExecutionOrder uint32 `json:\"executionOrder\"`\n\t// Whether the execution was successful or\n\t// not if known by the client.\n\tSuccess bool `json:\"success,omitempty\"`\n}\ntype FailureHandlingKind string\n\n// The file event type\ntype FileChangeType uint32\n\n// Represents information on a file/folder create.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#fileCreate\ntype FileCreate struct {\n\t// A file:// URI for the location of the file/folder being created.\n\tURI string `json:\"uri\"`\n}\n\n// Represents information on a file/folder delete.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#fileDelete\ntype FileDelete struct {\n\t// A file:// URI for the location of the file/folder being deleted.\n\tURI string `json:\"uri\"`\n}\n\n// An event describing a file change.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#fileEvent\ntype FileEvent struct {\n\t// The file's uri.\n\tURI DocumentUri `json:\"uri\"`\n\t// The change type.\n\tType FileChangeType `json:\"type\"`\n}\n\n// Capabilities relating to events from file operations by the user in the client.\n//\n// These events do not come from the file system, they come from user operations\n// like renaming a file in the UI.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#fileOperationClientCapabilities\ntype FileOperationClientCapabilities struct {\n\t// Whether the client supports dynamic registration for file requests/notifications.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n\t// The client has support for sending didCreateFiles notifications.\n\tDidCreate bool `json:\"didCreate,omitempty\"`\n\t// The client has support for sending willCreateFiles requests.\n\tWillCreate bool `json:\"willCreate,omitempty\"`\n\t// The client has support for sending didRenameFiles notifications.\n\tDidRename bool `json:\"didRename,omitempty\"`\n\t// The client has support for sending willRenameFiles requests.\n\tWillRename bool `json:\"willRename,omitempty\"`\n\t// The client has support for sending didDeleteFiles notifications.\n\tDidDelete bool `json:\"didDelete,omitempty\"`\n\t// The client has support for sending willDeleteFiles requests.\n\tWillDelete bool `json:\"willDelete,omitempty\"`\n}\n\n// A filter to describe in which file operation requests or notifications\n// the server is interested in receiving.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#fileOperationFilter\ntype FileOperationFilter struct {\n\t// A Uri scheme like `file` or `untitled`.\n\tScheme string `json:\"scheme,omitempty\"`\n\t// The actual file operation pattern.\n\tPattern FileOperationPattern `json:\"pattern\"`\n}\n\n// Options for notifications/requests for user operations on files.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#fileOperationOptions\ntype FileOperationOptions struct {\n\t// The server is interested in receiving didCreateFiles notifications.\n\tDidCreate *FileOperationRegistrationOptions `json:\"didCreate,omitempty\"`\n\t// The server is interested in receiving willCreateFiles requests.\n\tWillCreate *FileOperationRegistrationOptions `json:\"willCreate,omitempty\"`\n\t// The server is interested in receiving didRenameFiles notifications.\n\tDidRename *FileOperationRegistrationOptions `json:\"didRename,omitempty\"`\n\t// The server is interested in receiving willRenameFiles requests.\n\tWillRename *FileOperationRegistrationOptions `json:\"willRename,omitempty\"`\n\t// The server is interested in receiving didDeleteFiles file notifications.\n\tDidDelete *FileOperationRegistrationOptions `json:\"didDelete,omitempty\"`\n\t// The server is interested in receiving willDeleteFiles file requests.\n\tWillDelete *FileOperationRegistrationOptions `json:\"willDelete,omitempty\"`\n}\n\n// A pattern to describe in which file operation requests or notifications\n// the server is interested in receiving.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#fileOperationPattern\ntype FileOperationPattern struct {\n\t// The glob pattern to match. Glob patterns can have the following syntax:\n\t//\n\t// - `*` to match one or more characters in a path segment\n\t// - `?` to match on one character in a path segment\n\t// - `**` to match any number of path segments, including none\n\t// - `{}` to group sub patterns into an OR expression. (e.g. `**/*.{ts,js}` matches all TypeScript and JavaScript files)\n\t// - `[]` to declare a range of characters to match in a path segment (e.g., `example.[0-9]` to match on `example.0`, `example.1`, …)\n\t// - `[!...]` to negate a range of characters to match in a path segment (e.g., `example.[!0-9]` to match on `example.a`, `example.b`, but not `example.0`)\n\tGlob string `json:\"glob\"`\n\t// Whether to match files or folders with this pattern.\n\t//\n\t// Matches both if undefined.\n\tMatches *FileOperationPatternKind `json:\"matches,omitempty\"`\n\t// Additional options used during matching.\n\tOptions *FileOperationPatternOptions `json:\"options,omitempty\"`\n}\n\n// A pattern kind describing if a glob pattern matches a file a folder or\n// both.\n//\n// @since 3.16.0\ntype FileOperationPatternKind string\n\n// Matching options for the file operation pattern.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#fileOperationPatternOptions\ntype FileOperationPatternOptions struct {\n\t// The pattern should be matched ignoring casing.\n\tIgnoreCase bool `json:\"ignoreCase,omitempty\"`\n}\n\n// The options to register for file operations.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#fileOperationRegistrationOptions\ntype FileOperationRegistrationOptions struct {\n\t// The actual filters.\n\tFilters []FileOperationFilter `json:\"filters\"`\n}\n\n// Represents information on a file/folder rename.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#fileRename\ntype FileRename struct {\n\t// A file:// URI for the original location of the file/folder being renamed.\n\tOldURI string `json:\"oldUri\"`\n\t// A file:// URI for the new location of the file/folder being renamed.\n\tNewURI string `json:\"newUri\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#fileSystemWatcher\ntype FileSystemWatcher struct {\n\t// The glob pattern to watch. See {@link GlobPattern glob pattern} for more detail.\n\t//\n\t// @since 3.17.0 support for relative patterns.\n\tGlobPattern GlobPattern `json:\"globPattern\"`\n\t// The kind of events of interest. If omitted it defaults\n\t// to WatchKind.Create | WatchKind.Change | WatchKind.Delete\n\t// which is 7.\n\tKind *WatchKind `json:\"kind,omitempty\"`\n}\n\n// Represents a folding range. To be valid, start and end line must be bigger than zero and smaller\n// than the number of lines in the document. Clients are free to ignore invalid ranges.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#foldingRange\ntype FoldingRange struct {\n\t// The zero-based start line of the range to fold. The folded area starts after the line's last character.\n\t// To be valid, the end must be zero or larger and smaller than the number of lines in the document.\n\tStartLine uint32 `json:\"startLine\"`\n\t// The zero-based character offset from where the folded range starts. If not defined, defaults to the length of the start line.\n\tStartCharacter uint32 `json:\"startCharacter,omitempty\"`\n\t// The zero-based end line of the range to fold. The folded area ends with the line's last character.\n\t// To be valid, the end must be zero or larger and smaller than the number of lines in the document.\n\tEndLine uint32 `json:\"endLine\"`\n\t// The zero-based character offset before the folded range ends. If not defined, defaults to the length of the end line.\n\tEndCharacter uint32 `json:\"endCharacter,omitempty\"`\n\t// Describes the kind of the folding range such as 'comment' or 'region'. The kind\n\t// is used to categorize folding ranges and used by commands like 'Fold all comments'.\n\t// See {@link FoldingRangeKind} for an enumeration of standardized kinds.\n\tKind string `json:\"kind,omitempty\"`\n\t// The text that the client should show when the specified range is\n\t// collapsed. If not defined or not supported by the client, a default\n\t// will be chosen by the client.\n\t//\n\t// @since 3.17.0\n\tCollapsedText string `json:\"collapsedText,omitempty\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#foldingRangeClientCapabilities\ntype FoldingRangeClientCapabilities struct {\n\t// Whether implementation supports dynamic registration for folding range\n\t// providers. If this is set to `true` the client supports the new\n\t// `FoldingRangeRegistrationOptions` return value for the corresponding\n\t// server capability as well.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n\t// The maximum number of folding ranges that the client prefers to receive\n\t// per document. The value serves as a hint, servers are free to follow the\n\t// limit.\n\tRangeLimit uint32 `json:\"rangeLimit,omitempty\"`\n\t// If set, the client signals that it only supports folding complete lines.\n\t// If set, client will ignore specified `startCharacter` and `endCharacter`\n\t// properties in a FoldingRange.\n\tLineFoldingOnly bool `json:\"lineFoldingOnly,omitempty\"`\n\t// Specific options for the folding range kind.\n\t//\n\t// @since 3.17.0\n\tFoldingRangeKind *ClientFoldingRangeKindOptions `json:\"foldingRangeKind,omitempty\"`\n\t// Specific options for the folding range.\n\t//\n\t// @since 3.17.0\n\tFoldingRange *ClientFoldingRangeOptions `json:\"foldingRange,omitempty\"`\n}\n\n// A set of predefined range kinds.\ntype FoldingRangeKind string\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#foldingRangeOptions\ntype FoldingRangeOptions struct {\n\tWorkDoneProgressOptions\n}\n\n// Parameters for a {@link FoldingRangeRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#foldingRangeParams\ntype FoldingRangeParams struct {\n\t// The text document.\n\tTextDocument TextDocumentIdentifier `json:\"textDocument\"`\n\tWorkDoneProgressParams\n\tPartialResultParams\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#foldingRangeRegistrationOptions\ntype FoldingRangeRegistrationOptions struct {\n\tTextDocumentRegistrationOptions\n\tFoldingRangeOptions\n\tStaticRegistrationOptions\n}\n\n// Client workspace capabilities specific to folding ranges\n//\n// @since 3.18.0\n// @proposed\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#foldingRangeWorkspaceClientCapabilities\ntype FoldingRangeWorkspaceClientCapabilities struct {\n\t// Whether the client implementation supports a refresh request sent from the\n\t// server to the client.\n\t//\n\t// Note that this event is global and will force the client to refresh all\n\t// folding ranges currently shown. It should be used with absolute care and is\n\t// useful for situation where a server for example detects a project wide\n\t// change that requires such a calculation.\n\t//\n\t// @since 3.18.0\n\t// @proposed\n\tRefreshSupport bool `json:\"refreshSupport,omitempty\"`\n}\n\n// Value-object describing what options formatting should use.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#formattingOptions\ntype FormattingOptions struct {\n\t// Size of a tab in spaces.\n\tTabSize uint32 `json:\"tabSize\"`\n\t// Prefer spaces over tabs.\n\tInsertSpaces bool `json:\"insertSpaces\"`\n\t// Trim trailing whitespace on a line.\n\t//\n\t// @since 3.15.0\n\tTrimTrailingWhitespace bool `json:\"trimTrailingWhitespace,omitempty\"`\n\t// Insert a newline character at the end of the file if one does not exist.\n\t//\n\t// @since 3.15.0\n\tInsertFinalNewline bool `json:\"insertFinalNewline,omitempty\"`\n\t// Trim all newlines after the final newline at the end of the file.\n\t//\n\t// @since 3.15.0\n\tTrimFinalNewlines bool `json:\"trimFinalNewlines,omitempty\"`\n}\n\n// A diagnostic report with a full set of problems.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#fullDocumentDiagnosticReport\ntype FullDocumentDiagnosticReport struct {\n\t// A full document diagnostic report.\n\tKind string `json:\"kind\"`\n\t// An optional result id. If provided it will\n\t// be sent on the next diagnostic request for the\n\t// same document.\n\tResultID string `json:\"resultId,omitempty\"`\n\t// The actual items.\n\tItems []Diagnostic `json:\"items\"`\n}\n\n// General client capabilities.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#generalClientCapabilities\ntype GeneralClientCapabilities struct {\n\t// Client capability that signals how the client\n\t// handles stale requests (e.g. a request\n\t// for which the client will not process the response\n\t// anymore since the information is outdated).\n\t//\n\t// @since 3.17.0\n\tStaleRequestSupport *StaleRequestSupportOptions `json:\"staleRequestSupport,omitempty\"`\n\t// Client capabilities specific to regular expressions.\n\t//\n\t// @since 3.16.0\n\tRegularExpressions *RegularExpressionsClientCapabilities `json:\"regularExpressions,omitempty\"`\n\t// Client capabilities specific to the client's markdown parser.\n\t//\n\t// @since 3.16.0\n\tMarkdown *MarkdownClientCapabilities `json:\"markdown,omitempty\"`\n\t// The position encodings supported by the client. Client and server\n\t// have to agree on the same position encoding to ensure that offsets\n\t// (e.g. character position in a line) are interpreted the same on both\n\t// sides.\n\t//\n\t// To keep the protocol backwards compatible the following applies: if\n\t// the value 'utf-16' is missing from the array of position encodings\n\t// servers can assume that the client supports UTF-16. UTF-16 is\n\t// therefore a mandatory encoding.\n\t//\n\t// If omitted it defaults to ['utf-16'].\n\t//\n\t// Implementation considerations: since the conversion from one encoding\n\t// into another requires the content of the file / line the conversion\n\t// is best done where the file is read which is usually on the server\n\t// side.\n\t//\n\t// @since 3.17.0\n\tPositionEncodings []PositionEncodingKind `json:\"positionEncodings,omitempty\"`\n}\n\n// The glob pattern. Either a string pattern or a relative pattern.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#globPattern\ntype GlobPattern = Or_GlobPattern // (alias)\n// The result of a hover request.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#hover\ntype Hover struct {\n\t// The hover's content\n\tContents MarkupContent `json:\"contents\"`\n\t// An optional range inside the text document that is used to\n\t// visualize the hover, e.g. by changing the background color.\n\tRange Range `json:\"range,omitempty\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#hoverClientCapabilities\ntype HoverClientCapabilities struct {\n\t// Whether hover supports dynamic registration.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n\t// Client supports the following content formats for the content\n\t// property. The order describes the preferred format of the client.\n\tContentFormat []MarkupKind `json:\"contentFormat,omitempty\"`\n}\n\n// Hover options.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#hoverOptions\ntype HoverOptions struct {\n\tWorkDoneProgressOptions\n}\n\n// Parameters for a {@link HoverRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#hoverParams\ntype HoverParams struct {\n\tTextDocumentPositionParams\n\tWorkDoneProgressParams\n}\n\n// Registration options for a {@link HoverRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#hoverRegistrationOptions\ntype HoverRegistrationOptions struct {\n\tTextDocumentRegistrationOptions\n\tHoverOptions\n}\n\n// @since 3.6.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#implementationClientCapabilities\ntype ImplementationClientCapabilities struct {\n\t// Whether implementation supports dynamic registration. If this is set to `true`\n\t// the client supports the new `ImplementationRegistrationOptions` return value\n\t// for the corresponding server capability as well.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n\t// The client supports additional metadata in the form of definition links.\n\t//\n\t// @since 3.14.0\n\tLinkSupport bool `json:\"linkSupport,omitempty\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#implementationOptions\ntype ImplementationOptions struct {\n\tWorkDoneProgressOptions\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#implementationParams\ntype ImplementationParams struct {\n\tTextDocumentPositionParams\n\tWorkDoneProgressParams\n\tPartialResultParams\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#implementationRegistrationOptions\ntype ImplementationRegistrationOptions struct {\n\tTextDocumentRegistrationOptions\n\tImplementationOptions\n\tStaticRegistrationOptions\n}\n\n// The data type of the ResponseError if the\n// initialize request fails.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#initializeError\ntype InitializeError struct {\n\t// Indicates whether the client execute the following retry logic:\n\t// (1) show the message provided by the ResponseError to the user\n\t// (2) user selects retry or cancel\n\t// (3) if user selected retry the initialize method is sent again.\n\tRetry bool `json:\"retry\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#initializeParams\ntype InitializeParams struct {\n\tXInitializeParams\n\tWorkspaceFoldersInitializeParams\n}\n\n// The result returned from an initialize request.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#initializeResult\ntype InitializeResult struct {\n\t// The capabilities the language server provides.\n\tCapabilities ServerCapabilities `json:\"capabilities\"`\n\t// Information about the server.\n\t//\n\t// @since 3.15.0\n\tServerInfo *ServerInfo `json:\"serverInfo,omitempty\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#initializedParams\ntype InitializedParams struct {\n}\n\n// Inlay hint information.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#inlayHint\ntype InlayHint struct {\n\t// The position of this hint.\n\t//\n\t// If multiple hints have the same position, they will be shown in the order\n\t// they appear in the response.\n\tPosition Position `json:\"position\"`\n\t// The label of this hint. A human readable string or an array of\n\t// InlayHintLabelPart label parts.\n\t//\n\t// *Note* that neither the string nor the label part can be empty.\n\tLabel []InlayHintLabelPart `json:\"label\"`\n\t// The kind of this hint. Can be omitted in which case the client\n\t// should fall back to a reasonable default.\n\tKind InlayHintKind `json:\"kind,omitempty\"`\n\t// Optional text edits that are performed when accepting this inlay hint.\n\t//\n\t// *Note* that edits are expected to change the document so that the inlay\n\t// hint (or its nearest variant) is now part of the document and the inlay\n\t// hint itself is now obsolete.\n\tTextEdits []TextEdit `json:\"textEdits,omitempty\"`\n\t// The tooltip text when you hover over this item.\n\tTooltip *Or_InlayHint_tooltip `json:\"tooltip,omitempty\"`\n\t// Render padding before the hint.\n\t//\n\t// Note: Padding should use the editor's background color, not the\n\t// background color of the hint itself. That means padding can be used\n\t// to visually align/separate an inlay hint.\n\tPaddingLeft bool `json:\"paddingLeft,omitempty\"`\n\t// Render padding after the hint.\n\t//\n\t// Note: Padding should use the editor's background color, not the\n\t// background color of the hint itself. That means padding can be used\n\t// to visually align/separate an inlay hint.\n\tPaddingRight bool `json:\"paddingRight,omitempty\"`\n\t// A data entry field that is preserved on an inlay hint between\n\t// a `textDocument/inlayHint` and a `inlayHint/resolve` request.\n\tData interface{} `json:\"data,omitempty\"`\n}\n\n// Inlay hint client capabilities.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#inlayHintClientCapabilities\ntype InlayHintClientCapabilities struct {\n\t// Whether inlay hints support dynamic registration.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n\t// Indicates which properties a client can resolve lazily on an inlay\n\t// hint.\n\tResolveSupport *ClientInlayHintResolveOptions `json:\"resolveSupport,omitempty\"`\n}\n\n// Inlay hint kinds.\n//\n// @since 3.17.0\ntype InlayHintKind uint32\n\n// An inlay hint label part allows for interactive and composite labels\n// of inlay hints.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#inlayHintLabelPart\ntype InlayHintLabelPart struct {\n\t// The value of this label part.\n\tValue string `json:\"value\"`\n\t// The tooltip text when you hover over this label part. Depending on\n\t// the client capability `inlayHint.resolveSupport` clients might resolve\n\t// this property late using the resolve request.\n\tTooltip *Or_InlayHintLabelPart_tooltip `json:\"tooltip,omitempty\"`\n\t// An optional source code location that represents this\n\t// label part.\n\t//\n\t// The editor will use this location for the hover and for code navigation\n\t// features: This part will become a clickable link that resolves to the\n\t// definition of the symbol at the given location (not necessarily the\n\t// location itself), it shows the hover that shows at the given location,\n\t// and it shows a context menu with further code navigation commands.\n\t//\n\t// Depending on the client capability `inlayHint.resolveSupport` clients\n\t// might resolve this property late using the resolve request.\n\tLocation *Location `json:\"location,omitempty\"`\n\t// An optional command for this label part.\n\t//\n\t// Depending on the client capability `inlayHint.resolveSupport` clients\n\t// might resolve this property late using the resolve request.\n\tCommand *Command `json:\"command,omitempty\"`\n}\n\n// Inlay hint options used during static registration.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#inlayHintOptions\ntype InlayHintOptions struct {\n\t// The server provides support to resolve additional\n\t// information for an inlay hint item.\n\tResolveProvider bool `json:\"resolveProvider,omitempty\"`\n\tWorkDoneProgressOptions\n}\n\n// A parameter literal used in inlay hint requests.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#inlayHintParams\ntype InlayHintParams struct {\n\t// The text document.\n\tTextDocument TextDocumentIdentifier `json:\"textDocument\"`\n\t// The document range for which inlay hints should be computed.\n\tRange Range `json:\"range\"`\n\tWorkDoneProgressParams\n}\n\n// Inlay hint options used during static or dynamic registration.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#inlayHintRegistrationOptions\ntype InlayHintRegistrationOptions struct {\n\tInlayHintOptions\n\tTextDocumentRegistrationOptions\n\tStaticRegistrationOptions\n}\n\n// Client workspace capabilities specific to inlay hints.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#inlayHintWorkspaceClientCapabilities\ntype InlayHintWorkspaceClientCapabilities struct {\n\t// Whether the client implementation supports a refresh request sent from\n\t// the server to the client.\n\t//\n\t// Note that this event is global and will force the client to refresh all\n\t// inlay hints currently shown. It should be used with absolute care and\n\t// is useful for situation where a server for example detects a project wide\n\t// change that requires such a calculation.\n\tRefreshSupport bool `json:\"refreshSupport,omitempty\"`\n}\n\n// Client capabilities specific to inline completions.\n//\n// @since 3.18.0\n// @proposed\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#inlineCompletionClientCapabilities\ntype InlineCompletionClientCapabilities struct {\n\t// Whether implementation supports dynamic registration for inline completion providers.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n}\n\n// Provides information about the context in which an inline completion was requested.\n//\n// @since 3.18.0\n// @proposed\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#inlineCompletionContext\ntype InlineCompletionContext struct {\n\t// Describes how the inline completion was triggered.\n\tTriggerKind InlineCompletionTriggerKind `json:\"triggerKind\"`\n\t// Provides information about the currently selected item in the autocomplete widget if it is visible.\n\tSelectedCompletionInfo *SelectedCompletionInfo `json:\"selectedCompletionInfo,omitempty\"`\n}\n\n// An inline completion item represents a text snippet that is proposed inline to complete text that is being typed.\n//\n// @since 3.18.0\n// @proposed\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#inlineCompletionItem\ntype InlineCompletionItem struct {\n\t// The text to replace the range with. Must be set.\n\tInsertText Or_InlineCompletionItem_insertText `json:\"insertText\"`\n\t// A text that is used to decide if this inline completion should be shown. When `falsy` the {@link InlineCompletionItem.insertText} is used.\n\tFilterText string `json:\"filterText,omitempty\"`\n\t// The range to replace. Must begin and end on the same line.\n\tRange *Range `json:\"range,omitempty\"`\n\t// An optional {@link Command} that is executed *after* inserting this completion.\n\tCommand *Command `json:\"command,omitempty\"`\n}\n\n// Represents a collection of {@link InlineCompletionItem inline completion items} to be presented in the editor.\n//\n// @since 3.18.0\n// @proposed\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#inlineCompletionList\ntype InlineCompletionList struct {\n\t// The inline completion items\n\tItems []InlineCompletionItem `json:\"items\"`\n}\n\n// Inline completion options used during static registration.\n//\n// @since 3.18.0\n// @proposed\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#inlineCompletionOptions\ntype InlineCompletionOptions struct {\n\tWorkDoneProgressOptions\n}\n\n// A parameter literal used in inline completion requests.\n//\n// @since 3.18.0\n// @proposed\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#inlineCompletionParams\ntype InlineCompletionParams struct {\n\t// Additional information about the context in which inline completions were\n\t// requested.\n\tContext InlineCompletionContext `json:\"context\"`\n\tTextDocumentPositionParams\n\tWorkDoneProgressParams\n}\n\n// Inline completion options used during static or dynamic registration.\n//\n// @since 3.18.0\n// @proposed\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#inlineCompletionRegistrationOptions\ntype InlineCompletionRegistrationOptions struct {\n\tInlineCompletionOptions\n\tTextDocumentRegistrationOptions\n\tStaticRegistrationOptions\n}\n\n// Describes how an {@link InlineCompletionItemProvider inline completion provider} was triggered.\n//\n// @since 3.18.0\n// @proposed\ntype InlineCompletionTriggerKind uint32\n\n// Inline value information can be provided by different means:\n//\n// - directly as a text value (class InlineValueText).\n// - as a name to use for a variable lookup (class InlineValueVariableLookup)\n// - as an evaluatable expression (class InlineValueEvaluatableExpression)\n//\n// The InlineValue types combines all inline value types into one type.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#inlineValue\ntype InlineValue = Or_InlineValue // (alias)\n// Client capabilities specific to inline values.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#inlineValueClientCapabilities\ntype InlineValueClientCapabilities struct {\n\t// Whether implementation supports dynamic registration for inline value providers.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n}\n\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#inlineValueContext\ntype InlineValueContext struct {\n\t// The stack frame (as a DAP Id) where the execution has stopped.\n\tFrameID int32 `json:\"frameId\"`\n\t// The document range where execution has stopped.\n\t// Typically the end position of the range denotes the line where the inline values are shown.\n\tStoppedLocation Range `json:\"stoppedLocation\"`\n}\n\n// Provide an inline value through an expression evaluation.\n// If only a range is specified, the expression will be extracted from the underlying document.\n// An optional expression can be used to override the extracted expression.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#inlineValueEvaluatableExpression\ntype InlineValueEvaluatableExpression struct {\n\t// The document range for which the inline value applies.\n\t// The range is used to extract the evaluatable expression from the underlying document.\n\tRange Range `json:\"range\"`\n\t// If specified the expression overrides the extracted expression.\n\tExpression string `json:\"expression,omitempty\"`\n}\n\n// Inline value options used during static registration.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#inlineValueOptions\ntype InlineValueOptions struct {\n\tWorkDoneProgressOptions\n}\n\n// A parameter literal used in inline value requests.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#inlineValueParams\ntype InlineValueParams struct {\n\t// The text document.\n\tTextDocument TextDocumentIdentifier `json:\"textDocument\"`\n\t// The document range for which inline values should be computed.\n\tRange Range `json:\"range\"`\n\t// Additional information about the context in which inline values were\n\t// requested.\n\tContext InlineValueContext `json:\"context\"`\n\tWorkDoneProgressParams\n}\n\n// Inline value options used during static or dynamic registration.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#inlineValueRegistrationOptions\ntype InlineValueRegistrationOptions struct {\n\tInlineValueOptions\n\tTextDocumentRegistrationOptions\n\tStaticRegistrationOptions\n}\n\n// Provide inline value as text.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#inlineValueText\ntype InlineValueText struct {\n\t// The document range for which the inline value applies.\n\tRange Range `json:\"range\"`\n\t// The text of the inline value.\n\tText string `json:\"text\"`\n}\n\n// Provide inline value through a variable lookup.\n// If only a range is specified, the variable name will be extracted from the underlying document.\n// An optional variable name can be used to override the extracted name.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#inlineValueVariableLookup\ntype InlineValueVariableLookup struct {\n\t// The document range for which the inline value applies.\n\t// The range is used to extract the variable name from the underlying document.\n\tRange Range `json:\"range\"`\n\t// If specified the name of the variable to look up.\n\tVariableName string `json:\"variableName,omitempty\"`\n\t// How to perform the lookup.\n\tCaseSensitiveLookup bool `json:\"caseSensitiveLookup\"`\n}\n\n// Client workspace capabilities specific to inline values.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#inlineValueWorkspaceClientCapabilities\ntype InlineValueWorkspaceClientCapabilities struct {\n\t// Whether the client implementation supports a refresh request sent from the\n\t// server to the client.\n\t//\n\t// Note that this event is global and will force the client to refresh all\n\t// inline values currently shown. It should be used with absolute care and is\n\t// useful for situation where a server for example detects a project wide\n\t// change that requires such a calculation.\n\tRefreshSupport bool `json:\"refreshSupport,omitempty\"`\n}\n\n// A special text edit to provide an insert and a replace operation.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#insertReplaceEdit\ntype InsertReplaceEdit struct {\n\t// The string to be inserted.\n\tNewText string `json:\"newText\"`\n\t// The range if the insert is requested\n\tInsert Range `json:\"insert\"`\n\t// The range if the replace is requested.\n\tReplace Range `json:\"replace\"`\n}\n\n// Defines whether the insert text in a completion item should be interpreted as\n// plain text or a snippet.\ntype InsertTextFormat uint32\n\n// How whitespace and indentation is handled during completion\n// item insertion.\n//\n// @since 3.16.0\ntype InsertTextMode uint32\ntype LSPAny = interface{}\n\n// LSP arrays.\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#lSPArray\ntype LSPArray = []interface{} // (alias)\ntype LSPErrorCodes int32\n\n// LSP object definition.\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#lSPObject\ntype LSPObject = map[string]LSPAny // (alias)\n// Predefined Language kinds\n// @since 3.18.0\n// @proposed\ntype LanguageKind string\n\n// Client capabilities for the linked editing range request.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#linkedEditingRangeClientCapabilities\ntype LinkedEditingRangeClientCapabilities struct {\n\t// Whether implementation supports dynamic registration. If this is set to `true`\n\t// the client supports the new `(TextDocumentRegistrationOptions & StaticRegistrationOptions)`\n\t// return value for the corresponding server capability as well.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#linkedEditingRangeOptions\ntype LinkedEditingRangeOptions struct {\n\tWorkDoneProgressOptions\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#linkedEditingRangeParams\ntype LinkedEditingRangeParams struct {\n\tTextDocumentPositionParams\n\tWorkDoneProgressParams\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#linkedEditingRangeRegistrationOptions\ntype LinkedEditingRangeRegistrationOptions struct {\n\tTextDocumentRegistrationOptions\n\tLinkedEditingRangeOptions\n\tStaticRegistrationOptions\n}\n\n// The result of a linked editing range request.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#linkedEditingRanges\ntype LinkedEditingRanges struct {\n\t// A list of ranges that can be edited together. The ranges must have\n\t// identical length and contain identical text content. The ranges cannot overlap.\n\tRanges []Range `json:\"ranges\"`\n\t// An optional word pattern (regular expression) that describes valid contents for\n\t// the given ranges. If no pattern is provided, the client configuration's word\n\t// pattern will be used.\n\tWordPattern string `json:\"wordPattern,omitempty\"`\n}\n\n// created for Literal (Lit_ClientSemanticTokensRequestOptions_range_Item1)\ntype Lit_ClientSemanticTokensRequestOptions_range_Item1 struct {\n}\n\n// created for Literal (Lit_SemanticTokensOptions_range_Item1)\ntype Lit_SemanticTokensOptions_range_Item1 struct {\n}\n\n// Represents a location inside a resource, such as a line\n// inside a text file.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#location\ntype Location struct {\n\tURI DocumentUri `json:\"uri\"`\n\tRange Range `json:\"range\"`\n}\n\n// Represents the connection of two locations. Provides additional metadata over normal {@link Location locations},\n// including an origin range.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#locationLink\ntype LocationLink struct {\n\t// Span of the origin of this link.\n\t//\n\t// Used as the underlined span for mouse interaction. Defaults to the word range at\n\t// the definition position.\n\tOriginSelectionRange *Range `json:\"originSelectionRange,omitempty\"`\n\t// The target resource identifier of this link.\n\tTargetURI DocumentUri `json:\"targetUri\"`\n\t// The full target range of this link. If the target for example is a symbol then target range is the\n\t// range enclosing this symbol not including leading/trailing whitespace but everything else\n\t// like comments. This information is typically used to highlight the range in the editor.\n\tTargetRange Range `json:\"targetRange\"`\n\t// The range that should be selected and revealed when this link is being followed, e.g the name of a function.\n\t// Must be contained by the `targetRange`. See also `DocumentSymbol#range`\n\tTargetSelectionRange Range `json:\"targetSelectionRange\"`\n}\n\n// Location with only uri and does not include range.\n//\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#locationUriOnly\ntype LocationUriOnly struct {\n\tURI DocumentUri `json:\"uri\"`\n}\n\n// The log message parameters.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#logMessageParams\ntype LogMessageParams struct {\n\t// The message type. See {@link MessageType}\n\tType MessageType `json:\"type\"`\n\t// The actual message.\n\tMessage string `json:\"message\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#logTraceParams\ntype LogTraceParams struct {\n\tMessage string `json:\"message\"`\n\tVerbose string `json:\"verbose,omitempty\"`\n}\n\n// Client capabilities specific to the used markdown parser.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#markdownClientCapabilities\ntype MarkdownClientCapabilities struct {\n\t// The name of the parser.\n\tParser string `json:\"parser\"`\n\t// The version of the parser.\n\tVersion string `json:\"version,omitempty\"`\n\t// A list of HTML tags that the client allows / supports in\n\t// Markdown.\n\t//\n\t// @since 3.17.0\n\tAllowedTags []string `json:\"allowedTags,omitempty\"`\n}\n\n// MarkedString can be used to render human readable text. It is either a markdown string\n// or a code-block that provides a language and a code snippet. The language identifier\n// is semantically equal to the optional language identifier in fenced code blocks in GitHub\n// issues. See https://help.github.com/articles/creating-and-highlighting-code-blocks/#syntax-highlighting\n//\n// The pair of a language and a value is an equivalent to markdown:\n// ```${language}\n// ${value}\n// ```\n//\n// Note that markdown strings will be sanitized - that means html will be escaped.\n// @deprecated use MarkupContent instead.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#markedString\ntype MarkedString = Or_MarkedString // (alias)\n// @since 3.18.0\n// @deprecated use MarkupContent instead.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#markedStringWithLanguage\ntype MarkedStringWithLanguage struct {\n\tLanguage string `json:\"language\"`\n\tValue string `json:\"value\"`\n}\n\n// A `MarkupContent` literal represents a string value which content is interpreted base on its\n// kind flag. Currently the protocol supports `plaintext` and `markdown` as markup kinds.\n//\n// If the kind is `markdown` then the value can contain fenced code blocks like in GitHub issues.\n// See https://help.github.com/articles/creating-and-highlighting-code-blocks/#syntax-highlighting\n//\n// Here is an example how such a string can be constructed using JavaScript / TypeScript:\n// ```ts\n//\n//\tlet markdown: MarkdownContent = {\n//\t kind: MarkupKind.Markdown,\n//\t value: [\n//\t '# Header',\n//\t 'Some text',\n//\t '```typescript',\n//\t 'someCode();',\n//\t '```'\n//\t ].join('\\n')\n//\t};\n//\n// ```\n//\n// *Please Note* that clients might sanitize the return markdown. A client could decide to\n// remove HTML from the markdown to avoid script execution.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#markupContent\ntype MarkupContent struct {\n\t// The type of the Markup\n\tKind MarkupKind `json:\"kind\"`\n\t// The content itself\n\tValue string `json:\"value\"`\n}\n\n// Describes the content type that a client supports in various\n// result literals like `Hover`, `ParameterInfo` or `CompletionItem`.\n//\n// Please note that `MarkupKinds` must not start with a `$`. This kinds\n// are reserved for internal usage.\ntype MarkupKind string\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#messageActionItem\ntype MessageActionItem struct {\n\t// A short title like 'Retry', 'Open Log' etc.\n\tTitle string `json:\"title\"`\n}\n\n// The message type\ntype MessageType uint32\n\n// Moniker definition to match LSIF 0.5 moniker definition.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#moniker\ntype Moniker struct {\n\t// The scheme of the moniker. For example tsc or .Net\n\tScheme string `json:\"scheme\"`\n\t// The identifier of the moniker. The value is opaque in LSIF however\n\t// schema owners are allowed to define the structure if they want.\n\tIdentifier string `json:\"identifier\"`\n\t// The scope in which the moniker is unique\n\tUnique UniquenessLevel `json:\"unique\"`\n\t// The moniker kind if known.\n\tKind *MonikerKind `json:\"kind,omitempty\"`\n}\n\n// Client capabilities specific to the moniker request.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#monikerClientCapabilities\ntype MonikerClientCapabilities struct {\n\t// Whether moniker supports dynamic registration. If this is set to `true`\n\t// the client supports the new `MonikerRegistrationOptions` return value\n\t// for the corresponding server capability as well.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n}\n\n// The moniker kind.\n//\n// @since 3.16.0\ntype MonikerKind string\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#monikerOptions\ntype MonikerOptions struct {\n\tWorkDoneProgressOptions\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#monikerParams\ntype MonikerParams struct {\n\tTextDocumentPositionParams\n\tWorkDoneProgressParams\n\tPartialResultParams\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#monikerRegistrationOptions\ntype MonikerRegistrationOptions struct {\n\tTextDocumentRegistrationOptions\n\tMonikerOptions\n}\n\n// A notebook cell.\n//\n// A cell's document URI must be unique across ALL notebook\n// cells and can therefore be used to uniquely identify a\n// notebook cell or the cell's text document.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#notebookCell\ntype NotebookCell struct {\n\t// The cell's kind\n\tKind NotebookCellKind `json:\"kind\"`\n\t// The URI of the cell's text document\n\t// content.\n\tDocument DocumentUri `json:\"document\"`\n\t// Additional metadata stored with the cell.\n\t//\n\t// Note: should always be an object literal (e.g. LSPObject)\n\tMetadata *LSPObject `json:\"metadata,omitempty\"`\n\t// Additional execution summary information\n\t// if supported by the client.\n\tExecutionSummary *ExecutionSummary `json:\"executionSummary,omitempty\"`\n}\n\n// A change describing how to move a `NotebookCell`\n// array from state S to S'.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#notebookCellArrayChange\ntype NotebookCellArrayChange struct {\n\t// The start oftest of the cell that changed.\n\tStart uint32 `json:\"start\"`\n\t// The deleted cells\n\tDeleteCount uint32 `json:\"deleteCount\"`\n\t// The new cells, if any\n\tCells []NotebookCell `json:\"cells,omitempty\"`\n}\n\n// A notebook cell kind.\n//\n// @since 3.17.0\ntype NotebookCellKind uint32\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#notebookCellLanguage\ntype NotebookCellLanguage struct {\n\tLanguage string `json:\"language\"`\n}\n\n// A notebook cell text document filter denotes a cell text\n// document by different properties.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#notebookCellTextDocumentFilter\ntype NotebookCellTextDocumentFilter struct {\n\t// A filter that matches against the notebook\n\t// containing the notebook cell. If a string\n\t// value is provided it matches against the\n\t// notebook type. '*' matches every notebook.\n\tNotebook Or_NotebookCellTextDocumentFilter_notebook `json:\"notebook\"`\n\t// A language id like `python`.\n\t//\n\t// Will be matched against the language id of the\n\t// notebook cell document. '*' matches every language.\n\tLanguage string `json:\"language,omitempty\"`\n}\n\n// A notebook document.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#notebookDocument\ntype NotebookDocument struct {\n\t// The notebook document's uri.\n\tURI URI `json:\"uri\"`\n\t// The type of the notebook.\n\tNotebookType string `json:\"notebookType\"`\n\t// The version number of this document (it will increase after each\n\t// change, including undo/redo).\n\tVersion int32 `json:\"version\"`\n\t// Additional metadata stored with the notebook\n\t// document.\n\t//\n\t// Note: should always be an object literal (e.g. LSPObject)\n\tMetadata *LSPObject `json:\"metadata,omitempty\"`\n\t// The cells of a notebook.\n\tCells []NotebookCell `json:\"cells\"`\n}\n\n// Structural changes to cells in a notebook document.\n//\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#notebookDocumentCellChangeStructure\ntype NotebookDocumentCellChangeStructure struct {\n\t// The change to the cell array.\n\tArray NotebookCellArrayChange `json:\"array\"`\n\t// Additional opened cell text documents.\n\tDidOpen []TextDocumentItem `json:\"didOpen,omitempty\"`\n\t// Additional closed cell text documents.\n\tDidClose []TextDocumentIdentifier `json:\"didClose,omitempty\"`\n}\n\n// Cell changes to a notebook document.\n//\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#notebookDocumentCellChanges\ntype NotebookDocumentCellChanges struct {\n\t// Changes to the cell structure to add or\n\t// remove cells.\n\tStructure *NotebookDocumentCellChangeStructure `json:\"structure,omitempty\"`\n\t// Changes to notebook cells properties like its\n\t// kind, execution summary or metadata.\n\tData []NotebookCell `json:\"data,omitempty\"`\n\t// Changes to the text content of notebook cells.\n\tTextContent []NotebookDocumentCellContentChanges `json:\"textContent,omitempty\"`\n}\n\n// Content changes to a cell in a notebook document.\n//\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#notebookDocumentCellContentChanges\ntype NotebookDocumentCellContentChanges struct {\n\tDocument VersionedTextDocumentIdentifier `json:\"document\"`\n\tChanges []TextDocumentContentChangeEvent `json:\"changes\"`\n}\n\n// A change event for a notebook document.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#notebookDocumentChangeEvent\ntype NotebookDocumentChangeEvent struct {\n\t// The changed meta data if any.\n\t//\n\t// Note: should always be an object literal (e.g. LSPObject)\n\tMetadata *LSPObject `json:\"metadata,omitempty\"`\n\t// Changes to cells\n\tCells *NotebookDocumentCellChanges `json:\"cells,omitempty\"`\n}\n\n// Capabilities specific to the notebook document support.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#notebookDocumentClientCapabilities\ntype NotebookDocumentClientCapabilities struct {\n\t// Capabilities specific to notebook document synchronization\n\t//\n\t// @since 3.17.0\n\tSynchronization NotebookDocumentSyncClientCapabilities `json:\"synchronization\"`\n}\n\n// A notebook document filter denotes a notebook document by\n// different properties. The properties will be match\n// against the notebook's URI (same as with documents)\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#notebookDocumentFilter\ntype NotebookDocumentFilter = Or_NotebookDocumentFilter // (alias)\n// A notebook document filter where `notebookType` is required field.\n//\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#notebookDocumentFilterNotebookType\ntype NotebookDocumentFilterNotebookType struct {\n\t// The type of the enclosing notebook.\n\tNotebookType string `json:\"notebookType\"`\n\t// A Uri {@link Uri.scheme scheme}, like `file` or `untitled`.\n\tScheme string `json:\"scheme,omitempty\"`\n\t// A glob pattern.\n\tPattern *GlobPattern `json:\"pattern,omitempty\"`\n}\n\n// A notebook document filter where `pattern` is required field.\n//\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#notebookDocumentFilterPattern\ntype NotebookDocumentFilterPattern struct {\n\t// The type of the enclosing notebook.\n\tNotebookType string `json:\"notebookType,omitempty\"`\n\t// A Uri {@link Uri.scheme scheme}, like `file` or `untitled`.\n\tScheme string `json:\"scheme,omitempty\"`\n\t// A glob pattern.\n\tPattern GlobPattern `json:\"pattern\"`\n}\n\n// A notebook document filter where `scheme` is required field.\n//\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#notebookDocumentFilterScheme\ntype NotebookDocumentFilterScheme struct {\n\t// The type of the enclosing notebook.\n\tNotebookType string `json:\"notebookType,omitempty\"`\n\t// A Uri {@link Uri.scheme scheme}, like `file` or `untitled`.\n\tScheme string `json:\"scheme\"`\n\t// A glob pattern.\n\tPattern *GlobPattern `json:\"pattern,omitempty\"`\n}\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#notebookDocumentFilterWithCells\ntype NotebookDocumentFilterWithCells struct {\n\t// The notebook to be synced If a string\n\t// value is provided it matches against the\n\t// notebook type. '*' matches every notebook.\n\tNotebook *Or_NotebookDocumentFilterWithCells_notebook `json:\"notebook,omitempty\"`\n\t// The cells of the matching notebook to be synced.\n\tCells []NotebookCellLanguage `json:\"cells\"`\n}\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#notebookDocumentFilterWithNotebook\ntype NotebookDocumentFilterWithNotebook struct {\n\t// The notebook to be synced If a string\n\t// value is provided it matches against the\n\t// notebook type. '*' matches every notebook.\n\tNotebook Or_NotebookDocumentFilterWithNotebook_notebook `json:\"notebook\"`\n\t// The cells of the matching notebook to be synced.\n\tCells []NotebookCellLanguage `json:\"cells,omitempty\"`\n}\n\n// A literal to identify a notebook document in the client.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#notebookDocumentIdentifier\ntype NotebookDocumentIdentifier struct {\n\t// The notebook document's uri.\n\tURI URI `json:\"uri\"`\n}\n\n// Notebook specific client capabilities.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#notebookDocumentSyncClientCapabilities\ntype NotebookDocumentSyncClientCapabilities struct {\n\t// Whether implementation supports dynamic registration. If this is\n\t// set to `true` the client supports the new\n\t// `(TextDocumentRegistrationOptions & StaticRegistrationOptions)`\n\t// return value for the corresponding server capability as well.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n\t// The client supports sending execution summary data per cell.\n\tExecutionSummarySupport bool `json:\"executionSummarySupport,omitempty\"`\n}\n\n// Options specific to a notebook plus its cells\n// to be synced to the server.\n//\n// If a selector provides a notebook document\n// filter but no cell selector all cells of a\n// matching notebook document will be synced.\n//\n// If a selector provides no notebook document\n// filter but only a cell selector all notebook\n// document that contain at least one matching\n// cell will be synced.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#notebookDocumentSyncOptions\ntype NotebookDocumentSyncOptions struct {\n\t// The notebooks to be synced\n\tNotebookSelector []Or_NotebookDocumentSyncOptions_notebookSelector_Elem `json:\"notebookSelector\"`\n\t// Whether save notification should be forwarded to\n\t// the server. Will only be honored if mode === `notebook`.\n\tSave bool `json:\"save,omitempty\"`\n}\n\n// Registration options specific to a notebook.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#notebookDocumentSyncRegistrationOptions\ntype NotebookDocumentSyncRegistrationOptions struct {\n\tNotebookDocumentSyncOptions\n\tStaticRegistrationOptions\n}\n\n// A text document identifier to optionally denote a specific version of a text document.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#optionalVersionedTextDocumentIdentifier\ntype OptionalVersionedTextDocumentIdentifier struct {\n\t// The version number of this document. If a versioned text document identifier\n\t// is sent from the server to the client and the file is not open in the editor\n\t// (the server has not received an open notification before) the server can send\n\t// `null` to indicate that the version is unknown and the content on disk is the\n\t// truth (as specified with document content ownership).\n\tVersion int32 `json:\"version\"`\n\tTextDocumentIdentifier\n}\n\n// created for Or [int32 string]\ntype Or_CancelParams_id struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [ClientSemanticTokensRequestFullDelta bool]\ntype Or_ClientSemanticTokensRequestOptions_full struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [Lit_ClientSemanticTokensRequestOptions_range_Item1 bool]\ntype Or_ClientSemanticTokensRequestOptions_range struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [EditRangeWithInsertReplace Range]\ntype Or_CompletionItemDefaults_editRange struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [MarkupContent string]\ntype Or_CompletionItem_documentation struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [InsertReplaceEdit TextEdit]\ntype Or_CompletionItem_textEdit struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [Location []Location]\ntype Or_Declaration struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [Location []Location]\ntype Or_Definition struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [int32 string]\ntype Or_Diagnostic_code struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [[]string string]\ntype Or_DidChangeConfigurationRegistrationOptions_section struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [RelatedFullDocumentDiagnosticReport RelatedUnchangedDocumentDiagnosticReport]\ntype Or_DocumentDiagnosticReport struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [FullDocumentDiagnosticReport UnchangedDocumentDiagnosticReport]\ntype Or_DocumentDiagnosticReportPartialResult_relatedDocuments_Value struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [NotebookCellTextDocumentFilter TextDocumentFilter]\ntype Or_DocumentFilter struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [Pattern RelativePattern]\ntype Or_GlobPattern struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [MarkedString MarkupContent []MarkedString]\ntype Or_Hover_contents struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [MarkupContent string]\ntype Or_InlayHintLabelPart_tooltip struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [[]InlayHintLabelPart string]\ntype Or_InlayHint_label struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [MarkupContent string]\ntype Or_InlayHint_tooltip struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [StringValue string]\ntype Or_InlineCompletionItem_insertText struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [InlineValueEvaluatableExpression InlineValueText InlineValueVariableLookup]\ntype Or_InlineValue struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [LSPArray LSPObject bool float64 int32 string uint32]\ntype Or_LSPAny struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [MarkedStringWithLanguage string]\ntype Or_MarkedString struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [NotebookDocumentFilter string]\ntype Or_NotebookCellTextDocumentFilter_notebook struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [NotebookDocumentFilterNotebookType NotebookDocumentFilterPattern NotebookDocumentFilterScheme]\ntype Or_NotebookDocumentFilter struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [NotebookDocumentFilter string]\ntype Or_NotebookDocumentFilterWithCells_notebook struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [NotebookDocumentFilter string]\ntype Or_NotebookDocumentFilterWithNotebook_notebook struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [NotebookDocumentFilterWithCells NotebookDocumentFilterWithNotebook]\ntype Or_NotebookDocumentSyncOptions_notebookSelector_Elem struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [MarkupContent string]\ntype Or_ParameterInformation_documentation struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [Tuple_ParameterInformation_label_Item1 string]\ntype Or_ParameterInformation_label struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [PrepareRenameDefaultBehavior PrepareRenamePlaceholder Range]\ntype Or_PrepareRenameResult struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [int32 string]\ntype Or_ProgressToken struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [FullDocumentDiagnosticReport UnchangedDocumentDiagnosticReport]\ntype Or_RelatedFullDocumentDiagnosticReport_relatedDocuments_Value struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [FullDocumentDiagnosticReport UnchangedDocumentDiagnosticReport]\ntype Or_RelatedUnchangedDocumentDiagnosticReport_relatedDocuments_Value struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [URI WorkspaceFolder]\ntype Or_RelativePattern_baseUri struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [CodeAction Command]\ntype Or_Result_textDocument_codeAction_Item0_Elem struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [CompletionList []CompletionItem]\ntype Or_Result_textDocument_completion struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [Declaration []DeclarationLink]\ntype Or_Result_textDocument_declaration struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [Definition []DefinitionLink]\ntype Or_Result_textDocument_definition struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [[]DocumentSymbol []SymbolInformation]\ntype Or_Result_textDocument_documentSymbol struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [Definition []DefinitionLink]\ntype Or_Result_textDocument_implementation struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [InlineCompletionList []InlineCompletionItem]\ntype Or_Result_textDocument_inlineCompletion struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [SemanticTokens SemanticTokensDelta]\ntype Or_Result_textDocument_semanticTokens_full_delta struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [Definition []DefinitionLink]\ntype Or_Result_textDocument_typeDefinition struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [[]SymbolInformation []WorkspaceSymbol]\ntype Or_Result_workspace_symbol struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [SemanticTokensFullDelta bool]\ntype Or_SemanticTokensOptions_full struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [Lit_SemanticTokensOptions_range_Item1 bool]\ntype Or_SemanticTokensOptions_range struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [CallHierarchyOptions CallHierarchyRegistrationOptions bool]\ntype Or_ServerCapabilities_callHierarchyProvider struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [CodeActionOptions bool]\ntype Or_ServerCapabilities_codeActionProvider struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [DocumentColorOptions DocumentColorRegistrationOptions bool]\ntype Or_ServerCapabilities_colorProvider struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [DeclarationOptions DeclarationRegistrationOptions bool]\ntype Or_ServerCapabilities_declarationProvider struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [DefinitionOptions bool]\ntype Or_ServerCapabilities_definitionProvider struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [DiagnosticOptions DiagnosticRegistrationOptions]\ntype Or_ServerCapabilities_diagnosticProvider struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [DocumentFormattingOptions bool]\ntype Or_ServerCapabilities_documentFormattingProvider struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [DocumentHighlightOptions bool]\ntype Or_ServerCapabilities_documentHighlightProvider struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [DocumentRangeFormattingOptions bool]\ntype Or_ServerCapabilities_documentRangeFormattingProvider struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [DocumentSymbolOptions bool]\ntype Or_ServerCapabilities_documentSymbolProvider struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [FoldingRangeOptions FoldingRangeRegistrationOptions bool]\ntype Or_ServerCapabilities_foldingRangeProvider struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [HoverOptions bool]\ntype Or_ServerCapabilities_hoverProvider struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [ImplementationOptions ImplementationRegistrationOptions bool]\ntype Or_ServerCapabilities_implementationProvider struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [InlayHintOptions InlayHintRegistrationOptions bool]\ntype Or_ServerCapabilities_inlayHintProvider struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [InlineCompletionOptions bool]\ntype Or_ServerCapabilities_inlineCompletionProvider struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [InlineValueOptions InlineValueRegistrationOptions bool]\ntype Or_ServerCapabilities_inlineValueProvider struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [LinkedEditingRangeOptions LinkedEditingRangeRegistrationOptions bool]\ntype Or_ServerCapabilities_linkedEditingRangeProvider struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [MonikerOptions MonikerRegistrationOptions bool]\ntype Or_ServerCapabilities_monikerProvider struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [NotebookDocumentSyncOptions NotebookDocumentSyncRegistrationOptions]\ntype Or_ServerCapabilities_notebookDocumentSync struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [ReferenceOptions bool]\ntype Or_ServerCapabilities_referencesProvider struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [RenameOptions bool]\ntype Or_ServerCapabilities_renameProvider struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [SelectionRangeOptions SelectionRangeRegistrationOptions bool]\ntype Or_ServerCapabilities_selectionRangeProvider struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [SemanticTokensOptions SemanticTokensRegistrationOptions]\ntype Or_ServerCapabilities_semanticTokensProvider struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [TextDocumentSyncKind TextDocumentSyncOptions]\ntype Or_ServerCapabilities_textDocumentSync struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [TypeDefinitionOptions TypeDefinitionRegistrationOptions bool]\ntype Or_ServerCapabilities_typeDefinitionProvider struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [TypeHierarchyOptions TypeHierarchyRegistrationOptions bool]\ntype Or_ServerCapabilities_typeHierarchyProvider struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [WorkspaceSymbolOptions bool]\ntype Or_ServerCapabilities_workspaceSymbolProvider struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [MarkupContent string]\ntype Or_SignatureInformation_documentation struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [TextDocumentContentChangePartial TextDocumentContentChangeWholeDocument]\ntype Or_TextDocumentContentChangeEvent struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [AnnotatedTextEdit SnippetTextEdit TextEdit]\ntype Or_TextDocumentEdit_edits_Elem struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [TextDocumentFilterLanguage TextDocumentFilterPattern TextDocumentFilterScheme]\ntype Or_TextDocumentFilter struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [SaveOptions bool]\ntype Or_TextDocumentSyncOptions_save struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [WorkspaceFullDocumentDiagnosticReport WorkspaceUnchangedDocumentDiagnosticReport]\ntype Or_WorkspaceDocumentDiagnosticReport struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [CreateFile DeleteFile RenameFile TextDocumentEdit]\ntype Or_WorkspaceEdit_documentChanges_Elem struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [bool string]\ntype Or_WorkspaceFoldersServerCapabilities_changeNotifications struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [TextDocumentContentOptions TextDocumentContentRegistrationOptions]\ntype Or_WorkspaceOptions_textDocumentContent struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// created for Or [Location LocationUriOnly]\ntype Or_WorkspaceSymbol_location struct {\n\tValue interface{} `json:\"value\"`\n}\n\n// The parameters of a configuration request.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#configurationParams\ntype ParamConfiguration struct {\n\tItems []ConfigurationItem `json:\"items\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#initializeParams\ntype ParamInitialize struct {\n\tXInitializeParams\n\tWorkspaceFoldersInitializeParams\n}\n\n// Represents a parameter of a callable-signature. A parameter can\n// have a label and a doc-comment.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#parameterInformation\ntype ParameterInformation struct {\n\t// The label of this parameter information.\n\t//\n\t// Either a string or an inclusive start and exclusive end offsets within its containing\n\t// signature label. (see SignatureInformation.label). The offsets are based on a UTF-16\n\t// string representation as `Position` and `Range` does.\n\t//\n\t// To avoid ambiguities a server should use the [start, end] offset value instead of using\n\t// a substring. Whether a client support this is controlled via `labelOffsetSupport` client\n\t// capability.\n\t//\n\t// *Note*: a label of type string should be a substring of its containing signature label.\n\t// Its intended use case is to highlight the parameter label part in the `SignatureInformation.label`.\n\tLabel Or_ParameterInformation_label `json:\"label\"`\n\t// The human-readable doc-comment of this parameter. Will be shown\n\t// in the UI but can be omitted.\n\tDocumentation *Or_ParameterInformation_documentation `json:\"documentation,omitempty\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#partialResultParams\ntype PartialResultParams struct {\n\t// An optional token that a server can use to report partial results (e.g. streaming) to\n\t// the client.\n\tPartialResultToken *ProgressToken `json:\"partialResultToken,omitempty\"`\n}\n\n// The glob pattern to watch relative to the base path. Glob patterns can have the following syntax:\n//\n// - `*` to match one or more characters in a path segment\n// - `?` to match on one character in a path segment\n// - `**` to match any number of path segments, including none\n// - `{}` to group conditions (e.g. `**/*.{ts,js}` matches all TypeScript and JavaScript files)\n// - `[]` to declare a range of characters to match in a path segment (e.g., `example.[0-9]` to match on `example.0`, `example.1`, …)\n// - `[!...]` to negate a range of characters to match in a path segment (e.g., `example.[!0-9]` to match on `example.a`, `example.b`, but not `example.0`)\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#pattern\ntype Pattern = string // (alias)\n// Position in a text document expressed as zero-based line and character\n// offset. Prior to 3.17 the offsets were always based on a UTF-16 string\n// representation. So a string of the form `a𐐀b` the character offset of the\n// character `a` is 0, the character offset of `𐐀` is 1 and the character\n// offset of b is 3 since `𐐀` is represented using two code units in UTF-16.\n// Since 3.17 clients and servers can agree on a different string encoding\n// representation (e.g. UTF-8). The client announces it's supported encoding\n// via the client capability [`general.positionEncodings`](https://microsoft.github.io/language-server-protocol/specifications/specification-current/#clientCapabilities).\n// The value is an array of position encodings the client supports, with\n// decreasing preference (e.g. the encoding at index `0` is the most preferred\n// one). To stay backwards compatible the only mandatory encoding is UTF-16\n// represented via the string `utf-16`. The server can pick one of the\n// encodings offered by the client and signals that encoding back to the\n// client via the initialize result's property\n// [`capabilities.positionEncoding`](https://microsoft.github.io/language-server-protocol/specifications/specification-current/#serverCapabilities). If the string value\n// `utf-16` is missing from the client's capability `general.positionEncodings`\n// servers can safely assume that the client supports UTF-16. If the server\n// omits the position encoding in its initialize result the encoding defaults\n// to the string value `utf-16`. Implementation considerations: since the\n// conversion from one encoding into another requires the content of the\n// file / line the conversion is best done where the file is read which is\n// usually on the server side.\n//\n// Positions are line end character agnostic. So you can not specify a position\n// that denotes `\\r|\\n` or `\\n|` where `|` represents the character offset.\n//\n// @since 3.17.0 - support for negotiated position encoding.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#position\ntype Position struct {\n\t// Line position in a document (zero-based).\n\t//\n\t// If a line number is greater than the number of lines in a document, it defaults back to the number of lines in the document.\n\t// If a line number is negative, it defaults to 0.\n\tLine uint32 `json:\"line\"`\n\t// Character offset on a line in a document (zero-based).\n\t//\n\t// The meaning of this offset is determined by the negotiated\n\t// `PositionEncodingKind`.\n\t//\n\t// If the character value is greater than the line length it defaults back to the\n\t// line length.\n\tCharacter uint32 `json:\"character\"`\n}\n\n// A set of predefined position encoding kinds.\n//\n// @since 3.17.0\ntype PositionEncodingKind string\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#prepareRenameDefaultBehavior\ntype PrepareRenameDefaultBehavior struct {\n\tDefaultBehavior bool `json:\"defaultBehavior\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#prepareRenameParams\ntype PrepareRenameParams struct {\n\tTextDocumentPositionParams\n\tWorkDoneProgressParams\n}\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#prepareRenamePlaceholder\ntype PrepareRenamePlaceholder struct {\n\tRange Range `json:\"range\"`\n\tPlaceholder string `json:\"placeholder\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#prepareRenameResult\ntype PrepareRenameResult = Or_PrepareRenameResult // (alias)\ntype PrepareSupportDefaultBehavior uint32\n\n// A previous result id in a workspace pull request.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#previousResultId\ntype PreviousResultID struct {\n\t// The URI for which the client knowns a\n\t// result id.\n\tURI DocumentUri `json:\"uri\"`\n\t// The value of the previous result id.\n\tValue string `json:\"value\"`\n}\n\n// A previous result id in a workspace pull request.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#previousResultId\ntype PreviousResultId struct {\n\t// The URI for which the client knowns a\n\t// result id.\n\tURI DocumentUri `json:\"uri\"`\n\t// The value of the previous result id.\n\tValue string `json:\"value\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#progressParams\ntype ProgressParams struct {\n\t// The progress token provided by the client or server.\n\tToken ProgressToken `json:\"token\"`\n\t// The progress data.\n\tValue interface{} `json:\"value\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#progressToken\ntype ProgressToken = Or_ProgressToken // (alias)\n// The publish diagnostic client capabilities.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#publishDiagnosticsClientCapabilities\ntype PublishDiagnosticsClientCapabilities struct {\n\t// Whether the client interprets the version property of the\n\t// `textDocument/publishDiagnostics` notification's parameter.\n\t//\n\t// @since 3.15.0\n\tVersionSupport bool `json:\"versionSupport,omitempty\"`\n\tDiagnosticsCapabilities\n}\n\n// The publish diagnostic notification's parameters.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#publishDiagnosticsParams\ntype PublishDiagnosticsParams struct {\n\t// The URI for which diagnostic information is reported.\n\tURI DocumentUri `json:\"uri\"`\n\t// Optional the version number of the document the diagnostics are published for.\n\t//\n\t// @since 3.15.0\n\tVersion int32 `json:\"version,omitempty\"`\n\t// An array of diagnostic information items.\n\tDiagnostics []Diagnostic `json:\"diagnostics\"`\n}\n\n// A range in a text document expressed as (zero-based) start and end positions.\n//\n// If you want to specify a range that contains a line including the line ending\n// character(s) then use an end position denoting the start of the next line.\n// For example:\n// ```ts\n//\n//\t{\n//\t start: { line: 5, character: 23 }\n//\t end : { line 6, character : 0 }\n//\t}\n//\n// ```\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#range\ntype Range struct {\n\t// The range's start position.\n\tStart Position `json:\"start\"`\n\t// The range's end position.\n\tEnd Position `json:\"end\"`\n}\n\n// Client Capabilities for a {@link ReferencesRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#referenceClientCapabilities\ntype ReferenceClientCapabilities struct {\n\t// Whether references supports dynamic registration.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n}\n\n// Value-object that contains additional information when\n// requesting references.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#referenceContext\ntype ReferenceContext struct {\n\t// Include the declaration of the current symbol.\n\tIncludeDeclaration bool `json:\"includeDeclaration\"`\n}\n\n// Reference options.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#referenceOptions\ntype ReferenceOptions struct {\n\tWorkDoneProgressOptions\n}\n\n// Parameters for a {@link ReferencesRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#referenceParams\ntype ReferenceParams struct {\n\tContext ReferenceContext `json:\"context\"`\n\tTextDocumentPositionParams\n\tWorkDoneProgressParams\n\tPartialResultParams\n}\n\n// Registration options for a {@link ReferencesRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#referenceRegistrationOptions\ntype ReferenceRegistrationOptions struct {\n\tTextDocumentRegistrationOptions\n\tReferenceOptions\n}\n\n// General parameters to register for a notification or to register a provider.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#registration\ntype Registration struct {\n\t// The id used to register the request. The id can be used to deregister\n\t// the request again.\n\tID string `json:\"id\"`\n\t// The method / capability to register for.\n\tMethod string `json:\"method\"`\n\t// Options necessary for the registration.\n\tRegisterOptions interface{} `json:\"registerOptions,omitempty\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#registrationParams\ntype RegistrationParams struct {\n\tRegistrations []Registration `json:\"registrations\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#regularExpressionEngineKind\ntype RegularExpressionEngineKind = string // (alias)\n// Client capabilities specific to regular expressions.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#regularExpressionsClientCapabilities\ntype RegularExpressionsClientCapabilities struct {\n\t// The engine's name.\n\tEngine RegularExpressionEngineKind `json:\"engine\"`\n\t// The engine's version.\n\tVersion string `json:\"version,omitempty\"`\n}\n\n// A full diagnostic report with a set of related documents.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#relatedFullDocumentDiagnosticReport\ntype RelatedFullDocumentDiagnosticReport struct {\n\t// Diagnostics of related documents. This information is useful\n\t// in programming languages where code in a file A can generate\n\t// diagnostics in a file B which A depends on. An example of\n\t// such a language is C/C++ where marco definitions in a file\n\t// a.cpp and result in errors in a header file b.hpp.\n\t//\n\t// @since 3.17.0\n\tRelatedDocuments map[DocumentUri]interface{} `json:\"relatedDocuments,omitempty\"`\n\tFullDocumentDiagnosticReport\n}\n\n// An unchanged diagnostic report with a set of related documents.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#relatedUnchangedDocumentDiagnosticReport\ntype RelatedUnchangedDocumentDiagnosticReport struct {\n\t// Diagnostics of related documents. This information is useful\n\t// in programming languages where code in a file A can generate\n\t// diagnostics in a file B which A depends on. An example of\n\t// such a language is C/C++ where marco definitions in a file\n\t// a.cpp and result in errors in a header file b.hpp.\n\t//\n\t// @since 3.17.0\n\tRelatedDocuments map[DocumentUri]interface{} `json:\"relatedDocuments,omitempty\"`\n\tUnchangedDocumentDiagnosticReport\n}\n\n// A relative pattern is a helper to construct glob patterns that are matched\n// relatively to a base URI. The common value for a `baseUri` is a workspace\n// folder root, but it can be another absolute URI as well.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#relativePattern\ntype RelativePattern struct {\n\t// A workspace folder or a base URI to which this pattern will be matched\n\t// against relatively.\n\tBaseURI Or_RelativePattern_baseUri `json:\"baseUri\"`\n\t// The actual glob pattern;\n\tPattern Pattern `json:\"pattern\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#renameClientCapabilities\ntype RenameClientCapabilities struct {\n\t// Whether rename supports dynamic registration.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n\t// Client supports testing for validity of rename operations\n\t// before execution.\n\t//\n\t// @since 3.12.0\n\tPrepareSupport bool `json:\"prepareSupport,omitempty\"`\n\t// Client supports the default behavior result.\n\t//\n\t// The value indicates the default behavior used by the\n\t// client.\n\t//\n\t// @since 3.16.0\n\tPrepareSupportDefaultBehavior *PrepareSupportDefaultBehavior `json:\"prepareSupportDefaultBehavior,omitempty\"`\n\t// Whether the client honors the change annotations in\n\t// text edits and resource operations returned via the\n\t// rename request's workspace edit by for example presenting\n\t// the workspace edit in the user interface and asking\n\t// for confirmation.\n\t//\n\t// @since 3.16.0\n\tHonorsChangeAnnotations bool `json:\"honorsChangeAnnotations,omitempty\"`\n}\n\n// Rename file operation\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#renameFile\ntype RenameFile struct {\n\t// A rename\n\tKind string `json:\"kind\"`\n\t// The old (existing) location.\n\tOldURI DocumentUri `json:\"oldUri\"`\n\t// The new location.\n\tNewURI DocumentUri `json:\"newUri\"`\n\t// Rename options.\n\tOptions *RenameFileOptions `json:\"options,omitempty\"`\n\tResourceOperation\n}\n\n// Rename file options\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#renameFileOptions\ntype RenameFileOptions struct {\n\t// Overwrite target if existing. Overwrite wins over `ignoreIfExists`\n\tOverwrite bool `json:\"overwrite,omitempty\"`\n\t// Ignores if target exists.\n\tIgnoreIfExists bool `json:\"ignoreIfExists,omitempty\"`\n}\n\n// The parameters sent in notifications/requests for user-initiated renames of\n// files.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#renameFilesParams\ntype RenameFilesParams struct {\n\t// An array of all files/folders renamed in this operation. When a folder is renamed, only\n\t// the folder will be included, and not its children.\n\tFiles []FileRename `json:\"files\"`\n}\n\n// Provider options for a {@link RenameRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#renameOptions\ntype RenameOptions struct {\n\t// Renames should be checked and tested before being executed.\n\t//\n\t// @since version 3.12.0\n\tPrepareProvider bool `json:\"prepareProvider,omitempty\"`\n\tWorkDoneProgressOptions\n}\n\n// The parameters of a {@link RenameRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#renameParams\ntype RenameParams struct {\n\t// The document to rename.\n\tTextDocument TextDocumentIdentifier `json:\"textDocument\"`\n\t// The position at which this request was sent.\n\tPosition Position `json:\"position\"`\n\t// The new name of the symbol. If the given name is not valid the\n\t// request must return a {@link ResponseError} with an\n\t// appropriate message set.\n\tNewName string `json:\"newName\"`\n\tWorkDoneProgressParams\n}\n\n// Registration options for a {@link RenameRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#renameRegistrationOptions\ntype RenameRegistrationOptions struct {\n\tTextDocumentRegistrationOptions\n\tRenameOptions\n}\n\n// A generic resource operation.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#resourceOperation\ntype ResourceOperation struct {\n\t// The resource operation kind.\n\tKind string `json:\"kind\"`\n\t// An optional annotation identifier describing the operation.\n\t//\n\t// @since 3.16.0\n\tAnnotationID *ChangeAnnotationIdentifier `json:\"annotationId,omitempty\"`\n}\ntype ResourceOperationKind string\n\n// Save options.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#saveOptions\ntype SaveOptions struct {\n\t// The client is supposed to include the content on save.\n\tIncludeText bool `json:\"includeText,omitempty\"`\n}\n\n// Describes the currently selected completion item.\n//\n// @since 3.18.0\n// @proposed\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#selectedCompletionInfo\ntype SelectedCompletionInfo struct {\n\t// The range that will be replaced if this completion item is accepted.\n\tRange Range `json:\"range\"`\n\t// The text the range will be replaced with if this completion is accepted.\n\tText string `json:\"text\"`\n}\n\n// A selection range represents a part of a selection hierarchy. A selection range\n// may have a parent selection range that contains it.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#selectionRange\ntype SelectionRange struct {\n\t// The {@link Range range} of this selection range.\n\tRange Range `json:\"range\"`\n\t// The parent selection range containing this range. Therefore `parent.range` must contain `this.range`.\n\tParent *SelectionRange `json:\"parent,omitempty\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#selectionRangeClientCapabilities\ntype SelectionRangeClientCapabilities struct {\n\t// Whether implementation supports dynamic registration for selection range providers. If this is set to `true`\n\t// the client supports the new `SelectionRangeRegistrationOptions` return value for the corresponding server\n\t// capability as well.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#selectionRangeOptions\ntype SelectionRangeOptions struct {\n\tWorkDoneProgressOptions\n}\n\n// A parameter literal used in selection range requests.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#selectionRangeParams\ntype SelectionRangeParams struct {\n\t// The text document.\n\tTextDocument TextDocumentIdentifier `json:\"textDocument\"`\n\t// The positions inside the text document.\n\tPositions []Position `json:\"positions\"`\n\tWorkDoneProgressParams\n\tPartialResultParams\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#selectionRangeRegistrationOptions\ntype SelectionRangeRegistrationOptions struct {\n\tSelectionRangeOptions\n\tTextDocumentRegistrationOptions\n\tStaticRegistrationOptions\n}\n\n// A set of predefined token modifiers. This set is not fixed\n// an clients can specify additional token types via the\n// corresponding client capabilities.\n//\n// @since 3.16.0\ntype SemanticTokenModifiers string\n\n// A set of predefined token types. This set is not fixed\n// an clients can specify additional token types via the\n// corresponding client capabilities.\n//\n// @since 3.16.0\ntype SemanticTokenTypes string\n\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#semanticTokens\ntype SemanticTokens struct {\n\t// An optional result id. If provided and clients support delta updating\n\t// the client will include the result id in the next semantic token request.\n\t// A server can then instead of computing all semantic tokens again simply\n\t// send a delta.\n\tResultID string `json:\"resultId,omitempty\"`\n\t// The actual tokens.\n\tData []uint32 `json:\"data\"`\n}\n\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#semanticTokensClientCapabilities\ntype SemanticTokensClientCapabilities struct {\n\t// Whether implementation supports dynamic registration. If this is set to `true`\n\t// the client supports the new `(TextDocumentRegistrationOptions & StaticRegistrationOptions)`\n\t// return value for the corresponding server capability as well.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n\t// Which requests the client supports and might send to the server\n\t// depending on the server's capability. Please note that clients might not\n\t// show semantic tokens or degrade some of the user experience if a range\n\t// or full request is advertised by the client but not provided by the\n\t// server. If for example the client capability `requests.full` and\n\t// `request.range` are both set to true but the server only provides a\n\t// range provider the client might not render a minimap correctly or might\n\t// even decide to not show any semantic tokens at all.\n\tRequests ClientSemanticTokensRequestOptions `json:\"requests\"`\n\t// The token types that the client supports.\n\tTokenTypes []string `json:\"tokenTypes\"`\n\t// The token modifiers that the client supports.\n\tTokenModifiers []string `json:\"tokenModifiers\"`\n\t// The token formats the clients supports.\n\tFormats []TokenFormat `json:\"formats\"`\n\t// Whether the client supports tokens that can overlap each other.\n\tOverlappingTokenSupport bool `json:\"overlappingTokenSupport,omitempty\"`\n\t// Whether the client supports tokens that can span multiple lines.\n\tMultilineTokenSupport bool `json:\"multilineTokenSupport,omitempty\"`\n\t// Whether the client allows the server to actively cancel a\n\t// semantic token request, e.g. supports returning\n\t// LSPErrorCodes.ServerCancelled. If a server does the client\n\t// needs to retrigger the request.\n\t//\n\t// @since 3.17.0\n\tServerCancelSupport bool `json:\"serverCancelSupport,omitempty\"`\n\t// Whether the client uses semantic tokens to augment existing\n\t// syntax tokens. If set to `true` client side created syntax\n\t// tokens and semantic tokens are both used for colorization. If\n\t// set to `false` the client only uses the returned semantic tokens\n\t// for colorization.\n\t//\n\t// If the value is `undefined` then the client behavior is not\n\t// specified.\n\t//\n\t// @since 3.17.0\n\tAugmentsSyntaxTokens bool `json:\"augmentsSyntaxTokens,omitempty\"`\n}\n\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#semanticTokensDelta\ntype SemanticTokensDelta struct {\n\tResultID string `json:\"resultId,omitempty\"`\n\t// The semantic token edits to transform a previous result into a new result.\n\tEdits []SemanticTokensEdit `json:\"edits\"`\n}\n\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#semanticTokensDeltaParams\ntype SemanticTokensDeltaParams struct {\n\t// The text document.\n\tTextDocument TextDocumentIdentifier `json:\"textDocument\"`\n\t// The result id of a previous response. The result Id can either point to a full response\n\t// or a delta response depending on what was received last.\n\tPreviousResultID string `json:\"previousResultId\"`\n\tWorkDoneProgressParams\n\tPartialResultParams\n}\n\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#semanticTokensDeltaPartialResult\ntype SemanticTokensDeltaPartialResult struct {\n\tEdits []SemanticTokensEdit `json:\"edits\"`\n}\n\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#semanticTokensEdit\ntype SemanticTokensEdit struct {\n\t// The start offset of the edit.\n\tStart uint32 `json:\"start\"`\n\t// The count of elements to remove.\n\tDeleteCount uint32 `json:\"deleteCount\"`\n\t// The elements to insert.\n\tData []uint32 `json:\"data,omitempty\"`\n}\n\n// Semantic tokens options to support deltas for full documents\n//\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#semanticTokensFullDelta\ntype SemanticTokensFullDelta struct {\n\t// The server supports deltas for full documents.\n\tDelta bool `json:\"delta,omitempty\"`\n}\n\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#semanticTokensLegend\ntype SemanticTokensLegend struct {\n\t// The token types a server uses.\n\tTokenTypes []string `json:\"tokenTypes\"`\n\t// The token modifiers a server uses.\n\tTokenModifiers []string `json:\"tokenModifiers\"`\n}\n\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#semanticTokensOptions\ntype SemanticTokensOptions struct {\n\t// The legend used by the server\n\tLegend SemanticTokensLegend `json:\"legend\"`\n\t// Server supports providing semantic tokens for a specific range\n\t// of a document.\n\tRange *Or_SemanticTokensOptions_range `json:\"range,omitempty\"`\n\t// Server supports providing semantic tokens for a full document.\n\tFull *Or_SemanticTokensOptions_full `json:\"full,omitempty\"`\n\tWorkDoneProgressOptions\n}\n\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#semanticTokensParams\ntype SemanticTokensParams struct {\n\t// The text document.\n\tTextDocument TextDocumentIdentifier `json:\"textDocument\"`\n\tWorkDoneProgressParams\n\tPartialResultParams\n}\n\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#semanticTokensPartialResult\ntype SemanticTokensPartialResult struct {\n\tData []uint32 `json:\"data\"`\n}\n\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#semanticTokensRangeParams\ntype SemanticTokensRangeParams struct {\n\t// The text document.\n\tTextDocument TextDocumentIdentifier `json:\"textDocument\"`\n\t// The range the semantic tokens are requested for.\n\tRange Range `json:\"range\"`\n\tWorkDoneProgressParams\n\tPartialResultParams\n}\n\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#semanticTokensRegistrationOptions\ntype SemanticTokensRegistrationOptions struct {\n\tTextDocumentRegistrationOptions\n\tSemanticTokensOptions\n\tStaticRegistrationOptions\n}\n\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#semanticTokensWorkspaceClientCapabilities\ntype SemanticTokensWorkspaceClientCapabilities struct {\n\t// Whether the client implementation supports a refresh request sent from\n\t// the server to the client.\n\t//\n\t// Note that this event is global and will force the client to refresh all\n\t// semantic tokens currently shown. It should be used with absolute care\n\t// and is useful for situation where a server for example detects a project\n\t// wide change that requires such a calculation.\n\tRefreshSupport bool `json:\"refreshSupport,omitempty\"`\n}\n\n// Defines the capabilities provided by a language\n// server.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#serverCapabilities\ntype ServerCapabilities struct {\n\t// The position encoding the server picked from the encodings offered\n\t// by the client via the client capability `general.positionEncodings`.\n\t//\n\t// If the client didn't provide any position encodings the only valid\n\t// value that a server can return is 'utf-16'.\n\t//\n\t// If omitted it defaults to 'utf-16'.\n\t//\n\t// @since 3.17.0\n\tPositionEncoding *PositionEncodingKind `json:\"positionEncoding,omitempty\"`\n\t// Defines how text documents are synced. Is either a detailed structure\n\t// defining each notification or for backwards compatibility the\n\t// TextDocumentSyncKind number.\n\tTextDocumentSync interface{} `json:\"textDocumentSync,omitempty\"`\n\t// Defines how notebook documents are synced.\n\t//\n\t// @since 3.17.0\n\tNotebookDocumentSync *Or_ServerCapabilities_notebookDocumentSync `json:\"notebookDocumentSync,omitempty\"`\n\t// The server provides completion support.\n\tCompletionProvider *CompletionOptions `json:\"completionProvider,omitempty\"`\n\t// The server provides hover support.\n\tHoverProvider *Or_ServerCapabilities_hoverProvider `json:\"hoverProvider,omitempty\"`\n\t// The server provides signature help support.\n\tSignatureHelpProvider *SignatureHelpOptions `json:\"signatureHelpProvider,omitempty\"`\n\t// The server provides Goto Declaration support.\n\tDeclarationProvider *Or_ServerCapabilities_declarationProvider `json:\"declarationProvider,omitempty\"`\n\t// The server provides goto definition support.\n\tDefinitionProvider *Or_ServerCapabilities_definitionProvider `json:\"definitionProvider,omitempty\"`\n\t// The server provides Goto Type Definition support.\n\tTypeDefinitionProvider *Or_ServerCapabilities_typeDefinitionProvider `json:\"typeDefinitionProvider,omitempty\"`\n\t// The server provides Goto Implementation support.\n\tImplementationProvider *Or_ServerCapabilities_implementationProvider `json:\"implementationProvider,omitempty\"`\n\t// The server provides find references support.\n\tReferencesProvider *Or_ServerCapabilities_referencesProvider `json:\"referencesProvider,omitempty\"`\n\t// The server provides document highlight support.\n\tDocumentHighlightProvider *Or_ServerCapabilities_documentHighlightProvider `json:\"documentHighlightProvider,omitempty\"`\n\t// The server provides document symbol support.\n\tDocumentSymbolProvider *Or_ServerCapabilities_documentSymbolProvider `json:\"documentSymbolProvider,omitempty\"`\n\t// The server provides code actions. CodeActionOptions may only be\n\t// specified if the client states that it supports\n\t// `codeActionLiteralSupport` in its initial `initialize` request.\n\tCodeActionProvider interface{} `json:\"codeActionProvider,omitempty\"`\n\t// The server provides code lens.\n\tCodeLensProvider *CodeLensOptions `json:\"codeLensProvider,omitempty\"`\n\t// The server provides document link support.\n\tDocumentLinkProvider *DocumentLinkOptions `json:\"documentLinkProvider,omitempty\"`\n\t// The server provides color provider support.\n\tColorProvider *Or_ServerCapabilities_colorProvider `json:\"colorProvider,omitempty\"`\n\t// The server provides workspace symbol support.\n\tWorkspaceSymbolProvider *Or_ServerCapabilities_workspaceSymbolProvider `json:\"workspaceSymbolProvider,omitempty\"`\n\t// The server provides document formatting.\n\tDocumentFormattingProvider *Or_ServerCapabilities_documentFormattingProvider `json:\"documentFormattingProvider,omitempty\"`\n\t// The server provides document range formatting.\n\tDocumentRangeFormattingProvider *Or_ServerCapabilities_documentRangeFormattingProvider `json:\"documentRangeFormattingProvider,omitempty\"`\n\t// The server provides document formatting on typing.\n\tDocumentOnTypeFormattingProvider *DocumentOnTypeFormattingOptions `json:\"documentOnTypeFormattingProvider,omitempty\"`\n\t// The server provides rename support. RenameOptions may only be\n\t// specified if the client states that it supports\n\t// `prepareSupport` in its initial `initialize` request.\n\tRenameProvider interface{} `json:\"renameProvider,omitempty\"`\n\t// The server provides folding provider support.\n\tFoldingRangeProvider *Or_ServerCapabilities_foldingRangeProvider `json:\"foldingRangeProvider,omitempty\"`\n\t// The server provides selection range support.\n\tSelectionRangeProvider *Or_ServerCapabilities_selectionRangeProvider `json:\"selectionRangeProvider,omitempty\"`\n\t// The server provides execute command support.\n\tExecuteCommandProvider *ExecuteCommandOptions `json:\"executeCommandProvider,omitempty\"`\n\t// The server provides call hierarchy support.\n\t//\n\t// @since 3.16.0\n\tCallHierarchyProvider *Or_ServerCapabilities_callHierarchyProvider `json:\"callHierarchyProvider,omitempty\"`\n\t// The server provides linked editing range support.\n\t//\n\t// @since 3.16.0\n\tLinkedEditingRangeProvider *Or_ServerCapabilities_linkedEditingRangeProvider `json:\"linkedEditingRangeProvider,omitempty\"`\n\t// The server provides semantic tokens support.\n\t//\n\t// @since 3.16.0\n\tSemanticTokensProvider interface{} `json:\"semanticTokensProvider,omitempty\"`\n\t// The server provides moniker support.\n\t//\n\t// @since 3.16.0\n\tMonikerProvider *Or_ServerCapabilities_monikerProvider `json:\"monikerProvider,omitempty\"`\n\t// The server provides type hierarchy support.\n\t//\n\t// @since 3.17.0\n\tTypeHierarchyProvider *Or_ServerCapabilities_typeHierarchyProvider `json:\"typeHierarchyProvider,omitempty\"`\n\t// The server provides inline values.\n\t//\n\t// @since 3.17.0\n\tInlineValueProvider *Or_ServerCapabilities_inlineValueProvider `json:\"inlineValueProvider,omitempty\"`\n\t// The server provides inlay hints.\n\t//\n\t// @since 3.17.0\n\tInlayHintProvider interface{} `json:\"inlayHintProvider,omitempty\"`\n\t// The server has support for pull model diagnostics.\n\t//\n\t// @since 3.17.0\n\tDiagnosticProvider *Or_ServerCapabilities_diagnosticProvider `json:\"diagnosticProvider,omitempty\"`\n\t// Inline completion options used during static registration.\n\t//\n\t// @since 3.18.0\n\t// @proposed\n\tInlineCompletionProvider *Or_ServerCapabilities_inlineCompletionProvider `json:\"inlineCompletionProvider,omitempty\"`\n\t// Workspace specific server capabilities.\n\tWorkspace *WorkspaceOptions `json:\"workspace,omitempty\"`\n\t// Experimental server capabilities.\n\tExperimental interface{} `json:\"experimental,omitempty\"`\n}\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#serverCompletionItemOptions\ntype ServerCompletionItemOptions struct {\n\t// The server has support for completion item label\n\t// details (see also `CompletionItemLabelDetails`) when\n\t// receiving a completion item in a resolve call.\n\t//\n\t// @since 3.17.0\n\tLabelDetailsSupport bool `json:\"labelDetailsSupport,omitempty\"`\n}\n\n// Information about the server\n//\n// @since 3.15.0\n// @since 3.18.0 ServerInfo type name added.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#serverInfo\ntype ServerInfo struct {\n\t// The name of the server as defined by the server.\n\tName string `json:\"name\"`\n\t// The server's version as defined by the server.\n\tVersion string `json:\"version,omitempty\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#setTraceParams\ntype SetTraceParams struct {\n\tValue TraceValue `json:\"value\"`\n}\n\n// Client capabilities for the showDocument request.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#showDocumentClientCapabilities\ntype ShowDocumentClientCapabilities struct {\n\t// The client has support for the showDocument\n\t// request.\n\tSupport bool `json:\"support\"`\n}\n\n// Params to show a resource in the UI.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#showDocumentParams\ntype ShowDocumentParams struct {\n\t// The uri to show.\n\tURI URI `json:\"uri\"`\n\t// Indicates to show the resource in an external program.\n\t// To show, for example, `https://code.visualstudio.com/`\n\t// in the default WEB browser set `external` to `true`.\n\tExternal bool `json:\"external,omitempty\"`\n\t// An optional property to indicate whether the editor\n\t// showing the document should take focus or not.\n\t// Clients might ignore this property if an external\n\t// program is started.\n\tTakeFocus bool `json:\"takeFocus,omitempty\"`\n\t// An optional selection range if the document is a text\n\t// document. Clients might ignore the property if an\n\t// external program is started or the file is not a text\n\t// file.\n\tSelection *Range `json:\"selection,omitempty\"`\n}\n\n// The result of a showDocument request.\n//\n// @since 3.16.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#showDocumentResult\ntype ShowDocumentResult struct {\n\t// A boolean indicating if the show was successful.\n\tSuccess bool `json:\"success\"`\n}\n\n// The parameters of a notification message.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#showMessageParams\ntype ShowMessageParams struct {\n\t// The message type. See {@link MessageType}\n\tType MessageType `json:\"type\"`\n\t// The actual message.\n\tMessage string `json:\"message\"`\n}\n\n// Show message request client capabilities\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#showMessageRequestClientCapabilities\ntype ShowMessageRequestClientCapabilities struct {\n\t// Capabilities specific to the `MessageActionItem` type.\n\tMessageActionItem *ClientShowMessageActionItemOptions `json:\"messageActionItem,omitempty\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#showMessageRequestParams\ntype ShowMessageRequestParams struct {\n\t// The message type. See {@link MessageType}\n\tType MessageType `json:\"type\"`\n\t// The actual message.\n\tMessage string `json:\"message\"`\n\t// The message action items to present.\n\tActions []MessageActionItem `json:\"actions,omitempty\"`\n}\n\n// Signature help represents the signature of something\n// callable. There can be multiple signature but only one\n// active and only one active parameter.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#signatureHelp\ntype SignatureHelp struct {\n\t// One or more signatures.\n\tSignatures []SignatureInformation `json:\"signatures\"`\n\t// The active signature. If omitted or the value lies outside the\n\t// range of `signatures` the value defaults to zero or is ignored if\n\t// the `SignatureHelp` has no signatures.\n\t//\n\t// Whenever possible implementors should make an active decision about\n\t// the active signature and shouldn't rely on a default value.\n\t//\n\t// In future version of the protocol this property might become\n\t// mandatory to better express this.\n\tActiveSignature uint32 `json:\"activeSignature,omitempty\"`\n\t// The active parameter of the active signature.\n\t//\n\t// If `null`, no parameter of the signature is active (for example a named\n\t// argument that does not match any declared parameters). This is only valid\n\t// if the client specifies the client capability\n\t// `textDocument.signatureHelp.noActiveParameterSupport === true`\n\t//\n\t// If omitted or the value lies outside the range of\n\t// `signatures[activeSignature].parameters` defaults to 0 if the active\n\t// signature has parameters.\n\t//\n\t// If the active signature has no parameters it is ignored.\n\t//\n\t// In future version of the protocol this property might become\n\t// mandatory (but still nullable) to better express the active parameter if\n\t// the active signature does have any.\n\tActiveParameter uint32 `json:\"activeParameter,omitempty\"`\n}\n\n// Client Capabilities for a {@link SignatureHelpRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#signatureHelpClientCapabilities\ntype SignatureHelpClientCapabilities struct {\n\t// Whether signature help supports dynamic registration.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n\t// The client supports the following `SignatureInformation`\n\t// specific properties.\n\tSignatureInformation *ClientSignatureInformationOptions `json:\"signatureInformation,omitempty\"`\n\t// The client supports to send additional context information for a\n\t// `textDocument/signatureHelp` request. A client that opts into\n\t// contextSupport will also support the `retriggerCharacters` on\n\t// `SignatureHelpOptions`.\n\t//\n\t// @since 3.15.0\n\tContextSupport bool `json:\"contextSupport,omitempty\"`\n}\n\n// Additional information about the context in which a signature help request was triggered.\n//\n// @since 3.15.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#signatureHelpContext\ntype SignatureHelpContext struct {\n\t// Action that caused signature help to be triggered.\n\tTriggerKind SignatureHelpTriggerKind `json:\"triggerKind\"`\n\t// Character that caused signature help to be triggered.\n\t//\n\t// This is undefined when `triggerKind !== SignatureHelpTriggerKind.TriggerCharacter`\n\tTriggerCharacter string `json:\"triggerCharacter,omitempty\"`\n\t// `true` if signature help was already showing when it was triggered.\n\t//\n\t// Retriggers occurs when the signature help is already active and can be caused by actions such as\n\t// typing a trigger character, a cursor move, or document content changes.\n\tIsRetrigger bool `json:\"isRetrigger\"`\n\t// The currently active `SignatureHelp`.\n\t//\n\t// The `activeSignatureHelp` has its `SignatureHelp.activeSignature` field updated based on\n\t// the user navigating through available signatures.\n\tActiveSignatureHelp *SignatureHelp `json:\"activeSignatureHelp,omitempty\"`\n}\n\n// Server Capabilities for a {@link SignatureHelpRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#signatureHelpOptions\ntype SignatureHelpOptions struct {\n\t// List of characters that trigger signature help automatically.\n\tTriggerCharacters []string `json:\"triggerCharacters,omitempty\"`\n\t// List of characters that re-trigger signature help.\n\t//\n\t// These trigger characters are only active when signature help is already showing. All trigger characters\n\t// are also counted as re-trigger characters.\n\t//\n\t// @since 3.15.0\n\tRetriggerCharacters []string `json:\"retriggerCharacters,omitempty\"`\n\tWorkDoneProgressOptions\n}\n\n// Parameters for a {@link SignatureHelpRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#signatureHelpParams\ntype SignatureHelpParams struct {\n\t// The signature help context. This is only available if the client specifies\n\t// to send this using the client capability `textDocument.signatureHelp.contextSupport === true`\n\t//\n\t// @since 3.15.0\n\tContext *SignatureHelpContext `json:\"context,omitempty\"`\n\tTextDocumentPositionParams\n\tWorkDoneProgressParams\n}\n\n// Registration options for a {@link SignatureHelpRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#signatureHelpRegistrationOptions\ntype SignatureHelpRegistrationOptions struct {\n\tTextDocumentRegistrationOptions\n\tSignatureHelpOptions\n}\n\n// How a signature help was triggered.\n//\n// @since 3.15.0\ntype SignatureHelpTriggerKind uint32\n\n// Represents the signature of something callable. A signature\n// can have a label, like a function-name, a doc-comment, and\n// a set of parameters.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#signatureInformation\ntype SignatureInformation struct {\n\t// The label of this signature. Will be shown in\n\t// the UI.\n\tLabel string `json:\"label\"`\n\t// The human-readable doc-comment of this signature. Will be shown\n\t// in the UI but can be omitted.\n\tDocumentation *Or_SignatureInformation_documentation `json:\"documentation,omitempty\"`\n\t// The parameters of this signature.\n\tParameters []ParameterInformation `json:\"parameters,omitempty\"`\n\t// The index of the active parameter.\n\t//\n\t// If `null`, no parameter of the signature is active (for example a named\n\t// argument that does not match any declared parameters). This is only valid\n\t// if the client specifies the client capability\n\t// `textDocument.signatureHelp.noActiveParameterSupport === true`\n\t//\n\t// If provided (or `null`), this is used in place of\n\t// `SignatureHelp.activeParameter`.\n\t//\n\t// @since 3.16.0\n\tActiveParameter uint32 `json:\"activeParameter,omitempty\"`\n}\n\n// An interactive text edit.\n//\n// @since 3.18.0\n// @proposed\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#snippetTextEdit\ntype SnippetTextEdit struct {\n\t// The range of the text document to be manipulated.\n\tRange Range `json:\"range\"`\n\t// The snippet to be inserted.\n\tSnippet StringValue `json:\"snippet\"`\n\t// The actual identifier of the snippet edit.\n\tAnnotationID *ChangeAnnotationIdentifier `json:\"annotationId,omitempty\"`\n}\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#staleRequestSupportOptions\ntype StaleRequestSupportOptions struct {\n\t// The client will actively cancel the request.\n\tCancel bool `json:\"cancel\"`\n\t// The list of requests for which the client\n\t// will retry the request if it receives a\n\t// response with error code `ContentModified`\n\tRetryOnContentModified []string `json:\"retryOnContentModified\"`\n}\n\n// Static registration options to be returned in the initialize\n// request.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#staticRegistrationOptions\ntype StaticRegistrationOptions struct {\n\t// The id used to register the request. The id can be used to deregister\n\t// the request again. See also Registration#id.\n\tID string `json:\"id,omitempty\"`\n}\n\n// A string value used as a snippet is a template which allows to insert text\n// and to control the editor cursor when insertion happens.\n//\n// A snippet can define tab stops and placeholders with `$1`, `$2`\n// and `${3:foo}`. `$0` defines the final tab stop, it defaults to\n// the end of the snippet. Variables are defined with `$name` and\n// `${name:default value}`.\n//\n// @since 3.18.0\n// @proposed\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#stringValue\ntype StringValue struct {\n\t// The kind of string value.\n\tKind string `json:\"kind\"`\n\t// The snippet string.\n\tValue string `json:\"value\"`\n}\n\n// Represents information about programming constructs like variables, classes,\n// interfaces etc.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#symbolInformation\ntype SymbolInformation struct {\n\t// extends BaseSymbolInformation\n\t// Indicates if this symbol is deprecated.\n\t//\n\t// @deprecated Use tags instead\n\tDeprecated bool `json:\"deprecated,omitempty\"`\n\t// The location of this symbol. The location's range is used by a tool\n\t// to reveal the location in the editor. If the symbol is selected in the\n\t// tool the range's start information is used to position the cursor. So\n\t// the range usually spans more than the actual symbol's name and does\n\t// normally include things like visibility modifiers.\n\t//\n\t// The range doesn't have to denote a node range in the sense of an abstract\n\t// syntax tree. It can therefore not be used to re-construct a hierarchy of\n\t// the symbols.\n\tLocation Location `json:\"location\"`\n\t// The name of this symbol.\n\tName string `json:\"name\"`\n\t// The kind of this symbol.\n\tKind SymbolKind `json:\"kind\"`\n\t// Tags for this symbol.\n\t//\n\t// @since 3.16.0\n\tTags []SymbolTag `json:\"tags,omitempty\"`\n\t// The name of the symbol containing this symbol. This information is for\n\t// user interface purposes (e.g. to render a qualifier in the user interface\n\t// if necessary). It can't be used to re-infer a hierarchy for the document\n\t// symbols.\n\tContainerName string `json:\"containerName,omitempty\"`\n}\n\n// A symbol kind.\ntype SymbolKind uint32\n\n// Symbol tags are extra annotations that tweak the rendering of a symbol.\n//\n// @since 3.16\ntype SymbolTag uint32\n\n// Describe options to be used when registered for text document change events.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#textDocumentChangeRegistrationOptions\ntype TextDocumentChangeRegistrationOptions struct {\n\t// How documents are synced to the server.\n\tSyncKind TextDocumentSyncKind `json:\"syncKind\"`\n\tTextDocumentRegistrationOptions\n}\n\n// Text document specific client capabilities.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#textDocumentClientCapabilities\ntype TextDocumentClientCapabilities struct {\n\t// Defines which synchronization capabilities the client supports.\n\tSynchronization *TextDocumentSyncClientCapabilities `json:\"synchronization,omitempty\"`\n\t// Capabilities specific to the `textDocument/completion` request.\n\tCompletion CompletionClientCapabilities `json:\"completion,omitempty\"`\n\t// Capabilities specific to the `textDocument/hover` request.\n\tHover *HoverClientCapabilities `json:\"hover,omitempty\"`\n\t// Capabilities specific to the `textDocument/signatureHelp` request.\n\tSignatureHelp *SignatureHelpClientCapabilities `json:\"signatureHelp,omitempty\"`\n\t// Capabilities specific to the `textDocument/declaration` request.\n\t//\n\t// @since 3.14.0\n\tDeclaration *DeclarationClientCapabilities `json:\"declaration,omitempty\"`\n\t// Capabilities specific to the `textDocument/definition` request.\n\tDefinition *DefinitionClientCapabilities `json:\"definition,omitempty\"`\n\t// Capabilities specific to the `textDocument/typeDefinition` request.\n\t//\n\t// @since 3.6.0\n\tTypeDefinition *TypeDefinitionClientCapabilities `json:\"typeDefinition,omitempty\"`\n\t// Capabilities specific to the `textDocument/implementation` request.\n\t//\n\t// @since 3.6.0\n\tImplementation *ImplementationClientCapabilities `json:\"implementation,omitempty\"`\n\t// Capabilities specific to the `textDocument/references` request.\n\tReferences *ReferenceClientCapabilities `json:\"references,omitempty\"`\n\t// Capabilities specific to the `textDocument/documentHighlight` request.\n\tDocumentHighlight *DocumentHighlightClientCapabilities `json:\"documentHighlight,omitempty\"`\n\t// Capabilities specific to the `textDocument/documentSymbol` request.\n\tDocumentSymbol DocumentSymbolClientCapabilities `json:\"documentSymbol,omitempty\"`\n\t// Capabilities specific to the `textDocument/codeAction` request.\n\tCodeAction CodeActionClientCapabilities `json:\"codeAction,omitempty\"`\n\t// Capabilities specific to the `textDocument/codeLens` request.\n\tCodeLens *CodeLensClientCapabilities `json:\"codeLens,omitempty\"`\n\t// Capabilities specific to the `textDocument/documentLink` request.\n\tDocumentLink *DocumentLinkClientCapabilities `json:\"documentLink,omitempty\"`\n\t// Capabilities specific to the `textDocument/documentColor` and the\n\t// `textDocument/colorPresentation` request.\n\t//\n\t// @since 3.6.0\n\tColorProvider *DocumentColorClientCapabilities `json:\"colorProvider,omitempty\"`\n\t// Capabilities specific to the `textDocument/formatting` request.\n\tFormatting *DocumentFormattingClientCapabilities `json:\"formatting,omitempty\"`\n\t// Capabilities specific to the `textDocument/rangeFormatting` request.\n\tRangeFormatting *DocumentRangeFormattingClientCapabilities `json:\"rangeFormatting,omitempty\"`\n\t// Capabilities specific to the `textDocument/onTypeFormatting` request.\n\tOnTypeFormatting *DocumentOnTypeFormattingClientCapabilities `json:\"onTypeFormatting,omitempty\"`\n\t// Capabilities specific to the `textDocument/rename` request.\n\tRename *RenameClientCapabilities `json:\"rename,omitempty\"`\n\t// Capabilities specific to the `textDocument/foldingRange` request.\n\t//\n\t// @since 3.10.0\n\tFoldingRange *FoldingRangeClientCapabilities `json:\"foldingRange,omitempty\"`\n\t// Capabilities specific to the `textDocument/selectionRange` request.\n\t//\n\t// @since 3.15.0\n\tSelectionRange *SelectionRangeClientCapabilities `json:\"selectionRange,omitempty\"`\n\t// Capabilities specific to the `textDocument/publishDiagnostics` notification.\n\tPublishDiagnostics PublishDiagnosticsClientCapabilities `json:\"publishDiagnostics,omitempty\"`\n\t// Capabilities specific to the various call hierarchy requests.\n\t//\n\t// @since 3.16.0\n\tCallHierarchy *CallHierarchyClientCapabilities `json:\"callHierarchy,omitempty\"`\n\t// Capabilities specific to the various semantic token request.\n\t//\n\t// @since 3.16.0\n\tSemanticTokens SemanticTokensClientCapabilities `json:\"semanticTokens,omitempty\"`\n\t// Capabilities specific to the `textDocument/linkedEditingRange` request.\n\t//\n\t// @since 3.16.0\n\tLinkedEditingRange *LinkedEditingRangeClientCapabilities `json:\"linkedEditingRange,omitempty\"`\n\t// Client capabilities specific to the `textDocument/moniker` request.\n\t//\n\t// @since 3.16.0\n\tMoniker *MonikerClientCapabilities `json:\"moniker,omitempty\"`\n\t// Capabilities specific to the various type hierarchy requests.\n\t//\n\t// @since 3.17.0\n\tTypeHierarchy *TypeHierarchyClientCapabilities `json:\"typeHierarchy,omitempty\"`\n\t// Capabilities specific to the `textDocument/inlineValue` request.\n\t//\n\t// @since 3.17.0\n\tInlineValue *InlineValueClientCapabilities `json:\"inlineValue,omitempty\"`\n\t// Capabilities specific to the `textDocument/inlayHint` request.\n\t//\n\t// @since 3.17.0\n\tInlayHint *InlayHintClientCapabilities `json:\"inlayHint,omitempty\"`\n\t// Capabilities specific to the diagnostic pull model.\n\t//\n\t// @since 3.17.0\n\tDiagnostic *DiagnosticClientCapabilities `json:\"diagnostic,omitempty\"`\n\t// Client capabilities specific to inline completions.\n\t//\n\t// @since 3.18.0\n\t// @proposed\n\tInlineCompletion *InlineCompletionClientCapabilities `json:\"inlineCompletion,omitempty\"`\n}\n\n// An event describing a change to a text document. If only a text is provided\n// it is considered to be the full content of the document.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#textDocumentContentChangeEvent\ntype TextDocumentContentChangeEvent = Or_TextDocumentContentChangeEvent // (alias)\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#textDocumentContentChangePartial\ntype TextDocumentContentChangePartial struct {\n\t// The range of the document that changed.\n\tRange *Range `json:\"range,omitempty\"`\n\t// The optional length of the range that got replaced.\n\t//\n\t// @deprecated use range instead.\n\tRangeLength uint32 `json:\"rangeLength,omitempty\"`\n\t// The new text for the provided range.\n\tText string `json:\"text\"`\n}\n\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#textDocumentContentChangeWholeDocument\ntype TextDocumentContentChangeWholeDocument struct {\n\t// The new text of the whole document.\n\tText string `json:\"text\"`\n}\n\n// Client capabilities for a text document content provider.\n//\n// @since 3.18.0\n// @proposed\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#textDocumentContentClientCapabilities\ntype TextDocumentContentClientCapabilities struct {\n\t// Text document content provider supports dynamic registration.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n}\n\n// Text document content provider options.\n//\n// @since 3.18.0\n// @proposed\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#textDocumentContentOptions\ntype TextDocumentContentOptions struct {\n\t// The scheme for which the server provides content.\n\tScheme string `json:\"scheme\"`\n}\n\n// Parameters for the `workspace/textDocumentContent` request.\n//\n// @since 3.18.0\n// @proposed\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#textDocumentContentParams\ntype TextDocumentContentParams struct {\n\t// The uri of the text document.\n\tURI DocumentUri `json:\"uri\"`\n}\n\n// Parameters for the `workspace/textDocumentContent/refresh` request.\n//\n// @since 3.18.0\n// @proposed\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#textDocumentContentRefreshParams\ntype TextDocumentContentRefreshParams struct {\n\t// The uri of the text document to refresh.\n\tURI DocumentUri `json:\"uri\"`\n}\n\n// Text document content provider registration options.\n//\n// @since 3.18.0\n// @proposed\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#textDocumentContentRegistrationOptions\ntype TextDocumentContentRegistrationOptions struct {\n\tTextDocumentContentOptions\n\tStaticRegistrationOptions\n}\n\n// Describes textual changes on a text document. A TextDocumentEdit describes all changes\n// on a document version Si and after they are applied move the document to version Si+1.\n// So the creator of a TextDocumentEdit doesn't need to sort the array of edits or do any\n// kind of ordering. However the edits must be non overlapping.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#textDocumentEdit\ntype TextDocumentEdit struct {\n\t// The text document to change.\n\tTextDocument OptionalVersionedTextDocumentIdentifier `json:\"textDocument\"`\n\t// The edits to be applied.\n\t//\n\t// @since 3.16.0 - support for AnnotatedTextEdit. This is guarded using a\n\t// client capability.\n\t//\n\t// @since 3.18.0 - support for SnippetTextEdit. This is guarded using a\n\t// client capability.\n\tEdits []Or_TextDocumentEdit_edits_Elem `json:\"edits\"`\n}\n\n// A document filter denotes a document by different properties like\n// the {@link TextDocument.languageId language}, the {@link Uri.scheme scheme} of\n// its resource, or a glob-pattern that is applied to the {@link TextDocument.fileName path}.\n//\n// Glob patterns can have the following syntax:\n//\n// - `*` to match one or more characters in a path segment\n// - `?` to match on one character in a path segment\n// - `**` to match any number of path segments, including none\n// - `{}` to group sub patterns into an OR expression. (e.g. `**/*.{ts,js}` matches all TypeScript and JavaScript files)\n// - `[]` to declare a range of characters to match in a path segment (e.g., `example.[0-9]` to match on `example.0`, `example.1`, …)\n// - `[!...]` to negate a range of characters to match in a path segment (e.g., `example.[!0-9]` to match on `example.a`, `example.b`, but not `example.0`)\n//\n// @sample A language filter that applies to typescript files on disk: `{ language: 'typescript', scheme: 'file' }`\n// @sample A language filter that applies to all package.json paths: `{ language: 'json', pattern: '**package.json' }`\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#textDocumentFilter\ntype TextDocumentFilter = Or_TextDocumentFilter // (alias)\n// A document filter where `language` is required field.\n//\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#textDocumentFilterLanguage\ntype TextDocumentFilterLanguage struct {\n\t// A language id, like `typescript`.\n\tLanguage string `json:\"language\"`\n\t// A Uri {@link Uri.scheme scheme}, like `file` or `untitled`.\n\tScheme string `json:\"scheme,omitempty\"`\n\t// A glob pattern, like **/*.{ts,js}. See TextDocumentFilter for examples.\n\t//\n\t// @since 3.18.0 - support for relative patterns.\n\tPattern *GlobPattern `json:\"pattern,omitempty\"`\n}\n\n// A document filter where `pattern` is required field.\n//\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#textDocumentFilterPattern\ntype TextDocumentFilterPattern struct {\n\t// A language id, like `typescript`.\n\tLanguage string `json:\"language,omitempty\"`\n\t// A Uri {@link Uri.scheme scheme}, like `file` or `untitled`.\n\tScheme string `json:\"scheme,omitempty\"`\n\t// A glob pattern, like **/*.{ts,js}. See TextDocumentFilter for examples.\n\t//\n\t// @since 3.18.0 - support for relative patterns.\n\tPattern GlobPattern `json:\"pattern\"`\n}\n\n// A document filter where `scheme` is required field.\n//\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#textDocumentFilterScheme\ntype TextDocumentFilterScheme struct {\n\t// A language id, like `typescript`.\n\tLanguage string `json:\"language,omitempty\"`\n\t// A Uri {@link Uri.scheme scheme}, like `file` or `untitled`.\n\tScheme string `json:\"scheme\"`\n\t// A glob pattern, like **/*.{ts,js}. See TextDocumentFilter for examples.\n\t//\n\t// @since 3.18.0 - support for relative patterns.\n\tPattern *GlobPattern `json:\"pattern,omitempty\"`\n}\n\n// A literal to identify a text document in the client.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#textDocumentIdentifier\ntype TextDocumentIdentifier struct {\n\t// The text document's uri.\n\tURI DocumentUri `json:\"uri\"`\n}\n\n// An item to transfer a text document from the client to the\n// server.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#textDocumentItem\ntype TextDocumentItem struct {\n\t// The text document's uri.\n\tURI DocumentUri `json:\"uri\"`\n\t// The text document's language identifier.\n\tLanguageID LanguageKind `json:\"languageId\"`\n\t// The version number of this document (it will increase after each\n\t// change, including undo/redo).\n\tVersion int32 `json:\"version\"`\n\t// The content of the opened text document.\n\tText string `json:\"text\"`\n}\n\n// A parameter literal used in requests to pass a text document and a position inside that\n// document.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#textDocumentPositionParams\ntype TextDocumentPositionParams struct {\n\t// The text document.\n\tTextDocument TextDocumentIdentifier `json:\"textDocument\"`\n\t// The position inside the text document.\n\tPosition Position `json:\"position\"`\n}\n\n// General text document registration options.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#textDocumentRegistrationOptions\ntype TextDocumentRegistrationOptions struct {\n\t// A document selector to identify the scope of the registration. If set to null\n\t// the document selector provided on the client side will be used.\n\tDocumentSelector DocumentSelector `json:\"documentSelector\"`\n}\n\n// Represents reasons why a text document is saved.\ntype TextDocumentSaveReason uint32\n\n// Save registration options.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#textDocumentSaveRegistrationOptions\ntype TextDocumentSaveRegistrationOptions struct {\n\tTextDocumentRegistrationOptions\n\tSaveOptions\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#textDocumentSyncClientCapabilities\ntype TextDocumentSyncClientCapabilities struct {\n\t// Whether text document synchronization supports dynamic registration.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n\t// The client supports sending will save notifications.\n\tWillSave bool `json:\"willSave,omitempty\"`\n\t// The client supports sending a will save request and\n\t// waits for a response providing text edits which will\n\t// be applied to the document before it is saved.\n\tWillSaveWaitUntil bool `json:\"willSaveWaitUntil,omitempty\"`\n\t// The client supports did save notifications.\n\tDidSave bool `json:\"didSave,omitempty\"`\n}\n\n// Defines how the host (editor) should sync\n// document changes to the language server.\ntype TextDocumentSyncKind uint32\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#textDocumentSyncOptions\ntype TextDocumentSyncOptions struct {\n\t// Open and close notifications are sent to the server. If omitted open close notification should not\n\t// be sent.\n\tOpenClose bool `json:\"openClose,omitempty\"`\n\t// Change notifications are sent to the server. See TextDocumentSyncKind.None, TextDocumentSyncKind.Full\n\t// and TextDocumentSyncKind.Incremental. If omitted it defaults to TextDocumentSyncKind.None.\n\tChange TextDocumentSyncKind `json:\"change,omitempty\"`\n\t// If present will save notifications are sent to the server. If omitted the notification should not be\n\t// sent.\n\tWillSave bool `json:\"willSave,omitempty\"`\n\t// If present will save wait until requests are sent to the server. If omitted the request should not be\n\t// sent.\n\tWillSaveWaitUntil bool `json:\"willSaveWaitUntil,omitempty\"`\n\t// If present save notifications are sent to the server. If omitted the notification should not be\n\t// sent.\n\tSave *SaveOptions `json:\"save,omitempty\"`\n}\n\n// A text edit applicable to a text document.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#textEdit\ntype TextEdit struct {\n\t// The range of the text document to be manipulated. To insert\n\t// text into a document create a range where start === end.\n\tRange Range `json:\"range\"`\n\t// The string to be inserted. For delete operations use an\n\t// empty string.\n\tNewText string `json:\"newText\"`\n}\ntype TokenFormat string\ntype TraceValue string\n\n// created for Tuple\ntype Tuple_ParameterInformation_label_Item1 struct {\n\tFld0 uint32 `json:\"fld0\"`\n\tFld1 uint32 `json:\"fld1\"`\n}\n\n// Since 3.6.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#typeDefinitionClientCapabilities\ntype TypeDefinitionClientCapabilities struct {\n\t// Whether implementation supports dynamic registration. If this is set to `true`\n\t// the client supports the new `TypeDefinitionRegistrationOptions` return value\n\t// for the corresponding server capability as well.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n\t// The client supports additional metadata in the form of definition links.\n\t//\n\t// Since 3.14.0\n\tLinkSupport bool `json:\"linkSupport,omitempty\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#typeDefinitionOptions\ntype TypeDefinitionOptions struct {\n\tWorkDoneProgressOptions\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#typeDefinitionParams\ntype TypeDefinitionParams struct {\n\tTextDocumentPositionParams\n\tWorkDoneProgressParams\n\tPartialResultParams\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#typeDefinitionRegistrationOptions\ntype TypeDefinitionRegistrationOptions struct {\n\tTextDocumentRegistrationOptions\n\tTypeDefinitionOptions\n\tStaticRegistrationOptions\n}\n\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#typeHierarchyClientCapabilities\ntype TypeHierarchyClientCapabilities struct {\n\t// Whether implementation supports dynamic registration. If this is set to `true`\n\t// the client supports the new `(TextDocumentRegistrationOptions & StaticRegistrationOptions)`\n\t// return value for the corresponding server capability as well.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n}\n\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#typeHierarchyItem\ntype TypeHierarchyItem struct {\n\t// The name of this item.\n\tName string `json:\"name\"`\n\t// The kind of this item.\n\tKind SymbolKind `json:\"kind\"`\n\t// Tags for this item.\n\tTags []SymbolTag `json:\"tags,omitempty\"`\n\t// More detail for this item, e.g. the signature of a function.\n\tDetail string `json:\"detail,omitempty\"`\n\t// The resource identifier of this item.\n\tURI DocumentUri `json:\"uri\"`\n\t// The range enclosing this symbol not including leading/trailing whitespace\n\t// but everything else, e.g. comments and code.\n\tRange Range `json:\"range\"`\n\t// The range that should be selected and revealed when this symbol is being\n\t// picked, e.g. the name of a function. Must be contained by the\n\t// {@link TypeHierarchyItem.range `range`}.\n\tSelectionRange Range `json:\"selectionRange\"`\n\t// A data entry field that is preserved between a type hierarchy prepare and\n\t// supertypes or subtypes requests. It could also be used to identify the\n\t// type hierarchy in the server, helping improve the performance on\n\t// resolving supertypes and subtypes.\n\tData interface{} `json:\"data,omitempty\"`\n}\n\n// Type hierarchy options used during static registration.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#typeHierarchyOptions\ntype TypeHierarchyOptions struct {\n\tWorkDoneProgressOptions\n}\n\n// The parameter of a `textDocument/prepareTypeHierarchy` request.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#typeHierarchyPrepareParams\ntype TypeHierarchyPrepareParams struct {\n\tTextDocumentPositionParams\n\tWorkDoneProgressParams\n}\n\n// Type hierarchy options used during static or dynamic registration.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#typeHierarchyRegistrationOptions\ntype TypeHierarchyRegistrationOptions struct {\n\tTextDocumentRegistrationOptions\n\tTypeHierarchyOptions\n\tStaticRegistrationOptions\n}\n\n// The parameter of a `typeHierarchy/subtypes` request.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#typeHierarchySubtypesParams\ntype TypeHierarchySubtypesParams struct {\n\tItem TypeHierarchyItem `json:\"item\"`\n\tWorkDoneProgressParams\n\tPartialResultParams\n}\n\n// The parameter of a `typeHierarchy/supertypes` request.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#typeHierarchySupertypesParams\ntype TypeHierarchySupertypesParams struct {\n\tItem TypeHierarchyItem `json:\"item\"`\n\tWorkDoneProgressParams\n\tPartialResultParams\n}\n\n// A diagnostic report indicating that the last returned\n// report is still accurate.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#unchangedDocumentDiagnosticReport\ntype UnchangedDocumentDiagnosticReport struct {\n\t// A document diagnostic report indicating\n\t// no changes to the last result. A server can\n\t// only return `unchanged` if result ids are\n\t// provided.\n\tKind string `json:\"kind\"`\n\t// A result id which will be sent on the next\n\t// diagnostic request for the same document.\n\tResultID string `json:\"resultId\"`\n}\n\n// Moniker uniqueness level to define scope of the moniker.\n//\n// @since 3.16.0\ntype UniquenessLevel string\n\n// General parameters to unregister a request or notification.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#unregistration\ntype Unregistration struct {\n\t// The id used to unregister the request or notification. Usually an id\n\t// provided during the register request.\n\tID string `json:\"id\"`\n\t// The method to unregister for.\n\tMethod string `json:\"method\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#unregistrationParams\ntype UnregistrationParams struct {\n\tUnregisterations []Unregistration `json:\"unregisterations\"`\n}\n\n// A versioned notebook document identifier.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#versionedNotebookDocumentIdentifier\ntype VersionedNotebookDocumentIdentifier struct {\n\t// The version number of this notebook document.\n\tVersion int32 `json:\"version\"`\n\t// The notebook document's uri.\n\tURI URI `json:\"uri\"`\n}\n\n// A text document identifier to denote a specific version of a text document.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#versionedTextDocumentIdentifier\ntype VersionedTextDocumentIdentifier struct {\n\t// The version number of this document.\n\tVersion int32 `json:\"version\"`\n\tTextDocumentIdentifier\n}\ntype WatchKind = uint32 // The parameters sent in a will save text document notification.\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#willSaveTextDocumentParams\ntype WillSaveTextDocumentParams struct {\n\t// The document that will be saved.\n\tTextDocument TextDocumentIdentifier `json:\"textDocument\"`\n\t// The 'TextDocumentSaveReason'.\n\tReason TextDocumentSaveReason `json:\"reason\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#windowClientCapabilities\ntype WindowClientCapabilities struct {\n\t// It indicates whether the client supports server initiated\n\t// progress using the `window/workDoneProgress/create` request.\n\t//\n\t// The capability also controls Whether client supports handling\n\t// of progress notifications. If set servers are allowed to report a\n\t// `workDoneProgress` property in the request specific server\n\t// capabilities.\n\t//\n\t// @since 3.15.0\n\tWorkDoneProgress bool `json:\"workDoneProgress,omitempty\"`\n\t// Capabilities specific to the showMessage request.\n\t//\n\t// @since 3.16.0\n\tShowMessage *ShowMessageRequestClientCapabilities `json:\"showMessage,omitempty\"`\n\t// Capabilities specific to the showDocument request.\n\t//\n\t// @since 3.16.0\n\tShowDocument *ShowDocumentClientCapabilities `json:\"showDocument,omitempty\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#workDoneProgressBegin\ntype WorkDoneProgressBegin struct {\n\tKind string `json:\"kind\"`\n\t// Mandatory title of the progress operation. Used to briefly inform about\n\t// the kind of operation being performed.\n\t//\n\t// Examples: \"Indexing\" or \"Linking dependencies\".\n\tTitle string `json:\"title\"`\n\t// Controls if a cancel button should show to allow the user to cancel the\n\t// long running operation. Clients that don't support cancellation are allowed\n\t// to ignore the setting.\n\tCancellable bool `json:\"cancellable,omitempty\"`\n\t// Optional, more detailed associated progress message. Contains\n\t// complementary information to the `title`.\n\t//\n\t// Examples: \"3/25 files\", \"project/src/module2\", \"node_modules/some_dep\".\n\t// If unset, the previous progress message (if any) is still valid.\n\tMessage string `json:\"message,omitempty\"`\n\t// Optional progress percentage to display (value 100 is considered 100%).\n\t// If not provided infinite progress is assumed and clients are allowed\n\t// to ignore the `percentage` value in subsequent in report notifications.\n\t//\n\t// The value should be steadily rising. Clients are free to ignore values\n\t// that are not following this rule. The value range is [0, 100].\n\tPercentage uint32 `json:\"percentage,omitempty\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#workDoneProgressCancelParams\ntype WorkDoneProgressCancelParams struct {\n\t// The token to be used to report progress.\n\tToken ProgressToken `json:\"token\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#workDoneProgressCreateParams\ntype WorkDoneProgressCreateParams struct {\n\t// The token to be used to report progress.\n\tToken ProgressToken `json:\"token\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#workDoneProgressEnd\ntype WorkDoneProgressEnd struct {\n\tKind string `json:\"kind\"`\n\t// Optional, a final message indicating to for example indicate the outcome\n\t// of the operation.\n\tMessage string `json:\"message,omitempty\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#workDoneProgressOptions\ntype WorkDoneProgressOptions struct {\n\tWorkDoneProgress bool `json:\"workDoneProgress,omitempty\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#workDoneProgressParams\ntype WorkDoneProgressParams struct {\n\t// An optional token that a server can use to report work done progress.\n\tWorkDoneToken ProgressToken `json:\"workDoneToken,omitempty\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#workDoneProgressReport\ntype WorkDoneProgressReport struct {\n\tKind string `json:\"kind\"`\n\t// Controls enablement state of a cancel button.\n\t//\n\t// Clients that don't support cancellation or don't support controlling the button's\n\t// enablement state are allowed to ignore the property.\n\tCancellable bool `json:\"cancellable,omitempty\"`\n\t// Optional, more detailed associated progress message. Contains\n\t// complementary information to the `title`.\n\t//\n\t// Examples: \"3/25 files\", \"project/src/module2\", \"node_modules/some_dep\".\n\t// If unset, the previous progress message (if any) is still valid.\n\tMessage string `json:\"message,omitempty\"`\n\t// Optional progress percentage to display (value 100 is considered 100%).\n\t// If not provided infinite progress is assumed and clients are allowed\n\t// to ignore the `percentage` value in subsequent in report notifications.\n\t//\n\t// The value should be steadily rising. Clients are free to ignore values\n\t// that are not following this rule. The value range is [0, 100]\n\tPercentage uint32 `json:\"percentage,omitempty\"`\n}\n\n// Workspace specific client capabilities.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#workspaceClientCapabilities\ntype WorkspaceClientCapabilities struct {\n\t// The client supports applying batch edits\n\t// to the workspace by supporting the request\n\t// 'workspace/applyEdit'\n\tApplyEdit bool `json:\"applyEdit,omitempty\"`\n\t// Capabilities specific to `WorkspaceEdit`s.\n\tWorkspaceEdit *WorkspaceEditClientCapabilities `json:\"workspaceEdit,omitempty\"`\n\t// Capabilities specific to the `workspace/didChangeConfiguration` notification.\n\tDidChangeConfiguration DidChangeConfigurationClientCapabilities `json:\"didChangeConfiguration,omitempty\"`\n\t// Capabilities specific to the `workspace/didChangeWatchedFiles` notification.\n\tDidChangeWatchedFiles DidChangeWatchedFilesClientCapabilities `json:\"didChangeWatchedFiles,omitempty\"`\n\t// Capabilities specific to the `workspace/symbol` request.\n\tSymbol *WorkspaceSymbolClientCapabilities `json:\"symbol,omitempty\"`\n\t// Capabilities specific to the `workspace/executeCommand` request.\n\tExecuteCommand *ExecuteCommandClientCapabilities `json:\"executeCommand,omitempty\"`\n\t// The client has support for workspace folders.\n\t//\n\t// @since 3.6.0\n\tWorkspaceFolders bool `json:\"workspaceFolders,omitempty\"`\n\t// The client supports `workspace/configuration` requests.\n\t//\n\t// @since 3.6.0\n\tConfiguration bool `json:\"configuration,omitempty\"`\n\t// Capabilities specific to the semantic token requests scoped to the\n\t// workspace.\n\t//\n\t// @since 3.16.0.\n\tSemanticTokens *SemanticTokensWorkspaceClientCapabilities `json:\"semanticTokens,omitempty\"`\n\t// Capabilities specific to the code lens requests scoped to the\n\t// workspace.\n\t//\n\t// @since 3.16.0.\n\tCodeLens *CodeLensWorkspaceClientCapabilities `json:\"codeLens,omitempty\"`\n\t// The client has support for file notifications/requests for user operations on files.\n\t//\n\t// Since 3.16.0\n\tFileOperations *FileOperationClientCapabilities `json:\"fileOperations,omitempty\"`\n\t// Capabilities specific to the inline values requests scoped to the\n\t// workspace.\n\t//\n\t// @since 3.17.0.\n\tInlineValue *InlineValueWorkspaceClientCapabilities `json:\"inlineValue,omitempty\"`\n\t// Capabilities specific to the inlay hint requests scoped to the\n\t// workspace.\n\t//\n\t// @since 3.17.0.\n\tInlayHint *InlayHintWorkspaceClientCapabilities `json:\"inlayHint,omitempty\"`\n\t// Capabilities specific to the diagnostic requests scoped to the\n\t// workspace.\n\t//\n\t// @since 3.17.0.\n\tDiagnostics *DiagnosticWorkspaceClientCapabilities `json:\"diagnostics,omitempty\"`\n\t// Capabilities specific to the folding range requests scoped to the workspace.\n\t//\n\t// @since 3.18.0\n\t// @proposed\n\tFoldingRange *FoldingRangeWorkspaceClientCapabilities `json:\"foldingRange,omitempty\"`\n\t// Capabilities specific to the `workspace/textDocumentContent` request.\n\t//\n\t// @since 3.18.0\n\t// @proposed\n\tTextDocumentContent *TextDocumentContentClientCapabilities `json:\"textDocumentContent,omitempty\"`\n}\n\n// Parameters of the workspace diagnostic request.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#workspaceDiagnosticParams\ntype WorkspaceDiagnosticParams struct {\n\t// The additional identifier provided during registration.\n\tIdentifier string `json:\"identifier,omitempty\"`\n\t// The currently known diagnostic reports with their\n\t// previous result ids.\n\tPreviousResultIds []PreviousResultId `json:\"previousResultIds\"`\n\tWorkDoneProgressParams\n\tPartialResultParams\n}\n\n// A workspace diagnostic report.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#workspaceDiagnosticReport\ntype WorkspaceDiagnosticReport struct {\n\tItems []WorkspaceDocumentDiagnosticReport `json:\"items\"`\n}\n\n// A partial result for a workspace diagnostic report.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#workspaceDiagnosticReportPartialResult\ntype WorkspaceDiagnosticReportPartialResult struct {\n\tItems []WorkspaceDocumentDiagnosticReport `json:\"items\"`\n}\n\n// A workspace diagnostic document report.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#workspaceDocumentDiagnosticReport\ntype WorkspaceDocumentDiagnosticReport = Or_WorkspaceDocumentDiagnosticReport // (alias)\n// A workspace edit represents changes to many resources managed in the workspace. The edit\n// should either provide `changes` or `documentChanges`. If documentChanges are present\n// they are preferred over `changes` if the client can handle versioned document edits.\n//\n// Since version 3.13.0 a workspace edit can contain resource operations as well. If resource\n// operations are present clients need to execute the operations in the order in which they\n// are provided. So a workspace edit for example can consist of the following two changes:\n// (1) a create file a.txt and (2) a text document edit which insert text into file a.txt.\n//\n// An invalid sequence (e.g. (1) delete file a.txt and (2) insert text into file a.txt) will\n// cause failure of the operation. How the client recovers from the failure is described by\n// the client capability: `workspace.workspaceEdit.failureHandling`\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#workspaceEdit\ntype WorkspaceEdit struct {\n\t// Holds changes to existing resources.\n\tChanges map[DocumentUri][]TextEdit `json:\"changes,omitempty\"`\n\t// Depending on the client capability `workspace.workspaceEdit.resourceOperations` document changes\n\t// are either an array of `TextDocumentEdit`s to express changes to n different text documents\n\t// where each text document edit addresses a specific version of a text document. Or it can contain\n\t// above `TextDocumentEdit`s mixed with create, rename and delete file / folder operations.\n\t//\n\t// Whether a client supports versioned document edits is expressed via\n\t// `workspace.workspaceEdit.documentChanges` client capability.\n\t//\n\t// If a client neither supports `documentChanges` nor `workspace.workspaceEdit.resourceOperations` then\n\t// only plain `TextEdit`s using the `changes` property are supported.\n\tDocumentChanges []DocumentChange `json:\"documentChanges,omitempty\"`\n\t// A map of change annotations that can be referenced in `AnnotatedTextEdit`s or create, rename and\n\t// delete file / folder operations.\n\t//\n\t// Whether clients honor this property depends on the client capability `workspace.changeAnnotationSupport`.\n\t//\n\t// @since 3.16.0\n\tChangeAnnotations map[ChangeAnnotationIdentifier]ChangeAnnotation `json:\"changeAnnotations,omitempty\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#workspaceEditClientCapabilities\ntype WorkspaceEditClientCapabilities struct {\n\t// The client supports versioned document changes in `WorkspaceEdit`s\n\tDocumentChanges bool `json:\"documentChanges,omitempty\"`\n\t// The resource operations the client supports. Clients should at least\n\t// support 'create', 'rename' and 'delete' files and folders.\n\t//\n\t// @since 3.13.0\n\tResourceOperations []ResourceOperationKind `json:\"resourceOperations,omitempty\"`\n\t// The failure handling strategy of a client if applying the workspace edit\n\t// fails.\n\t//\n\t// @since 3.13.0\n\tFailureHandling *FailureHandlingKind `json:\"failureHandling,omitempty\"`\n\t// Whether the client normalizes line endings to the client specific\n\t// setting.\n\t// If set to `true` the client will normalize line ending characters\n\t// in a workspace edit to the client-specified new line\n\t// character.\n\t//\n\t// @since 3.16.0\n\tNormalizesLineEndings bool `json:\"normalizesLineEndings,omitempty\"`\n\t// Whether the client in general supports change annotations on text edits,\n\t// create file, rename file and delete file changes.\n\t//\n\t// @since 3.16.0\n\tChangeAnnotationSupport *ChangeAnnotationsSupportOptions `json:\"changeAnnotationSupport,omitempty\"`\n\t// Whether the client supports `WorkspaceEditMetadata` in `WorkspaceEdit`s.\n\t//\n\t// @since 3.18.0\n\t// @proposed\n\tMetadataSupport bool `json:\"metadataSupport,omitempty\"`\n\t// Whether the client supports snippets as text edits.\n\t//\n\t// @since 3.18.0\n\t// @proposed\n\tSnippetEditSupport bool `json:\"snippetEditSupport,omitempty\"`\n}\n\n// Additional data about a workspace edit.\n//\n// @since 3.18.0\n// @proposed\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#workspaceEditMetadata\ntype WorkspaceEditMetadata struct {\n\t// Signal to the editor that this edit is a refactoring.\n\tIsRefactoring bool `json:\"isRefactoring,omitempty\"`\n}\n\n// A workspace folder inside a client.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#workspaceFolder\ntype WorkspaceFolder struct {\n\t// The associated URI for this workspace folder.\n\tURI URI `json:\"uri\"`\n\t// The name of the workspace folder. Used to refer to this\n\t// workspace folder in the user interface.\n\tName string `json:\"name\"`\n}\n\n// The workspace folder change event.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#workspaceFoldersChangeEvent\ntype WorkspaceFoldersChangeEvent struct {\n\t// The array of added workspace folders\n\tAdded []WorkspaceFolder `json:\"added\"`\n\t// The array of the removed workspace folders\n\tRemoved []WorkspaceFolder `json:\"removed\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#workspaceFoldersInitializeParams\ntype WorkspaceFoldersInitializeParams struct {\n\t// The workspace folders configured in the client when the server starts.\n\t//\n\t// This property is only available if the client supports workspace folders.\n\t// It can be `null` if the client supports workspace folders but none are\n\t// configured.\n\t//\n\t// @since 3.6.0\n\tWorkspaceFolders []WorkspaceFolder `json:\"workspaceFolders,omitempty\"`\n}\n\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#workspaceFoldersServerCapabilities\ntype WorkspaceFoldersServerCapabilities struct {\n\t// The server has support for workspace folders\n\tSupported bool `json:\"supported,omitempty\"`\n\t// Whether the server wants to receive workspace folder\n\t// change notifications.\n\t//\n\t// If a string is provided the string is treated as an ID\n\t// under which the notification is registered on the client\n\t// side. The ID can be used to unregister for these events\n\t// using the `client/unregisterCapability` request.\n\tChangeNotifications *Or_WorkspaceFoldersServerCapabilities_changeNotifications `json:\"changeNotifications,omitempty\"`\n}\n\n// A full document diagnostic report for a workspace diagnostic result.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#workspaceFullDocumentDiagnosticReport\ntype WorkspaceFullDocumentDiagnosticReport struct {\n\t// The URI for which diagnostic information is reported.\n\tURI DocumentUri `json:\"uri\"`\n\t// The version number for which the diagnostics are reported.\n\t// If the document is not marked as open `null` can be provided.\n\tVersion int32 `json:\"version\"`\n\tFullDocumentDiagnosticReport\n}\n\n// Defines workspace specific capabilities of the server.\n//\n// @since 3.18.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#workspaceOptions\ntype WorkspaceOptions struct {\n\t// The server supports workspace folder.\n\t//\n\t// @since 3.6.0\n\tWorkspaceFolders *WorkspaceFoldersServerCapabilities `json:\"workspaceFolders,omitempty\"`\n\t// The server is interested in notifications/requests for operations on files.\n\t//\n\t// @since 3.16.0\n\tFileOperations *FileOperationOptions `json:\"fileOperations,omitempty\"`\n\t// The server supports the `workspace/textDocumentContent` request.\n\t//\n\t// @since 3.18.0\n\t// @proposed\n\tTextDocumentContent *Or_WorkspaceOptions_textDocumentContent `json:\"textDocumentContent,omitempty\"`\n}\n\n// A special workspace symbol that supports locations without a range.\n//\n// See also SymbolInformation.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#workspaceSymbol\ntype WorkspaceSymbol struct {\n\t// The location of the symbol. Whether a server is allowed to\n\t// return a location without a range depends on the client\n\t// capability `workspace.symbol.resolveSupport`.\n\t//\n\t// See SymbolInformation#location for more details.\n\tLocation Or_WorkspaceSymbol_location `json:\"location\"`\n\t// A data entry field that is preserved on a workspace symbol between a\n\t// workspace symbol request and a workspace symbol resolve request.\n\tData interface{} `json:\"data,omitempty\"`\n\tBaseSymbolInformation\n}\n\n// Client capabilities for a {@link WorkspaceSymbolRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#workspaceSymbolClientCapabilities\ntype WorkspaceSymbolClientCapabilities struct {\n\t// Symbol request supports dynamic registration.\n\tDynamicRegistration bool `json:\"dynamicRegistration,omitempty\"`\n\t// Specific capabilities for the `SymbolKind` in the `workspace/symbol` request.\n\tSymbolKind *ClientSymbolKindOptions `json:\"symbolKind,omitempty\"`\n\t// The client supports tags on `SymbolInformation`.\n\t// Clients supporting tags have to handle unknown tags gracefully.\n\t//\n\t// @since 3.16.0\n\tTagSupport *ClientSymbolTagOptions `json:\"tagSupport,omitempty\"`\n\t// The client support partial workspace symbols. The client will send the\n\t// request `workspaceSymbol/resolve` to the server to resolve additional\n\t// properties.\n\t//\n\t// @since 3.17.0\n\tResolveSupport *ClientSymbolResolveOptions `json:\"resolveSupport,omitempty\"`\n}\n\n// Server capabilities for a {@link WorkspaceSymbolRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#workspaceSymbolOptions\ntype WorkspaceSymbolOptions struct {\n\t// The server provides support to resolve additional\n\t// information for a workspace symbol.\n\t//\n\t// @since 3.17.0\n\tResolveProvider bool `json:\"resolveProvider,omitempty\"`\n\tWorkDoneProgressOptions\n}\n\n// The parameters of a {@link WorkspaceSymbolRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#workspaceSymbolParams\ntype WorkspaceSymbolParams struct {\n\t// A query string to filter symbols by. Clients may send an empty\n\t// string here to request all symbols.\n\t//\n\t// The `query`-parameter should be interpreted in a *relaxed way* as editors\n\t// will apply their own highlighting and scoring on the results. A good rule\n\t// of thumb is to match case-insensitive and to simply check that the\n\t// characters of *query* appear in their order in a candidate symbol.\n\t// Servers shouldn't use prefix, substring, or similar strict matching.\n\tQuery string `json:\"query\"`\n\tWorkDoneProgressParams\n\tPartialResultParams\n}\n\n// Registration options for a {@link WorkspaceSymbolRequest}.\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#workspaceSymbolRegistrationOptions\ntype WorkspaceSymbolRegistrationOptions struct {\n\tWorkspaceSymbolOptions\n}\n\n// An unchanged document diagnostic report for a workspace diagnostic result.\n//\n// @since 3.17.0\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#workspaceUnchangedDocumentDiagnosticReport\ntype WorkspaceUnchangedDocumentDiagnosticReport struct {\n\t// The URI for which diagnostic information is reported.\n\tURI DocumentUri `json:\"uri\"`\n\t// The version number for which the diagnostics are reported.\n\t// If the document is not marked as open `null` can be provided.\n\tVersion int32 `json:\"version\"`\n\tUnchangedDocumentDiagnosticReport\n}\n\n// The initialize parameters\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#_InitializeParams\ntype XInitializeParams struct {\n\t// The process Id of the parent process that started\n\t// the server.\n\t//\n\t// Is `null` if the process has not been started by another process.\n\t// If the parent process is not alive then the server should exit.\n\tProcessID int32 `json:\"processId\"`\n\t// Information about the client\n\t//\n\t// @since 3.15.0\n\tClientInfo *ClientInfo `json:\"clientInfo,omitempty\"`\n\t// The locale the client is currently showing the user interface\n\t// in. This must not necessarily be the locale of the operating\n\t// system.\n\t//\n\t// Uses IETF language tags as the value's syntax\n\t// (See https://en.wikipedia.org/wiki/IETF_language_tag)\n\t//\n\t// @since 3.16.0\n\tLocale string `json:\"locale,omitempty\"`\n\t// The rootPath of the workspace. Is null\n\t// if no folder is open.\n\t//\n\t// @deprecated in favour of rootUri.\n\tRootPath string `json:\"rootPath,omitempty\"`\n\t// The rootUri of the workspace. Is null if no\n\t// folder is open. If both `rootPath` and `rootUri` are set\n\t// `rootUri` wins.\n\t//\n\t// @deprecated in favour of workspaceFolders.\n\tRootURI DocumentUri `json:\"rootUri\"`\n\t// The capabilities provided by the client (editor or tool)\n\tCapabilities ClientCapabilities `json:\"capabilities\"`\n\t// User provided initialization options.\n\tInitializationOptions interface{} `json:\"initializationOptions,omitempty\"`\n\t// The initial trace setting. If omitted trace is disabled ('off').\n\tTrace *TraceValue `json:\"trace,omitempty\"`\n\tWorkDoneProgressParams\n}\n\n// The initialize parameters\n//\n// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#_InitializeParams\ntype _InitializeParams struct {\n\t// The process Id of the parent process that started\n\t// the server.\n\t//\n\t// Is `null` if the process has not been started by another process.\n\t// If the parent process is not alive then the server should exit.\n\tProcessID int32 `json:\"processId\"`\n\t// Information about the client\n\t//\n\t// @since 3.15.0\n\tClientInfo *ClientInfo `json:\"clientInfo,omitempty\"`\n\t// The locale the client is currently showing the user interface\n\t// in. This must not necessarily be the locale of the operating\n\t// system.\n\t//\n\t// Uses IETF language tags as the value's syntax\n\t// (See https://en.wikipedia.org/wiki/IETF_language_tag)\n\t//\n\t// @since 3.16.0\n\tLocale string `json:\"locale,omitempty\"`\n\t// The rootPath of the workspace. Is null\n\t// if no folder is open.\n\t//\n\t// @deprecated in favour of rootUri.\n\tRootPath string `json:\"rootPath,omitempty\"`\n\t// The rootUri of the workspace. Is null if no\n\t// folder is open. If both `rootPath` and `rootUri` are set\n\t// `rootUri` wins.\n\t//\n\t// @deprecated in favour of workspaceFolders.\n\tRootURI DocumentUri `json:\"rootUri\"`\n\t// The capabilities provided by the client (editor or tool)\n\tCapabilities ClientCapabilities `json:\"capabilities\"`\n\t// User provided initialization options.\n\tInitializationOptions interface{} `json:\"initializationOptions,omitempty\"`\n\t// The initial trace setting. If omitted trace is disabled ('off').\n\tTrace *TraceValue `json:\"trace,omitempty\"`\n\tWorkDoneProgressParams\n}\n\nconst (\n\t// A set of predefined code action kinds\n\t// Empty kind.\n\tEmpty CodeActionKind = \"\"\n\t// Base kind for quickfix actions: 'quickfix'\n\tQuickFix CodeActionKind = \"quickfix\"\n\t// Base kind for refactoring actions: 'refactor'\n\tRefactor CodeActionKind = \"refactor\"\n\t// Base kind for refactoring extraction actions: 'refactor.extract'\n\t//\n\t// Example extract actions:\n\t//\n\t//\n\t// - Extract method\n\t// - Extract function\n\t// - Extract variable\n\t// - Extract interface from class\n\t// - ...\n\tRefactorExtract CodeActionKind = \"refactor.extract\"\n\t// Base kind for refactoring inline actions: 'refactor.inline'\n\t//\n\t// Example inline actions:\n\t//\n\t//\n\t// - Inline function\n\t// - Inline variable\n\t// - Inline constant\n\t// - ...\n\tRefactorInline CodeActionKind = \"refactor.inline\"\n\t// Base kind for refactoring move actions: `refactor.move`\n\t//\n\t// Example move actions:\n\t//\n\t//\n\t// - Move a function to a new file\n\t// - Move a property between classes\n\t// - Move method to base class\n\t// - ...\n\t//\n\t// @since 3.18.0\n\t// @proposed\n\tRefactorMove CodeActionKind = \"refactor.move\"\n\t// Base kind for refactoring rewrite actions: 'refactor.rewrite'\n\t//\n\t// Example rewrite actions:\n\t//\n\t//\n\t// - Convert JavaScript function to class\n\t// - Add or remove parameter\n\t// - Encapsulate field\n\t// - Make method static\n\t// - Move method to base class\n\t// - ...\n\tRefactorRewrite CodeActionKind = \"refactor.rewrite\"\n\t// Base kind for source actions: `source`\n\t//\n\t// Source code actions apply to the entire file.\n\tSource CodeActionKind = \"source\"\n\t// Base kind for an organize imports source action: `source.organizeImports`\n\tSourceOrganizeImports CodeActionKind = \"source.organizeImports\"\n\t// Base kind for auto-fix source actions: `source.fixAll`.\n\t//\n\t// Fix all actions automatically fix errors that have a clear fix that do not require user input.\n\t// They should not suppress errors or perform unsafe fixes such as generating new types or classes.\n\t//\n\t// @since 3.15.0\n\tSourceFixAll CodeActionKind = \"source.fixAll\"\n\t// Base kind for all code actions applying to the entire notebook's scope. CodeActionKinds using\n\t// this should always begin with `notebook.`\n\t//\n\t// @since 3.18.0\n\tNotebook CodeActionKind = \"notebook\"\n\t// The reason why code actions were requested.\n\t//\n\t// @since 3.17.0\n\t// Code actions were explicitly requested by the user or by an extension.\n\tCodeActionInvoked CodeActionTriggerKind = 1\n\t// Code actions were requested automatically.\n\t//\n\t// This typically happens when current selection in a file changes, but can\n\t// also be triggered when file content changes.\n\tCodeActionAutomatic CodeActionTriggerKind = 2\n\t// The kind of a completion entry.\n\tTextCompletion CompletionItemKind = 1\n\tMethodCompletion CompletionItemKind = 2\n\tFunctionCompletion CompletionItemKind = 3\n\tConstructorCompletion CompletionItemKind = 4\n\tFieldCompletion CompletionItemKind = 5\n\tVariableCompletion CompletionItemKind = 6\n\tClassCompletion CompletionItemKind = 7\n\tInterfaceCompletion CompletionItemKind = 8\n\tModuleCompletion CompletionItemKind = 9\n\tPropertyCompletion CompletionItemKind = 10\n\tUnitCompletion CompletionItemKind = 11\n\tValueCompletion CompletionItemKind = 12\n\tEnumCompletion CompletionItemKind = 13\n\tKeywordCompletion CompletionItemKind = 14\n\tSnippetCompletion CompletionItemKind = 15\n\tColorCompletion CompletionItemKind = 16\n\tFileCompletion CompletionItemKind = 17\n\tReferenceCompletion CompletionItemKind = 18\n\tFolderCompletion CompletionItemKind = 19\n\tEnumMemberCompletion CompletionItemKind = 20\n\tConstantCompletion CompletionItemKind = 21\n\tStructCompletion CompletionItemKind = 22\n\tEventCompletion CompletionItemKind = 23\n\tOperatorCompletion CompletionItemKind = 24\n\tTypeParameterCompletion CompletionItemKind = 25\n\t// Completion item tags are extra annotations that tweak the rendering of a completion\n\t// item.\n\t//\n\t// @since 3.15.0\n\t// Render a completion as obsolete, usually using a strike-out.\n\tComplDeprecated CompletionItemTag = 1\n\t// How a completion was triggered\n\t// Completion was triggered by typing an identifier (24x7 code\n\t// complete), manual invocation (e.g Ctrl+Space) or via API.\n\tInvoked CompletionTriggerKind = 1\n\t// Completion was triggered by a trigger character specified by\n\t// the `triggerCharacters` properties of the `CompletionRegistrationOptions`.\n\tTriggerCharacter CompletionTriggerKind = 2\n\t// Completion was re-triggered as current completion list is incomplete\n\tTriggerForIncompleteCompletions CompletionTriggerKind = 3\n\t// The diagnostic's severity.\n\t// Reports an error.\n\tSeverityError DiagnosticSeverity = 1\n\t// Reports a warning.\n\tSeverityWarning DiagnosticSeverity = 2\n\t// Reports an information.\n\tSeverityInformation DiagnosticSeverity = 3\n\t// Reports a hint.\n\tSeverityHint DiagnosticSeverity = 4\n\t// The diagnostic tags.\n\t//\n\t// @since 3.15.0\n\t// Unused or unnecessary code.\n\t//\n\t// Clients are allowed to render diagnostics with this tag faded out instead of having\n\t// an error squiggle.\n\tUnnecessary DiagnosticTag = 1\n\t// Deprecated or obsolete code.\n\t//\n\t// Clients are allowed to rendered diagnostics with this tag strike through.\n\tDeprecated DiagnosticTag = 2\n\t// The document diagnostic report kinds.\n\t//\n\t// @since 3.17.0\n\t// A diagnostic report with a full\n\t// set of problems.\n\tDiagnosticFull DocumentDiagnosticReportKind = \"full\"\n\t// A report indicating that the last\n\t// returned report is still accurate.\n\tDiagnosticUnchanged DocumentDiagnosticReportKind = \"unchanged\"\n\t// A document highlight kind.\n\t// A textual occurrence.\n\tText DocumentHighlightKind = 1\n\t// Read-access of a symbol, like reading a variable.\n\tRead DocumentHighlightKind = 2\n\t// Write-access of a symbol, like writing to a variable.\n\tWrite DocumentHighlightKind = 3\n\t// Predefined error codes.\n\tParseError ErrorCodes = -32700\n\tInvalidRequest ErrorCodes = -32600\n\tMethodNotFound ErrorCodes = -32601\n\tInvalidParams ErrorCodes = -32602\n\tInternalError ErrorCodes = -32603\n\t// Error code indicating that a server received a notification or\n\t// request before the server has received the `initialize` request.\n\tServerNotInitialized ErrorCodes = -32002\n\tUnknownErrorCode ErrorCodes = -32001\n\t// Applying the workspace change is simply aborted if one of the changes provided\n\t// fails. All operations executed before the failing operation stay executed.\n\tAbort FailureHandlingKind = \"abort\"\n\t// All operations are executed transactional. That means they either all\n\t// succeed or no changes at all are applied to the workspace.\n\tTransactional FailureHandlingKind = \"transactional\"\n\t// If the workspace edit contains only textual file changes they are executed transactional.\n\t// If resource changes (create, rename or delete file) are part of the change the failure\n\t// handling strategy is abort.\n\tTextOnlyTransactional FailureHandlingKind = \"textOnlyTransactional\"\n\t// The client tries to undo the operations already executed. But there is no\n\t// guarantee that this is succeeding.\n\tUndo FailureHandlingKind = \"undo\"\n\t// The file event type\n\t// The file got created.\n\tCreated FileChangeType = 1\n\t// The file got changed.\n\tChanged FileChangeType = 2\n\t// The file got deleted.\n\tDeleted FileChangeType = 3\n\t// A pattern kind describing if a glob pattern matches a file a folder or\n\t// both.\n\t//\n\t// @since 3.16.0\n\t// The pattern matches a file only.\n\tFilePattern FileOperationPatternKind = \"file\"\n\t// The pattern matches a folder only.\n\tFolderPattern FileOperationPatternKind = \"folder\"\n\t// A set of predefined range kinds.\n\t// Folding range for a comment\n\tComment FoldingRangeKind = \"comment\"\n\t// Folding range for an import or include\n\tImports FoldingRangeKind = \"imports\"\n\t// Folding range for a region (e.g. `#region`)\n\tRegion FoldingRangeKind = \"region\"\n\t// Inlay hint kinds.\n\t//\n\t// @since 3.17.0\n\t// An inlay hint that for a type annotation.\n\tType InlayHintKind = 1\n\t// An inlay hint that is for a parameter.\n\tParameter InlayHintKind = 2\n\t// Describes how an {@link InlineCompletionItemProvider inline completion provider} was triggered.\n\t//\n\t// @since 3.18.0\n\t// @proposed\n\t// Completion was triggered explicitly by a user gesture.\n\tInlineInvoked InlineCompletionTriggerKind = 1\n\t// Completion was triggered automatically while editing.\n\tInlineAutomatic InlineCompletionTriggerKind = 2\n\t// Defines whether the insert text in a completion item should be interpreted as\n\t// plain text or a snippet.\n\t// The primary text to be inserted is treated as a plain string.\n\tPlainTextTextFormat InsertTextFormat = 1\n\t// The primary text to be inserted is treated as a snippet.\n\t//\n\t// A snippet can define tab stops and placeholders with `$1`, `$2`\n\t// and `${3:foo}`. `$0` defines the final tab stop, it defaults to\n\t// the end of the snippet. Placeholders with equal identifiers are linked,\n\t// that is typing in one will update others too.\n\t//\n\t// See also: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#snippet_syntax\n\tSnippetTextFormat InsertTextFormat = 2\n\t// How whitespace and indentation is handled during completion\n\t// item insertion.\n\t//\n\t// @since 3.16.0\n\t// The insertion or replace strings is taken as it is. If the\n\t// value is multi line the lines below the cursor will be\n\t// inserted using the indentation defined in the string value.\n\t// The client will not apply any kind of adjustments to the\n\t// string.\n\tAsIs InsertTextMode = 1\n\t// The editor adjusts leading whitespace of new lines so that\n\t// they match the indentation up to the cursor of the line for\n\t// which the item is accepted.\n\t//\n\t// Consider a line like this: <2tabs><3tabs>foo. Accepting a\n\t// multi line completion item is indented using 2 tabs and all\n\t// following lines inserted will be indented using 2 tabs as well.\n\tAdjustIndentation InsertTextMode = 2\n\t// A request failed but it was syntactically correct, e.g the\n\t// method name was known and the parameters were valid. The error\n\t// message should contain human readable information about why\n\t// the request failed.\n\t//\n\t// @since 3.17.0\n\tRequestFailed LSPErrorCodes = -32803\n\t// The server cancelled the request. This error code should\n\t// only be used for requests that explicitly support being\n\t// server cancellable.\n\t//\n\t// @since 3.17.0\n\tServerCancelled LSPErrorCodes = -32802\n\t// The server detected that the content of a document got\n\t// modified outside normal conditions. A server should\n\t// NOT send this error code if it detects a content change\n\t// in it unprocessed messages. The result even computed\n\t// on an older state might still be useful for the client.\n\t//\n\t// If a client decides that a result is not of any use anymore\n\t// the client should cancel the request.\n\tContentModified LSPErrorCodes = -32801\n\t// The client has canceled a request and a server has detected\n\t// the cancel.\n\tRequestCancelled LSPErrorCodes = -32800\n\t// Predefined Language kinds\n\t// @since 3.18.0\n\t// @proposed\n\tLangABAP LanguageKind = \"abap\"\n\tLangWindowsBat LanguageKind = \"bat\"\n\tLangBibTeX LanguageKind = \"bibtex\"\n\tLangClojure LanguageKind = \"clojure\"\n\tLangCoffeescript LanguageKind = \"coffeescript\"\n\tLangC LanguageKind = \"c\"\n\tLangCPP LanguageKind = \"cpp\"\n\tLangCSharp LanguageKind = \"csharp\"\n\tLangCSS LanguageKind = \"css\"\n\t// @since 3.18.0\n\t// @proposed\n\tLangD LanguageKind = \"d\"\n\t// @since 3.18.0\n\t// @proposed\n\tLangDelphi LanguageKind = \"pascal\"\n\tLangDiff LanguageKind = \"diff\"\n\tLangDart LanguageKind = \"dart\"\n\tLangDockerfile LanguageKind = \"dockerfile\"\n\tLangElixir LanguageKind = \"elixir\"\n\tLangErlang LanguageKind = \"erlang\"\n\tLangFSharp LanguageKind = \"fsharp\"\n\tLangGitCommit LanguageKind = \"git-commit\"\n\tLangGitRebase LanguageKind = \"rebase\"\n\tLangGo LanguageKind = \"go\"\n\tLangGroovy LanguageKind = \"groovy\"\n\tLangHandlebars LanguageKind = \"handlebars\"\n\tLangHaskell LanguageKind = \"haskell\"\n\tLangHTML LanguageKind = \"html\"\n\tLangIni LanguageKind = \"ini\"\n\tLangJava LanguageKind = \"java\"\n\tLangJavaScript LanguageKind = \"javascript\"\n\tLangJavaScriptReact LanguageKind = \"javascriptreact\"\n\tLangJSON LanguageKind = \"json\"\n\tLangLaTeX LanguageKind = \"latex\"\n\tLangLess LanguageKind = \"less\"\n\tLangLua LanguageKind = \"lua\"\n\tLangMakefile LanguageKind = \"makefile\"\n\tLangMarkdown LanguageKind = \"markdown\"\n\tLangObjectiveC LanguageKind = \"objective-c\"\n\tLangObjectiveCPP LanguageKind = \"objective-cpp\"\n\t// @since 3.18.0\n\t// @proposed\n\tLangPascal LanguageKind = \"pascal\"\n\tLangPerl LanguageKind = \"perl\"\n\tLangPerl6 LanguageKind = \"perl6\"\n\tLangPHP LanguageKind = \"php\"\n\tLangPowershell LanguageKind = \"powershell\"\n\tLangPug LanguageKind = \"jade\"\n\tLangPython LanguageKind = \"python\"\n\tLangR LanguageKind = \"r\"\n\tLangRazor LanguageKind = \"razor\"\n\tLangRuby LanguageKind = \"ruby\"\n\tLangRust LanguageKind = \"rust\"\n\tLangSCSS LanguageKind = \"scss\"\n\tLangSASS LanguageKind = \"sass\"\n\tLangScala LanguageKind = \"scala\"\n\tLangShaderLab LanguageKind = \"shaderlab\"\n\tLangShellScript LanguageKind = \"shellscript\"\n\tLangSQL LanguageKind = \"sql\"\n\tLangSwift LanguageKind = \"swift\"\n\tLangTypeScript LanguageKind = \"typescript\"\n\tLangTypeScriptReact LanguageKind = \"typescriptreact\"\n\tLangTeX LanguageKind = \"tex\"\n\tLangVisualBasic LanguageKind = \"vb\"\n\tLangXML LanguageKind = \"xml\"\n\tLangXSL LanguageKind = \"xsl\"\n\tLangYAML LanguageKind = \"yaml\"\n\t// Describes the content type that a client supports in various\n\t// result literals like `Hover`, `ParameterInfo` or `CompletionItem`.\n\t//\n\t// Please note that `MarkupKinds` must not start with a `$`. This kinds\n\t// are reserved for internal usage.\n\t// Plain text is supported as a content format\n\tPlainText MarkupKind = \"plaintext\"\n\t// Markdown is supported as a content format\n\tMarkdown MarkupKind = \"markdown\"\n\t// The message type\n\t// An error message.\n\tError MessageType = 1\n\t// A warning message.\n\tWarning MessageType = 2\n\t// An information message.\n\tInfo MessageType = 3\n\t// A log message.\n\tLog MessageType = 4\n\t// A debug message.\n\t//\n\t// @since 3.18.0\n\t// @proposed\n\tDebug MessageType = 5\n\t// The moniker kind.\n\t//\n\t// @since 3.16.0\n\t// The moniker represent a symbol that is imported into a project\n\tImport MonikerKind = \"import\"\n\t// The moniker represents a symbol that is exported from a project\n\tExport MonikerKind = \"export\"\n\t// The moniker represents a symbol that is local to a project (e.g. a local\n\t// variable of a function, a class not visible outside the project, ...)\n\tLocal MonikerKind = \"local\"\n\t// A notebook cell kind.\n\t//\n\t// @since 3.17.0\n\t// A markup-cell is formatted source that is used for display.\n\tMarkup NotebookCellKind = 1\n\t// A code-cell is source code.\n\tCode NotebookCellKind = 2\n\t// A set of predefined position encoding kinds.\n\t//\n\t// @since 3.17.0\n\t// Character offsets count UTF-8 code units (e.g. bytes).\n\tUTF8 PositionEncodingKind = \"utf-8\"\n\t// Character offsets count UTF-16 code units.\n\t//\n\t// This is the default and must always be supported\n\t// by servers\n\tUTF16 PositionEncodingKind = \"utf-16\"\n\t// Character offsets count UTF-32 code units.\n\t//\n\t// Implementation note: these are the same as Unicode codepoints,\n\t// so this `PositionEncodingKind` may also be used for an\n\t// encoding-agnostic representation of character offsets.\n\tUTF32 PositionEncodingKind = \"utf-32\"\n\t// The client's default behavior is to select the identifier\n\t// according the to language's syntax rule.\n\tIdentifier PrepareSupportDefaultBehavior = 1\n\t// Supports creating new files and folders.\n\tCreate ResourceOperationKind = \"create\"\n\t// Supports renaming existing files and folders.\n\tRename ResourceOperationKind = \"rename\"\n\t// Supports deleting existing files and folders.\n\tDelete ResourceOperationKind = \"delete\"\n\t// A set of predefined token modifiers. This set is not fixed\n\t// an clients can specify additional token types via the\n\t// corresponding client capabilities.\n\t//\n\t// @since 3.16.0\n\tModDeclaration SemanticTokenModifiers = \"declaration\"\n\tModDefinition SemanticTokenModifiers = \"definition\"\n\tModReadonly SemanticTokenModifiers = \"readonly\"\n\tModStatic SemanticTokenModifiers = \"static\"\n\tModDeprecated SemanticTokenModifiers = \"deprecated\"\n\tModAbstract SemanticTokenModifiers = \"abstract\"\n\tModAsync SemanticTokenModifiers = \"async\"\n\tModModification SemanticTokenModifiers = \"modification\"\n\tModDocumentation SemanticTokenModifiers = \"documentation\"\n\tModDefaultLibrary SemanticTokenModifiers = \"defaultLibrary\"\n\t// A set of predefined token types. This set is not fixed\n\t// an clients can specify additional token types via the\n\t// corresponding client capabilities.\n\t//\n\t// @since 3.16.0\n\tNamespaceType SemanticTokenTypes = \"namespace\"\n\t// Represents a generic type. Acts as a fallback for types which can't be mapped to\n\t// a specific type like class or enum.\n\tTypeType SemanticTokenTypes = \"type\"\n\tClassType SemanticTokenTypes = \"class\"\n\tEnumType SemanticTokenTypes = \"enum\"\n\tInterfaceType SemanticTokenTypes = \"interface\"\n\tStructType SemanticTokenTypes = \"struct\"\n\tTypeParameterType SemanticTokenTypes = \"typeParameter\"\n\tParameterType SemanticTokenTypes = \"parameter\"\n\tVariableType SemanticTokenTypes = \"variable\"\n\tPropertyType SemanticTokenTypes = \"property\"\n\tEnumMemberType SemanticTokenTypes = \"enumMember\"\n\tEventType SemanticTokenTypes = \"event\"\n\tFunctionType SemanticTokenTypes = \"function\"\n\tMethodType SemanticTokenTypes = \"method\"\n\tMacroType SemanticTokenTypes = \"macro\"\n\tKeywordType SemanticTokenTypes = \"keyword\"\n\tModifierType SemanticTokenTypes = \"modifier\"\n\tCommentType SemanticTokenTypes = \"comment\"\n\tStringType SemanticTokenTypes = \"string\"\n\tNumberType SemanticTokenTypes = \"number\"\n\tRegexpType SemanticTokenTypes = \"regexp\"\n\tOperatorType SemanticTokenTypes = \"operator\"\n\t// @since 3.17.0\n\tDecoratorType SemanticTokenTypes = \"decorator\"\n\t// @since 3.18.0\n\tLabelType SemanticTokenTypes = \"label\"\n\t// How a signature help was triggered.\n\t//\n\t// @since 3.15.0\n\t// Signature help was invoked manually by the user or by a command.\n\tSigInvoked SignatureHelpTriggerKind = 1\n\t// Signature help was triggered by a trigger character.\n\tSigTriggerCharacter SignatureHelpTriggerKind = 2\n\t// Signature help was triggered by the cursor moving or by the document content changing.\n\tSigContentChange SignatureHelpTriggerKind = 3\n\t// A symbol kind.\n\tFile SymbolKind = 1\n\tModule SymbolKind = 2\n\tNamespace SymbolKind = 3\n\tPackage SymbolKind = 4\n\tClass SymbolKind = 5\n\tMethod SymbolKind = 6\n\tProperty SymbolKind = 7\n\tField SymbolKind = 8\n\tConstructor SymbolKind = 9\n\tEnum SymbolKind = 10\n\tInterface SymbolKind = 11\n\tFunction SymbolKind = 12\n\tVariable SymbolKind = 13\n\tConstant SymbolKind = 14\n\tString SymbolKind = 15\n\tNumber SymbolKind = 16\n\tBoolean SymbolKind = 17\n\tArray SymbolKind = 18\n\tObject SymbolKind = 19\n\tKey SymbolKind = 20\n\tNull SymbolKind = 21\n\tEnumMember SymbolKind = 22\n\tStruct SymbolKind = 23\n\tEvent SymbolKind = 24\n\tOperator SymbolKind = 25\n\tTypeParameter SymbolKind = 26\n\t// Symbol tags are extra annotations that tweak the rendering of a symbol.\n\t//\n\t// @since 3.16\n\t// Render a symbol as obsolete, usually using a strike-out.\n\tDeprecatedSymbol SymbolTag = 1\n\t// Represents reasons why a text document is saved.\n\t// Manually triggered, e.g. by the user pressing save, by starting debugging,\n\t// or by an API call.\n\tManual TextDocumentSaveReason = 1\n\t// Automatic after a delay.\n\tAfterDelay TextDocumentSaveReason = 2\n\t// When the editor lost focus.\n\tFocusOut TextDocumentSaveReason = 3\n\t// Defines how the host (editor) should sync\n\t// document changes to the language server.\n\t// Documents should not be synced at all.\n\tNone TextDocumentSyncKind = 0\n\t// Documents are synced by always sending the full content\n\t// of the document.\n\tFull TextDocumentSyncKind = 1\n\t// Documents are synced by sending the full content on open.\n\t// After that only incremental updates to the document are\n\t// send.\n\tIncremental TextDocumentSyncKind = 2\n\tRelative TokenFormat = \"relative\"\n\t// Turn tracing off.\n\tOff TraceValue = \"off\"\n\t// Trace messages only.\n\tMessages TraceValue = \"messages\"\n\t// Verbose message tracing.\n\tVerbose TraceValue = \"verbose\"\n\t// Moniker uniqueness level to define scope of the moniker.\n\t//\n\t// @since 3.16.0\n\t// The moniker is only unique inside a document\n\tDocument UniquenessLevel = \"document\"\n\t// The moniker is unique inside a project for which a dump got created\n\tProject UniquenessLevel = \"project\"\n\t// The moniker is unique inside the group to which a project belongs\n\tGroup UniquenessLevel = \"group\"\n\t// The moniker is unique inside the moniker scheme.\n\tScheme UniquenessLevel = \"scheme\"\n\t// The moniker is globally unique\n\tGlobal UniquenessLevel = \"global\"\n\t// Interested in create events.\n\tWatchCreate WatchKind = 1\n\t// Interested in change events\n\tWatchChange WatchKind = 2\n\t// Interested in delete events\n\tWatchDelete WatchKind = 4\n)\n"], ["/opencode/internal/tui/components/chat/editor.go", "package chat\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"os/exec\"\n\t\"slices\"\n\t\"strings\"\n\t\"unicode\"\n\n\t\"github.com/charmbracelet/bubbles/key\"\n\t\"github.com/charmbracelet/bubbles/textarea\"\n\ttea \"github.com/charmbracelet/bubbletea\"\n\t\"github.com/charmbracelet/lipgloss\"\n\t\"github.com/opencode-ai/opencode/internal/app\"\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n\t\"github.com/opencode-ai/opencode/internal/message\"\n\t\"github.com/opencode-ai/opencode/internal/session\"\n\t\"github.com/opencode-ai/opencode/internal/tui/components/dialog\"\n\t\"github.com/opencode-ai/opencode/internal/tui/layout\"\n\t\"github.com/opencode-ai/opencode/internal/tui/styles\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n\t\"github.com/opencode-ai/opencode/internal/tui/util\"\n)\n\ntype editorCmp struct {\n\twidth int\n\theight int\n\tapp *app.App\n\tsession session.Session\n\ttextarea textarea.Model\n\tattachments []message.Attachment\n\tdeleteMode bool\n}\n\ntype EditorKeyMaps struct {\n\tSend key.Binding\n\tOpenEditor key.Binding\n}\n\ntype bluredEditorKeyMaps struct {\n\tSend key.Binding\n\tFocus key.Binding\n\tOpenEditor key.Binding\n}\ntype DeleteAttachmentKeyMaps struct {\n\tAttachmentDeleteMode key.Binding\n\tEscape key.Binding\n\tDeleteAllAttachments key.Binding\n}\n\nvar editorMaps = EditorKeyMaps{\n\tSend: key.NewBinding(\n\t\tkey.WithKeys(\"enter\", \"ctrl+s\"),\n\t\tkey.WithHelp(\"enter\", \"send message\"),\n\t),\n\tOpenEditor: key.NewBinding(\n\t\tkey.WithKeys(\"ctrl+e\"),\n\t\tkey.WithHelp(\"ctrl+e\", \"open editor\"),\n\t),\n}\n\nvar DeleteKeyMaps = DeleteAttachmentKeyMaps{\n\tAttachmentDeleteMode: key.NewBinding(\n\t\tkey.WithKeys(\"ctrl+r\"),\n\t\tkey.WithHelp(\"ctrl+r+{i}\", \"delete attachment at index i\"),\n\t),\n\tEscape: key.NewBinding(\n\t\tkey.WithKeys(\"esc\"),\n\t\tkey.WithHelp(\"esc\", \"cancel delete mode\"),\n\t),\n\tDeleteAllAttachments: key.NewBinding(\n\t\tkey.WithKeys(\"r\"),\n\t\tkey.WithHelp(\"ctrl+r+r\", \"delete all attchments\"),\n\t),\n}\n\nconst (\n\tmaxAttachments = 5\n)\n\nfunc (m *editorCmp) openEditor() tea.Cmd {\n\teditor := os.Getenv(\"EDITOR\")\n\tif editor == \"\" {\n\t\teditor = \"nvim\"\n\t}\n\n\ttmpfile, err := os.CreateTemp(\"\", \"msg_*.md\")\n\tif err != nil {\n\t\treturn util.ReportError(err)\n\t}\n\ttmpfile.Close()\n\tc := exec.Command(editor, tmpfile.Name()) //nolint:gosec\n\tc.Stdin = os.Stdin\n\tc.Stdout = os.Stdout\n\tc.Stderr = os.Stderr\n\treturn tea.ExecProcess(c, func(err error) tea.Msg {\n\t\tif err != nil {\n\t\t\treturn util.ReportError(err)\n\t\t}\n\t\tcontent, err := os.ReadFile(tmpfile.Name())\n\t\tif err != nil {\n\t\t\treturn util.ReportError(err)\n\t\t}\n\t\tif len(content) == 0 {\n\t\t\treturn util.ReportWarn(\"Message is empty\")\n\t\t}\n\t\tos.Remove(tmpfile.Name())\n\t\tattachments := m.attachments\n\t\tm.attachments = nil\n\t\treturn SendMsg{\n\t\t\tText: string(content),\n\t\t\tAttachments: attachments,\n\t\t}\n\t})\n}\n\nfunc (m *editorCmp) Init() tea.Cmd {\n\treturn textarea.Blink\n}\n\nfunc (m *editorCmp) send() tea.Cmd {\n\tif m.app.CoderAgent.IsSessionBusy(m.session.ID) {\n\t\treturn util.ReportWarn(\"Agent is working, please wait...\")\n\t}\n\n\tvalue := m.textarea.Value()\n\tm.textarea.Reset()\n\tattachments := m.attachments\n\n\tm.attachments = nil\n\tif value == \"\" {\n\t\treturn nil\n\t}\n\treturn tea.Batch(\n\t\tutil.CmdHandler(SendMsg{\n\t\t\tText: value,\n\t\t\tAttachments: attachments,\n\t\t}),\n\t)\n}\n\nfunc (m *editorCmp) Update(msg tea.Msg) (tea.Model, tea.Cmd) {\n\tvar cmd tea.Cmd\n\tswitch msg := msg.(type) {\n\tcase dialog.ThemeChangedMsg:\n\t\tm.textarea = CreateTextArea(&m.textarea)\n\tcase dialog.CompletionSelectedMsg:\n\t\texistingValue := m.textarea.Value()\n\t\tmodifiedValue := strings.Replace(existingValue, msg.SearchString, msg.CompletionValue, 1)\n\n\t\tm.textarea.SetValue(modifiedValue)\n\t\treturn m, nil\n\tcase SessionSelectedMsg:\n\t\tif msg.ID != m.session.ID {\n\t\t\tm.session = msg\n\t\t}\n\t\treturn m, nil\n\tcase dialog.AttachmentAddedMsg:\n\t\tif len(m.attachments) >= maxAttachments {\n\t\t\tlogging.ErrorPersist(fmt.Sprintf(\"cannot add more than %d images\", maxAttachments))\n\t\t\treturn m, cmd\n\t\t}\n\t\tm.attachments = append(m.attachments, msg.Attachment)\n\tcase tea.KeyMsg:\n\t\tif key.Matches(msg, DeleteKeyMaps.AttachmentDeleteMode) {\n\t\t\tm.deleteMode = true\n\t\t\treturn m, nil\n\t\t}\n\t\tif key.Matches(msg, DeleteKeyMaps.DeleteAllAttachments) && m.deleteMode {\n\t\t\tm.deleteMode = false\n\t\t\tm.attachments = nil\n\t\t\treturn m, nil\n\t\t}\n\t\tif m.deleteMode && len(msg.Runes) > 0 && unicode.IsDigit(msg.Runes[0]) {\n\t\t\tnum := int(msg.Runes[0] - '0')\n\t\t\tm.deleteMode = false\n\t\t\tif num < 10 && len(m.attachments) > num {\n\t\t\t\tif num == 0 {\n\t\t\t\t\tm.attachments = m.attachments[num+1:]\n\t\t\t\t} else {\n\t\t\t\t\tm.attachments = slices.Delete(m.attachments, num, num+1)\n\t\t\t\t}\n\t\t\t\treturn m, nil\n\t\t\t}\n\t\t}\n\t\tif key.Matches(msg, messageKeys.PageUp) || key.Matches(msg, messageKeys.PageDown) ||\n\t\t\tkey.Matches(msg, messageKeys.HalfPageUp) || key.Matches(msg, messageKeys.HalfPageDown) {\n\t\t\treturn m, nil\n\t\t}\n\t\tif key.Matches(msg, editorMaps.OpenEditor) {\n\t\t\tif m.app.CoderAgent.IsSessionBusy(m.session.ID) {\n\t\t\t\treturn m, util.ReportWarn(\"Agent is working, please wait...\")\n\t\t\t}\n\t\t\treturn m, m.openEditor()\n\t\t}\n\t\tif key.Matches(msg, DeleteKeyMaps.Escape) {\n\t\t\tm.deleteMode = false\n\t\t\treturn m, nil\n\t\t}\n\t\t// Hanlde Enter key\n\t\tif m.textarea.Focused() && key.Matches(msg, editorMaps.Send) {\n\t\t\tvalue := m.textarea.Value()\n\t\t\tif len(value) > 0 && value[len(value)-1] == '\\\\' {\n\t\t\t\t// If the last character is a backslash, remove it and add a newline\n\t\t\t\tm.textarea.SetValue(value[:len(value)-1] + \"\\n\")\n\t\t\t\treturn m, nil\n\t\t\t} else {\n\t\t\t\t// Otherwise, send the message\n\t\t\t\treturn m, m.send()\n\t\t\t}\n\t\t}\n\n\t}\n\tm.textarea, cmd = m.textarea.Update(msg)\n\treturn m, cmd\n}\n\nfunc (m *editorCmp) View() string {\n\tt := theme.CurrentTheme()\n\n\t// Style the prompt with theme colors\n\tstyle := lipgloss.NewStyle().\n\t\tPadding(0, 0, 0, 1).\n\t\tBold(true).\n\t\tForeground(t.Primary())\n\n\tif len(m.attachments) == 0 {\n\t\treturn lipgloss.JoinHorizontal(lipgloss.Top, style.Render(\">\"), m.textarea.View())\n\t}\n\tm.textarea.SetHeight(m.height - 1)\n\treturn lipgloss.JoinVertical(lipgloss.Top,\n\t\tm.attachmentsContent(),\n\t\tlipgloss.JoinHorizontal(lipgloss.Top, style.Render(\">\"),\n\t\t\tm.textarea.View()),\n\t)\n}\n\nfunc (m *editorCmp) SetSize(width, height int) tea.Cmd {\n\tm.width = width\n\tm.height = height\n\tm.textarea.SetWidth(width - 3) // account for the prompt and padding right\n\tm.textarea.SetHeight(height)\n\tm.textarea.SetWidth(width)\n\treturn nil\n}\n\nfunc (m *editorCmp) GetSize() (int, int) {\n\treturn m.textarea.Width(), m.textarea.Height()\n}\n\nfunc (m *editorCmp) attachmentsContent() string {\n\tvar styledAttachments []string\n\tt := theme.CurrentTheme()\n\tattachmentStyles := styles.BaseStyle().\n\t\tMarginLeft(1).\n\t\tBackground(t.TextMuted()).\n\t\tForeground(t.Text())\n\tfor i, attachment := range m.attachments {\n\t\tvar filename string\n\t\tif len(attachment.FileName) > 10 {\n\t\t\tfilename = fmt.Sprintf(\" %s %s...\", styles.DocumentIcon, attachment.FileName[0:7])\n\t\t} else {\n\t\t\tfilename = fmt.Sprintf(\" %s %s\", styles.DocumentIcon, attachment.FileName)\n\t\t}\n\t\tif m.deleteMode {\n\t\t\tfilename = fmt.Sprintf(\"%d%s\", i, filename)\n\t\t}\n\t\tstyledAttachments = append(styledAttachments, attachmentStyles.Render(filename))\n\t}\n\tcontent := lipgloss.JoinHorizontal(lipgloss.Left, styledAttachments...)\n\treturn content\n}\n\nfunc (m *editorCmp) BindingKeys() []key.Binding {\n\tbindings := []key.Binding{}\n\tbindings = append(bindings, layout.KeyMapToSlice(editorMaps)...)\n\tbindings = append(bindings, layout.KeyMapToSlice(DeleteKeyMaps)...)\n\treturn bindings\n}\n\nfunc CreateTextArea(existing *textarea.Model) textarea.Model {\n\tt := theme.CurrentTheme()\n\tbgColor := t.Background()\n\ttextColor := t.Text()\n\ttextMutedColor := t.TextMuted()\n\n\tta := textarea.New()\n\tta.BlurredStyle.Base = styles.BaseStyle().Background(bgColor).Foreground(textColor)\n\tta.BlurredStyle.CursorLine = styles.BaseStyle().Background(bgColor)\n\tta.BlurredStyle.Placeholder = styles.BaseStyle().Background(bgColor).Foreground(textMutedColor)\n\tta.BlurredStyle.Text = styles.BaseStyle().Background(bgColor).Foreground(textColor)\n\tta.FocusedStyle.Base = styles.BaseStyle().Background(bgColor).Foreground(textColor)\n\tta.FocusedStyle.CursorLine = styles.BaseStyle().Background(bgColor)\n\tta.FocusedStyle.Placeholder = styles.BaseStyle().Background(bgColor).Foreground(textMutedColor)\n\tta.FocusedStyle.Text = styles.BaseStyle().Background(bgColor).Foreground(textColor)\n\n\tta.Prompt = \" \"\n\tta.ShowLineNumbers = false\n\tta.CharLimit = -1\n\n\tif existing != nil {\n\t\tta.SetValue(existing.Value())\n\t\tta.SetWidth(existing.Width())\n\t\tta.SetHeight(existing.Height())\n\t}\n\n\tta.Focus()\n\treturn ta\n}\n\nfunc NewEditorCmp(app *app.App) tea.Model {\n\tta := CreateTextArea(nil)\n\treturn &editorCmp{\n\t\tapp: app,\n\t\ttextarea: ta,\n\t}\n}\n"], ["/opencode/internal/lsp/protocol/tables.go", "package protocol\n\nvar TableKindMap = map[SymbolKind]string{\n\tFile: \"File\",\n\tModule: \"Module\",\n\tNamespace: \"Namespace\",\n\tPackage: \"Package\",\n\tClass: \"Class\",\n\tMethod: \"Method\",\n\tProperty: \"Property\",\n\tField: \"Field\",\n\tConstructor: \"Constructor\",\n\tEnum: \"Enum\",\n\tInterface: \"Interface\",\n\tFunction: \"Function\",\n\tVariable: \"Variable\",\n\tConstant: \"Constant\",\n\tString: \"String\",\n\tNumber: \"Number\",\n\tBoolean: \"Boolean\",\n\tArray: \"Array\",\n\tObject: \"Object\",\n\tKey: \"Key\",\n\tNull: \"Null\",\n\tEnumMember: \"EnumMember\",\n\tStruct: \"Struct\",\n\tEvent: \"Event\",\n\tOperator: \"Operator\",\n\tTypeParameter: \"TypeParameter\",\n}\n"], ["/opencode/internal/tui/components/dialog/models.go", "package dialog\n\nimport (\n\t\"fmt\"\n\t\"slices\"\n\t\"strings\"\n\n\t\"github.com/charmbracelet/bubbles/key\"\n\ttea \"github.com/charmbracelet/bubbletea\"\n\t\"github.com/charmbracelet/lipgloss\"\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/llm/models\"\n\t\"github.com/opencode-ai/opencode/internal/tui/layout\"\n\t\"github.com/opencode-ai/opencode/internal/tui/styles\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n\t\"github.com/opencode-ai/opencode/internal/tui/util\"\n)\n\nconst (\n\tnumVisibleModels = 10\n\tmaxDialogWidth = 40\n)\n\n// ModelSelectedMsg is sent when a model is selected\ntype ModelSelectedMsg struct {\n\tModel models.Model\n}\n\n// CloseModelDialogMsg is sent when a model is selected\ntype CloseModelDialogMsg struct{}\n\n// ModelDialog interface for the model selection dialog\ntype ModelDialog interface {\n\ttea.Model\n\tlayout.Bindings\n}\n\ntype modelDialogCmp struct {\n\tmodels []models.Model\n\tprovider models.ModelProvider\n\tavailableProviders []models.ModelProvider\n\n\tselectedIdx int\n\twidth int\n\theight int\n\tscrollOffset int\n\thScrollOffset int\n\thScrollPossible bool\n}\n\ntype modelKeyMap struct {\n\tUp key.Binding\n\tDown key.Binding\n\tLeft key.Binding\n\tRight key.Binding\n\tEnter key.Binding\n\tEscape key.Binding\n\tJ key.Binding\n\tK key.Binding\n\tH key.Binding\n\tL key.Binding\n}\n\nvar modelKeys = modelKeyMap{\n\tUp: key.NewBinding(\n\t\tkey.WithKeys(\"up\"),\n\t\tkey.WithHelp(\"↑\", \"previous model\"),\n\t),\n\tDown: key.NewBinding(\n\t\tkey.WithKeys(\"down\"),\n\t\tkey.WithHelp(\"↓\", \"next model\"),\n\t),\n\tLeft: key.NewBinding(\n\t\tkey.WithKeys(\"left\"),\n\t\tkey.WithHelp(\"←\", \"scroll left\"),\n\t),\n\tRight: key.NewBinding(\n\t\tkey.WithKeys(\"right\"),\n\t\tkey.WithHelp(\"→\", \"scroll right\"),\n\t),\n\tEnter: key.NewBinding(\n\t\tkey.WithKeys(\"enter\"),\n\t\tkey.WithHelp(\"enter\", \"select model\"),\n\t),\n\tEscape: key.NewBinding(\n\t\tkey.WithKeys(\"esc\"),\n\t\tkey.WithHelp(\"esc\", \"close\"),\n\t),\n\tJ: key.NewBinding(\n\t\tkey.WithKeys(\"j\"),\n\t\tkey.WithHelp(\"j\", \"next model\"),\n\t),\n\tK: key.NewBinding(\n\t\tkey.WithKeys(\"k\"),\n\t\tkey.WithHelp(\"k\", \"previous model\"),\n\t),\n\tH: key.NewBinding(\n\t\tkey.WithKeys(\"h\"),\n\t\tkey.WithHelp(\"h\", \"scroll left\"),\n\t),\n\tL: key.NewBinding(\n\t\tkey.WithKeys(\"l\"),\n\t\tkey.WithHelp(\"l\", \"scroll right\"),\n\t),\n}\n\nfunc (m *modelDialogCmp) Init() tea.Cmd {\n\tm.setupModels()\n\treturn nil\n}\n\nfunc (m *modelDialogCmp) Update(msg tea.Msg) (tea.Model, tea.Cmd) {\n\tswitch msg := msg.(type) {\n\tcase tea.KeyMsg:\n\t\tswitch {\n\t\tcase key.Matches(msg, modelKeys.Up) || key.Matches(msg, modelKeys.K):\n\t\t\tm.moveSelectionUp()\n\t\tcase key.Matches(msg, modelKeys.Down) || key.Matches(msg, modelKeys.J):\n\t\t\tm.moveSelectionDown()\n\t\tcase key.Matches(msg, modelKeys.Left) || key.Matches(msg, modelKeys.H):\n\t\t\tif m.hScrollPossible {\n\t\t\t\tm.switchProvider(-1)\n\t\t\t}\n\t\tcase key.Matches(msg, modelKeys.Right) || key.Matches(msg, modelKeys.L):\n\t\t\tif m.hScrollPossible {\n\t\t\t\tm.switchProvider(1)\n\t\t\t}\n\t\tcase key.Matches(msg, modelKeys.Enter):\n\t\t\tutil.ReportInfo(fmt.Sprintf(\"selected model: %s\", m.models[m.selectedIdx].Name))\n\t\t\treturn m, util.CmdHandler(ModelSelectedMsg{Model: m.models[m.selectedIdx]})\n\t\tcase key.Matches(msg, modelKeys.Escape):\n\t\t\treturn m, util.CmdHandler(CloseModelDialogMsg{})\n\t\t}\n\tcase tea.WindowSizeMsg:\n\t\tm.width = msg.Width\n\t\tm.height = msg.Height\n\t}\n\n\treturn m, nil\n}\n\n// moveSelectionUp moves the selection up or wraps to bottom\nfunc (m *modelDialogCmp) moveSelectionUp() {\n\tif m.selectedIdx > 0 {\n\t\tm.selectedIdx--\n\t} else {\n\t\tm.selectedIdx = len(m.models) - 1\n\t\tm.scrollOffset = max(0, len(m.models)-numVisibleModels)\n\t}\n\n\t// Keep selection visible\n\tif m.selectedIdx < m.scrollOffset {\n\t\tm.scrollOffset = m.selectedIdx\n\t}\n}\n\n// moveSelectionDown moves the selection down or wraps to top\nfunc (m *modelDialogCmp) moveSelectionDown() {\n\tif m.selectedIdx < len(m.models)-1 {\n\t\tm.selectedIdx++\n\t} else {\n\t\tm.selectedIdx = 0\n\t\tm.scrollOffset = 0\n\t}\n\n\t// Keep selection visible\n\tif m.selectedIdx >= m.scrollOffset+numVisibleModels {\n\t\tm.scrollOffset = m.selectedIdx - (numVisibleModels - 1)\n\t}\n}\n\nfunc (m *modelDialogCmp) switchProvider(offset int) {\n\tnewOffset := m.hScrollOffset + offset\n\n\t// Ensure we stay within bounds\n\tif newOffset < 0 {\n\t\tnewOffset = len(m.availableProviders) - 1\n\t}\n\tif newOffset >= len(m.availableProviders) {\n\t\tnewOffset = 0\n\t}\n\n\tm.hScrollOffset = newOffset\n\tm.provider = m.availableProviders[m.hScrollOffset]\n\tm.setupModelsForProvider(m.provider)\n}\n\nfunc (m *modelDialogCmp) View() string {\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\n\t// Capitalize first letter of provider name\n\tproviderName := strings.ToUpper(string(m.provider)[:1]) + string(m.provider[1:])\n\ttitle := baseStyle.\n\t\tForeground(t.Primary()).\n\t\tBold(true).\n\t\tWidth(maxDialogWidth).\n\t\tPadding(0, 0, 1).\n\t\tRender(fmt.Sprintf(\"Select %s Model\", providerName))\n\n\t// Render visible models\n\tendIdx := min(m.scrollOffset+numVisibleModels, len(m.models))\n\tmodelItems := make([]string, 0, endIdx-m.scrollOffset)\n\n\tfor i := m.scrollOffset; i < endIdx; i++ {\n\t\titemStyle := baseStyle.Width(maxDialogWidth)\n\t\tif i == m.selectedIdx {\n\t\t\titemStyle = itemStyle.Background(t.Primary()).\n\t\t\t\tForeground(t.Background()).Bold(true)\n\t\t}\n\t\tmodelItems = append(modelItems, itemStyle.Render(m.models[i].Name))\n\t}\n\n\tscrollIndicator := m.getScrollIndicators(maxDialogWidth)\n\n\tcontent := lipgloss.JoinVertical(\n\t\tlipgloss.Left,\n\t\ttitle,\n\t\tbaseStyle.Width(maxDialogWidth).Render(lipgloss.JoinVertical(lipgloss.Left, modelItems...)),\n\t\tscrollIndicator,\n\t)\n\n\treturn baseStyle.Padding(1, 2).\n\t\tBorder(lipgloss.RoundedBorder()).\n\t\tBorderBackground(t.Background()).\n\t\tBorderForeground(t.TextMuted()).\n\t\tWidth(lipgloss.Width(content) + 4).\n\t\tRender(content)\n}\n\nfunc (m *modelDialogCmp) getScrollIndicators(maxWidth int) string {\n\tvar indicator string\n\n\tif len(m.models) > numVisibleModels {\n\t\tif m.scrollOffset > 0 {\n\t\t\tindicator += \"↑ \"\n\t\t}\n\t\tif m.scrollOffset+numVisibleModels < len(m.models) {\n\t\t\tindicator += \"↓ \"\n\t\t}\n\t}\n\n\tif m.hScrollPossible {\n\t\tif m.hScrollOffset > 0 {\n\t\t\tindicator = \"← \" + indicator\n\t\t}\n\t\tif m.hScrollOffset < len(m.availableProviders)-1 {\n\t\t\tindicator += \"→\"\n\t\t}\n\t}\n\n\tif indicator == \"\" {\n\t\treturn \"\"\n\t}\n\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\n\treturn baseStyle.\n\t\tForeground(t.Primary()).\n\t\tWidth(maxWidth).\n\t\tAlign(lipgloss.Right).\n\t\tBold(true).\n\t\tRender(indicator)\n}\n\nfunc (m *modelDialogCmp) BindingKeys() []key.Binding {\n\treturn layout.KeyMapToSlice(modelKeys)\n}\n\nfunc (m *modelDialogCmp) setupModels() {\n\tcfg := config.Get()\n\tmodelInfo := GetSelectedModel(cfg)\n\tm.availableProviders = getEnabledProviders(cfg)\n\tm.hScrollPossible = len(m.availableProviders) > 1\n\n\tm.provider = modelInfo.Provider\n\tm.hScrollOffset = findProviderIndex(m.availableProviders, m.provider)\n\n\tm.setupModelsForProvider(m.provider)\n}\n\nfunc GetSelectedModel(cfg *config.Config) models.Model {\n\n\tagentCfg := cfg.Agents[config.AgentCoder]\n\tselectedModelId := agentCfg.Model\n\treturn models.SupportedModels[selectedModelId]\n}\n\nfunc getEnabledProviders(cfg *config.Config) []models.ModelProvider {\n\tvar providers []models.ModelProvider\n\tfor providerId, provider := range cfg.Providers {\n\t\tif !provider.Disabled {\n\t\t\tproviders = append(providers, providerId)\n\t\t}\n\t}\n\n\t// Sort by provider popularity\n\tslices.SortFunc(providers, func(a, b models.ModelProvider) int {\n\t\trA := models.ProviderPopularity[a]\n\t\trB := models.ProviderPopularity[b]\n\n\t\t// models not included in popularity ranking default to last\n\t\tif rA == 0 {\n\t\t\trA = 999\n\t\t}\n\t\tif rB == 0 {\n\t\t\trB = 999\n\t\t}\n\t\treturn rA - rB\n\t})\n\treturn providers\n}\n\n// findProviderIndex returns the index of the provider in the list, or -1 if not found\nfunc findProviderIndex(providers []models.ModelProvider, provider models.ModelProvider) int {\n\tfor i, p := range providers {\n\t\tif p == provider {\n\t\t\treturn i\n\t\t}\n\t}\n\treturn -1\n}\n\nfunc (m *modelDialogCmp) setupModelsForProvider(provider models.ModelProvider) {\n\tcfg := config.Get()\n\tagentCfg := cfg.Agents[config.AgentCoder]\n\tselectedModelId := agentCfg.Model\n\n\tm.provider = provider\n\tm.models = getModelsForProvider(provider)\n\tm.selectedIdx = 0\n\tm.scrollOffset = 0\n\n\t// Try to select the current model if it belongs to this provider\n\tif provider == models.SupportedModels[selectedModelId].Provider {\n\t\tfor i, model := range m.models {\n\t\t\tif model.ID == selectedModelId {\n\t\t\t\tm.selectedIdx = i\n\t\t\t\t// Adjust scroll position to keep selected model visible\n\t\t\t\tif m.selectedIdx >= numVisibleModels {\n\t\t\t\t\tm.scrollOffset = m.selectedIdx - (numVisibleModels - 1)\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc getModelsForProvider(provider models.ModelProvider) []models.Model {\n\tvar providerModels []models.Model\n\tfor _, model := range models.SupportedModels {\n\t\tif model.Provider == provider {\n\t\t\tproviderModels = append(providerModels, model)\n\t\t}\n\t}\n\n\t// reverse alphabetical order (if llm naming was consistent latest would appear first)\n\tslices.SortFunc(providerModels, func(a, b models.Model) int {\n\t\tif a.Name > b.Name {\n\t\t\treturn -1\n\t\t} else if a.Name < b.Name {\n\t\t\treturn 1\n\t\t}\n\t\treturn 0\n\t})\n\n\treturn providerModels\n}\n\nfunc NewModelDialogCmp() ModelDialog {\n\treturn &modelDialogCmp{}\n}\n"], ["/opencode/internal/tui/components/dialog/init.go", "package dialog\n\nimport (\n\t\"github.com/charmbracelet/bubbles/key\"\n\ttea \"github.com/charmbracelet/bubbletea\"\n\t\"github.com/charmbracelet/lipgloss\"\n\n\t\"github.com/opencode-ai/opencode/internal/tui/styles\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n\t\"github.com/opencode-ai/opencode/internal/tui/util\"\n)\n\n// InitDialogCmp is a component that asks the user if they want to initialize the project.\ntype InitDialogCmp struct {\n\twidth, height int\n\tselected int\n\tkeys initDialogKeyMap\n}\n\n// NewInitDialogCmp creates a new InitDialogCmp.\nfunc NewInitDialogCmp() InitDialogCmp {\n\treturn InitDialogCmp{\n\t\tselected: 0,\n\t\tkeys: initDialogKeyMap{},\n\t}\n}\n\ntype initDialogKeyMap struct {\n\tTab key.Binding\n\tLeft key.Binding\n\tRight key.Binding\n\tEnter key.Binding\n\tEscape key.Binding\n\tY key.Binding\n\tN key.Binding\n}\n\n// ShortHelp implements key.Map.\nfunc (k initDialogKeyMap) ShortHelp() []key.Binding {\n\treturn []key.Binding{\n\t\tkey.NewBinding(\n\t\t\tkey.WithKeys(\"tab\", \"left\", \"right\"),\n\t\t\tkey.WithHelp(\"tab/←/→\", \"toggle selection\"),\n\t\t),\n\t\tkey.NewBinding(\n\t\t\tkey.WithKeys(\"enter\"),\n\t\t\tkey.WithHelp(\"enter\", \"confirm\"),\n\t\t),\n\t\tkey.NewBinding(\n\t\t\tkey.WithKeys(\"esc\", \"q\"),\n\t\t\tkey.WithHelp(\"esc/q\", \"cancel\"),\n\t\t),\n\t\tkey.NewBinding(\n\t\t\tkey.WithKeys(\"y\", \"n\"),\n\t\t\tkey.WithHelp(\"y/n\", \"yes/no\"),\n\t\t),\n\t}\n}\n\n// FullHelp implements key.Map.\nfunc (k initDialogKeyMap) FullHelp() [][]key.Binding {\n\treturn [][]key.Binding{k.ShortHelp()}\n}\n\n// Init implements tea.Model.\nfunc (m InitDialogCmp) Init() tea.Cmd {\n\treturn nil\n}\n\n// Update implements tea.Model.\nfunc (m InitDialogCmp) Update(msg tea.Msg) (tea.Model, tea.Cmd) {\n\tswitch msg := msg.(type) {\n\tcase tea.KeyMsg:\n\t\tswitch {\n\t\tcase key.Matches(msg, key.NewBinding(key.WithKeys(\"esc\"))):\n\t\t\treturn m, util.CmdHandler(CloseInitDialogMsg{Initialize: false})\n\t\tcase key.Matches(msg, key.NewBinding(key.WithKeys(\"tab\", \"left\", \"right\", \"h\", \"l\"))):\n\t\t\tm.selected = (m.selected + 1) % 2\n\t\t\treturn m, nil\n\t\tcase key.Matches(msg, key.NewBinding(key.WithKeys(\"enter\"))):\n\t\t\treturn m, util.CmdHandler(CloseInitDialogMsg{Initialize: m.selected == 0})\n\t\tcase key.Matches(msg, key.NewBinding(key.WithKeys(\"y\"))):\n\t\t\treturn m, util.CmdHandler(CloseInitDialogMsg{Initialize: true})\n\t\tcase key.Matches(msg, key.NewBinding(key.WithKeys(\"n\"))):\n\t\t\treturn m, util.CmdHandler(CloseInitDialogMsg{Initialize: false})\n\t\t}\n\tcase tea.WindowSizeMsg:\n\t\tm.width = msg.Width\n\t\tm.height = msg.Height\n\t}\n\treturn m, nil\n}\n\n// View implements tea.Model.\nfunc (m InitDialogCmp) View() string {\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\t\n\t// Calculate width needed for content\n\tmaxWidth := 60 // Width for explanation text\n\n\ttitle := baseStyle.\n\t\tForeground(t.Primary()).\n\t\tBold(true).\n\t\tWidth(maxWidth).\n\t\tPadding(0, 1).\n\t\tRender(\"Initialize Project\")\n\n\texplanation := baseStyle.\n\t\tForeground(t.Text()).\n\t\tWidth(maxWidth).\n\t\tPadding(0, 1).\n\t\tRender(\"Initialization generates a new OpenCode.md file that contains information about your codebase, this file serves as memory for each project, you can freely add to it to help the agents be better at their job.\")\n\n\tquestion := baseStyle.\n\t\tForeground(t.Text()).\n\t\tWidth(maxWidth).\n\t\tPadding(1, 1).\n\t\tRender(\"Would you like to initialize this project?\")\n\n\tmaxWidth = min(maxWidth, m.width-10)\n\tyesStyle := baseStyle\n\tnoStyle := baseStyle\n\n\tif m.selected == 0 {\n\t\tyesStyle = yesStyle.\n\t\t\tBackground(t.Primary()).\n\t\t\tForeground(t.Background()).\n\t\t\tBold(true)\n\t\tnoStyle = noStyle.\n\t\t\tBackground(t.Background()).\n\t\t\tForeground(t.Primary())\n\t} else {\n\t\tnoStyle = noStyle.\n\t\t\tBackground(t.Primary()).\n\t\t\tForeground(t.Background()).\n\t\t\tBold(true)\n\t\tyesStyle = yesStyle.\n\t\t\tBackground(t.Background()).\n\t\t\tForeground(t.Primary())\n\t}\n\n\tyes := yesStyle.Padding(0, 3).Render(\"Yes\")\n\tno := noStyle.Padding(0, 3).Render(\"No\")\n\n\tbuttons := lipgloss.JoinHorizontal(lipgloss.Center, yes, baseStyle.Render(\" \"), no)\n\tbuttons = baseStyle.\n\t\tWidth(maxWidth).\n\t\tPadding(1, 0).\n\t\tRender(buttons)\n\n\tcontent := lipgloss.JoinVertical(\n\t\tlipgloss.Left,\n\t\ttitle,\n\t\tbaseStyle.Width(maxWidth).Render(\"\"),\n\t\texplanation,\n\t\tquestion,\n\t\tbuttons,\n\t\tbaseStyle.Width(maxWidth).Render(\"\"),\n\t)\n\n\treturn baseStyle.Padding(1, 2).\n\t\tBorder(lipgloss.RoundedBorder()).\n\t\tBorderBackground(t.Background()).\n\t\tBorderForeground(t.TextMuted()).\n\t\tWidth(lipgloss.Width(content) + 4).\n\t\tRender(content)\n}\n\n// SetSize sets the size of the component.\nfunc (m *InitDialogCmp) SetSize(width, height int) {\n\tm.width = width\n\tm.height = height\n}\n\n// Bindings implements layout.Bindings.\nfunc (m InitDialogCmp) Bindings() []key.Binding {\n\treturn m.keys.ShortHelp()\n}\n\n// CloseInitDialogMsg is a message that is sent when the init dialog is closed.\ntype CloseInitDialogMsg struct {\n\tInitialize bool\n}\n\n// ShowInitDialogMsg is a message that is sent to show the init dialog.\ntype ShowInitDialogMsg struct {\n\tShow bool\n}\n"], ["/opencode/internal/llm/provider/provider.go", "package provider\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"os\"\n\n\t\"github.com/opencode-ai/opencode/internal/llm/models\"\n\t\"github.com/opencode-ai/opencode/internal/llm/tools\"\n\t\"github.com/opencode-ai/opencode/internal/message\"\n)\n\ntype EventType string\n\nconst maxRetries = 8\n\nconst (\n\tEventContentStart EventType = \"content_start\"\n\tEventToolUseStart EventType = \"tool_use_start\"\n\tEventToolUseDelta EventType = \"tool_use_delta\"\n\tEventToolUseStop EventType = \"tool_use_stop\"\n\tEventContentDelta EventType = \"content_delta\"\n\tEventThinkingDelta EventType = \"thinking_delta\"\n\tEventContentStop EventType = \"content_stop\"\n\tEventComplete EventType = \"complete\"\n\tEventError EventType = \"error\"\n\tEventWarning EventType = \"warning\"\n)\n\ntype TokenUsage struct {\n\tInputTokens int64\n\tOutputTokens int64\n\tCacheCreationTokens int64\n\tCacheReadTokens int64\n}\n\ntype ProviderResponse struct {\n\tContent string\n\tToolCalls []message.ToolCall\n\tUsage TokenUsage\n\tFinishReason message.FinishReason\n}\n\ntype ProviderEvent struct {\n\tType EventType\n\n\tContent string\n\tThinking string\n\tResponse *ProviderResponse\n\tToolCall *message.ToolCall\n\tError error\n}\ntype Provider interface {\n\tSendMessages(ctx context.Context, messages []message.Message, tools []tools.BaseTool) (*ProviderResponse, error)\n\n\tStreamResponse(ctx context.Context, messages []message.Message, tools []tools.BaseTool) <-chan ProviderEvent\n\n\tModel() models.Model\n}\n\ntype providerClientOptions struct {\n\tapiKey string\n\tmodel models.Model\n\tmaxTokens int64\n\tsystemMessage string\n\n\tanthropicOptions []AnthropicOption\n\topenaiOptions []OpenAIOption\n\tgeminiOptions []GeminiOption\n\tbedrockOptions []BedrockOption\n\tcopilotOptions []CopilotOption\n}\n\ntype ProviderClientOption func(*providerClientOptions)\n\ntype ProviderClient interface {\n\tsend(ctx context.Context, messages []message.Message, tools []tools.BaseTool) (*ProviderResponse, error)\n\tstream(ctx context.Context, messages []message.Message, tools []tools.BaseTool) <-chan ProviderEvent\n}\n\ntype baseProvider[C ProviderClient] struct {\n\toptions providerClientOptions\n\tclient C\n}\n\nfunc NewProvider(providerName models.ModelProvider, opts ...ProviderClientOption) (Provider, error) {\n\tclientOptions := providerClientOptions{}\n\tfor _, o := range opts {\n\t\to(&clientOptions)\n\t}\n\tswitch providerName {\n\tcase models.ProviderCopilot:\n\t\treturn &baseProvider[CopilotClient]{\n\t\t\toptions: clientOptions,\n\t\t\tclient: newCopilotClient(clientOptions),\n\t\t}, nil\n\tcase models.ProviderAnthropic:\n\t\treturn &baseProvider[AnthropicClient]{\n\t\t\toptions: clientOptions,\n\t\t\tclient: newAnthropicClient(clientOptions),\n\t\t}, nil\n\tcase models.ProviderOpenAI:\n\t\treturn &baseProvider[OpenAIClient]{\n\t\t\toptions: clientOptions,\n\t\t\tclient: newOpenAIClient(clientOptions),\n\t\t}, nil\n\tcase models.ProviderGemini:\n\t\treturn &baseProvider[GeminiClient]{\n\t\t\toptions: clientOptions,\n\t\t\tclient: newGeminiClient(clientOptions),\n\t\t}, nil\n\tcase models.ProviderBedrock:\n\t\treturn &baseProvider[BedrockClient]{\n\t\t\toptions: clientOptions,\n\t\t\tclient: newBedrockClient(clientOptions),\n\t\t}, nil\n\tcase models.ProviderGROQ:\n\t\tclientOptions.openaiOptions = append(clientOptions.openaiOptions,\n\t\t\tWithOpenAIBaseURL(\"https://api.groq.com/openai/v1\"),\n\t\t)\n\t\treturn &baseProvider[OpenAIClient]{\n\t\t\toptions: clientOptions,\n\t\t\tclient: newOpenAIClient(clientOptions),\n\t\t}, nil\n\tcase models.ProviderAzure:\n\t\treturn &baseProvider[AzureClient]{\n\t\t\toptions: clientOptions,\n\t\t\tclient: newAzureClient(clientOptions),\n\t\t}, nil\n\tcase models.ProviderVertexAI:\n\t\treturn &baseProvider[VertexAIClient]{\n\t\t\toptions: clientOptions,\n\t\t\tclient: newVertexAIClient(clientOptions),\n\t\t}, nil\n\tcase models.ProviderOpenRouter:\n\t\tclientOptions.openaiOptions = append(clientOptions.openaiOptions,\n\t\t\tWithOpenAIBaseURL(\"https://openrouter.ai/api/v1\"),\n\t\t\tWithOpenAIExtraHeaders(map[string]string{\n\t\t\t\t\"HTTP-Referer\": \"opencode.ai\",\n\t\t\t\t\"X-Title\": \"OpenCode\",\n\t\t\t}),\n\t\t)\n\t\treturn &baseProvider[OpenAIClient]{\n\t\t\toptions: clientOptions,\n\t\t\tclient: newOpenAIClient(clientOptions),\n\t\t}, nil\n\tcase models.ProviderXAI:\n\t\tclientOptions.openaiOptions = append(clientOptions.openaiOptions,\n\t\t\tWithOpenAIBaseURL(\"https://api.x.ai/v1\"),\n\t\t)\n\t\treturn &baseProvider[OpenAIClient]{\n\t\t\toptions: clientOptions,\n\t\t\tclient: newOpenAIClient(clientOptions),\n\t\t}, nil\n\tcase models.ProviderLocal:\n\t\tclientOptions.openaiOptions = append(clientOptions.openaiOptions,\n\t\t\tWithOpenAIBaseURL(os.Getenv(\"LOCAL_ENDPOINT\")),\n\t\t)\n\t\treturn &baseProvider[OpenAIClient]{\n\t\t\toptions: clientOptions,\n\t\t\tclient: newOpenAIClient(clientOptions),\n\t\t}, nil\n\tcase models.ProviderMock:\n\t\t// TODO: implement mock client for test\n\t\tpanic(\"not implemented\")\n\t}\n\treturn nil, fmt.Errorf(\"provider not supported: %s\", providerName)\n}\n\nfunc (p *baseProvider[C]) cleanMessages(messages []message.Message) (cleaned []message.Message) {\n\tfor _, msg := range messages {\n\t\t// The message has no content\n\t\tif len(msg.Parts) == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tcleaned = append(cleaned, msg)\n\t}\n\treturn\n}\n\nfunc (p *baseProvider[C]) SendMessages(ctx context.Context, messages []message.Message, tools []tools.BaseTool) (*ProviderResponse, error) {\n\tmessages = p.cleanMessages(messages)\n\treturn p.client.send(ctx, messages, tools)\n}\n\nfunc (p *baseProvider[C]) Model() models.Model {\n\treturn p.options.model\n}\n\nfunc (p *baseProvider[C]) StreamResponse(ctx context.Context, messages []message.Message, tools []tools.BaseTool) <-chan ProviderEvent {\n\tmessages = p.cleanMessages(messages)\n\treturn p.client.stream(ctx, messages, tools)\n}\n\nfunc WithAPIKey(apiKey string) ProviderClientOption {\n\treturn func(options *providerClientOptions) {\n\t\toptions.apiKey = apiKey\n\t}\n}\n\nfunc WithModel(model models.Model) ProviderClientOption {\n\treturn func(options *providerClientOptions) {\n\t\toptions.model = model\n\t}\n}\n\nfunc WithMaxTokens(maxTokens int64) ProviderClientOption {\n\treturn func(options *providerClientOptions) {\n\t\toptions.maxTokens = maxTokens\n\t}\n}\n\nfunc WithSystemMessage(systemMessage string) ProviderClientOption {\n\treturn func(options *providerClientOptions) {\n\t\toptions.systemMessage = systemMessage\n\t}\n}\n\nfunc WithAnthropicOptions(anthropicOptions ...AnthropicOption) ProviderClientOption {\n\treturn func(options *providerClientOptions) {\n\t\toptions.anthropicOptions = anthropicOptions\n\t}\n}\n\nfunc WithOpenAIOptions(openaiOptions ...OpenAIOption) ProviderClientOption {\n\treturn func(options *providerClientOptions) {\n\t\toptions.openaiOptions = openaiOptions\n\t}\n}\n\nfunc WithGeminiOptions(geminiOptions ...GeminiOption) ProviderClientOption {\n\treturn func(options *providerClientOptions) {\n\t\toptions.geminiOptions = geminiOptions\n\t}\n}\n\nfunc WithBedrockOptions(bedrockOptions ...BedrockOption) ProviderClientOption {\n\treturn func(options *providerClientOptions) {\n\t\toptions.bedrockOptions = bedrockOptions\n\t}\n}\n\nfunc WithCopilotOptions(copilotOptions ...CopilotOption) ProviderClientOption {\n\treturn func(options *providerClientOptions) {\n\t\toptions.copilotOptions = copilotOptions\n\t}\n}\n"], ["/opencode/internal/message/message.go", "package message\n\nimport (\n\t\"context\"\n\t\"database/sql\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com/google/uuid\"\n\t\"github.com/opencode-ai/opencode/internal/db\"\n\t\"github.com/opencode-ai/opencode/internal/llm/models\"\n\t\"github.com/opencode-ai/opencode/internal/pubsub\"\n)\n\ntype CreateMessageParams struct {\n\tRole MessageRole\n\tParts []ContentPart\n\tModel models.ModelID\n}\n\ntype Service interface {\n\tpubsub.Suscriber[Message]\n\tCreate(ctx context.Context, sessionID string, params CreateMessageParams) (Message, error)\n\tUpdate(ctx context.Context, message Message) error\n\tGet(ctx context.Context, id string) (Message, error)\n\tList(ctx context.Context, sessionID string) ([]Message, error)\n\tDelete(ctx context.Context, id string) error\n\tDeleteSessionMessages(ctx context.Context, sessionID string) error\n}\n\ntype service struct {\n\t*pubsub.Broker[Message]\n\tq db.Querier\n}\n\nfunc NewService(q db.Querier) Service {\n\treturn &service{\n\t\tBroker: pubsub.NewBroker[Message](),\n\t\tq: q,\n\t}\n}\n\nfunc (s *service) Delete(ctx context.Context, id string) error {\n\tmessage, err := s.Get(ctx, id)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = s.q.DeleteMessage(ctx, message.ID)\n\tif err != nil {\n\t\treturn err\n\t}\n\ts.Publish(pubsub.DeletedEvent, message)\n\treturn nil\n}\n\nfunc (s *service) Create(ctx context.Context, sessionID string, params CreateMessageParams) (Message, error) {\n\tif params.Role != Assistant {\n\t\tparams.Parts = append(params.Parts, Finish{\n\t\t\tReason: \"stop\",\n\t\t})\n\t}\n\tpartsJSON, err := marshallParts(params.Parts)\n\tif err != nil {\n\t\treturn Message{}, err\n\t}\n\tdbMessage, err := s.q.CreateMessage(ctx, db.CreateMessageParams{\n\t\tID: uuid.New().String(),\n\t\tSessionID: sessionID,\n\t\tRole: string(params.Role),\n\t\tParts: string(partsJSON),\n\t\tModel: sql.NullString{String: string(params.Model), Valid: true},\n\t})\n\tif err != nil {\n\t\treturn Message{}, err\n\t}\n\tmessage, err := s.fromDBItem(dbMessage)\n\tif err != nil {\n\t\treturn Message{}, err\n\t}\n\ts.Publish(pubsub.CreatedEvent, message)\n\treturn message, nil\n}\n\nfunc (s *service) DeleteSessionMessages(ctx context.Context, sessionID string) error {\n\tmessages, err := s.List(ctx, sessionID)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor _, message := range messages {\n\t\tif message.SessionID == sessionID {\n\t\t\terr = s.Delete(ctx, message.ID)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (s *service) Update(ctx context.Context, message Message) error {\n\tparts, err := marshallParts(message.Parts)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfinishedAt := sql.NullInt64{}\n\tif f := message.FinishPart(); f != nil {\n\t\tfinishedAt.Int64 = f.Time\n\t\tfinishedAt.Valid = true\n\t}\n\terr = s.q.UpdateMessage(ctx, db.UpdateMessageParams{\n\t\tID: message.ID,\n\t\tParts: string(parts),\n\t\tFinishedAt: finishedAt,\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\tmessage.UpdatedAt = time.Now().Unix()\n\ts.Publish(pubsub.UpdatedEvent, message)\n\treturn nil\n}\n\nfunc (s *service) Get(ctx context.Context, id string) (Message, error) {\n\tdbMessage, err := s.q.GetMessage(ctx, id)\n\tif err != nil {\n\t\treturn Message{}, err\n\t}\n\treturn s.fromDBItem(dbMessage)\n}\n\nfunc (s *service) List(ctx context.Context, sessionID string) ([]Message, error) {\n\tdbMessages, err := s.q.ListMessagesBySession(ctx, sessionID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tmessages := make([]Message, len(dbMessages))\n\tfor i, dbMessage := range dbMessages {\n\t\tmessages[i], err = s.fromDBItem(dbMessage)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn messages, nil\n}\n\nfunc (s *service) fromDBItem(item db.Message) (Message, error) {\n\tparts, err := unmarshallParts([]byte(item.Parts))\n\tif err != nil {\n\t\treturn Message{}, err\n\t}\n\treturn Message{\n\t\tID: item.ID,\n\t\tSessionID: item.SessionID,\n\t\tRole: MessageRole(item.Role),\n\t\tParts: parts,\n\t\tModel: models.ModelID(item.Model.String),\n\t\tCreatedAt: item.CreatedAt,\n\t\tUpdatedAt: item.UpdatedAt,\n\t}, nil\n}\n\ntype partType string\n\nconst (\n\treasoningType partType = \"reasoning\"\n\ttextType partType = \"text\"\n\timageURLType partType = \"image_url\"\n\tbinaryType partType = \"binary\"\n\ttoolCallType partType = \"tool_call\"\n\ttoolResultType partType = \"tool_result\"\n\tfinishType partType = \"finish\"\n)\n\ntype partWrapper struct {\n\tType partType `json:\"type\"`\n\tData ContentPart `json:\"data\"`\n}\n\nfunc marshallParts(parts []ContentPart) ([]byte, error) {\n\twrappedParts := make([]partWrapper, len(parts))\n\n\tfor i, part := range parts {\n\t\tvar typ partType\n\n\t\tswitch part.(type) {\n\t\tcase ReasoningContent:\n\t\t\ttyp = reasoningType\n\t\tcase TextContent:\n\t\t\ttyp = textType\n\t\tcase ImageURLContent:\n\t\t\ttyp = imageURLType\n\t\tcase BinaryContent:\n\t\t\ttyp = binaryType\n\t\tcase ToolCall:\n\t\t\ttyp = toolCallType\n\t\tcase ToolResult:\n\t\t\ttyp = toolResultType\n\t\tcase Finish:\n\t\t\ttyp = finishType\n\t\tdefault:\n\t\t\treturn nil, fmt.Errorf(\"unknown part type: %T\", part)\n\t\t}\n\n\t\twrappedParts[i] = partWrapper{\n\t\t\tType: typ,\n\t\t\tData: part,\n\t\t}\n\t}\n\treturn json.Marshal(wrappedParts)\n}\n\nfunc unmarshallParts(data []byte) ([]ContentPart, error) {\n\ttemp := []json.RawMessage{}\n\n\tif err := json.Unmarshal(data, &temp); err != nil {\n\t\treturn nil, err\n\t}\n\n\tparts := make([]ContentPart, 0)\n\n\tfor _, rawPart := range temp {\n\t\tvar wrapper struct {\n\t\t\tType partType `json:\"type\"`\n\t\t\tData json.RawMessage `json:\"data\"`\n\t\t}\n\n\t\tif err := json.Unmarshal(rawPart, &wrapper); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tswitch wrapper.Type {\n\t\tcase reasoningType:\n\t\t\tpart := ReasoningContent{}\n\t\t\tif err := json.Unmarshal(wrapper.Data, &part); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tparts = append(parts, part)\n\t\tcase textType:\n\t\t\tpart := TextContent{}\n\t\t\tif err := json.Unmarshal(wrapper.Data, &part); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tparts = append(parts, part)\n\t\tcase imageURLType:\n\t\t\tpart := ImageURLContent{}\n\t\t\tif err := json.Unmarshal(wrapper.Data, &part); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\tcase binaryType:\n\t\t\tpart := BinaryContent{}\n\t\t\tif err := json.Unmarshal(wrapper.Data, &part); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tparts = append(parts, part)\n\t\tcase toolCallType:\n\t\t\tpart := ToolCall{}\n\t\t\tif err := json.Unmarshal(wrapper.Data, &part); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tparts = append(parts, part)\n\t\tcase toolResultType:\n\t\t\tpart := ToolResult{}\n\t\t\tif err := json.Unmarshal(wrapper.Data, &part); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tparts = append(parts, part)\n\t\tcase finishType:\n\t\t\tpart := Finish{}\n\t\t\tif err := json.Unmarshal(wrapper.Data, &part); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tparts = append(parts, part)\n\t\tdefault:\n\t\t\treturn nil, fmt.Errorf(\"unknown part type: %s\", wrapper.Type)\n\t\t}\n\n\t}\n\n\treturn parts, nil\n}\n"], ["/opencode/internal/llm/agent/agent.go", "package agent\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/llm/models\"\n\t\"github.com/opencode-ai/opencode/internal/llm/prompt\"\n\t\"github.com/opencode-ai/opencode/internal/llm/provider\"\n\t\"github.com/opencode-ai/opencode/internal/llm/tools\"\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n\t\"github.com/opencode-ai/opencode/internal/message\"\n\t\"github.com/opencode-ai/opencode/internal/permission\"\n\t\"github.com/opencode-ai/opencode/internal/pubsub\"\n\t\"github.com/opencode-ai/opencode/internal/session\"\n)\n\n// Common errors\nvar (\n\tErrRequestCancelled = errors.New(\"request cancelled by user\")\n\tErrSessionBusy = errors.New(\"session is currently processing another request\")\n)\n\ntype AgentEventType string\n\nconst (\n\tAgentEventTypeError AgentEventType = \"error\"\n\tAgentEventTypeResponse AgentEventType = \"response\"\n\tAgentEventTypeSummarize AgentEventType = \"summarize\"\n)\n\ntype AgentEvent struct {\n\tType AgentEventType\n\tMessage message.Message\n\tError error\n\n\t// When summarizing\n\tSessionID string\n\tProgress string\n\tDone bool\n}\n\ntype Service interface {\n\tpubsub.Suscriber[AgentEvent]\n\tModel() models.Model\n\tRun(ctx context.Context, sessionID string, content string, attachments ...message.Attachment) (<-chan AgentEvent, error)\n\tCancel(sessionID string)\n\tIsSessionBusy(sessionID string) bool\n\tIsBusy() bool\n\tUpdate(agentName config.AgentName, modelID models.ModelID) (models.Model, error)\n\tSummarize(ctx context.Context, sessionID string) error\n}\n\ntype agent struct {\n\t*pubsub.Broker[AgentEvent]\n\tsessions session.Service\n\tmessages message.Service\n\n\ttools []tools.BaseTool\n\tprovider provider.Provider\n\n\ttitleProvider provider.Provider\n\tsummarizeProvider provider.Provider\n\n\tactiveRequests sync.Map\n}\n\nfunc NewAgent(\n\tagentName config.AgentName,\n\tsessions session.Service,\n\tmessages message.Service,\n\tagentTools []tools.BaseTool,\n) (Service, error) {\n\tagentProvider, err := createAgentProvider(agentName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar titleProvider provider.Provider\n\t// Only generate titles for the coder agent\n\tif agentName == config.AgentCoder {\n\t\ttitleProvider, err = createAgentProvider(config.AgentTitle)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tvar summarizeProvider provider.Provider\n\tif agentName == config.AgentCoder {\n\t\tsummarizeProvider, err = createAgentProvider(config.AgentSummarizer)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tagent := &agent{\n\t\tBroker: pubsub.NewBroker[AgentEvent](),\n\t\tprovider: agentProvider,\n\t\tmessages: messages,\n\t\tsessions: sessions,\n\t\ttools: agentTools,\n\t\ttitleProvider: titleProvider,\n\t\tsummarizeProvider: summarizeProvider,\n\t\tactiveRequests: sync.Map{},\n\t}\n\n\treturn agent, nil\n}\n\nfunc (a *agent) Model() models.Model {\n\treturn a.provider.Model()\n}\n\nfunc (a *agent) Cancel(sessionID string) {\n\t// Cancel regular requests\n\tif cancelFunc, exists := a.activeRequests.LoadAndDelete(sessionID); exists {\n\t\tif cancel, ok := cancelFunc.(context.CancelFunc); ok {\n\t\t\tlogging.InfoPersist(fmt.Sprintf(\"Request cancellation initiated for session: %s\", sessionID))\n\t\t\tcancel()\n\t\t}\n\t}\n\n\t// Also check for summarize requests\n\tif cancelFunc, exists := a.activeRequests.LoadAndDelete(sessionID + \"-summarize\"); exists {\n\t\tif cancel, ok := cancelFunc.(context.CancelFunc); ok {\n\t\t\tlogging.InfoPersist(fmt.Sprintf(\"Summarize cancellation initiated for session: %s\", sessionID))\n\t\t\tcancel()\n\t\t}\n\t}\n}\n\nfunc (a *agent) IsBusy() bool {\n\tbusy := false\n\ta.activeRequests.Range(func(key, value interface{}) bool {\n\t\tif cancelFunc, ok := value.(context.CancelFunc); ok {\n\t\t\tif cancelFunc != nil {\n\t\t\t\tbusy = true\n\t\t\t\treturn false // Stop iterating\n\t\t\t}\n\t\t}\n\t\treturn true // Continue iterating\n\t})\n\treturn busy\n}\n\nfunc (a *agent) IsSessionBusy(sessionID string) bool {\n\t_, busy := a.activeRequests.Load(sessionID)\n\treturn busy\n}\n\nfunc (a *agent) generateTitle(ctx context.Context, sessionID string, content string) error {\n\tif content == \"\" {\n\t\treturn nil\n\t}\n\tif a.titleProvider == nil {\n\t\treturn nil\n\t}\n\tsession, err := a.sessions.Get(ctx, sessionID)\n\tif err != nil {\n\t\treturn err\n\t}\n\tctx = context.WithValue(ctx, tools.SessionIDContextKey, sessionID)\n\tparts := []message.ContentPart{message.TextContent{Text: content}}\n\tresponse, err := a.titleProvider.SendMessages(\n\t\tctx,\n\t\t[]message.Message{\n\t\t\t{\n\t\t\t\tRole: message.User,\n\t\t\t\tParts: parts,\n\t\t\t},\n\t\t},\n\t\tmake([]tools.BaseTool, 0),\n\t)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ttitle := strings.TrimSpace(strings.ReplaceAll(response.Content, \"\\n\", \" \"))\n\tif title == \"\" {\n\t\treturn nil\n\t}\n\n\tsession.Title = title\n\t_, err = a.sessions.Save(ctx, session)\n\treturn err\n}\n\nfunc (a *agent) err(err error) AgentEvent {\n\treturn AgentEvent{\n\t\tType: AgentEventTypeError,\n\t\tError: err,\n\t}\n}\n\nfunc (a *agent) Run(ctx context.Context, sessionID string, content string, attachments ...message.Attachment) (<-chan AgentEvent, error) {\n\tif !a.provider.Model().SupportsAttachments && attachments != nil {\n\t\tattachments = nil\n\t}\n\tevents := make(chan AgentEvent)\n\tif a.IsSessionBusy(sessionID) {\n\t\treturn nil, ErrSessionBusy\n\t}\n\n\tgenCtx, cancel := context.WithCancel(ctx)\n\n\ta.activeRequests.Store(sessionID, cancel)\n\tgo func() {\n\t\tlogging.Debug(\"Request started\", \"sessionID\", sessionID)\n\t\tdefer logging.RecoverPanic(\"agent.Run\", func() {\n\t\t\tevents <- a.err(fmt.Errorf(\"panic while running the agent\"))\n\t\t})\n\t\tvar attachmentParts []message.ContentPart\n\t\tfor _, attachment := range attachments {\n\t\t\tattachmentParts = append(attachmentParts, message.BinaryContent{Path: attachment.FilePath, MIMEType: attachment.MimeType, Data: attachment.Content})\n\t\t}\n\t\tresult := a.processGeneration(genCtx, sessionID, content, attachmentParts)\n\t\tif result.Error != nil && !errors.Is(result.Error, ErrRequestCancelled) && !errors.Is(result.Error, context.Canceled) {\n\t\t\tlogging.ErrorPersist(result.Error.Error())\n\t\t}\n\t\tlogging.Debug(\"Request completed\", \"sessionID\", sessionID)\n\t\ta.activeRequests.Delete(sessionID)\n\t\tcancel()\n\t\ta.Publish(pubsub.CreatedEvent, result)\n\t\tevents <- result\n\t\tclose(events)\n\t}()\n\treturn events, nil\n}\n\nfunc (a *agent) processGeneration(ctx context.Context, sessionID, content string, attachmentParts []message.ContentPart) AgentEvent {\n\tcfg := config.Get()\n\t// List existing messages; if none, start title generation asynchronously.\n\tmsgs, err := a.messages.List(ctx, sessionID)\n\tif err != nil {\n\t\treturn a.err(fmt.Errorf(\"failed to list messages: %w\", err))\n\t}\n\tif len(msgs) == 0 {\n\t\tgo func() {\n\t\t\tdefer logging.RecoverPanic(\"agent.Run\", func() {\n\t\t\t\tlogging.ErrorPersist(\"panic while generating title\")\n\t\t\t})\n\t\t\ttitleErr := a.generateTitle(context.Background(), sessionID, content)\n\t\t\tif titleErr != nil {\n\t\t\t\tlogging.ErrorPersist(fmt.Sprintf(\"failed to generate title: %v\", titleErr))\n\t\t\t}\n\t\t}()\n\t}\n\tsession, err := a.sessions.Get(ctx, sessionID)\n\tif err != nil {\n\t\treturn a.err(fmt.Errorf(\"failed to get session: %w\", err))\n\t}\n\tif session.SummaryMessageID != \"\" {\n\t\tsummaryMsgInex := -1\n\t\tfor i, msg := range msgs {\n\t\t\tif msg.ID == session.SummaryMessageID {\n\t\t\t\tsummaryMsgInex = i\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif summaryMsgInex != -1 {\n\t\t\tmsgs = msgs[summaryMsgInex:]\n\t\t\tmsgs[0].Role = message.User\n\t\t}\n\t}\n\n\tuserMsg, err := a.createUserMessage(ctx, sessionID, content, attachmentParts)\n\tif err != nil {\n\t\treturn a.err(fmt.Errorf(\"failed to create user message: %w\", err))\n\t}\n\t// Append the new user message to the conversation history.\n\tmsgHistory := append(msgs, userMsg)\n\n\tfor {\n\t\t// Check for cancellation before each iteration\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn a.err(ctx.Err())\n\t\tdefault:\n\t\t\t// Continue processing\n\t\t}\n\t\tagentMessage, toolResults, err := a.streamAndHandleEvents(ctx, sessionID, msgHistory)\n\t\tif err != nil {\n\t\t\tif errors.Is(err, context.Canceled) {\n\t\t\t\tagentMessage.AddFinish(message.FinishReasonCanceled)\n\t\t\t\ta.messages.Update(context.Background(), agentMessage)\n\t\t\t\treturn a.err(ErrRequestCancelled)\n\t\t\t}\n\t\t\treturn a.err(fmt.Errorf(\"failed to process events: %w\", err))\n\t\t}\n\t\tif cfg.Debug {\n\t\t\tseqId := (len(msgHistory) + 1) / 2\n\t\t\ttoolResultFilepath := logging.WriteToolResultsJson(sessionID, seqId, toolResults)\n\t\t\tlogging.Info(\"Result\", \"message\", agentMessage.FinishReason(), \"toolResults\", \"{}\", \"filepath\", toolResultFilepath)\n\t\t} else {\n\t\t\tlogging.Info(\"Result\", \"message\", agentMessage.FinishReason(), \"toolResults\", toolResults)\n\t\t}\n\t\tif (agentMessage.FinishReason() == message.FinishReasonToolUse) && toolResults != nil {\n\t\t\t// We are not done, we need to respond with the tool response\n\t\t\tmsgHistory = append(msgHistory, agentMessage, *toolResults)\n\t\t\tcontinue\n\t\t}\n\t\treturn AgentEvent{\n\t\t\tType: AgentEventTypeResponse,\n\t\t\tMessage: agentMessage,\n\t\t\tDone: true,\n\t\t}\n\t}\n}\n\nfunc (a *agent) createUserMessage(ctx context.Context, sessionID, content string, attachmentParts []message.ContentPart) (message.Message, error) {\n\tparts := []message.ContentPart{message.TextContent{Text: content}}\n\tparts = append(parts, attachmentParts...)\n\treturn a.messages.Create(ctx, sessionID, message.CreateMessageParams{\n\t\tRole: message.User,\n\t\tParts: parts,\n\t})\n}\n\nfunc (a *agent) streamAndHandleEvents(ctx context.Context, sessionID string, msgHistory []message.Message) (message.Message, *message.Message, error) {\n\tctx = context.WithValue(ctx, tools.SessionIDContextKey, sessionID)\n\teventChan := a.provider.StreamResponse(ctx, msgHistory, a.tools)\n\n\tassistantMsg, err := a.messages.Create(ctx, sessionID, message.CreateMessageParams{\n\t\tRole: message.Assistant,\n\t\tParts: []message.ContentPart{},\n\t\tModel: a.provider.Model().ID,\n\t})\n\tif err != nil {\n\t\treturn assistantMsg, nil, fmt.Errorf(\"failed to create assistant message: %w\", err)\n\t}\n\n\t// Add the session and message ID into the context if needed by tools.\n\tctx = context.WithValue(ctx, tools.MessageIDContextKey, assistantMsg.ID)\n\n\t// Process each event in the stream.\n\tfor event := range eventChan {\n\t\tif processErr := a.processEvent(ctx, sessionID, &assistantMsg, event); processErr != nil {\n\t\t\ta.finishMessage(ctx, &assistantMsg, message.FinishReasonCanceled)\n\t\t\treturn assistantMsg, nil, processErr\n\t\t}\n\t\tif ctx.Err() != nil {\n\t\t\ta.finishMessage(context.Background(), &assistantMsg, message.FinishReasonCanceled)\n\t\t\treturn assistantMsg, nil, ctx.Err()\n\t\t}\n\t}\n\n\ttoolResults := make([]message.ToolResult, len(assistantMsg.ToolCalls()))\n\ttoolCalls := assistantMsg.ToolCalls()\n\tfor i, toolCall := range toolCalls {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\ta.finishMessage(context.Background(), &assistantMsg, message.FinishReasonCanceled)\n\t\t\t// Make all future tool calls cancelled\n\t\t\tfor j := i; j < len(toolCalls); j++ {\n\t\t\t\ttoolResults[j] = message.ToolResult{\n\t\t\t\t\tToolCallID: toolCalls[j].ID,\n\t\t\t\t\tContent: \"Tool execution canceled by user\",\n\t\t\t\t\tIsError: true,\n\t\t\t\t}\n\t\t\t}\n\t\t\tgoto out\n\t\tdefault:\n\t\t\t// Continue processing\n\t\t\tvar tool tools.BaseTool\n\t\t\tfor _, availableTool := range a.tools {\n\t\t\t\tif availableTool.Info().Name == toolCall.Name {\n\t\t\t\t\ttool = availableTool\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\t// Monkey patch for Copilot Sonnet-4 tool repetition obfuscation\n\t\t\t\t// if strings.HasPrefix(toolCall.Name, availableTool.Info().Name) &&\n\t\t\t\t// \tstrings.HasPrefix(toolCall.Name, availableTool.Info().Name+availableTool.Info().Name) {\n\t\t\t\t// \ttool = availableTool\n\t\t\t\t// \tbreak\n\t\t\t\t// }\n\t\t\t}\n\n\t\t\t// Tool not found\n\t\t\tif tool == nil {\n\t\t\t\ttoolResults[i] = message.ToolResult{\n\t\t\t\t\tToolCallID: toolCall.ID,\n\t\t\t\t\tContent: fmt.Sprintf(\"Tool not found: %s\", toolCall.Name),\n\t\t\t\t\tIsError: true,\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\ttoolResult, toolErr := tool.Run(ctx, tools.ToolCall{\n\t\t\t\tID: toolCall.ID,\n\t\t\t\tName: toolCall.Name,\n\t\t\t\tInput: toolCall.Input,\n\t\t\t})\n\t\t\tif toolErr != nil {\n\t\t\t\tif errors.Is(toolErr, permission.ErrorPermissionDenied) {\n\t\t\t\t\ttoolResults[i] = message.ToolResult{\n\t\t\t\t\t\tToolCallID: toolCall.ID,\n\t\t\t\t\t\tContent: \"Permission denied\",\n\t\t\t\t\t\tIsError: true,\n\t\t\t\t\t}\n\t\t\t\t\tfor j := i + 1; j < len(toolCalls); j++ {\n\t\t\t\t\t\ttoolResults[j] = message.ToolResult{\n\t\t\t\t\t\t\tToolCallID: toolCalls[j].ID,\n\t\t\t\t\t\t\tContent: \"Tool execution canceled by user\",\n\t\t\t\t\t\t\tIsError: true,\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\ta.finishMessage(ctx, &assistantMsg, message.FinishReasonPermissionDenied)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\ttoolResults[i] = message.ToolResult{\n\t\t\t\tToolCallID: toolCall.ID,\n\t\t\t\tContent: toolResult.Content,\n\t\t\t\tMetadata: toolResult.Metadata,\n\t\t\t\tIsError: toolResult.IsError,\n\t\t\t}\n\t\t}\n\t}\nout:\n\tif len(toolResults) == 0 {\n\t\treturn assistantMsg, nil, nil\n\t}\n\tparts := make([]message.ContentPart, 0)\n\tfor _, tr := range toolResults {\n\t\tparts = append(parts, tr)\n\t}\n\tmsg, err := a.messages.Create(context.Background(), assistantMsg.SessionID, message.CreateMessageParams{\n\t\tRole: message.Tool,\n\t\tParts: parts,\n\t})\n\tif err != nil {\n\t\treturn assistantMsg, nil, fmt.Errorf(\"failed to create cancelled tool message: %w\", err)\n\t}\n\n\treturn assistantMsg, &msg, err\n}\n\nfunc (a *agent) finishMessage(ctx context.Context, msg *message.Message, finishReson message.FinishReason) {\n\tmsg.AddFinish(finishReson)\n\t_ = a.messages.Update(ctx, *msg)\n}\n\nfunc (a *agent) processEvent(ctx context.Context, sessionID string, assistantMsg *message.Message, event provider.ProviderEvent) error {\n\tselect {\n\tcase <-ctx.Done():\n\t\treturn ctx.Err()\n\tdefault:\n\t\t// Continue processing.\n\t}\n\n\tswitch event.Type {\n\tcase provider.EventThinkingDelta:\n\t\tassistantMsg.AppendReasoningContent(event.Content)\n\t\treturn a.messages.Update(ctx, *assistantMsg)\n\tcase provider.EventContentDelta:\n\t\tassistantMsg.AppendContent(event.Content)\n\t\treturn a.messages.Update(ctx, *assistantMsg)\n\tcase provider.EventToolUseStart:\n\t\tassistantMsg.AddToolCall(*event.ToolCall)\n\t\treturn a.messages.Update(ctx, *assistantMsg)\n\t// TODO: see how to handle this\n\t// case provider.EventToolUseDelta:\n\t// \ttm := time.Unix(assistantMsg.UpdatedAt, 0)\n\t// \tassistantMsg.AppendToolCallInput(event.ToolCall.ID, event.ToolCall.Input)\n\t// \tif time.Since(tm) > 1000*time.Millisecond {\n\t// \t\terr := a.messages.Update(ctx, *assistantMsg)\n\t// \t\tassistantMsg.UpdatedAt = time.Now().Unix()\n\t// \t\treturn err\n\t// \t}\n\tcase provider.EventToolUseStop:\n\t\tassistantMsg.FinishToolCall(event.ToolCall.ID)\n\t\treturn a.messages.Update(ctx, *assistantMsg)\n\tcase provider.EventError:\n\t\tif errors.Is(event.Error, context.Canceled) {\n\t\t\tlogging.InfoPersist(fmt.Sprintf(\"Event processing canceled for session: %s\", sessionID))\n\t\t\treturn context.Canceled\n\t\t}\n\t\tlogging.ErrorPersist(event.Error.Error())\n\t\treturn event.Error\n\tcase provider.EventComplete:\n\t\tassistantMsg.SetToolCalls(event.Response.ToolCalls)\n\t\tassistantMsg.AddFinish(event.Response.FinishReason)\n\t\tif err := a.messages.Update(ctx, *assistantMsg); err != nil {\n\t\t\treturn fmt.Errorf(\"failed to update message: %w\", err)\n\t\t}\n\t\treturn a.TrackUsage(ctx, sessionID, a.provider.Model(), event.Response.Usage)\n\t}\n\n\treturn nil\n}\n\nfunc (a *agent) TrackUsage(ctx context.Context, sessionID string, model models.Model, usage provider.TokenUsage) error {\n\tsess, err := a.sessions.Get(ctx, sessionID)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to get session: %w\", err)\n\t}\n\n\tcost := model.CostPer1MInCached/1e6*float64(usage.CacheCreationTokens) +\n\t\tmodel.CostPer1MOutCached/1e6*float64(usage.CacheReadTokens) +\n\t\tmodel.CostPer1MIn/1e6*float64(usage.InputTokens) +\n\t\tmodel.CostPer1MOut/1e6*float64(usage.OutputTokens)\n\n\tsess.Cost += cost\n\tsess.CompletionTokens = usage.OutputTokens + usage.CacheReadTokens\n\tsess.PromptTokens = usage.InputTokens + usage.CacheCreationTokens\n\n\t_, err = a.sessions.Save(ctx, sess)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to save session: %w\", err)\n\t}\n\treturn nil\n}\n\nfunc (a *agent) Update(agentName config.AgentName, modelID models.ModelID) (models.Model, error) {\n\tif a.IsBusy() {\n\t\treturn models.Model{}, fmt.Errorf(\"cannot change model while processing requests\")\n\t}\n\n\tif err := config.UpdateAgentModel(agentName, modelID); err != nil {\n\t\treturn models.Model{}, fmt.Errorf(\"failed to update config: %w\", err)\n\t}\n\n\tprovider, err := createAgentProvider(agentName)\n\tif err != nil {\n\t\treturn models.Model{}, fmt.Errorf(\"failed to create provider for model %s: %w\", modelID, err)\n\t}\n\n\ta.provider = provider\n\n\treturn a.provider.Model(), nil\n}\n\nfunc (a *agent) Summarize(ctx context.Context, sessionID string) error {\n\tif a.summarizeProvider == nil {\n\t\treturn fmt.Errorf(\"summarize provider not available\")\n\t}\n\n\t// Check if session is busy\n\tif a.IsSessionBusy(sessionID) {\n\t\treturn ErrSessionBusy\n\t}\n\n\t// Create a new context with cancellation\n\tsummarizeCtx, cancel := context.WithCancel(ctx)\n\n\t// Store the cancel function in activeRequests to allow cancellation\n\ta.activeRequests.Store(sessionID+\"-summarize\", cancel)\n\n\tgo func() {\n\t\tdefer a.activeRequests.Delete(sessionID + \"-summarize\")\n\t\tdefer cancel()\n\t\tevent := AgentEvent{\n\t\t\tType: AgentEventTypeSummarize,\n\t\t\tProgress: \"Starting summarization...\",\n\t\t}\n\n\t\ta.Publish(pubsub.CreatedEvent, event)\n\t\t// Get all messages from the session\n\t\tmsgs, err := a.messages.List(summarizeCtx, sessionID)\n\t\tif err != nil {\n\t\t\tevent = AgentEvent{\n\t\t\t\tType: AgentEventTypeError,\n\t\t\t\tError: fmt.Errorf(\"failed to list messages: %w\", err),\n\t\t\t\tDone: true,\n\t\t\t}\n\t\t\ta.Publish(pubsub.CreatedEvent, event)\n\t\t\treturn\n\t\t}\n\t\tsummarizeCtx = context.WithValue(summarizeCtx, tools.SessionIDContextKey, sessionID)\n\n\t\tif len(msgs) == 0 {\n\t\t\tevent = AgentEvent{\n\t\t\t\tType: AgentEventTypeError,\n\t\t\t\tError: fmt.Errorf(\"no messages to summarize\"),\n\t\t\t\tDone: true,\n\t\t\t}\n\t\t\ta.Publish(pubsub.CreatedEvent, event)\n\t\t\treturn\n\t\t}\n\n\t\tevent = AgentEvent{\n\t\t\tType: AgentEventTypeSummarize,\n\t\t\tProgress: \"Analyzing conversation...\",\n\t\t}\n\t\ta.Publish(pubsub.CreatedEvent, event)\n\n\t\t// Add a system message to guide the summarization\n\t\tsummarizePrompt := \"Provide a detailed but concise summary of our conversation above. Focus on information that would be helpful for continuing the conversation, including what we did, what we're doing, which files we're working on, and what we're going to do next.\"\n\n\t\t// Create a new message with the summarize prompt\n\t\tpromptMsg := message.Message{\n\t\t\tRole: message.User,\n\t\t\tParts: []message.ContentPart{message.TextContent{Text: summarizePrompt}},\n\t\t}\n\n\t\t// Append the prompt to the messages\n\t\tmsgsWithPrompt := append(msgs, promptMsg)\n\n\t\tevent = AgentEvent{\n\t\t\tType: AgentEventTypeSummarize,\n\t\t\tProgress: \"Generating summary...\",\n\t\t}\n\n\t\ta.Publish(pubsub.CreatedEvent, event)\n\n\t\t// Send the messages to the summarize provider\n\t\tresponse, err := a.summarizeProvider.SendMessages(\n\t\t\tsummarizeCtx,\n\t\t\tmsgsWithPrompt,\n\t\t\tmake([]tools.BaseTool, 0),\n\t\t)\n\t\tif err != nil {\n\t\t\tevent = AgentEvent{\n\t\t\t\tType: AgentEventTypeError,\n\t\t\t\tError: fmt.Errorf(\"failed to summarize: %w\", err),\n\t\t\t\tDone: true,\n\t\t\t}\n\t\t\ta.Publish(pubsub.CreatedEvent, event)\n\t\t\treturn\n\t\t}\n\n\t\tsummary := strings.TrimSpace(response.Content)\n\t\tif summary == \"\" {\n\t\t\tevent = AgentEvent{\n\t\t\t\tType: AgentEventTypeError,\n\t\t\t\tError: fmt.Errorf(\"empty summary returned\"),\n\t\t\t\tDone: true,\n\t\t\t}\n\t\t\ta.Publish(pubsub.CreatedEvent, event)\n\t\t\treturn\n\t\t}\n\t\tevent = AgentEvent{\n\t\t\tType: AgentEventTypeSummarize,\n\t\t\tProgress: \"Creating new session...\",\n\t\t}\n\n\t\ta.Publish(pubsub.CreatedEvent, event)\n\t\toldSession, err := a.sessions.Get(summarizeCtx, sessionID)\n\t\tif err != nil {\n\t\t\tevent = AgentEvent{\n\t\t\t\tType: AgentEventTypeError,\n\t\t\t\tError: fmt.Errorf(\"failed to get session: %w\", err),\n\t\t\t\tDone: true,\n\t\t\t}\n\n\t\t\ta.Publish(pubsub.CreatedEvent, event)\n\t\t\treturn\n\t\t}\n\t\t// Create a message in the new session with the summary\n\t\tmsg, err := a.messages.Create(summarizeCtx, oldSession.ID, message.CreateMessageParams{\n\t\t\tRole: message.Assistant,\n\t\t\tParts: []message.ContentPart{\n\t\t\t\tmessage.TextContent{Text: summary},\n\t\t\t\tmessage.Finish{\n\t\t\t\t\tReason: message.FinishReasonEndTurn,\n\t\t\t\t\tTime: time.Now().Unix(),\n\t\t\t\t},\n\t\t\t},\n\t\t\tModel: a.summarizeProvider.Model().ID,\n\t\t})\n\t\tif err != nil {\n\t\t\tevent = AgentEvent{\n\t\t\t\tType: AgentEventTypeError,\n\t\t\t\tError: fmt.Errorf(\"failed to create summary message: %w\", err),\n\t\t\t\tDone: true,\n\t\t\t}\n\n\t\t\ta.Publish(pubsub.CreatedEvent, event)\n\t\t\treturn\n\t\t}\n\t\toldSession.SummaryMessageID = msg.ID\n\t\toldSession.CompletionTokens = response.Usage.OutputTokens\n\t\toldSession.PromptTokens = 0\n\t\tmodel := a.summarizeProvider.Model()\n\t\tusage := response.Usage\n\t\tcost := model.CostPer1MInCached/1e6*float64(usage.CacheCreationTokens) +\n\t\t\tmodel.CostPer1MOutCached/1e6*float64(usage.CacheReadTokens) +\n\t\t\tmodel.CostPer1MIn/1e6*float64(usage.InputTokens) +\n\t\t\tmodel.CostPer1MOut/1e6*float64(usage.OutputTokens)\n\t\toldSession.Cost += cost\n\t\t_, err = a.sessions.Save(summarizeCtx, oldSession)\n\t\tif err != nil {\n\t\t\tevent = AgentEvent{\n\t\t\t\tType: AgentEventTypeError,\n\t\t\t\tError: fmt.Errorf(\"failed to save session: %w\", err),\n\t\t\t\tDone: true,\n\t\t\t}\n\t\t\ta.Publish(pubsub.CreatedEvent, event)\n\t\t}\n\n\t\tevent = AgentEvent{\n\t\t\tType: AgentEventTypeSummarize,\n\t\t\tSessionID: oldSession.ID,\n\t\t\tProgress: \"Summary complete\",\n\t\t\tDone: true,\n\t\t}\n\t\ta.Publish(pubsub.CreatedEvent, event)\n\t\t// Send final success event with the new session ID\n\t}()\n\n\treturn nil\n}\n\nfunc createAgentProvider(agentName config.AgentName) (provider.Provider, error) {\n\tcfg := config.Get()\n\tagentConfig, ok := cfg.Agents[agentName]\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"agent %s not found\", agentName)\n\t}\n\tmodel, ok := models.SupportedModels[agentConfig.Model]\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"model %s not supported\", agentConfig.Model)\n\t}\n\n\tproviderCfg, ok := cfg.Providers[model.Provider]\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"provider %s not supported\", model.Provider)\n\t}\n\tif providerCfg.Disabled {\n\t\treturn nil, fmt.Errorf(\"provider %s is not enabled\", model.Provider)\n\t}\n\tmaxTokens := model.DefaultMaxTokens\n\tif agentConfig.MaxTokens > 0 {\n\t\tmaxTokens = agentConfig.MaxTokens\n\t}\n\topts := []provider.ProviderClientOption{\n\t\tprovider.WithAPIKey(providerCfg.APIKey),\n\t\tprovider.WithModel(model),\n\t\tprovider.WithSystemMessage(prompt.GetAgentPrompt(agentName, model.Provider)),\n\t\tprovider.WithMaxTokens(maxTokens),\n\t}\n\tif model.Provider == models.ProviderOpenAI || model.Provider == models.ProviderLocal && model.CanReason {\n\t\topts = append(\n\t\t\topts,\n\t\t\tprovider.WithOpenAIOptions(\n\t\t\t\tprovider.WithReasoningEffort(agentConfig.ReasoningEffort),\n\t\t\t),\n\t\t)\n\t} else if model.Provider == models.ProviderAnthropic && model.CanReason && agentName == config.AgentCoder {\n\t\topts = append(\n\t\t\topts,\n\t\t\tprovider.WithAnthropicOptions(\n\t\t\t\tprovider.WithAnthropicShouldThinkFn(provider.DefaultShouldThinkFn),\n\t\t\t),\n\t\t)\n\t}\n\tagentProvider, err := provider.NewProvider(\n\t\tmodel.Provider,\n\t\topts...,\n\t)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"could not create provider: %v\", err)\n\t}\n\n\treturn agentProvider, nil\n}\n"], ["/opencode/internal/tui/components/dialog/session.go", "package dialog\n\nimport (\n\t\"github.com/charmbracelet/bubbles/key\"\n\ttea \"github.com/charmbracelet/bubbletea\"\n\t\"github.com/charmbracelet/lipgloss\"\n\t\"github.com/opencode-ai/opencode/internal/session\"\n\t\"github.com/opencode-ai/opencode/internal/tui/layout\"\n\t\"github.com/opencode-ai/opencode/internal/tui/styles\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n\t\"github.com/opencode-ai/opencode/internal/tui/util\"\n)\n\n// SessionSelectedMsg is sent when a session is selected\ntype SessionSelectedMsg struct {\n\tSession session.Session\n}\n\n// CloseSessionDialogMsg is sent when the session dialog is closed\ntype CloseSessionDialogMsg struct{}\n\n// SessionDialog interface for the session switching dialog\ntype SessionDialog interface {\n\ttea.Model\n\tlayout.Bindings\n\tSetSessions(sessions []session.Session)\n\tSetSelectedSession(sessionID string)\n}\n\ntype sessionDialogCmp struct {\n\tsessions []session.Session\n\tselectedIdx int\n\twidth int\n\theight int\n\tselectedSessionID string\n}\n\ntype sessionKeyMap struct {\n\tUp key.Binding\n\tDown key.Binding\n\tEnter key.Binding\n\tEscape key.Binding\n\tJ key.Binding\n\tK key.Binding\n}\n\nvar sessionKeys = sessionKeyMap{\n\tUp: key.NewBinding(\n\t\tkey.WithKeys(\"up\"),\n\t\tkey.WithHelp(\"↑\", \"previous session\"),\n\t),\n\tDown: key.NewBinding(\n\t\tkey.WithKeys(\"down\"),\n\t\tkey.WithHelp(\"↓\", \"next session\"),\n\t),\n\tEnter: key.NewBinding(\n\t\tkey.WithKeys(\"enter\"),\n\t\tkey.WithHelp(\"enter\", \"select session\"),\n\t),\n\tEscape: key.NewBinding(\n\t\tkey.WithKeys(\"esc\"),\n\t\tkey.WithHelp(\"esc\", \"close\"),\n\t),\n\tJ: key.NewBinding(\n\t\tkey.WithKeys(\"j\"),\n\t\tkey.WithHelp(\"j\", \"next session\"),\n\t),\n\tK: key.NewBinding(\n\t\tkey.WithKeys(\"k\"),\n\t\tkey.WithHelp(\"k\", \"previous session\"),\n\t),\n}\n\nfunc (s *sessionDialogCmp) Init() tea.Cmd {\n\treturn nil\n}\n\nfunc (s *sessionDialogCmp) Update(msg tea.Msg) (tea.Model, tea.Cmd) {\n\tswitch msg := msg.(type) {\n\tcase tea.KeyMsg:\n\t\tswitch {\n\t\tcase key.Matches(msg, sessionKeys.Up) || key.Matches(msg, sessionKeys.K):\n\t\t\tif s.selectedIdx > 0 {\n\t\t\t\ts.selectedIdx--\n\t\t\t}\n\t\t\treturn s, nil\n\t\tcase key.Matches(msg, sessionKeys.Down) || key.Matches(msg, sessionKeys.J):\n\t\t\tif s.selectedIdx < len(s.sessions)-1 {\n\t\t\t\ts.selectedIdx++\n\t\t\t}\n\t\t\treturn s, nil\n\t\tcase key.Matches(msg, sessionKeys.Enter):\n\t\t\tif len(s.sessions) > 0 {\n\t\t\t\treturn s, util.CmdHandler(SessionSelectedMsg{\n\t\t\t\t\tSession: s.sessions[s.selectedIdx],\n\t\t\t\t})\n\t\t\t}\n\t\tcase key.Matches(msg, sessionKeys.Escape):\n\t\t\treturn s, util.CmdHandler(CloseSessionDialogMsg{})\n\t\t}\n\tcase tea.WindowSizeMsg:\n\t\ts.width = msg.Width\n\t\ts.height = msg.Height\n\t}\n\treturn s, nil\n}\n\nfunc (s *sessionDialogCmp) View() string {\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\t\n\tif len(s.sessions) == 0 {\n\t\treturn baseStyle.Padding(1, 2).\n\t\t\tBorder(lipgloss.RoundedBorder()).\n\t\t\tBorderBackground(t.Background()).\n\t\t\tBorderForeground(t.TextMuted()).\n\t\t\tWidth(40).\n\t\t\tRender(\"No sessions available\")\n\t}\n\n\t// Calculate max width needed for session titles\n\tmaxWidth := 40 // Minimum width\n\tfor _, sess := range s.sessions {\n\t\tif len(sess.Title) > maxWidth-4 { // Account for padding\n\t\t\tmaxWidth = len(sess.Title) + 4\n\t\t}\n\t}\n\n\tmaxWidth = max(30, min(maxWidth, s.width-15)) // Limit width to avoid overflow\n\n\t// Limit height to avoid taking up too much screen space\n\tmaxVisibleSessions := min(10, len(s.sessions))\n\n\t// Build the session list\n\tsessionItems := make([]string, 0, maxVisibleSessions)\n\tstartIdx := 0\n\n\t// If we have more sessions than can be displayed, adjust the start index\n\tif len(s.sessions) > maxVisibleSessions {\n\t\t// Center the selected item when possible\n\t\thalfVisible := maxVisibleSessions / 2\n\t\tif s.selectedIdx >= halfVisible && s.selectedIdx < len(s.sessions)-halfVisible {\n\t\t\tstartIdx = s.selectedIdx - halfVisible\n\t\t} else if s.selectedIdx >= len(s.sessions)-halfVisible {\n\t\t\tstartIdx = len(s.sessions) - maxVisibleSessions\n\t\t}\n\t}\n\n\tendIdx := min(startIdx+maxVisibleSessions, len(s.sessions))\n\n\tfor i := startIdx; i < endIdx; i++ {\n\t\tsess := s.sessions[i]\n\t\titemStyle := baseStyle.Width(maxWidth)\n\n\t\tif i == s.selectedIdx {\n\t\t\titemStyle = itemStyle.\n\t\t\t\tBackground(t.Primary()).\n\t\t\t\tForeground(t.Background()).\n\t\t\t\tBold(true)\n\t\t}\n\n\t\tsessionItems = append(sessionItems, itemStyle.Padding(0, 1).Render(sess.Title))\n\t}\n\n\ttitle := baseStyle.\n\t\tForeground(t.Primary()).\n\t\tBold(true).\n\t\tWidth(maxWidth).\n\t\tPadding(0, 1).\n\t\tRender(\"Switch Session\")\n\n\tcontent := lipgloss.JoinVertical(\n\t\tlipgloss.Left,\n\t\ttitle,\n\t\tbaseStyle.Width(maxWidth).Render(\"\"),\n\t\tbaseStyle.Width(maxWidth).Render(lipgloss.JoinVertical(lipgloss.Left, sessionItems...)),\n\t\tbaseStyle.Width(maxWidth).Render(\"\"),\n\t)\n\n\treturn baseStyle.Padding(1, 2).\n\t\tBorder(lipgloss.RoundedBorder()).\n\t\tBorderBackground(t.Background()).\n\t\tBorderForeground(t.TextMuted()).\n\t\tWidth(lipgloss.Width(content) + 4).\n\t\tRender(content)\n}\n\nfunc (s *sessionDialogCmp) BindingKeys() []key.Binding {\n\treturn layout.KeyMapToSlice(sessionKeys)\n}\n\nfunc (s *sessionDialogCmp) SetSessions(sessions []session.Session) {\n\ts.sessions = sessions\n\n\t// If we have a selected session ID, find its index\n\tif s.selectedSessionID != \"\" {\n\t\tfor i, sess := range sessions {\n\t\t\tif sess.ID == s.selectedSessionID {\n\t\t\t\ts.selectedIdx = i\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\n\t// Default to first session if selected not found\n\ts.selectedIdx = 0\n}\n\nfunc (s *sessionDialogCmp) SetSelectedSession(sessionID string) {\n\ts.selectedSessionID = sessionID\n\n\t// Update the selected index if sessions are already loaded\n\tif len(s.sessions) > 0 {\n\t\tfor i, sess := range s.sessions {\n\t\t\tif sess.ID == sessionID {\n\t\t\t\ts.selectedIdx = i\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}\n\n// NewSessionDialogCmp creates a new session switching dialog\nfunc NewSessionDialogCmp() SessionDialog {\n\treturn &sessionDialogCmp{\n\t\tsessions: []session.Session{},\n\t\tselectedIdx: 0,\n\t\tselectedSessionID: \"\",\n\t}\n}\n"], ["/opencode/internal/tui/page/chat.go", "package page\n\nimport (\n\t\"context\"\n\t\"strings\"\n\n\t\"github.com/charmbracelet/bubbles/key\"\n\ttea \"github.com/charmbracelet/bubbletea\"\n\t\"github.com/charmbracelet/lipgloss\"\n\t\"github.com/opencode-ai/opencode/internal/app\"\n\t\"github.com/opencode-ai/opencode/internal/completions\"\n\t\"github.com/opencode-ai/opencode/internal/message\"\n\t\"github.com/opencode-ai/opencode/internal/session\"\n\t\"github.com/opencode-ai/opencode/internal/tui/components/chat\"\n\t\"github.com/opencode-ai/opencode/internal/tui/components/dialog\"\n\t\"github.com/opencode-ai/opencode/internal/tui/layout\"\n\t\"github.com/opencode-ai/opencode/internal/tui/util\"\n)\n\nvar ChatPage PageID = \"chat\"\n\ntype chatPage struct {\n\tapp *app.App\n\teditor layout.Container\n\tmessages layout.Container\n\tlayout layout.SplitPaneLayout\n\tsession session.Session\n\tcompletionDialog dialog.CompletionDialog\n\tshowCompletionDialog bool\n}\n\ntype ChatKeyMap struct {\n\tShowCompletionDialog key.Binding\n\tNewSession key.Binding\n\tCancel key.Binding\n}\n\nvar keyMap = ChatKeyMap{\n\tShowCompletionDialog: key.NewBinding(\n\t\tkey.WithKeys(\"@\"),\n\t\tkey.WithHelp(\"@\", \"Complete\"),\n\t),\n\tNewSession: key.NewBinding(\n\t\tkey.WithKeys(\"ctrl+n\"),\n\t\tkey.WithHelp(\"ctrl+n\", \"new session\"),\n\t),\n\tCancel: key.NewBinding(\n\t\tkey.WithKeys(\"esc\"),\n\t\tkey.WithHelp(\"esc\", \"cancel\"),\n\t),\n}\n\nfunc (p *chatPage) Init() tea.Cmd {\n\tcmds := []tea.Cmd{\n\t\tp.layout.Init(),\n\t\tp.completionDialog.Init(),\n\t}\n\treturn tea.Batch(cmds...)\n}\n\nfunc (p *chatPage) Update(msg tea.Msg) (tea.Model, tea.Cmd) {\n\tvar cmds []tea.Cmd\n\tswitch msg := msg.(type) {\n\tcase tea.WindowSizeMsg:\n\t\tcmd := p.layout.SetSize(msg.Width, msg.Height)\n\t\tcmds = append(cmds, cmd)\n\tcase dialog.CompletionDialogCloseMsg:\n\t\tp.showCompletionDialog = false\n\tcase chat.SendMsg:\n\t\tcmd := p.sendMessage(msg.Text, msg.Attachments)\n\t\tif cmd != nil {\n\t\t\treturn p, cmd\n\t\t}\n\tcase dialog.CommandRunCustomMsg:\n\t\t// Check if the agent is busy before executing custom commands\n\t\tif p.app.CoderAgent.IsBusy() {\n\t\t\treturn p, util.ReportWarn(\"Agent is busy, please wait before executing a command...\")\n\t\t}\n\t\t\n\t\t// Process the command content with arguments if any\n\t\tcontent := msg.Content\n\t\tif msg.Args != nil {\n\t\t\t// Replace all named arguments with their values\n\t\t\tfor name, value := range msg.Args {\n\t\t\t\tplaceholder := \"$\" + name\n\t\t\t\tcontent = strings.ReplaceAll(content, placeholder, value)\n\t\t\t}\n\t\t}\n\t\t\n\t\t// Handle custom command execution\n\t\tcmd := p.sendMessage(content, nil)\n\t\tif cmd != nil {\n\t\t\treturn p, cmd\n\t\t}\n\tcase chat.SessionSelectedMsg:\n\t\tif p.session.ID == \"\" {\n\t\t\tcmd := p.setSidebar()\n\t\t\tif cmd != nil {\n\t\t\t\tcmds = append(cmds, cmd)\n\t\t\t}\n\t\t}\n\t\tp.session = msg\n\tcase tea.KeyMsg:\n\t\tswitch {\n\t\tcase key.Matches(msg, keyMap.ShowCompletionDialog):\n\t\t\tp.showCompletionDialog = true\n\t\t\t// Continue sending keys to layout->chat\n\t\tcase key.Matches(msg, keyMap.NewSession):\n\t\t\tp.session = session.Session{}\n\t\t\treturn p, tea.Batch(\n\t\t\t\tp.clearSidebar(),\n\t\t\t\tutil.CmdHandler(chat.SessionClearedMsg{}),\n\t\t\t)\n\t\tcase key.Matches(msg, keyMap.Cancel):\n\t\t\tif p.session.ID != \"\" {\n\t\t\t\t// Cancel the current session's generation process\n\t\t\t\t// This allows users to interrupt long-running operations\n\t\t\t\tp.app.CoderAgent.Cancel(p.session.ID)\n\t\t\t\treturn p, nil\n\t\t\t}\n\t\t}\n\t}\n\tif p.showCompletionDialog {\n\t\tcontext, contextCmd := p.completionDialog.Update(msg)\n\t\tp.completionDialog = context.(dialog.CompletionDialog)\n\t\tcmds = append(cmds, contextCmd)\n\n\t\t// Doesn't forward event if enter key is pressed\n\t\tif keyMsg, ok := msg.(tea.KeyMsg); ok {\n\t\t\tif keyMsg.String() == \"enter\" {\n\t\t\t\treturn p, tea.Batch(cmds...)\n\t\t\t}\n\t\t}\n\t}\n\n\tu, cmd := p.layout.Update(msg)\n\tcmds = append(cmds, cmd)\n\tp.layout = u.(layout.SplitPaneLayout)\n\n\treturn p, tea.Batch(cmds...)\n}\n\nfunc (p *chatPage) setSidebar() tea.Cmd {\n\tsidebarContainer := layout.NewContainer(\n\t\tchat.NewSidebarCmp(p.session, p.app.History),\n\t\tlayout.WithPadding(1, 1, 1, 1),\n\t)\n\treturn tea.Batch(p.layout.SetRightPanel(sidebarContainer), sidebarContainer.Init())\n}\n\nfunc (p *chatPage) clearSidebar() tea.Cmd {\n\treturn p.layout.ClearRightPanel()\n}\n\nfunc (p *chatPage) sendMessage(text string, attachments []message.Attachment) tea.Cmd {\n\tvar cmds []tea.Cmd\n\tif p.session.ID == \"\" {\n\t\tsession, err := p.app.Sessions.Create(context.Background(), \"New Session\")\n\t\tif err != nil {\n\t\t\treturn util.ReportError(err)\n\t\t}\n\n\t\tp.session = session\n\t\tcmd := p.setSidebar()\n\t\tif cmd != nil {\n\t\t\tcmds = append(cmds, cmd)\n\t\t}\n\t\tcmds = append(cmds, util.CmdHandler(chat.SessionSelectedMsg(session)))\n\t}\n\n\t_, err := p.app.CoderAgent.Run(context.Background(), p.session.ID, text, attachments...)\n\tif err != nil {\n\t\treturn util.ReportError(err)\n\t}\n\treturn tea.Batch(cmds...)\n}\n\nfunc (p *chatPage) SetSize(width, height int) tea.Cmd {\n\treturn p.layout.SetSize(width, height)\n}\n\nfunc (p *chatPage) GetSize() (int, int) {\n\treturn p.layout.GetSize()\n}\n\nfunc (p *chatPage) View() string {\n\tlayoutView := p.layout.View()\n\n\tif p.showCompletionDialog {\n\t\t_, layoutHeight := p.layout.GetSize()\n\t\teditorWidth, editorHeight := p.editor.GetSize()\n\n\t\tp.completionDialog.SetWidth(editorWidth)\n\t\toverlay := p.completionDialog.View()\n\n\t\tlayoutView = layout.PlaceOverlay(\n\t\t\t0,\n\t\t\tlayoutHeight-editorHeight-lipgloss.Height(overlay),\n\t\t\toverlay,\n\t\t\tlayoutView,\n\t\t\tfalse,\n\t\t)\n\t}\n\n\treturn layoutView\n}\n\nfunc (p *chatPage) BindingKeys() []key.Binding {\n\tbindings := layout.KeyMapToSlice(keyMap)\n\tbindings = append(bindings, p.messages.BindingKeys()...)\n\tbindings = append(bindings, p.editor.BindingKeys()...)\n\treturn bindings\n}\n\nfunc NewChatPage(app *app.App) tea.Model {\n\tcg := completions.NewFileAndFolderContextGroup()\n\tcompletionDialog := dialog.NewCompletionDialogCmp(cg)\n\n\tmessagesContainer := layout.NewContainer(\n\t\tchat.NewMessagesCmp(app),\n\t\tlayout.WithPadding(1, 1, 0, 1),\n\t)\n\teditorContainer := layout.NewContainer(\n\t\tchat.NewEditorCmp(app),\n\t\tlayout.WithBorder(true, false, false, false),\n\t)\n\treturn &chatPage{\n\t\tapp: app,\n\t\teditor: editorContainer,\n\t\tmessages: messagesContainer,\n\t\tcompletionDialog: completionDialog,\n\t\tlayout: layout.NewSplitPane(\n\t\t\tlayout.WithLeftPanel(messagesContainer),\n\t\t\tlayout.WithBottomPanel(editorContainer),\n\t\t),\n\t}\n}\n"], ["/opencode/internal/tui/components/dialog/quit.go", "package dialog\n\nimport (\n\t\"strings\"\n\n\t\"github.com/charmbracelet/bubbles/key\"\n\ttea \"github.com/charmbracelet/bubbletea\"\n\t\"github.com/charmbracelet/lipgloss\"\n\t\"github.com/opencode-ai/opencode/internal/tui/layout\"\n\t\"github.com/opencode-ai/opencode/internal/tui/styles\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n\t\"github.com/opencode-ai/opencode/internal/tui/util\"\n)\n\nconst question = \"Are you sure you want to quit?\"\n\ntype CloseQuitMsg struct{}\n\ntype QuitDialog interface {\n\ttea.Model\n\tlayout.Bindings\n}\n\ntype quitDialogCmp struct {\n\tselectedNo bool\n}\n\ntype helpMapping struct {\n\tLeftRight key.Binding\n\tEnterSpace key.Binding\n\tYes key.Binding\n\tNo key.Binding\n\tTab key.Binding\n}\n\nvar helpKeys = helpMapping{\n\tLeftRight: key.NewBinding(\n\t\tkey.WithKeys(\"left\", \"right\"),\n\t\tkey.WithHelp(\"←/→\", \"switch options\"),\n\t),\n\tEnterSpace: key.NewBinding(\n\t\tkey.WithKeys(\"enter\", \" \"),\n\t\tkey.WithHelp(\"enter/space\", \"confirm\"),\n\t),\n\tYes: key.NewBinding(\n\t\tkey.WithKeys(\"y\", \"Y\"),\n\t\tkey.WithHelp(\"y/Y\", \"yes\"),\n\t),\n\tNo: key.NewBinding(\n\t\tkey.WithKeys(\"n\", \"N\"),\n\t\tkey.WithHelp(\"n/N\", \"no\"),\n\t),\n\tTab: key.NewBinding(\n\t\tkey.WithKeys(\"tab\"),\n\t\tkey.WithHelp(\"tab\", \"switch options\"),\n\t),\n}\n\nfunc (q *quitDialogCmp) Init() tea.Cmd {\n\treturn nil\n}\n\nfunc (q *quitDialogCmp) Update(msg tea.Msg) (tea.Model, tea.Cmd) {\n\tswitch msg := msg.(type) {\n\tcase tea.KeyMsg:\n\t\tswitch {\n\t\tcase key.Matches(msg, helpKeys.LeftRight) || key.Matches(msg, helpKeys.Tab):\n\t\t\tq.selectedNo = !q.selectedNo\n\t\t\treturn q, nil\n\t\tcase key.Matches(msg, helpKeys.EnterSpace):\n\t\t\tif !q.selectedNo {\n\t\t\t\treturn q, tea.Quit\n\t\t\t}\n\t\t\treturn q, util.CmdHandler(CloseQuitMsg{})\n\t\tcase key.Matches(msg, helpKeys.Yes):\n\t\t\treturn q, tea.Quit\n\t\tcase key.Matches(msg, helpKeys.No):\n\t\t\treturn q, util.CmdHandler(CloseQuitMsg{})\n\t\t}\n\t}\n\treturn q, nil\n}\n\nfunc (q *quitDialogCmp) View() string {\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\t\n\tyesStyle := baseStyle\n\tnoStyle := baseStyle\n\tspacerStyle := baseStyle.Background(t.Background())\n\n\tif q.selectedNo {\n\t\tnoStyle = noStyle.Background(t.Primary()).Foreground(t.Background())\n\t\tyesStyle = yesStyle.Background(t.Background()).Foreground(t.Primary())\n\t} else {\n\t\tyesStyle = yesStyle.Background(t.Primary()).Foreground(t.Background())\n\t\tnoStyle = noStyle.Background(t.Background()).Foreground(t.Primary())\n\t}\n\n\tyesButton := yesStyle.Padding(0, 1).Render(\"Yes\")\n\tnoButton := noStyle.Padding(0, 1).Render(\"No\")\n\n\tbuttons := lipgloss.JoinHorizontal(lipgloss.Left, yesButton, spacerStyle.Render(\" \"), noButton)\n\n\twidth := lipgloss.Width(question)\n\tremainingWidth := width - lipgloss.Width(buttons)\n\tif remainingWidth > 0 {\n\t\tbuttons = spacerStyle.Render(strings.Repeat(\" \", remainingWidth)) + buttons\n\t}\n\n\tcontent := baseStyle.Render(\n\t\tlipgloss.JoinVertical(\n\t\t\tlipgloss.Center,\n\t\t\tquestion,\n\t\t\t\"\",\n\t\t\tbuttons,\n\t\t),\n\t)\n\n\treturn baseStyle.Padding(1, 2).\n\t\tBorder(lipgloss.RoundedBorder()).\n\t\tBorderBackground(t.Background()).\n\t\tBorderForeground(t.TextMuted()).\n\t\tWidth(lipgloss.Width(content) + 4).\n\t\tRender(content)\n}\n\nfunc (q *quitDialogCmp) BindingKeys() []key.Binding {\n\treturn layout.KeyMapToSlice(helpKeys)\n}\n\nfunc NewQuitCmp() QuitDialog {\n\treturn &quitDialogCmp{\n\t\tselectedNo: true,\n\t}\n}\n"], ["/opencode/internal/tui/components/dialog/theme.go", "package dialog\n\nimport (\n\t\"github.com/charmbracelet/bubbles/key\"\n\ttea \"github.com/charmbracelet/bubbletea\"\n\t\"github.com/charmbracelet/lipgloss\"\n\t\"github.com/opencode-ai/opencode/internal/tui/layout\"\n\t\"github.com/opencode-ai/opencode/internal/tui/styles\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n\t\"github.com/opencode-ai/opencode/internal/tui/util\"\n)\n\n// ThemeChangedMsg is sent when the theme is changed\ntype ThemeChangedMsg struct {\n\tThemeName string\n}\n\n// CloseThemeDialogMsg is sent when the theme dialog is closed\ntype CloseThemeDialogMsg struct{}\n\n// ThemeDialog interface for the theme switching dialog\ntype ThemeDialog interface {\n\ttea.Model\n\tlayout.Bindings\n}\n\ntype themeDialogCmp struct {\n\tthemes []string\n\tselectedIdx int\n\twidth int\n\theight int\n\tcurrentTheme string\n}\n\ntype themeKeyMap struct {\n\tUp key.Binding\n\tDown key.Binding\n\tEnter key.Binding\n\tEscape key.Binding\n\tJ key.Binding\n\tK key.Binding\n}\n\nvar themeKeys = themeKeyMap{\n\tUp: key.NewBinding(\n\t\tkey.WithKeys(\"up\"),\n\t\tkey.WithHelp(\"↑\", \"previous theme\"),\n\t),\n\tDown: key.NewBinding(\n\t\tkey.WithKeys(\"down\"),\n\t\tkey.WithHelp(\"↓\", \"next theme\"),\n\t),\n\tEnter: key.NewBinding(\n\t\tkey.WithKeys(\"enter\"),\n\t\tkey.WithHelp(\"enter\", \"select theme\"),\n\t),\n\tEscape: key.NewBinding(\n\t\tkey.WithKeys(\"esc\"),\n\t\tkey.WithHelp(\"esc\", \"close\"),\n\t),\n\tJ: key.NewBinding(\n\t\tkey.WithKeys(\"j\"),\n\t\tkey.WithHelp(\"j\", \"next theme\"),\n\t),\n\tK: key.NewBinding(\n\t\tkey.WithKeys(\"k\"),\n\t\tkey.WithHelp(\"k\", \"previous theme\"),\n\t),\n}\n\nfunc (t *themeDialogCmp) Init() tea.Cmd {\n\t// Load available themes and update selectedIdx based on current theme\n\tt.themes = theme.AvailableThemes()\n\tt.currentTheme = theme.CurrentThemeName()\n\n\t// Find the current theme in the list\n\tfor i, name := range t.themes {\n\t\tif name == t.currentTheme {\n\t\t\tt.selectedIdx = i\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc (t *themeDialogCmp) Update(msg tea.Msg) (tea.Model, tea.Cmd) {\n\tswitch msg := msg.(type) {\n\tcase tea.KeyMsg:\n\t\tswitch {\n\t\tcase key.Matches(msg, themeKeys.Up) || key.Matches(msg, themeKeys.K):\n\t\t\tif t.selectedIdx > 0 {\n\t\t\t\tt.selectedIdx--\n\t\t\t}\n\t\t\treturn t, nil\n\t\tcase key.Matches(msg, themeKeys.Down) || key.Matches(msg, themeKeys.J):\n\t\t\tif t.selectedIdx < len(t.themes)-1 {\n\t\t\t\tt.selectedIdx++\n\t\t\t}\n\t\t\treturn t, nil\n\t\tcase key.Matches(msg, themeKeys.Enter):\n\t\t\tif len(t.themes) > 0 {\n\t\t\t\tpreviousTheme := theme.CurrentThemeName()\n\t\t\t\tselectedTheme := t.themes[t.selectedIdx]\n\t\t\t\tif previousTheme == selectedTheme {\n\t\t\t\t\treturn t, util.CmdHandler(CloseThemeDialogMsg{})\n\t\t\t\t}\n\t\t\t\tif err := theme.SetTheme(selectedTheme); err != nil {\n\t\t\t\t\treturn t, util.ReportError(err)\n\t\t\t\t}\n\t\t\t\treturn t, util.CmdHandler(ThemeChangedMsg{\n\t\t\t\t\tThemeName: selectedTheme,\n\t\t\t\t})\n\t\t\t}\n\t\tcase key.Matches(msg, themeKeys.Escape):\n\t\t\treturn t, util.CmdHandler(CloseThemeDialogMsg{})\n\t\t}\n\tcase tea.WindowSizeMsg:\n\t\tt.width = msg.Width\n\t\tt.height = msg.Height\n\t}\n\treturn t, nil\n}\n\nfunc (t *themeDialogCmp) View() string {\n\tcurrentTheme := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\n\tif len(t.themes) == 0 {\n\t\treturn baseStyle.Padding(1, 2).\n\t\t\tBorder(lipgloss.RoundedBorder()).\n\t\t\tBorderBackground(currentTheme.Background()).\n\t\t\tBorderForeground(currentTheme.TextMuted()).\n\t\t\tWidth(40).\n\t\t\tRender(\"No themes available\")\n\t}\n\n\t// Calculate max width needed for theme names\n\tmaxWidth := 40 // Minimum width\n\tfor _, themeName := range t.themes {\n\t\tif len(themeName) > maxWidth-4 { // Account for padding\n\t\t\tmaxWidth = len(themeName) + 4\n\t\t}\n\t}\n\n\tmaxWidth = max(30, min(maxWidth, t.width-15)) // Limit width to avoid overflow\n\n\t// Build the theme list\n\tthemeItems := make([]string, 0, len(t.themes))\n\tfor i, themeName := range t.themes {\n\t\titemStyle := baseStyle.Width(maxWidth)\n\n\t\tif i == t.selectedIdx {\n\t\t\titemStyle = itemStyle.\n\t\t\t\tBackground(currentTheme.Primary()).\n\t\t\t\tForeground(currentTheme.Background()).\n\t\t\t\tBold(true)\n\t\t}\n\n\t\tthemeItems = append(themeItems, itemStyle.Padding(0, 1).Render(themeName))\n\t}\n\n\ttitle := baseStyle.\n\t\tForeground(currentTheme.Primary()).\n\t\tBold(true).\n\t\tWidth(maxWidth).\n\t\tPadding(0, 1).\n\t\tRender(\"Select Theme\")\n\n\tcontent := lipgloss.JoinVertical(\n\t\tlipgloss.Left,\n\t\ttitle,\n\t\tbaseStyle.Width(maxWidth).Render(\"\"),\n\t\tbaseStyle.Width(maxWidth).Render(lipgloss.JoinVertical(lipgloss.Left, themeItems...)),\n\t\tbaseStyle.Width(maxWidth).Render(\"\"),\n\t)\n\n\treturn baseStyle.Padding(1, 2).\n\t\tBorder(lipgloss.RoundedBorder()).\n\t\tBorderBackground(currentTheme.Background()).\n\t\tBorderForeground(currentTheme.TextMuted()).\n\t\tWidth(lipgloss.Width(content) + 4).\n\t\tRender(content)\n}\n\nfunc (t *themeDialogCmp) BindingKeys() []key.Binding {\n\treturn layout.KeyMapToSlice(themeKeys)\n}\n\n// NewThemeDialogCmp creates a new theme switching dialog\nfunc NewThemeDialogCmp() ThemeDialog {\n\treturn &themeDialogCmp{\n\t\tthemes: []string{},\n\t\tselectedIdx: 0,\n\t\tcurrentTheme: \"\",\n\t}\n}\n\n"], ["/opencode/internal/llm/agent/mcp-tools.go", "package agent\n\nimport (\n\t\"context\"\n\t\"encoding/json\"\n\t\"fmt\"\n\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/llm/tools\"\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n\t\"github.com/opencode-ai/opencode/internal/permission\"\n\t\"github.com/opencode-ai/opencode/internal/version\"\n\n\t\"github.com/mark3labs/mcp-go/client\"\n\t\"github.com/mark3labs/mcp-go/mcp\"\n)\n\ntype mcpTool struct {\n\tmcpName string\n\ttool mcp.Tool\n\tmcpConfig config.MCPServer\n\tpermissions permission.Service\n}\n\ntype MCPClient interface {\n\tInitialize(\n\t\tctx context.Context,\n\t\trequest mcp.InitializeRequest,\n\t) (*mcp.InitializeResult, error)\n\tListTools(ctx context.Context, request mcp.ListToolsRequest) (*mcp.ListToolsResult, error)\n\tCallTool(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error)\n\tClose() error\n}\n\nfunc (b *mcpTool) Info() tools.ToolInfo {\n\trequired := b.tool.InputSchema.Required\n\tif required == nil {\n\t\trequired = make([]string, 0)\n\t}\n\treturn tools.ToolInfo{\n\t\tName: fmt.Sprintf(\"%s_%s\", b.mcpName, b.tool.Name),\n\t\tDescription: b.tool.Description,\n\t\tParameters: b.tool.InputSchema.Properties,\n\t\tRequired: required,\n\t}\n}\n\nfunc runTool(ctx context.Context, c MCPClient, toolName string, input string) (tools.ToolResponse, error) {\n\tdefer c.Close()\n\tinitRequest := mcp.InitializeRequest{}\n\tinitRequest.Params.ProtocolVersion = mcp.LATEST_PROTOCOL_VERSION\n\tinitRequest.Params.ClientInfo = mcp.Implementation{\n\t\tName: \"OpenCode\",\n\t\tVersion: version.Version,\n\t}\n\n\t_, err := c.Initialize(ctx, initRequest)\n\tif err != nil {\n\t\treturn tools.NewTextErrorResponse(err.Error()), nil\n\t}\n\n\ttoolRequest := mcp.CallToolRequest{}\n\ttoolRequest.Params.Name = toolName\n\tvar args map[string]any\n\tif err = json.Unmarshal([]byte(input), &args); err != nil {\n\t\treturn tools.NewTextErrorResponse(fmt.Sprintf(\"error parsing parameters: %s\", err)), nil\n\t}\n\ttoolRequest.Params.Arguments = args\n\tresult, err := c.CallTool(ctx, toolRequest)\n\tif err != nil {\n\t\treturn tools.NewTextErrorResponse(err.Error()), nil\n\t}\n\n\toutput := \"\"\n\tfor _, v := range result.Content {\n\t\tif v, ok := v.(mcp.TextContent); ok {\n\t\t\toutput = v.Text\n\t\t} else {\n\t\t\toutput = fmt.Sprintf(\"%v\", v)\n\t\t}\n\t}\n\n\treturn tools.NewTextResponse(output), nil\n}\n\nfunc (b *mcpTool) Run(ctx context.Context, params tools.ToolCall) (tools.ToolResponse, error) {\n\tsessionID, messageID := tools.GetContextValues(ctx)\n\tif sessionID == \"\" || messageID == \"\" {\n\t\treturn tools.ToolResponse{}, fmt.Errorf(\"session ID and message ID are required for creating a new file\")\n\t}\n\tpermissionDescription := fmt.Sprintf(\"execute %s with the following parameters: %s\", b.Info().Name, params.Input)\n\tp := b.permissions.Request(\n\t\tpermission.CreatePermissionRequest{\n\t\t\tSessionID: sessionID,\n\t\t\tPath: config.WorkingDirectory(),\n\t\t\tToolName: b.Info().Name,\n\t\t\tAction: \"execute\",\n\t\t\tDescription: permissionDescription,\n\t\t\tParams: params.Input,\n\t\t},\n\t)\n\tif !p {\n\t\treturn tools.NewTextErrorResponse(\"permission denied\"), nil\n\t}\n\n\tswitch b.mcpConfig.Type {\n\tcase config.MCPStdio:\n\t\tc, err := client.NewStdioMCPClient(\n\t\t\tb.mcpConfig.Command,\n\t\t\tb.mcpConfig.Env,\n\t\t\tb.mcpConfig.Args...,\n\t\t)\n\t\tif err != nil {\n\t\t\treturn tools.NewTextErrorResponse(err.Error()), nil\n\t\t}\n\t\treturn runTool(ctx, c, b.tool.Name, params.Input)\n\tcase config.MCPSse:\n\t\tc, err := client.NewSSEMCPClient(\n\t\t\tb.mcpConfig.URL,\n\t\t\tclient.WithHeaders(b.mcpConfig.Headers),\n\t\t)\n\t\tif err != nil {\n\t\t\treturn tools.NewTextErrorResponse(err.Error()), nil\n\t\t}\n\t\treturn runTool(ctx, c, b.tool.Name, params.Input)\n\t}\n\n\treturn tools.NewTextErrorResponse(\"invalid mcp type\"), nil\n}\n\nfunc NewMcpTool(name string, tool mcp.Tool, permissions permission.Service, mcpConfig config.MCPServer) tools.BaseTool {\n\treturn &mcpTool{\n\t\tmcpName: name,\n\t\ttool: tool,\n\t\tmcpConfig: mcpConfig,\n\t\tpermissions: permissions,\n\t}\n}\n\nvar mcpTools []tools.BaseTool\n\nfunc getTools(ctx context.Context, name string, m config.MCPServer, permissions permission.Service, c MCPClient) []tools.BaseTool {\n\tvar stdioTools []tools.BaseTool\n\tinitRequest := mcp.InitializeRequest{}\n\tinitRequest.Params.ProtocolVersion = mcp.LATEST_PROTOCOL_VERSION\n\tinitRequest.Params.ClientInfo = mcp.Implementation{\n\t\tName: \"OpenCode\",\n\t\tVersion: version.Version,\n\t}\n\n\t_, err := c.Initialize(ctx, initRequest)\n\tif err != nil {\n\t\tlogging.Error(\"error initializing mcp client\", \"error\", err)\n\t\treturn stdioTools\n\t}\n\ttoolsRequest := mcp.ListToolsRequest{}\n\ttools, err := c.ListTools(ctx, toolsRequest)\n\tif err != nil {\n\t\tlogging.Error(\"error listing tools\", \"error\", err)\n\t\treturn stdioTools\n\t}\n\tfor _, t := range tools.Tools {\n\t\tstdioTools = append(stdioTools, NewMcpTool(name, t, permissions, m))\n\t}\n\tdefer c.Close()\n\treturn stdioTools\n}\n\nfunc GetMcpTools(ctx context.Context, permissions permission.Service) []tools.BaseTool {\n\tif len(mcpTools) > 0 {\n\t\treturn mcpTools\n\t}\n\tfor name, m := range config.Get().MCPServers {\n\t\tswitch m.Type {\n\t\tcase config.MCPStdio:\n\t\t\tc, err := client.NewStdioMCPClient(\n\t\t\t\tm.Command,\n\t\t\t\tm.Env,\n\t\t\t\tm.Args...,\n\t\t\t)\n\t\t\tif err != nil {\n\t\t\t\tlogging.Error(\"error creating mcp client\", \"error\", err)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tmcpTools = append(mcpTools, getTools(ctx, name, m, permissions, c)...)\n\t\tcase config.MCPSse:\n\t\t\tc, err := client.NewSSEMCPClient(\n\t\t\t\tm.URL,\n\t\t\t\tclient.WithHeaders(m.Headers),\n\t\t\t)\n\t\t\tif err != nil {\n\t\t\t\tlogging.Error(\"error creating mcp client\", \"error\", err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tmcpTools = append(mcpTools, getTools(ctx, name, m, permissions, c)...)\n\t\t}\n\t}\n\n\treturn mcpTools\n}\n"], ["/opencode/internal/tui/components/util/simple-list.go", "package utilComponents\n\nimport (\n\t\"github.com/charmbracelet/bubbles/key\"\n\ttea \"github.com/charmbracelet/bubbletea\"\n\t\"github.com/charmbracelet/lipgloss\"\n\t\"github.com/opencode-ai/opencode/internal/tui/layout\"\n\t\"github.com/opencode-ai/opencode/internal/tui/styles\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n)\n\ntype SimpleListItem interface {\n\tRender(selected bool, width int) string\n}\n\ntype SimpleList[T SimpleListItem] interface {\n\ttea.Model\n\tlayout.Bindings\n\tSetMaxWidth(maxWidth int)\n\tGetSelectedItem() (item T, idx int)\n\tSetItems(items []T)\n\tGetItems() []T\n}\n\ntype simpleListCmp[T SimpleListItem] struct {\n\tfallbackMsg string\n\titems []T\n\tselectedIdx int\n\tmaxWidth int\n\tmaxVisibleItems int\n\tuseAlphaNumericKeys bool\n\twidth int\n\theight int\n}\n\ntype simpleListKeyMap struct {\n\tUp key.Binding\n\tDown key.Binding\n\tUpAlpha key.Binding\n\tDownAlpha key.Binding\n}\n\nvar simpleListKeys = simpleListKeyMap{\n\tUp: key.NewBinding(\n\t\tkey.WithKeys(\"up\"),\n\t\tkey.WithHelp(\"↑\", \"previous list item\"),\n\t),\n\tDown: key.NewBinding(\n\t\tkey.WithKeys(\"down\"),\n\t\tkey.WithHelp(\"↓\", \"next list item\"),\n\t),\n\tUpAlpha: key.NewBinding(\n\t\tkey.WithKeys(\"k\"),\n\t\tkey.WithHelp(\"k\", \"previous list item\"),\n\t),\n\tDownAlpha: key.NewBinding(\n\t\tkey.WithKeys(\"j\"),\n\t\tkey.WithHelp(\"j\", \"next list item\"),\n\t),\n}\n\nfunc (c *simpleListCmp[T]) Init() tea.Cmd {\n\treturn nil\n}\n\nfunc (c *simpleListCmp[T]) Update(msg tea.Msg) (tea.Model, tea.Cmd) {\n\tswitch msg := msg.(type) {\n\tcase tea.KeyMsg:\n\t\tswitch {\n\t\tcase key.Matches(msg, simpleListKeys.Up) || (c.useAlphaNumericKeys && key.Matches(msg, simpleListKeys.UpAlpha)):\n\t\t\tif c.selectedIdx > 0 {\n\t\t\t\tc.selectedIdx--\n\t\t\t}\n\t\t\treturn c, nil\n\t\tcase key.Matches(msg, simpleListKeys.Down) || (c.useAlphaNumericKeys && key.Matches(msg, simpleListKeys.DownAlpha)):\n\t\t\tif c.selectedIdx < len(c.items)-1 {\n\t\t\t\tc.selectedIdx++\n\t\t\t}\n\t\t\treturn c, nil\n\t\t}\n\t}\n\n\treturn c, nil\n}\n\nfunc (c *simpleListCmp[T]) BindingKeys() []key.Binding {\n\treturn layout.KeyMapToSlice(simpleListKeys)\n}\n\nfunc (c *simpleListCmp[T]) GetSelectedItem() (T, int) {\n\tif len(c.items) > 0 {\n\t\treturn c.items[c.selectedIdx], c.selectedIdx\n\t}\n\n\tvar zero T\n\treturn zero, -1\n}\n\nfunc (c *simpleListCmp[T]) SetItems(items []T) {\n\tc.selectedIdx = 0\n\tc.items = items\n}\n\nfunc (c *simpleListCmp[T]) GetItems() []T {\n\treturn c.items\n}\n\nfunc (c *simpleListCmp[T]) SetMaxWidth(width int) {\n\tc.maxWidth = width\n}\n\nfunc (c *simpleListCmp[T]) View() string {\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\n\titems := c.items\n\tmaxWidth := c.maxWidth\n\tmaxVisibleItems := min(c.maxVisibleItems, len(items))\n\tstartIdx := 0\n\n\tif len(items) <= 0 {\n\t\treturn baseStyle.\n\t\t\tBackground(t.Background()).\n\t\t\tPadding(0, 1).\n\t\t\tWidth(maxWidth).\n\t\t\tRender(c.fallbackMsg)\n\t}\n\n\tif len(items) > maxVisibleItems {\n\t\thalfVisible := maxVisibleItems / 2\n\t\tif c.selectedIdx >= halfVisible && c.selectedIdx < len(items)-halfVisible {\n\t\t\tstartIdx = c.selectedIdx - halfVisible\n\t\t} else if c.selectedIdx >= len(items)-halfVisible {\n\t\t\tstartIdx = len(items) - maxVisibleItems\n\t\t}\n\t}\n\n\tendIdx := min(startIdx+maxVisibleItems, len(items))\n\n\tlistItems := make([]string, 0, maxVisibleItems)\n\n\tfor i := startIdx; i < endIdx; i++ {\n\t\titem := items[i]\n\t\ttitle := item.Render(i == c.selectedIdx, maxWidth)\n\t\tlistItems = append(listItems, title)\n\t}\n\n\treturn lipgloss.JoinVertical(lipgloss.Left, listItems...)\n}\n\nfunc NewSimpleList[T SimpleListItem](items []T, maxVisibleItems int, fallbackMsg string, useAlphaNumericKeys bool) SimpleList[T] {\n\treturn &simpleListCmp[T]{\n\t\tfallbackMsg: fallbackMsg,\n\t\titems: items,\n\t\tmaxVisibleItems: maxVisibleItems,\n\t\tuseAlphaNumericKeys: useAlphaNumericKeys,\n\t\tselectedIdx: 0,\n\t}\n}\n"], ["/opencode/internal/llm/prompt/prompt.go", "package prompt\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"strings\"\n\t\"sync\"\n\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/llm/models\"\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n)\n\nfunc GetAgentPrompt(agentName config.AgentName, provider models.ModelProvider) string {\n\tbasePrompt := \"\"\n\tswitch agentName {\n\tcase config.AgentCoder:\n\t\tbasePrompt = CoderPrompt(provider)\n\tcase config.AgentTitle:\n\t\tbasePrompt = TitlePrompt(provider)\n\tcase config.AgentTask:\n\t\tbasePrompt = TaskPrompt(provider)\n\tcase config.AgentSummarizer:\n\t\tbasePrompt = SummarizerPrompt(provider)\n\tdefault:\n\t\tbasePrompt = \"You are a helpful assistant\"\n\t}\n\n\tif agentName == config.AgentCoder || agentName == config.AgentTask {\n\t\t// Add context from project-specific instruction files if they exist\n\t\tcontextContent := getContextFromPaths()\n\t\tlogging.Debug(\"Context content\", \"Context\", contextContent)\n\t\tif contextContent != \"\" {\n\t\t\treturn fmt.Sprintf(\"%s\\n\\n# Project-Specific Context\\n Make sure to follow the instructions in the context below\\n%s\", basePrompt, contextContent)\n\t\t}\n\t}\n\treturn basePrompt\n}\n\nvar (\n\tonceContext sync.Once\n\tcontextContent string\n)\n\nfunc getContextFromPaths() string {\n\tonceContext.Do(func() {\n\t\tvar (\n\t\t\tcfg = config.Get()\n\t\t\tworkDir = cfg.WorkingDir\n\t\t\tcontextPaths = cfg.ContextPaths\n\t\t)\n\n\t\tcontextContent = processContextPaths(workDir, contextPaths)\n\t})\n\n\treturn contextContent\n}\n\nfunc processContextPaths(workDir string, paths []string) string {\n\tvar (\n\t\twg sync.WaitGroup\n\t\tresultCh = make(chan string)\n\t)\n\n\t// Track processed files to avoid duplicates\n\tprocessedFiles := make(map[string]bool)\n\tvar processedMutex sync.Mutex\n\n\tfor _, path := range paths {\n\t\twg.Add(1)\n\t\tgo func(p string) {\n\t\t\tdefer wg.Done()\n\n\t\t\tif strings.HasSuffix(p, \"/\") {\n\t\t\t\tfilepath.WalkDir(filepath.Join(workDir, p), func(path string, d os.DirEntry, err error) error {\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn err\n\t\t\t\t\t}\n\t\t\t\t\tif !d.IsDir() {\n\t\t\t\t\t\t// Check if we've already processed this file (case-insensitive)\n\t\t\t\t\t\tprocessedMutex.Lock()\n\t\t\t\t\t\tlowerPath := strings.ToLower(path)\n\t\t\t\t\t\tif !processedFiles[lowerPath] {\n\t\t\t\t\t\t\tprocessedFiles[lowerPath] = true\n\t\t\t\t\t\t\tprocessedMutex.Unlock()\n\n\t\t\t\t\t\t\tif result := processFile(path); result != \"\" {\n\t\t\t\t\t\t\t\tresultCh <- result\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tprocessedMutex.Unlock()\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\treturn nil\n\t\t\t\t})\n\t\t\t} else {\n\t\t\t\tfullPath := filepath.Join(workDir, p)\n\n\t\t\t\t// Check if we've already processed this file (case-insensitive)\n\t\t\t\tprocessedMutex.Lock()\n\t\t\t\tlowerPath := strings.ToLower(fullPath)\n\t\t\t\tif !processedFiles[lowerPath] {\n\t\t\t\t\tprocessedFiles[lowerPath] = true\n\t\t\t\t\tprocessedMutex.Unlock()\n\n\t\t\t\t\tresult := processFile(fullPath)\n\t\t\t\t\tif result != \"\" {\n\t\t\t\t\t\tresultCh <- result\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tprocessedMutex.Unlock()\n\t\t\t\t}\n\t\t\t}\n\t\t}(path)\n\t}\n\n\tgo func() {\n\t\twg.Wait()\n\t\tclose(resultCh)\n\t}()\n\n\tresults := make([]string, 0)\n\tfor result := range resultCh {\n\t\tresults = append(results, result)\n\t}\n\n\treturn strings.Join(results, \"\\n\")\n}\n\nfunc processFile(filePath string) string {\n\tcontent, err := os.ReadFile(filePath)\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\treturn \"# From:\" + filePath + \"\\n\" + string(content)\n}\n"], ["/opencode/internal/format/format.go", "package format\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"strings\"\n)\n\n// OutputFormat represents the output format type for non-interactive mode\ntype OutputFormat string\n\nconst (\n\t// Text format outputs the AI response as plain text.\n\tText OutputFormat = \"text\"\n\n\t// JSON format outputs the AI response wrapped in a JSON object.\n\tJSON OutputFormat = \"json\"\n)\n\n// String returns the string representation of the OutputFormat\nfunc (f OutputFormat) String() string {\n\treturn string(f)\n}\n\n// SupportedFormats is a list of all supported output formats as strings\nvar SupportedFormats = []string{\n\tstring(Text),\n\tstring(JSON),\n}\n\n// Parse converts a string to an OutputFormat\nfunc Parse(s string) (OutputFormat, error) {\n\ts = strings.ToLower(strings.TrimSpace(s))\n\n\tswitch s {\n\tcase string(Text):\n\t\treturn Text, nil\n\tcase string(JSON):\n\t\treturn JSON, nil\n\tdefault:\n\t\treturn \"\", fmt.Errorf(\"invalid format: %s\", s)\n\t}\n}\n\n// IsValid checks if the provided format string is supported\nfunc IsValid(s string) bool {\n\t_, err := Parse(s)\n\treturn err == nil\n}\n\n// GetHelpText returns a formatted string describing all supported formats\nfunc GetHelpText() string {\n\treturn fmt.Sprintf(`Supported output formats:\n- %s: Plain text output (default)\n- %s: Output wrapped in a JSON object`,\n\t\tText, JSON)\n}\n\n// FormatOutput formats the AI response according to the specified format\nfunc FormatOutput(content string, formatStr string) string {\n\tformat, err := Parse(formatStr)\n\tif err != nil {\n\t\t// Default to text format on error\n\t\treturn content\n\t}\n\n\tswitch format {\n\tcase JSON:\n\t\treturn formatAsJSON(content)\n\tcase Text:\n\t\tfallthrough\n\tdefault:\n\t\treturn content\n\t}\n}\n\n// formatAsJSON wraps the content in a simple JSON object\nfunc formatAsJSON(content string) string {\n\t// Use the JSON package to properly escape the content\n\tresponse := struct {\n\t\tResponse string `json:\"response\"`\n\t}{\n\t\tResponse: content,\n\t}\n\n\tjsonBytes, err := json.MarshalIndent(response, \"\", \" \")\n\tif err != nil {\n\t\t// In case of an error, return a manually formatted JSON\n\t\tjsonEscaped := strings.Replace(content, \"\\\\\", \"\\\\\\\\\", -1)\n\t\tjsonEscaped = strings.Replace(jsonEscaped, \"\\\"\", \"\\\\\\\"\", -1)\n\t\tjsonEscaped = strings.Replace(jsonEscaped, \"\\n\", \"\\\\n\", -1)\n\t\tjsonEscaped = strings.Replace(jsonEscaped, \"\\r\", \"\\\\r\", -1)\n\t\tjsonEscaped = strings.Replace(jsonEscaped, \"\\t\", \"\\\\t\", -1)\n\n\t\treturn fmt.Sprintf(\"{\\n \\\"response\\\": \\\"%s\\\"\\n}\", jsonEscaped)\n\t}\n\n\treturn string(jsonBytes)\n}\n"], ["/opencode/internal/tui/components/dialog/complete.go", "package dialog\n\nimport (\n\t\"github.com/charmbracelet/bubbles/key\"\n\t\"github.com/charmbracelet/bubbles/textarea\"\n\ttea \"github.com/charmbracelet/bubbletea\"\n\t\"github.com/charmbracelet/lipgloss\"\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n\tutilComponents \"github.com/opencode-ai/opencode/internal/tui/components/util\"\n\t\"github.com/opencode-ai/opencode/internal/tui/layout\"\n\t\"github.com/opencode-ai/opencode/internal/tui/styles\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n\t\"github.com/opencode-ai/opencode/internal/tui/util\"\n)\n\ntype CompletionItem struct {\n\ttitle string\n\tTitle string\n\tValue string\n}\n\ntype CompletionItemI interface {\n\tutilComponents.SimpleListItem\n\tGetValue() string\n\tDisplayValue() string\n}\n\nfunc (ci *CompletionItem) Render(selected bool, width int) string {\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\n\titemStyle := baseStyle.\n\t\tWidth(width).\n\t\tPadding(0, 1)\n\n\tif selected {\n\t\titemStyle = itemStyle.\n\t\t\tBackground(t.Background()).\n\t\t\tForeground(t.Primary()).\n\t\t\tBold(true)\n\t}\n\n\ttitle := itemStyle.Render(\n\t\tci.GetValue(),\n\t)\n\n\treturn title\n}\n\nfunc (ci *CompletionItem) DisplayValue() string {\n\treturn ci.Title\n}\n\nfunc (ci *CompletionItem) GetValue() string {\n\treturn ci.Value\n}\n\nfunc NewCompletionItem(completionItem CompletionItem) CompletionItemI {\n\treturn &completionItem\n}\n\ntype CompletionProvider interface {\n\tGetId() string\n\tGetEntry() CompletionItemI\n\tGetChildEntries(query string) ([]CompletionItemI, error)\n}\n\ntype CompletionSelectedMsg struct {\n\tSearchString string\n\tCompletionValue string\n}\n\ntype CompletionDialogCompleteItemMsg struct {\n\tValue string\n}\n\ntype CompletionDialogCloseMsg struct{}\n\ntype CompletionDialog interface {\n\ttea.Model\n\tlayout.Bindings\n\tSetWidth(width int)\n}\n\ntype completionDialogCmp struct {\n\tquery string\n\tcompletionProvider CompletionProvider\n\twidth int\n\theight int\n\tpseudoSearchTextArea textarea.Model\n\tlistView utilComponents.SimpleList[CompletionItemI]\n}\n\ntype completionDialogKeyMap struct {\n\tComplete key.Binding\n\tCancel key.Binding\n}\n\nvar completionDialogKeys = completionDialogKeyMap{\n\tComplete: key.NewBinding(\n\t\tkey.WithKeys(\"tab\", \"enter\"),\n\t),\n\tCancel: key.NewBinding(\n\t\tkey.WithKeys(\" \", \"esc\", \"backspace\"),\n\t),\n}\n\nfunc (c *completionDialogCmp) Init() tea.Cmd {\n\treturn nil\n}\n\nfunc (c *completionDialogCmp) complete(item CompletionItemI) tea.Cmd {\n\tvalue := c.pseudoSearchTextArea.Value()\n\n\tif value == \"\" {\n\t\treturn nil\n\t}\n\n\treturn tea.Batch(\n\t\tutil.CmdHandler(CompletionSelectedMsg{\n\t\t\tSearchString: value,\n\t\t\tCompletionValue: item.GetValue(),\n\t\t}),\n\t\tc.close(),\n\t)\n}\n\nfunc (c *completionDialogCmp) close() tea.Cmd {\n\tc.listView.SetItems([]CompletionItemI{})\n\tc.pseudoSearchTextArea.Reset()\n\tc.pseudoSearchTextArea.Blur()\n\n\treturn util.CmdHandler(CompletionDialogCloseMsg{})\n}\n\nfunc (c *completionDialogCmp) Update(msg tea.Msg) (tea.Model, tea.Cmd) {\n\tvar cmds []tea.Cmd\n\tswitch msg := msg.(type) {\n\tcase tea.KeyMsg:\n\t\tif c.pseudoSearchTextArea.Focused() {\n\n\t\t\tif !key.Matches(msg, completionDialogKeys.Complete) {\n\n\t\t\t\tvar cmd tea.Cmd\n\t\t\t\tc.pseudoSearchTextArea, cmd = c.pseudoSearchTextArea.Update(msg)\n\t\t\t\tcmds = append(cmds, cmd)\n\n\t\t\t\tvar query string\n\t\t\t\tquery = c.pseudoSearchTextArea.Value()\n\t\t\t\tif query != \"\" {\n\t\t\t\t\tquery = query[1:]\n\t\t\t\t}\n\n\t\t\t\tif query != c.query {\n\t\t\t\t\tlogging.Info(\"Query\", query)\n\t\t\t\t\titems, err := c.completionProvider.GetChildEntries(query)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlogging.Error(\"Failed to get child entries\", err)\n\t\t\t\t\t}\n\n\t\t\t\t\tc.listView.SetItems(items)\n\t\t\t\t\tc.query = query\n\t\t\t\t}\n\n\t\t\t\tu, cmd := c.listView.Update(msg)\n\t\t\t\tc.listView = u.(utilComponents.SimpleList[CompletionItemI])\n\n\t\t\t\tcmds = append(cmds, cmd)\n\t\t\t}\n\n\t\t\tswitch {\n\t\t\tcase key.Matches(msg, completionDialogKeys.Complete):\n\t\t\t\titem, i := c.listView.GetSelectedItem()\n\t\t\t\tif i == -1 {\n\t\t\t\t\treturn c, nil\n\t\t\t\t}\n\n\t\t\t\tcmd := c.complete(item)\n\n\t\t\t\treturn c, cmd\n\t\t\tcase key.Matches(msg, completionDialogKeys.Cancel):\n\t\t\t\t// Only close on backspace when there are no characters left\n\t\t\t\tif msg.String() != \"backspace\" || len(c.pseudoSearchTextArea.Value()) <= 0 {\n\t\t\t\t\treturn c, c.close()\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn c, tea.Batch(cmds...)\n\t\t} else {\n\t\t\titems, err := c.completionProvider.GetChildEntries(\"\")\n\t\t\tif err != nil {\n\t\t\t\tlogging.Error(\"Failed to get child entries\", err)\n\t\t\t}\n\n\t\t\tc.listView.SetItems(items)\n\t\t\tc.pseudoSearchTextArea.SetValue(msg.String())\n\t\t\treturn c, c.pseudoSearchTextArea.Focus()\n\t\t}\n\tcase tea.WindowSizeMsg:\n\t\tc.width = msg.Width\n\t\tc.height = msg.Height\n\t}\n\n\treturn c, tea.Batch(cmds...)\n}\n\nfunc (c *completionDialogCmp) View() string {\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\n\tmaxWidth := 40\n\n\tcompletions := c.listView.GetItems()\n\n\tfor _, cmd := range completions {\n\t\ttitle := cmd.DisplayValue()\n\t\tif len(title) > maxWidth-4 {\n\t\t\tmaxWidth = len(title) + 4\n\t\t}\n\t}\n\n\tc.listView.SetMaxWidth(maxWidth)\n\n\treturn baseStyle.Padding(0, 0).\n\t\tBorder(lipgloss.NormalBorder()).\n\t\tBorderBottom(false).\n\t\tBorderRight(false).\n\t\tBorderLeft(false).\n\t\tBorderBackground(t.Background()).\n\t\tBorderForeground(t.TextMuted()).\n\t\tWidth(c.width).\n\t\tRender(c.listView.View())\n}\n\nfunc (c *completionDialogCmp) SetWidth(width int) {\n\tc.width = width\n}\n\nfunc (c *completionDialogCmp) BindingKeys() []key.Binding {\n\treturn layout.KeyMapToSlice(completionDialogKeys)\n}\n\nfunc NewCompletionDialogCmp(completionProvider CompletionProvider) CompletionDialog {\n\tti := textarea.New()\n\n\titems, err := completionProvider.GetChildEntries(\"\")\n\tif err != nil {\n\t\tlogging.Error(\"Failed to get child entries\", err)\n\t}\n\n\tli := utilComponents.NewSimpleList(\n\t\titems,\n\t\t7,\n\t\t\"No file matches found\",\n\t\tfalse,\n\t)\n\n\treturn &completionDialogCmp{\n\t\tquery: \"\",\n\t\tcompletionProvider: completionProvider,\n\t\tpseudoSearchTextArea: ti,\n\t\tlistView: li,\n\t}\n}\n"], ["/opencode/internal/tui/components/dialog/arguments.go", "package dialog\n\nimport (\n\t\"fmt\"\n\t\"github.com/charmbracelet/bubbles/key\"\n\t\"github.com/charmbracelet/bubbles/textinput\"\n\ttea \"github.com/charmbracelet/bubbletea\"\n\t\"github.com/charmbracelet/lipgloss\"\n\n\t\"github.com/opencode-ai/opencode/internal/tui/styles\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n\t\"github.com/opencode-ai/opencode/internal/tui/util\"\n)\n\ntype argumentsDialogKeyMap struct {\n\tEnter key.Binding\n\tEscape key.Binding\n}\n\n// ShortHelp implements key.Map.\nfunc (k argumentsDialogKeyMap) ShortHelp() []key.Binding {\n\treturn []key.Binding{\n\t\tkey.NewBinding(\n\t\t\tkey.WithKeys(\"enter\"),\n\t\t\tkey.WithHelp(\"enter\", \"confirm\"),\n\t\t),\n\t\tkey.NewBinding(\n\t\t\tkey.WithKeys(\"esc\"),\n\t\t\tkey.WithHelp(\"esc\", \"cancel\"),\n\t\t),\n\t}\n}\n\n// FullHelp implements key.Map.\nfunc (k argumentsDialogKeyMap) FullHelp() [][]key.Binding {\n\treturn [][]key.Binding{k.ShortHelp()}\n}\n\n// ShowMultiArgumentsDialogMsg is a message that is sent to show the multi-arguments dialog.\ntype ShowMultiArgumentsDialogMsg struct {\n\tCommandID string\n\tContent string\n\tArgNames []string\n}\n\n// CloseMultiArgumentsDialogMsg is a message that is sent when the multi-arguments dialog is closed.\ntype CloseMultiArgumentsDialogMsg struct {\n\tSubmit bool\n\tCommandID string\n\tContent string\n\tArgs map[string]string\n}\n\n// MultiArgumentsDialogCmp is a component that asks the user for multiple command arguments.\ntype MultiArgumentsDialogCmp struct {\n\twidth, height int\n\tinputs []textinput.Model\n\tfocusIndex int\n\tkeys argumentsDialogKeyMap\n\tcommandID string\n\tcontent string\n\targNames []string\n}\n\n// NewMultiArgumentsDialogCmp creates a new MultiArgumentsDialogCmp.\nfunc NewMultiArgumentsDialogCmp(commandID, content string, argNames []string) MultiArgumentsDialogCmp {\n\tt := theme.CurrentTheme()\n\tinputs := make([]textinput.Model, len(argNames))\n\n\tfor i, name := range argNames {\n\t\tti := textinput.New()\n\t\tti.Placeholder = fmt.Sprintf(\"Enter value for %s...\", name)\n\t\tti.Width = 40\n\t\tti.Prompt = \"\"\n\t\tti.PlaceholderStyle = ti.PlaceholderStyle.Background(t.Background())\n\t\tti.PromptStyle = ti.PromptStyle.Background(t.Background())\n\t\tti.TextStyle = ti.TextStyle.Background(t.Background())\n\t\t\n\t\t// Only focus the first input initially\n\t\tif i == 0 {\n\t\t\tti.Focus()\n\t\t\tti.PromptStyle = ti.PromptStyle.Foreground(t.Primary())\n\t\t\tti.TextStyle = ti.TextStyle.Foreground(t.Primary())\n\t\t} else {\n\t\t\tti.Blur()\n\t\t}\n\n\t\tinputs[i] = ti\n\t}\n\n\treturn MultiArgumentsDialogCmp{\n\t\tinputs: inputs,\n\t\tkeys: argumentsDialogKeyMap{},\n\t\tcommandID: commandID,\n\t\tcontent: content,\n\t\targNames: argNames,\n\t\tfocusIndex: 0,\n\t}\n}\n\n// Init implements tea.Model.\nfunc (m MultiArgumentsDialogCmp) Init() tea.Cmd {\n\t// Make sure only the first input is focused\n\tfor i := range m.inputs {\n\t\tif i == 0 {\n\t\t\tm.inputs[i].Focus()\n\t\t} else {\n\t\t\tm.inputs[i].Blur()\n\t\t}\n\t}\n\t\n\treturn textinput.Blink\n}\n\n// Update implements tea.Model.\nfunc (m MultiArgumentsDialogCmp) Update(msg tea.Msg) (tea.Model, tea.Cmd) {\n\tvar cmds []tea.Cmd\n\tt := theme.CurrentTheme()\n\n\tswitch msg := msg.(type) {\n\tcase tea.KeyMsg:\n\t\tswitch {\n\t\tcase key.Matches(msg, key.NewBinding(key.WithKeys(\"esc\"))):\n\t\t\treturn m, util.CmdHandler(CloseMultiArgumentsDialogMsg{\n\t\t\t\tSubmit: false,\n\t\t\t\tCommandID: m.commandID,\n\t\t\t\tContent: m.content,\n\t\t\t\tArgs: nil,\n\t\t\t})\n\t\tcase key.Matches(msg, key.NewBinding(key.WithKeys(\"enter\"))):\n\t\t\t// If we're on the last input, submit the form\n\t\t\tif m.focusIndex == len(m.inputs)-1 {\n\t\t\t\targs := make(map[string]string)\n\t\t\t\tfor i, name := range m.argNames {\n\t\t\t\t\targs[name] = m.inputs[i].Value()\n\t\t\t\t}\n\t\t\t\treturn m, util.CmdHandler(CloseMultiArgumentsDialogMsg{\n\t\t\t\t\tSubmit: true,\n\t\t\t\t\tCommandID: m.commandID,\n\t\t\t\t\tContent: m.content,\n\t\t\t\t\tArgs: args,\n\t\t\t\t})\n\t\t\t}\n\t\t\t// Otherwise, move to the next input\n\t\t\tm.inputs[m.focusIndex].Blur()\n\t\t\tm.focusIndex++\n\t\t\tm.inputs[m.focusIndex].Focus()\n\t\t\tm.inputs[m.focusIndex].PromptStyle = m.inputs[m.focusIndex].PromptStyle.Foreground(t.Primary())\n\t\t\tm.inputs[m.focusIndex].TextStyle = m.inputs[m.focusIndex].TextStyle.Foreground(t.Primary())\n\t\tcase key.Matches(msg, key.NewBinding(key.WithKeys(\"tab\"))):\n\t\t\t// Move to the next input\n\t\t\tm.inputs[m.focusIndex].Blur()\n\t\t\tm.focusIndex = (m.focusIndex + 1) % len(m.inputs)\n\t\t\tm.inputs[m.focusIndex].Focus()\n\t\t\tm.inputs[m.focusIndex].PromptStyle = m.inputs[m.focusIndex].PromptStyle.Foreground(t.Primary())\n\t\t\tm.inputs[m.focusIndex].TextStyle = m.inputs[m.focusIndex].TextStyle.Foreground(t.Primary())\n\t\tcase key.Matches(msg, key.NewBinding(key.WithKeys(\"shift+tab\"))):\n\t\t\t// Move to the previous input\n\t\t\tm.inputs[m.focusIndex].Blur()\n\t\t\tm.focusIndex = (m.focusIndex - 1 + len(m.inputs)) % len(m.inputs)\n\t\t\tm.inputs[m.focusIndex].Focus()\n\t\t\tm.inputs[m.focusIndex].PromptStyle = m.inputs[m.focusIndex].PromptStyle.Foreground(t.Primary())\n\t\t\tm.inputs[m.focusIndex].TextStyle = m.inputs[m.focusIndex].TextStyle.Foreground(t.Primary())\n\t\t}\n\tcase tea.WindowSizeMsg:\n\t\tm.width = msg.Width\n\t\tm.height = msg.Height\n\t}\n\n\t// Update the focused input\n\tvar cmd tea.Cmd\n\tm.inputs[m.focusIndex], cmd = m.inputs[m.focusIndex].Update(msg)\n\tcmds = append(cmds, cmd)\n\n\treturn m, tea.Batch(cmds...)\n}\n\n// View implements tea.Model.\nfunc (m MultiArgumentsDialogCmp) View() string {\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\n\t// Calculate width needed for content\n\tmaxWidth := 60 // Width for explanation text\n\n\ttitle := lipgloss.NewStyle().\n\t\tForeground(t.Primary()).\n\t\tBold(true).\n\t\tWidth(maxWidth).\n\t\tPadding(0, 1).\n\t\tBackground(t.Background()).\n\t\tRender(\"Command Arguments\")\n\n\texplanation := lipgloss.NewStyle().\n\t\tForeground(t.Text()).\n\t\tWidth(maxWidth).\n\t\tPadding(0, 1).\n\t\tBackground(t.Background()).\n\t\tRender(\"This command requires multiple arguments. Please enter values for each:\")\n\n\t// Create input fields for each argument\n\tinputFields := make([]string, len(m.inputs))\n\tfor i, input := range m.inputs {\n\t\t// Highlight the label of the focused input\n\t\tlabelStyle := lipgloss.NewStyle().\n\t\t\tWidth(maxWidth).\n\t\t\tPadding(1, 1, 0, 1).\n\t\t\tBackground(t.Background())\n\t\t\t\n\t\tif i == m.focusIndex {\n\t\t\tlabelStyle = labelStyle.Foreground(t.Primary()).Bold(true)\n\t\t} else {\n\t\t\tlabelStyle = labelStyle.Foreground(t.TextMuted())\n\t\t}\n\t\t\n\t\tlabel := labelStyle.Render(m.argNames[i] + \":\")\n\n\t\tfield := lipgloss.NewStyle().\n\t\t\tForeground(t.Text()).\n\t\t\tWidth(maxWidth).\n\t\t\tPadding(0, 1).\n\t\t\tBackground(t.Background()).\n\t\t\tRender(input.View())\n\n\t\tinputFields[i] = lipgloss.JoinVertical(lipgloss.Left, label, field)\n\t}\n\n\tmaxWidth = min(maxWidth, m.width-10)\n\n\t// Join all elements vertically\n\telements := []string{title, explanation}\n\telements = append(elements, inputFields...)\n\n\tcontent := lipgloss.JoinVertical(\n\t\tlipgloss.Left,\n\t\telements...,\n\t)\n\n\treturn baseStyle.Padding(1, 2).\n\t\tBorder(lipgloss.RoundedBorder()).\n\t\tBorderBackground(t.Background()).\n\t\tBorderForeground(t.TextMuted()).\n\t\tBackground(t.Background()).\n\t\tWidth(lipgloss.Width(content) + 4).\n\t\tRender(content)\n}\n\n// SetSize sets the size of the component.\nfunc (m *MultiArgumentsDialogCmp) SetSize(width, height int) {\n\tm.width = width\n\tm.height = height\n}\n\n// Bindings implements layout.Bindings.\nfunc (m MultiArgumentsDialogCmp) Bindings() []key.Binding {\n\treturn m.keys.ShortHelp()\n}"], ["/opencode/internal/tui/components/dialog/commands.go", "package dialog\n\nimport (\n\t\"github.com/charmbracelet/bubbles/key\"\n\ttea \"github.com/charmbracelet/bubbletea\"\n\t\"github.com/charmbracelet/lipgloss\"\n\tutilComponents \"github.com/opencode-ai/opencode/internal/tui/components/util\"\n\t\"github.com/opencode-ai/opencode/internal/tui/layout\"\n\t\"github.com/opencode-ai/opencode/internal/tui/styles\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n\t\"github.com/opencode-ai/opencode/internal/tui/util\"\n)\n\n// Command represents a command that can be executed\ntype Command struct {\n\tID string\n\tTitle string\n\tDescription string\n\tHandler func(cmd Command) tea.Cmd\n}\n\nfunc (ci Command) Render(selected bool, width int) string {\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\n\tdescStyle := baseStyle.Width(width).Foreground(t.TextMuted())\n\titemStyle := baseStyle.Width(width).\n\t\tForeground(t.Text()).\n\t\tBackground(t.Background())\n\n\tif selected {\n\t\titemStyle = itemStyle.\n\t\t\tBackground(t.Primary()).\n\t\t\tForeground(t.Background()).\n\t\t\tBold(true)\n\t\tdescStyle = descStyle.\n\t\t\tBackground(t.Primary()).\n\t\t\tForeground(t.Background())\n\t}\n\n\ttitle := itemStyle.Padding(0, 1).Render(ci.Title)\n\tif ci.Description != \"\" {\n\t\tdescription := descStyle.Padding(0, 1).Render(ci.Description)\n\t\treturn lipgloss.JoinVertical(lipgloss.Left, title, description)\n\t}\n\treturn title\n}\n\n// CommandSelectedMsg is sent when a command is selected\ntype CommandSelectedMsg struct {\n\tCommand Command\n}\n\n// CloseCommandDialogMsg is sent when the command dialog is closed\ntype CloseCommandDialogMsg struct{}\n\n// CommandDialog interface for the command selection dialog\ntype CommandDialog interface {\n\ttea.Model\n\tlayout.Bindings\n\tSetCommands(commands []Command)\n}\n\ntype commandDialogCmp struct {\n\tlistView utilComponents.SimpleList[Command]\n\twidth int\n\theight int\n}\n\ntype commandKeyMap struct {\n\tEnter key.Binding\n\tEscape key.Binding\n}\n\nvar commandKeys = commandKeyMap{\n\tEnter: key.NewBinding(\n\t\tkey.WithKeys(\"enter\"),\n\t\tkey.WithHelp(\"enter\", \"select command\"),\n\t),\n\tEscape: key.NewBinding(\n\t\tkey.WithKeys(\"esc\"),\n\t\tkey.WithHelp(\"esc\", \"close\"),\n\t),\n}\n\nfunc (c *commandDialogCmp) Init() tea.Cmd {\n\treturn c.listView.Init()\n}\n\nfunc (c *commandDialogCmp) Update(msg tea.Msg) (tea.Model, tea.Cmd) {\n\tvar cmds []tea.Cmd\n\tswitch msg := msg.(type) {\n\tcase tea.KeyMsg:\n\t\tswitch {\n\t\tcase key.Matches(msg, commandKeys.Enter):\n\t\t\tselectedItem, idx := c.listView.GetSelectedItem()\n\t\t\tif idx != -1 {\n\t\t\t\treturn c, util.CmdHandler(CommandSelectedMsg{\n\t\t\t\t\tCommand: selectedItem,\n\t\t\t\t})\n\t\t\t}\n\t\tcase key.Matches(msg, commandKeys.Escape):\n\t\t\treturn c, util.CmdHandler(CloseCommandDialogMsg{})\n\t\t}\n\tcase tea.WindowSizeMsg:\n\t\tc.width = msg.Width\n\t\tc.height = msg.Height\n\t}\n\n\tu, cmd := c.listView.Update(msg)\n\tc.listView = u.(utilComponents.SimpleList[Command])\n\tcmds = append(cmds, cmd)\n\n\treturn c, tea.Batch(cmds...)\n}\n\nfunc (c *commandDialogCmp) View() string {\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\n\tmaxWidth := 40\n\n\tcommands := c.listView.GetItems()\n\n\tfor _, cmd := range commands {\n\t\tif len(cmd.Title) > maxWidth-4 {\n\t\t\tmaxWidth = len(cmd.Title) + 4\n\t\t}\n\t\tif cmd.Description != \"\" {\n\t\t\tif len(cmd.Description) > maxWidth-4 {\n\t\t\t\tmaxWidth = len(cmd.Description) + 4\n\t\t\t}\n\t\t}\n\t}\n\n\tc.listView.SetMaxWidth(maxWidth)\n\n\ttitle := baseStyle.\n\t\tForeground(t.Primary()).\n\t\tBold(true).\n\t\tWidth(maxWidth).\n\t\tPadding(0, 1).\n\t\tRender(\"Commands\")\n\n\tcontent := lipgloss.JoinVertical(\n\t\tlipgloss.Left,\n\t\ttitle,\n\t\tbaseStyle.Width(maxWidth).Render(\"\"),\n\t\tbaseStyle.Width(maxWidth).Render(c.listView.View()),\n\t\tbaseStyle.Width(maxWidth).Render(\"\"),\n\t)\n\n\treturn baseStyle.Padding(1, 2).\n\t\tBorder(lipgloss.RoundedBorder()).\n\t\tBorderBackground(t.Background()).\n\t\tBorderForeground(t.TextMuted()).\n\t\tWidth(lipgloss.Width(content) + 4).\n\t\tRender(content)\n}\n\nfunc (c *commandDialogCmp) BindingKeys() []key.Binding {\n\treturn layout.KeyMapToSlice(commandKeys)\n}\n\nfunc (c *commandDialogCmp) SetCommands(commands []Command) {\n\tc.listView.SetItems(commands)\n}\n\n// NewCommandDialogCmp creates a new command selection dialog\nfunc NewCommandDialogCmp() CommandDialog {\n\tlistView := utilComponents.NewSimpleList[Command](\n\t\t[]Command{},\n\t\t10,\n\t\t\"No commands available\",\n\t\ttrue,\n\t)\n\treturn &commandDialogCmp{\n\t\tlistView: listView,\n\t}\n}\n"], ["/opencode/internal/tui/components/chat/sidebar.go", "package chat\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"sort\"\n\t\"strings\"\n\n\ttea \"github.com/charmbracelet/bubbletea\"\n\t\"github.com/charmbracelet/lipgloss\"\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/diff\"\n\t\"github.com/opencode-ai/opencode/internal/history\"\n\t\"github.com/opencode-ai/opencode/internal/pubsub\"\n\t\"github.com/opencode-ai/opencode/internal/session\"\n\t\"github.com/opencode-ai/opencode/internal/tui/styles\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n)\n\ntype sidebarCmp struct {\n\twidth, height int\n\tsession session.Session\n\thistory history.Service\n\tmodFiles map[string]struct {\n\t\tadditions int\n\t\tremovals int\n\t}\n}\n\nfunc (m *sidebarCmp) Init() tea.Cmd {\n\tif m.history != nil {\n\t\tctx := context.Background()\n\t\t// Subscribe to file events\n\t\tfilesCh := m.history.Subscribe(ctx)\n\n\t\t// Initialize the modified files map\n\t\tm.modFiles = make(map[string]struct {\n\t\t\tadditions int\n\t\t\tremovals int\n\t\t})\n\n\t\t// Load initial files and calculate diffs\n\t\tm.loadModifiedFiles(ctx)\n\n\t\t// Return a command that will send file events to the Update method\n\t\treturn func() tea.Msg {\n\t\t\treturn <-filesCh\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (m *sidebarCmp) Update(msg tea.Msg) (tea.Model, tea.Cmd) {\n\tswitch msg := msg.(type) {\n\tcase SessionSelectedMsg:\n\t\tif msg.ID != m.session.ID {\n\t\t\tm.session = msg\n\t\t\tctx := context.Background()\n\t\t\tm.loadModifiedFiles(ctx)\n\t\t}\n\tcase pubsub.Event[session.Session]:\n\t\tif msg.Type == pubsub.UpdatedEvent {\n\t\t\tif m.session.ID == msg.Payload.ID {\n\t\t\t\tm.session = msg.Payload\n\t\t\t}\n\t\t}\n\tcase pubsub.Event[history.File]:\n\t\tif msg.Payload.SessionID == m.session.ID {\n\t\t\t// Process the individual file change instead of reloading all files\n\t\t\tctx := context.Background()\n\t\t\tm.processFileChanges(ctx, msg.Payload)\n\n\t\t\t// Return a command to continue receiving events\n\t\t\treturn m, func() tea.Msg {\n\t\t\t\tctx := context.Background()\n\t\t\t\tfilesCh := m.history.Subscribe(ctx)\n\t\t\t\treturn <-filesCh\n\t\t\t}\n\t\t}\n\t}\n\treturn m, nil\n}\n\nfunc (m *sidebarCmp) View() string {\n\tbaseStyle := styles.BaseStyle()\n\n\treturn baseStyle.\n\t\tWidth(m.width).\n\t\tPaddingLeft(4).\n\t\tPaddingRight(2).\n\t\tHeight(m.height - 1).\n\t\tRender(\n\t\t\tlipgloss.JoinVertical(\n\t\t\t\tlipgloss.Top,\n\t\t\t\theader(m.width),\n\t\t\t\t\" \",\n\t\t\t\tm.sessionSection(),\n\t\t\t\t\" \",\n\t\t\t\tlspsConfigured(m.width),\n\t\t\t\t\" \",\n\t\t\t\tm.modifiedFiles(),\n\t\t\t),\n\t\t)\n}\n\nfunc (m *sidebarCmp) sessionSection() string {\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\n\tsessionKey := baseStyle.\n\t\tForeground(t.Primary()).\n\t\tBold(true).\n\t\tRender(\"Session\")\n\n\tsessionValue := baseStyle.\n\t\tForeground(t.Text()).\n\t\tWidth(m.width - lipgloss.Width(sessionKey)).\n\t\tRender(fmt.Sprintf(\": %s\", m.session.Title))\n\n\treturn lipgloss.JoinHorizontal(\n\t\tlipgloss.Left,\n\t\tsessionKey,\n\t\tsessionValue,\n\t)\n}\n\nfunc (m *sidebarCmp) modifiedFile(filePath string, additions, removals int) string {\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\n\tstats := \"\"\n\tif additions > 0 && removals > 0 {\n\t\tadditionsStr := baseStyle.\n\t\t\tForeground(t.Success()).\n\t\t\tPaddingLeft(1).\n\t\t\tRender(fmt.Sprintf(\"+%d\", additions))\n\n\t\tremovalsStr := baseStyle.\n\t\t\tForeground(t.Error()).\n\t\t\tPaddingLeft(1).\n\t\t\tRender(fmt.Sprintf(\"-%d\", removals))\n\n\t\tcontent := lipgloss.JoinHorizontal(lipgloss.Left, additionsStr, removalsStr)\n\t\tstats = baseStyle.Width(lipgloss.Width(content)).Render(content)\n\t} else if additions > 0 {\n\t\tadditionsStr := fmt.Sprintf(\" %s\", baseStyle.\n\t\t\tPaddingLeft(1).\n\t\t\tForeground(t.Success()).\n\t\t\tRender(fmt.Sprintf(\"+%d\", additions)))\n\t\tstats = baseStyle.Width(lipgloss.Width(additionsStr)).Render(additionsStr)\n\t} else if removals > 0 {\n\t\tremovalsStr := fmt.Sprintf(\" %s\", baseStyle.\n\t\t\tPaddingLeft(1).\n\t\t\tForeground(t.Error()).\n\t\t\tRender(fmt.Sprintf(\"-%d\", removals)))\n\t\tstats = baseStyle.Width(lipgloss.Width(removalsStr)).Render(removalsStr)\n\t}\n\n\tfilePathStr := baseStyle.Render(filePath)\n\n\treturn baseStyle.\n\t\tWidth(m.width).\n\t\tRender(\n\t\t\tlipgloss.JoinHorizontal(\n\t\t\t\tlipgloss.Left,\n\t\t\t\tfilePathStr,\n\t\t\t\tstats,\n\t\t\t),\n\t\t)\n}\n\nfunc (m *sidebarCmp) modifiedFiles() string {\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\n\tmodifiedFiles := baseStyle.\n\t\tWidth(m.width).\n\t\tForeground(t.Primary()).\n\t\tBold(true).\n\t\tRender(\"Modified Files:\")\n\n\t// If no modified files, show a placeholder message\n\tif m.modFiles == nil || len(m.modFiles) == 0 {\n\t\tmessage := \"No modified files\"\n\t\tremainingWidth := m.width - lipgloss.Width(message)\n\t\tif remainingWidth > 0 {\n\t\t\tmessage += strings.Repeat(\" \", remainingWidth)\n\t\t}\n\t\treturn baseStyle.\n\t\t\tWidth(m.width).\n\t\t\tRender(\n\t\t\t\tlipgloss.JoinVertical(\n\t\t\t\t\tlipgloss.Top,\n\t\t\t\t\tmodifiedFiles,\n\t\t\t\t\tbaseStyle.Foreground(t.TextMuted()).Render(message),\n\t\t\t\t),\n\t\t\t)\n\t}\n\n\t// Sort file paths alphabetically for consistent ordering\n\tvar paths []string\n\tfor path := range m.modFiles {\n\t\tpaths = append(paths, path)\n\t}\n\tsort.Strings(paths)\n\n\t// Create views for each file in sorted order\n\tvar fileViews []string\n\tfor _, path := range paths {\n\t\tstats := m.modFiles[path]\n\t\tfileViews = append(fileViews, m.modifiedFile(path, stats.additions, stats.removals))\n\t}\n\n\treturn baseStyle.\n\t\tWidth(m.width).\n\t\tRender(\n\t\t\tlipgloss.JoinVertical(\n\t\t\t\tlipgloss.Top,\n\t\t\t\tmodifiedFiles,\n\t\t\t\tlipgloss.JoinVertical(\n\t\t\t\t\tlipgloss.Left,\n\t\t\t\t\tfileViews...,\n\t\t\t\t),\n\t\t\t),\n\t\t)\n}\n\nfunc (m *sidebarCmp) SetSize(width, height int) tea.Cmd {\n\tm.width = width\n\tm.height = height\n\treturn nil\n}\n\nfunc (m *sidebarCmp) GetSize() (int, int) {\n\treturn m.width, m.height\n}\n\nfunc NewSidebarCmp(session session.Session, history history.Service) tea.Model {\n\treturn &sidebarCmp{\n\t\tsession: session,\n\t\thistory: history,\n\t}\n}\n\nfunc (m *sidebarCmp) loadModifiedFiles(ctx context.Context) {\n\tif m.history == nil || m.session.ID == \"\" {\n\t\treturn\n\t}\n\n\t// Get all latest files for this session\n\tlatestFiles, err := m.history.ListLatestSessionFiles(ctx, m.session.ID)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t// Get all files for this session (to find initial versions)\n\tallFiles, err := m.history.ListBySession(ctx, m.session.ID)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t// Clear the existing map to rebuild it\n\tm.modFiles = make(map[string]struct {\n\t\tadditions int\n\t\tremovals int\n\t})\n\n\t// Process each latest file\n\tfor _, file := range latestFiles {\n\t\t// Skip if this is the initial version (no changes to show)\n\t\tif file.Version == history.InitialVersion {\n\t\t\tcontinue\n\t\t}\n\n\t\t// Find the initial version for this specific file\n\t\tvar initialVersion history.File\n\t\tfor _, v := range allFiles {\n\t\t\tif v.Path == file.Path && v.Version == history.InitialVersion {\n\t\t\t\tinitialVersion = v\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\t// Skip if we can't find the initial version\n\t\tif initialVersion.ID == \"\" {\n\t\t\tcontinue\n\t\t}\n\t\tif initialVersion.Content == file.Content {\n\t\t\tcontinue\n\t\t}\n\n\t\t// Calculate diff between initial and latest version\n\t\t_, additions, removals := diff.GenerateDiff(initialVersion.Content, file.Content, file.Path)\n\n\t\t// Only add to modified files if there are changes\n\t\tif additions > 0 || removals > 0 {\n\t\t\t// Remove working directory prefix from file path\n\t\t\tdisplayPath := file.Path\n\t\t\tworkingDir := config.WorkingDirectory()\n\t\t\tdisplayPath = strings.TrimPrefix(displayPath, workingDir)\n\t\t\tdisplayPath = strings.TrimPrefix(displayPath, \"/\")\n\n\t\t\tm.modFiles[displayPath] = struct {\n\t\t\t\tadditions int\n\t\t\t\tremovals int\n\t\t\t}{\n\t\t\t\tadditions: additions,\n\t\t\t\tremovals: removals,\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc (m *sidebarCmp) processFileChanges(ctx context.Context, file history.File) {\n\t// Skip if this is the initial version (no changes to show)\n\tif file.Version == history.InitialVersion {\n\t\treturn\n\t}\n\n\t// Find the initial version for this file\n\tinitialVersion, err := m.findInitialVersion(ctx, file.Path)\n\tif err != nil || initialVersion.ID == \"\" {\n\t\treturn\n\t}\n\n\t// Skip if content hasn't changed\n\tif initialVersion.Content == file.Content {\n\t\t// If this file was previously modified but now matches the initial version,\n\t\t// remove it from the modified files list\n\t\tdisplayPath := getDisplayPath(file.Path)\n\t\tdelete(m.modFiles, displayPath)\n\t\treturn\n\t}\n\n\t// Calculate diff between initial and latest version\n\t_, additions, removals := diff.GenerateDiff(initialVersion.Content, file.Content, file.Path)\n\n\t// Only add to modified files if there are changes\n\tif additions > 0 || removals > 0 {\n\t\tdisplayPath := getDisplayPath(file.Path)\n\t\tm.modFiles[displayPath] = struct {\n\t\t\tadditions int\n\t\t\tremovals int\n\t\t}{\n\t\t\tadditions: additions,\n\t\t\tremovals: removals,\n\t\t}\n\t} else {\n\t\t// If no changes, remove from modified files\n\t\tdisplayPath := getDisplayPath(file.Path)\n\t\tdelete(m.modFiles, displayPath)\n\t}\n}\n\n// Helper function to find the initial version of a file\nfunc (m *sidebarCmp) findInitialVersion(ctx context.Context, path string) (history.File, error) {\n\t// Get all versions of this file for the session\n\tfileVersions, err := m.history.ListBySession(ctx, m.session.ID)\n\tif err != nil {\n\t\treturn history.File{}, err\n\t}\n\n\t// Find the initial version\n\tfor _, v := range fileVersions {\n\t\tif v.Path == path && v.Version == history.InitialVersion {\n\t\t\treturn v, nil\n\t\t}\n\t}\n\n\treturn history.File{}, fmt.Errorf(\"initial version not found\")\n}\n\n// Helper function to get the display path for a file\nfunc getDisplayPath(path string) string {\n\tworkingDir := config.WorkingDirectory()\n\tdisplayPath := strings.TrimPrefix(path, workingDir)\n\treturn strings.TrimPrefix(displayPath, \"/\")\n}\n"], ["/opencode/internal/db/db.go", "// Code generated by sqlc. DO NOT EDIT.\n// versions:\n// sqlc v1.29.0\n\npackage db\n\nimport (\n\t\"context\"\n\t\"database/sql\"\n\t\"fmt\"\n)\n\ntype DBTX interface {\n\tExecContext(context.Context, string, ...interface{}) (sql.Result, error)\n\tPrepareContext(context.Context, string) (*sql.Stmt, error)\n\tQueryContext(context.Context, string, ...interface{}) (*sql.Rows, error)\n\tQueryRowContext(context.Context, string, ...interface{}) *sql.Row\n}\n\nfunc New(db DBTX) *Queries {\n\treturn &Queries{db: db}\n}\n\nfunc Prepare(ctx context.Context, db DBTX) (*Queries, error) {\n\tq := Queries{db: db}\n\tvar err error\n\tif q.createFileStmt, err = db.PrepareContext(ctx, createFile); err != nil {\n\t\treturn nil, fmt.Errorf(\"error preparing query CreateFile: %w\", err)\n\t}\n\tif q.createMessageStmt, err = db.PrepareContext(ctx, createMessage); err != nil {\n\t\treturn nil, fmt.Errorf(\"error preparing query CreateMessage: %w\", err)\n\t}\n\tif q.createSessionStmt, err = db.PrepareContext(ctx, createSession); err != nil {\n\t\treturn nil, fmt.Errorf(\"error preparing query CreateSession: %w\", err)\n\t}\n\tif q.deleteFileStmt, err = db.PrepareContext(ctx, deleteFile); err != nil {\n\t\treturn nil, fmt.Errorf(\"error preparing query DeleteFile: %w\", err)\n\t}\n\tif q.deleteMessageStmt, err = db.PrepareContext(ctx, deleteMessage); err != nil {\n\t\treturn nil, fmt.Errorf(\"error preparing query DeleteMessage: %w\", err)\n\t}\n\tif q.deleteSessionStmt, err = db.PrepareContext(ctx, deleteSession); err != nil {\n\t\treturn nil, fmt.Errorf(\"error preparing query DeleteSession: %w\", err)\n\t}\n\tif q.deleteSessionFilesStmt, err = db.PrepareContext(ctx, deleteSessionFiles); err != nil {\n\t\treturn nil, fmt.Errorf(\"error preparing query DeleteSessionFiles: %w\", err)\n\t}\n\tif q.deleteSessionMessagesStmt, err = db.PrepareContext(ctx, deleteSessionMessages); err != nil {\n\t\treturn nil, fmt.Errorf(\"error preparing query DeleteSessionMessages: %w\", err)\n\t}\n\tif q.getFileStmt, err = db.PrepareContext(ctx, getFile); err != nil {\n\t\treturn nil, fmt.Errorf(\"error preparing query GetFile: %w\", err)\n\t}\n\tif q.getFileByPathAndSessionStmt, err = db.PrepareContext(ctx, getFileByPathAndSession); err != nil {\n\t\treturn nil, fmt.Errorf(\"error preparing query GetFileByPathAndSession: %w\", err)\n\t}\n\tif q.getMessageStmt, err = db.PrepareContext(ctx, getMessage); err != nil {\n\t\treturn nil, fmt.Errorf(\"error preparing query GetMessage: %w\", err)\n\t}\n\tif q.getSessionByIDStmt, err = db.PrepareContext(ctx, getSessionByID); err != nil {\n\t\treturn nil, fmt.Errorf(\"error preparing query GetSessionByID: %w\", err)\n\t}\n\tif q.listFilesByPathStmt, err = db.PrepareContext(ctx, listFilesByPath); err != nil {\n\t\treturn nil, fmt.Errorf(\"error preparing query ListFilesByPath: %w\", err)\n\t}\n\tif q.listFilesBySessionStmt, err = db.PrepareContext(ctx, listFilesBySession); err != nil {\n\t\treturn nil, fmt.Errorf(\"error preparing query ListFilesBySession: %w\", err)\n\t}\n\tif q.listLatestSessionFilesStmt, err = db.PrepareContext(ctx, listLatestSessionFiles); err != nil {\n\t\treturn nil, fmt.Errorf(\"error preparing query ListLatestSessionFiles: %w\", err)\n\t}\n\tif q.listMessagesBySessionStmt, err = db.PrepareContext(ctx, listMessagesBySession); err != nil {\n\t\treturn nil, fmt.Errorf(\"error preparing query ListMessagesBySession: %w\", err)\n\t}\n\tif q.listNewFilesStmt, err = db.PrepareContext(ctx, listNewFiles); err != nil {\n\t\treturn nil, fmt.Errorf(\"error preparing query ListNewFiles: %w\", err)\n\t}\n\tif q.listSessionsStmt, err = db.PrepareContext(ctx, listSessions); err != nil {\n\t\treturn nil, fmt.Errorf(\"error preparing query ListSessions: %w\", err)\n\t}\n\tif q.updateFileStmt, err = db.PrepareContext(ctx, updateFile); err != nil {\n\t\treturn nil, fmt.Errorf(\"error preparing query UpdateFile: %w\", err)\n\t}\n\tif q.updateMessageStmt, err = db.PrepareContext(ctx, updateMessage); err != nil {\n\t\treturn nil, fmt.Errorf(\"error preparing query UpdateMessage: %w\", err)\n\t}\n\tif q.updateSessionStmt, err = db.PrepareContext(ctx, updateSession); err != nil {\n\t\treturn nil, fmt.Errorf(\"error preparing query UpdateSession: %w\", err)\n\t}\n\treturn &q, nil\n}\n\nfunc (q *Queries) Close() error {\n\tvar err error\n\tif q.createFileStmt != nil {\n\t\tif cerr := q.createFileStmt.Close(); cerr != nil {\n\t\t\terr = fmt.Errorf(\"error closing createFileStmt: %w\", cerr)\n\t\t}\n\t}\n\tif q.createMessageStmt != nil {\n\t\tif cerr := q.createMessageStmt.Close(); cerr != nil {\n\t\t\terr = fmt.Errorf(\"error closing createMessageStmt: %w\", cerr)\n\t\t}\n\t}\n\tif q.createSessionStmt != nil {\n\t\tif cerr := q.createSessionStmt.Close(); cerr != nil {\n\t\t\terr = fmt.Errorf(\"error closing createSessionStmt: %w\", cerr)\n\t\t}\n\t}\n\tif q.deleteFileStmt != nil {\n\t\tif cerr := q.deleteFileStmt.Close(); cerr != nil {\n\t\t\terr = fmt.Errorf(\"error closing deleteFileStmt: %w\", cerr)\n\t\t}\n\t}\n\tif q.deleteMessageStmt != nil {\n\t\tif cerr := q.deleteMessageStmt.Close(); cerr != nil {\n\t\t\terr = fmt.Errorf(\"error closing deleteMessageStmt: %w\", cerr)\n\t\t}\n\t}\n\tif q.deleteSessionStmt != nil {\n\t\tif cerr := q.deleteSessionStmt.Close(); cerr != nil {\n\t\t\terr = fmt.Errorf(\"error closing deleteSessionStmt: %w\", cerr)\n\t\t}\n\t}\n\tif q.deleteSessionFilesStmt != nil {\n\t\tif cerr := q.deleteSessionFilesStmt.Close(); cerr != nil {\n\t\t\terr = fmt.Errorf(\"error closing deleteSessionFilesStmt: %w\", cerr)\n\t\t}\n\t}\n\tif q.deleteSessionMessagesStmt != nil {\n\t\tif cerr := q.deleteSessionMessagesStmt.Close(); cerr != nil {\n\t\t\terr = fmt.Errorf(\"error closing deleteSessionMessagesStmt: %w\", cerr)\n\t\t}\n\t}\n\tif q.getFileStmt != nil {\n\t\tif cerr := q.getFileStmt.Close(); cerr != nil {\n\t\t\terr = fmt.Errorf(\"error closing getFileStmt: %w\", cerr)\n\t\t}\n\t}\n\tif q.getFileByPathAndSessionStmt != nil {\n\t\tif cerr := q.getFileByPathAndSessionStmt.Close(); cerr != nil {\n\t\t\terr = fmt.Errorf(\"error closing getFileByPathAndSessionStmt: %w\", cerr)\n\t\t}\n\t}\n\tif q.getMessageStmt != nil {\n\t\tif cerr := q.getMessageStmt.Close(); cerr != nil {\n\t\t\terr = fmt.Errorf(\"error closing getMessageStmt: %w\", cerr)\n\t\t}\n\t}\n\tif q.getSessionByIDStmt != nil {\n\t\tif cerr := q.getSessionByIDStmt.Close(); cerr != nil {\n\t\t\terr = fmt.Errorf(\"error closing getSessionByIDStmt: %w\", cerr)\n\t\t}\n\t}\n\tif q.listFilesByPathStmt != nil {\n\t\tif cerr := q.listFilesByPathStmt.Close(); cerr != nil {\n\t\t\terr = fmt.Errorf(\"error closing listFilesByPathStmt: %w\", cerr)\n\t\t}\n\t}\n\tif q.listFilesBySessionStmt != nil {\n\t\tif cerr := q.listFilesBySessionStmt.Close(); cerr != nil {\n\t\t\terr = fmt.Errorf(\"error closing listFilesBySessionStmt: %w\", cerr)\n\t\t}\n\t}\n\tif q.listLatestSessionFilesStmt != nil {\n\t\tif cerr := q.listLatestSessionFilesStmt.Close(); cerr != nil {\n\t\t\terr = fmt.Errorf(\"error closing listLatestSessionFilesStmt: %w\", cerr)\n\t\t}\n\t}\n\tif q.listMessagesBySessionStmt != nil {\n\t\tif cerr := q.listMessagesBySessionStmt.Close(); cerr != nil {\n\t\t\terr = fmt.Errorf(\"error closing listMessagesBySessionStmt: %w\", cerr)\n\t\t}\n\t}\n\tif q.listNewFilesStmt != nil {\n\t\tif cerr := q.listNewFilesStmt.Close(); cerr != nil {\n\t\t\terr = fmt.Errorf(\"error closing listNewFilesStmt: %w\", cerr)\n\t\t}\n\t}\n\tif q.listSessionsStmt != nil {\n\t\tif cerr := q.listSessionsStmt.Close(); cerr != nil {\n\t\t\terr = fmt.Errorf(\"error closing listSessionsStmt: %w\", cerr)\n\t\t}\n\t}\n\tif q.updateFileStmt != nil {\n\t\tif cerr := q.updateFileStmt.Close(); cerr != nil {\n\t\t\terr = fmt.Errorf(\"error closing updateFileStmt: %w\", cerr)\n\t\t}\n\t}\n\tif q.updateMessageStmt != nil {\n\t\tif cerr := q.updateMessageStmt.Close(); cerr != nil {\n\t\t\terr = fmt.Errorf(\"error closing updateMessageStmt: %w\", cerr)\n\t\t}\n\t}\n\tif q.updateSessionStmt != nil {\n\t\tif cerr := q.updateSessionStmt.Close(); cerr != nil {\n\t\t\terr = fmt.Errorf(\"error closing updateSessionStmt: %w\", cerr)\n\t\t}\n\t}\n\treturn err\n}\n\nfunc (q *Queries) exec(ctx context.Context, stmt *sql.Stmt, query string, args ...interface{}) (sql.Result, error) {\n\tswitch {\n\tcase stmt != nil && q.tx != nil:\n\t\treturn q.tx.StmtContext(ctx, stmt).ExecContext(ctx, args...)\n\tcase stmt != nil:\n\t\treturn stmt.ExecContext(ctx, args...)\n\tdefault:\n\t\treturn q.db.ExecContext(ctx, query, args...)\n\t}\n}\n\nfunc (q *Queries) query(ctx context.Context, stmt *sql.Stmt, query string, args ...interface{}) (*sql.Rows, error) {\n\tswitch {\n\tcase stmt != nil && q.tx != nil:\n\t\treturn q.tx.StmtContext(ctx, stmt).QueryContext(ctx, args...)\n\tcase stmt != nil:\n\t\treturn stmt.QueryContext(ctx, args...)\n\tdefault:\n\t\treturn q.db.QueryContext(ctx, query, args...)\n\t}\n}\n\nfunc (q *Queries) queryRow(ctx context.Context, stmt *sql.Stmt, query string, args ...interface{}) *sql.Row {\n\tswitch {\n\tcase stmt != nil && q.tx != nil:\n\t\treturn q.tx.StmtContext(ctx, stmt).QueryRowContext(ctx, args...)\n\tcase stmt != nil:\n\t\treturn stmt.QueryRowContext(ctx, args...)\n\tdefault:\n\t\treturn q.db.QueryRowContext(ctx, query, args...)\n\t}\n}\n\ntype Queries struct {\n\tdb DBTX\n\ttx *sql.Tx\n\tcreateFileStmt *sql.Stmt\n\tcreateMessageStmt *sql.Stmt\n\tcreateSessionStmt *sql.Stmt\n\tdeleteFileStmt *sql.Stmt\n\tdeleteMessageStmt *sql.Stmt\n\tdeleteSessionStmt *sql.Stmt\n\tdeleteSessionFilesStmt *sql.Stmt\n\tdeleteSessionMessagesStmt *sql.Stmt\n\tgetFileStmt *sql.Stmt\n\tgetFileByPathAndSessionStmt *sql.Stmt\n\tgetMessageStmt *sql.Stmt\n\tgetSessionByIDStmt *sql.Stmt\n\tlistFilesByPathStmt *sql.Stmt\n\tlistFilesBySessionStmt *sql.Stmt\n\tlistLatestSessionFilesStmt *sql.Stmt\n\tlistMessagesBySessionStmt *sql.Stmt\n\tlistNewFilesStmt *sql.Stmt\n\tlistSessionsStmt *sql.Stmt\n\tupdateFileStmt *sql.Stmt\n\tupdateMessageStmt *sql.Stmt\n\tupdateSessionStmt *sql.Stmt\n}\n\nfunc (q *Queries) WithTx(tx *sql.Tx) *Queries {\n\treturn &Queries{\n\t\tdb: tx,\n\t\ttx: tx,\n\t\tcreateFileStmt: q.createFileStmt,\n\t\tcreateMessageStmt: q.createMessageStmt,\n\t\tcreateSessionStmt: q.createSessionStmt,\n\t\tdeleteFileStmt: q.deleteFileStmt,\n\t\tdeleteMessageStmt: q.deleteMessageStmt,\n\t\tdeleteSessionStmt: q.deleteSessionStmt,\n\t\tdeleteSessionFilesStmt: q.deleteSessionFilesStmt,\n\t\tdeleteSessionMessagesStmt: q.deleteSessionMessagesStmt,\n\t\tgetFileStmt: q.getFileStmt,\n\t\tgetFileByPathAndSessionStmt: q.getFileByPathAndSessionStmt,\n\t\tgetMessageStmt: q.getMessageStmt,\n\t\tgetSessionByIDStmt: q.getSessionByIDStmt,\n\t\tlistFilesByPathStmt: q.listFilesByPathStmt,\n\t\tlistFilesBySessionStmt: q.listFilesBySessionStmt,\n\t\tlistLatestSessionFilesStmt: q.listLatestSessionFilesStmt,\n\t\tlistMessagesBySessionStmt: q.listMessagesBySessionStmt,\n\t\tlistNewFilesStmt: q.listNewFilesStmt,\n\t\tlistSessionsStmt: q.listSessionsStmt,\n\t\tupdateFileStmt: q.updateFileStmt,\n\t\tupdateMessageStmt: q.updateMessageStmt,\n\t\tupdateSessionStmt: q.updateSessionStmt,\n\t}\n}\n"], ["/opencode/internal/format/spinner.go", "package format\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"os\"\n\n\t\"github.com/charmbracelet/bubbles/spinner\"\n\ttea \"github.com/charmbracelet/bubbletea\"\n)\n\n// Spinner wraps the bubbles spinner for non-interactive mode\ntype Spinner struct {\n\tmodel spinner.Model\n\tdone chan struct{}\n\tprog *tea.Program\n\tctx context.Context\n\tcancel context.CancelFunc\n}\n\n// spinnerModel is the tea.Model for the spinner\ntype spinnerModel struct {\n\tspinner spinner.Model\n\tmessage string\n\tquitting bool\n}\n\nfunc (m spinnerModel) Init() tea.Cmd {\n\treturn m.spinner.Tick\n}\n\nfunc (m spinnerModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {\n\tswitch msg := msg.(type) {\n\tcase tea.KeyMsg:\n\t\tm.quitting = true\n\t\treturn m, tea.Quit\n\tcase spinner.TickMsg:\n\t\tvar cmd tea.Cmd\n\t\tm.spinner, cmd = m.spinner.Update(msg)\n\t\treturn m, cmd\n\tcase quitMsg:\n\t\tm.quitting = true\n\t\treturn m, tea.Quit\n\tdefault:\n\t\treturn m, nil\n\t}\n}\n\nfunc (m spinnerModel) View() string {\n\tif m.quitting {\n\t\treturn \"\"\n\t}\n\treturn fmt.Sprintf(\"%s %s\", m.spinner.View(), m.message)\n}\n\n// quitMsg is sent when we want to quit the spinner\ntype quitMsg struct{}\n\n// NewSpinner creates a new spinner with the given message\nfunc NewSpinner(message string) *Spinner {\n\ts := spinner.New()\n\ts.Spinner = spinner.Dot\n\ts.Style = s.Style.Foreground(s.Style.GetForeground())\n\n\tctx, cancel := context.WithCancel(context.Background())\n\n\tmodel := spinnerModel{\n\t\tspinner: s,\n\t\tmessage: message,\n\t}\n\n\tprog := tea.NewProgram(model, tea.WithOutput(os.Stderr), tea.WithoutCatchPanics())\n\n\treturn &Spinner{\n\t\tmodel: s,\n\t\tdone: make(chan struct{}),\n\t\tprog: prog,\n\t\tctx: ctx,\n\t\tcancel: cancel,\n\t}\n}\n\n// Start begins the spinner animation\nfunc (s *Spinner) Start() {\n\tgo func() {\n\t\tdefer close(s.done)\n\t\tgo func() {\n\t\t\t<-s.ctx.Done()\n\t\t\ts.prog.Send(quitMsg{})\n\t\t}()\n\t\t_, err := s.prog.Run()\n\t\tif err != nil {\n\t\t\tfmt.Fprintf(os.Stderr, \"Error running spinner: %v\\n\", err)\n\t\t}\n\t}()\n}\n\n// Stop ends the spinner animation\nfunc (s *Spinner) Stop() {\n\ts.cancel()\n\t<-s.done\n}\n"], ["/opencode/internal/tui/components/logs/table.go", "package logs\n\nimport (\n\t\"encoding/json\"\n\t\"slices\"\n\n\t\"github.com/charmbracelet/bubbles/key\"\n\t\"github.com/charmbracelet/bubbles/table\"\n\ttea \"github.com/charmbracelet/bubbletea\"\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n\t\"github.com/opencode-ai/opencode/internal/pubsub\"\n\t\"github.com/opencode-ai/opencode/internal/tui/layout\"\n\t\"github.com/opencode-ai/opencode/internal/tui/styles\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n\t\"github.com/opencode-ai/opencode/internal/tui/util\"\n)\n\ntype TableComponent interface {\n\ttea.Model\n\tlayout.Sizeable\n\tlayout.Bindings\n}\n\ntype tableCmp struct {\n\ttable table.Model\n}\n\ntype selectedLogMsg logging.LogMessage\n\nfunc (i *tableCmp) Init() tea.Cmd {\n\ti.setRows()\n\treturn nil\n}\n\nfunc (i *tableCmp) Update(msg tea.Msg) (tea.Model, tea.Cmd) {\n\tvar cmds []tea.Cmd\n\tswitch msg.(type) {\n\tcase pubsub.Event[logging.LogMessage]:\n\t\ti.setRows()\n\t\treturn i, nil\n\t}\n\tprevSelectedRow := i.table.SelectedRow()\n\tt, cmd := i.table.Update(msg)\n\tcmds = append(cmds, cmd)\n\ti.table = t\n\tselectedRow := i.table.SelectedRow()\n\tif selectedRow != nil {\n\t\tif prevSelectedRow == nil || selectedRow[0] == prevSelectedRow[0] {\n\t\t\tvar log logging.LogMessage\n\t\t\tfor _, row := range logging.List() {\n\t\t\t\tif row.ID == selectedRow[0] {\n\t\t\t\t\tlog = row\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\tif log.ID != \"\" {\n\t\t\t\tcmds = append(cmds, util.CmdHandler(selectedLogMsg(log)))\n\t\t\t}\n\t\t}\n\t}\n\treturn i, tea.Batch(cmds...)\n}\n\nfunc (i *tableCmp) View() string {\n\tt := theme.CurrentTheme()\n\tdefaultStyles := table.DefaultStyles()\n\tdefaultStyles.Selected = defaultStyles.Selected.Foreground(t.Primary())\n\ti.table.SetStyles(defaultStyles)\n\treturn styles.ForceReplaceBackgroundWithLipgloss(i.table.View(), t.Background())\n}\n\nfunc (i *tableCmp) GetSize() (int, int) {\n\treturn i.table.Width(), i.table.Height()\n}\n\nfunc (i *tableCmp) SetSize(width int, height int) tea.Cmd {\n\ti.table.SetWidth(width)\n\ti.table.SetHeight(height)\n\tcloumns := i.table.Columns()\n\tfor i, col := range cloumns {\n\t\tcol.Width = (width / len(cloumns)) - 2\n\t\tcloumns[i] = col\n\t}\n\ti.table.SetColumns(cloumns)\n\treturn nil\n}\n\nfunc (i *tableCmp) BindingKeys() []key.Binding {\n\treturn layout.KeyMapToSlice(i.table.KeyMap)\n}\n\nfunc (i *tableCmp) setRows() {\n\trows := []table.Row{}\n\n\tlogs := logging.List()\n\tslices.SortFunc(logs, func(a, b logging.LogMessage) int {\n\t\tif a.Time.Before(b.Time) {\n\t\t\treturn 1\n\t\t}\n\t\tif a.Time.After(b.Time) {\n\t\t\treturn -1\n\t\t}\n\t\treturn 0\n\t})\n\n\tfor _, log := range logs {\n\t\tbm, _ := json.Marshal(log.Attributes)\n\n\t\trow := table.Row{\n\t\t\tlog.ID,\n\t\t\tlog.Time.Format(\"15:04:05\"),\n\t\t\tlog.Level,\n\t\t\tlog.Message,\n\t\t\tstring(bm),\n\t\t}\n\t\trows = append(rows, row)\n\t}\n\ti.table.SetRows(rows)\n}\n\nfunc NewLogsTable() TableComponent {\n\tcolumns := []table.Column{\n\t\t{Title: \"ID\", Width: 4},\n\t\t{Title: \"Time\", Width: 4},\n\t\t{Title: \"Level\", Width: 10},\n\t\t{Title: \"Message\", Width: 10},\n\t\t{Title: \"Attributes\", Width: 10},\n\t}\n\n\ttableModel := table.New(\n\t\ttable.WithColumns(columns),\n\t)\n\ttableModel.Focus()\n\treturn &tableCmp{\n\t\ttable: tableModel,\n\t}\n}\n"], ["/opencode/internal/pubsub/broker.go", "package pubsub\n\nimport (\n\t\"context\"\n\t\"sync\"\n)\n\nconst bufferSize = 64\n\ntype Broker[T any] struct {\n\tsubs map[chan Event[T]]struct{}\n\tmu sync.RWMutex\n\tdone chan struct{}\n\tsubCount int\n\tmaxEvents int\n}\n\nfunc NewBroker[T any]() *Broker[T] {\n\treturn NewBrokerWithOptions[T](bufferSize, 1000)\n}\n\nfunc NewBrokerWithOptions[T any](channelBufferSize, maxEvents int) *Broker[T] {\n\tb := &Broker[T]{\n\t\tsubs: make(map[chan Event[T]]struct{}),\n\t\tdone: make(chan struct{}),\n\t\tsubCount: 0,\n\t\tmaxEvents: maxEvents,\n\t}\n\treturn b\n}\n\nfunc (b *Broker[T]) Shutdown() {\n\tselect {\n\tcase <-b.done: // Already closed\n\t\treturn\n\tdefault:\n\t\tclose(b.done)\n\t}\n\n\tb.mu.Lock()\n\tdefer b.mu.Unlock()\n\n\tfor ch := range b.subs {\n\t\tdelete(b.subs, ch)\n\t\tclose(ch)\n\t}\n\n\tb.subCount = 0\n}\n\nfunc (b *Broker[T]) Subscribe(ctx context.Context) <-chan Event[T] {\n\tb.mu.Lock()\n\tdefer b.mu.Unlock()\n\n\tselect {\n\tcase <-b.done:\n\t\tch := make(chan Event[T])\n\t\tclose(ch)\n\t\treturn ch\n\tdefault:\n\t}\n\n\tsub := make(chan Event[T], bufferSize)\n\tb.subs[sub] = struct{}{}\n\tb.subCount++\n\n\tgo func() {\n\t\t<-ctx.Done()\n\n\t\tb.mu.Lock()\n\t\tdefer b.mu.Unlock()\n\n\t\tselect {\n\t\tcase <-b.done:\n\t\t\treturn\n\t\tdefault:\n\t\t}\n\n\t\tdelete(b.subs, sub)\n\t\tclose(sub)\n\t\tb.subCount--\n\t}()\n\n\treturn sub\n}\n\nfunc (b *Broker[T]) GetSubscriberCount() int {\n\tb.mu.RLock()\n\tdefer b.mu.RUnlock()\n\treturn b.subCount\n}\n\nfunc (b *Broker[T]) Publish(t EventType, payload T) {\n\tb.mu.RLock()\n\tselect {\n\tcase <-b.done:\n\t\tb.mu.RUnlock()\n\t\treturn\n\tdefault:\n\t}\n\n\tsubscribers := make([]chan Event[T], 0, len(b.subs))\n\tfor sub := range b.subs {\n\t\tsubscribers = append(subscribers, sub)\n\t}\n\tb.mu.RUnlock()\n\n\tevent := Event[T]{Type: t, Payload: payload}\n\n\tfor _, sub := range subscribers {\n\t\tselect {\n\t\tcase sub <- event:\n\t\tdefault:\n\t\t}\n\t}\n}\n"], ["/opencode/internal/tui/components/dialog/help.go", "package dialog\n\nimport (\n\t\"strings\"\n\n\t\"github.com/charmbracelet/bubbles/key\"\n\ttea \"github.com/charmbracelet/bubbletea\"\n\t\"github.com/charmbracelet/lipgloss\"\n\t\"github.com/opencode-ai/opencode/internal/tui/styles\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n)\n\ntype helpCmp struct {\n\twidth int\n\theight int\n\tkeys []key.Binding\n}\n\nfunc (h *helpCmp) Init() tea.Cmd {\n\treturn nil\n}\n\nfunc (h *helpCmp) SetBindings(k []key.Binding) {\n\th.keys = k\n}\n\nfunc (h *helpCmp) Update(msg tea.Msg) (tea.Model, tea.Cmd) {\n\tswitch msg := msg.(type) {\n\tcase tea.WindowSizeMsg:\n\t\th.width = 90\n\t\th.height = msg.Height\n\t}\n\treturn h, nil\n}\n\nfunc removeDuplicateBindings(bindings []key.Binding) []key.Binding {\n\tseen := make(map[string]struct{})\n\tresult := make([]key.Binding, 0, len(bindings))\n\n\t// Process bindings in reverse order\n\tfor i := len(bindings) - 1; i >= 0; i-- {\n\t\tb := bindings[i]\n\t\tk := strings.Join(b.Keys(), \" \")\n\t\tif _, ok := seen[k]; ok {\n\t\t\t// duplicate, skip\n\t\t\tcontinue\n\t\t}\n\t\tseen[k] = struct{}{}\n\t\t// Add to the beginning of result to maintain original order\n\t\tresult = append([]key.Binding{b}, result...)\n\t}\n\n\treturn result\n}\n\nfunc (h *helpCmp) render() string {\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\n\thelpKeyStyle := styles.Bold().\n\t\tBackground(t.Background()).\n\t\tForeground(t.Text()).\n\t\tPadding(0, 1, 0, 0)\n\n\thelpDescStyle := styles.Regular().\n\t\tBackground(t.Background()).\n\t\tForeground(t.TextMuted())\n\n\t// Compile list of bindings to render\n\tbindings := removeDuplicateBindings(h.keys)\n\n\t// Enumerate through each group of bindings, populating a series of\n\t// pairs of columns, one for keys, one for descriptions\n\tvar (\n\t\tpairs []string\n\t\twidth int\n\t\trows = 12 - 2\n\t)\n\n\tfor i := 0; i < len(bindings); i += rows {\n\t\tvar (\n\t\t\tkeys []string\n\t\t\tdescs []string\n\t\t)\n\t\tfor j := i; j < min(i+rows, len(bindings)); j++ {\n\t\t\tkeys = append(keys, helpKeyStyle.Render(bindings[j].Help().Key))\n\t\t\tdescs = append(descs, helpDescStyle.Render(bindings[j].Help().Desc))\n\t\t}\n\n\t\t// Render pair of columns; beyond the first pair, render a three space\n\t\t// left margin, in order to visually separate the pairs.\n\t\tvar cols []string\n\t\tif len(pairs) > 0 {\n\t\t\tcols = []string{baseStyle.Render(\" \")}\n\t\t}\n\n\t\tmaxDescWidth := 0\n\t\tfor _, desc := range descs {\n\t\t\tif maxDescWidth < lipgloss.Width(desc) {\n\t\t\t\tmaxDescWidth = lipgloss.Width(desc)\n\t\t\t}\n\t\t}\n\t\tfor i := range descs {\n\t\t\tremainingWidth := maxDescWidth - lipgloss.Width(descs[i])\n\t\t\tif remainingWidth > 0 {\n\t\t\t\tdescs[i] = descs[i] + baseStyle.Render(strings.Repeat(\" \", remainingWidth))\n\t\t\t}\n\t\t}\n\t\tmaxKeyWidth := 0\n\t\tfor _, key := range keys {\n\t\t\tif maxKeyWidth < lipgloss.Width(key) {\n\t\t\t\tmaxKeyWidth = lipgloss.Width(key)\n\t\t\t}\n\t\t}\n\t\tfor i := range keys {\n\t\t\tremainingWidth := maxKeyWidth - lipgloss.Width(keys[i])\n\t\t\tif remainingWidth > 0 {\n\t\t\t\tkeys[i] = keys[i] + baseStyle.Render(strings.Repeat(\" \", remainingWidth))\n\t\t\t}\n\t\t}\n\n\t\tcols = append(cols,\n\t\t\tstrings.Join(keys, \"\\n\"),\n\t\t\tstrings.Join(descs, \"\\n\"),\n\t\t)\n\n\t\tpair := baseStyle.Render(lipgloss.JoinHorizontal(lipgloss.Top, cols...))\n\t\t// check whether it exceeds the maximum width avail (the width of the\n\t\t// terminal, subtracting 2 for the borders).\n\t\twidth += lipgloss.Width(pair)\n\t\tif width > h.width-2 {\n\t\t\tbreak\n\t\t}\n\t\tpairs = append(pairs, pair)\n\t}\n\n\t// https://github.com/charmbracelet/lipgloss/issues/209\n\tif len(pairs) > 1 {\n\t\tprefix := pairs[:len(pairs)-1]\n\t\tlastPair := pairs[len(pairs)-1]\n\t\tprefix = append(prefix, lipgloss.Place(\n\t\t\tlipgloss.Width(lastPair), // width\n\t\t\tlipgloss.Height(prefix[0]), // height\n\t\t\tlipgloss.Left, // x\n\t\t\tlipgloss.Top, // y\n\t\t\tlastPair, // content\n\t\t\tlipgloss.WithWhitespaceBackground(t.Background()),\n\t\t))\n\t\tcontent := baseStyle.Width(h.width).Render(\n\t\t\tlipgloss.JoinHorizontal(\n\t\t\t\tlipgloss.Top,\n\t\t\t\tprefix...,\n\t\t\t),\n\t\t)\n\t\treturn content\n\t}\n\n\t// Join pairs of columns and enclose in a border\n\tcontent := baseStyle.Width(h.width).Render(\n\t\tlipgloss.JoinHorizontal(\n\t\t\tlipgloss.Top,\n\t\t\tpairs...,\n\t\t),\n\t)\n\treturn content\n}\n\nfunc (h *helpCmp) View() string {\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\n\tcontent := h.render()\n\theader := baseStyle.\n\t\tBold(true).\n\t\tWidth(lipgloss.Width(content)).\n\t\tForeground(t.Primary()).\n\t\tRender(\"Keyboard Shortcuts\")\n\n\treturn baseStyle.Padding(1).\n\t\tBorder(lipgloss.RoundedBorder()).\n\t\tBorderForeground(t.TextMuted()).\n\t\tWidth(h.width).\n\t\tBorderBackground(t.Background()).\n\t\tRender(\n\t\t\tlipgloss.JoinVertical(lipgloss.Center,\n\t\t\t\theader,\n\t\t\t\tbaseStyle.Render(strings.Repeat(\" \", lipgloss.Width(header))),\n\t\t\t\tcontent,\n\t\t\t),\n\t\t)\n}\n\ntype HelpCmp interface {\n\ttea.Model\n\tSetBindings([]key.Binding)\n}\n\nfunc NewHelpCmp() HelpCmp {\n\treturn &helpCmp{}\n}\n"], ["/opencode/internal/tui/page/logs.go", "package page\n\nimport (\n\t\"github.com/charmbracelet/bubbles/key\"\n\ttea \"github.com/charmbracelet/bubbletea\"\n\t\"github.com/charmbracelet/lipgloss\"\n\t\"github.com/opencode-ai/opencode/internal/tui/components/logs\"\n\t\"github.com/opencode-ai/opencode/internal/tui/layout\"\n\t\"github.com/opencode-ai/opencode/internal/tui/styles\"\n)\n\nvar LogsPage PageID = \"logs\"\n\ntype LogPage interface {\n\ttea.Model\n\tlayout.Sizeable\n\tlayout.Bindings\n}\ntype logsPage struct {\n\twidth, height int\n\ttable layout.Container\n\tdetails layout.Container\n}\n\nfunc (p *logsPage) Update(msg tea.Msg) (tea.Model, tea.Cmd) {\n\tvar cmds []tea.Cmd\n\tswitch msg := msg.(type) {\n\tcase tea.WindowSizeMsg:\n\t\tp.width = msg.Width\n\t\tp.height = msg.Height\n\t\treturn p, p.SetSize(msg.Width, msg.Height)\n\t}\n\n\ttable, cmd := p.table.Update(msg)\n\tcmds = append(cmds, cmd)\n\tp.table = table.(layout.Container)\n\tdetails, cmd := p.details.Update(msg)\n\tcmds = append(cmds, cmd)\n\tp.details = details.(layout.Container)\n\n\treturn p, tea.Batch(cmds...)\n}\n\nfunc (p *logsPage) View() string {\n\tstyle := styles.BaseStyle().Width(p.width).Height(p.height)\n\treturn style.Render(lipgloss.JoinVertical(lipgloss.Top,\n\t\tp.table.View(),\n\t\tp.details.View(),\n\t))\n}\n\nfunc (p *logsPage) BindingKeys() []key.Binding {\n\treturn p.table.BindingKeys()\n}\n\n// GetSize implements LogPage.\nfunc (p *logsPage) GetSize() (int, int) {\n\treturn p.width, p.height\n}\n\n// SetSize implements LogPage.\nfunc (p *logsPage) SetSize(width int, height int) tea.Cmd {\n\tp.width = width\n\tp.height = height\n\treturn tea.Batch(\n\t\tp.table.SetSize(width, height/2),\n\t\tp.details.SetSize(width, height/2),\n\t)\n}\n\nfunc (p *logsPage) Init() tea.Cmd {\n\treturn tea.Batch(\n\t\tp.table.Init(),\n\t\tp.details.Init(),\n\t)\n}\n\nfunc NewLogsPage() LogPage {\n\treturn &logsPage{\n\t\ttable: layout.NewContainer(logs.NewLogsTable(), layout.WithBorderAll()),\n\t\tdetails: layout.NewContainer(logs.NewLogsDetails(), layout.WithBorderAll()),\n\t}\n}\n"], ["/opencode/internal/completions/files-folders.go", "package completions\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"os/exec\"\n\t\"path/filepath\"\n\n\t\"github.com/lithammer/fuzzysearch/fuzzy\"\n\t\"github.com/opencode-ai/opencode/internal/fileutil\"\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n\t\"github.com/opencode-ai/opencode/internal/tui/components/dialog\"\n)\n\ntype filesAndFoldersContextGroup struct {\n\tprefix string\n}\n\nfunc (cg *filesAndFoldersContextGroup) GetId() string {\n\treturn cg.prefix\n}\n\nfunc (cg *filesAndFoldersContextGroup) GetEntry() dialog.CompletionItemI {\n\treturn dialog.NewCompletionItem(dialog.CompletionItem{\n\t\tTitle: \"Files & Folders\",\n\t\tValue: \"files\",\n\t})\n}\n\nfunc processNullTerminatedOutput(outputBytes []byte) []string {\n\tif len(outputBytes) > 0 && outputBytes[len(outputBytes)-1] == 0 {\n\t\toutputBytes = outputBytes[:len(outputBytes)-1]\n\t}\n\n\tif len(outputBytes) == 0 {\n\t\treturn []string{}\n\t}\n\n\tsplit := bytes.Split(outputBytes, []byte{0})\n\tmatches := make([]string, 0, len(split))\n\n\tfor _, p := range split {\n\t\tif len(p) == 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\tpath := string(p)\n\t\tpath = filepath.Join(\".\", path)\n\n\t\tif !fileutil.SkipHidden(path) {\n\t\t\tmatches = append(matches, path)\n\t\t}\n\t}\n\n\treturn matches\n}\n\nfunc (cg *filesAndFoldersContextGroup) getFiles(query string) ([]string, error) {\n\tcmdRg := fileutil.GetRgCmd(\"\") // No glob pattern for this use case\n\tcmdFzf := fileutil.GetFzfCmd(query)\n\n\tvar matches []string\n\t// Case 1: Both rg and fzf available\n\tif cmdRg != nil && cmdFzf != nil {\n\t\trgPipe, err := cmdRg.StdoutPipe()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to get rg stdout pipe: %w\", err)\n\t\t}\n\t\tdefer rgPipe.Close()\n\n\t\tcmdFzf.Stdin = rgPipe\n\t\tvar fzfOut bytes.Buffer\n\t\tvar fzfErr bytes.Buffer\n\t\tcmdFzf.Stdout = &fzfOut\n\t\tcmdFzf.Stderr = &fzfErr\n\n\t\tif err := cmdFzf.Start(); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to start fzf: %w\", err)\n\t\t}\n\n\t\terrRg := cmdRg.Run()\n\t\terrFzf := cmdFzf.Wait()\n\n\t\tif errRg != nil {\n\t\t\tlogging.Warn(fmt.Sprintf(\"rg command failed during pipe: %v\", errRg))\n\t\t}\n\n\t\tif errFzf != nil {\n\t\t\tif exitErr, ok := errFzf.(*exec.ExitError); ok && exitErr.ExitCode() == 1 {\n\t\t\t\treturn []string{}, nil // No matches from fzf\n\t\t\t}\n\t\t\treturn nil, fmt.Errorf(\"fzf command failed: %w\\nStderr: %s\", errFzf, fzfErr.String())\n\t\t}\n\n\t\tmatches = processNullTerminatedOutput(fzfOut.Bytes())\n\n\t\t// Case 2: Only rg available\n\t} else if cmdRg != nil {\n\t\tlogging.Debug(\"Using Ripgrep with fuzzy match fallback for file completions\")\n\t\tvar rgOut bytes.Buffer\n\t\tvar rgErr bytes.Buffer\n\t\tcmdRg.Stdout = &rgOut\n\t\tcmdRg.Stderr = &rgErr\n\n\t\tif err := cmdRg.Run(); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"rg command failed: %w\\nStderr: %s\", err, rgErr.String())\n\t\t}\n\n\t\tallFiles := processNullTerminatedOutput(rgOut.Bytes())\n\t\tmatches = fuzzy.Find(query, allFiles)\n\n\t\t// Case 3: Only fzf available\n\t} else if cmdFzf != nil {\n\t\tlogging.Debug(\"Using FZF with doublestar fallback for file completions\")\n\t\tfiles, _, err := fileutil.GlobWithDoublestar(\"**/*\", \".\", 0)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to list files for fzf: %w\", err)\n\t\t}\n\n\t\tallFiles := make([]string, 0, len(files))\n\t\tfor _, file := range files {\n\t\t\tif !fileutil.SkipHidden(file) {\n\t\t\t\tallFiles = append(allFiles, file)\n\t\t\t}\n\t\t}\n\n\t\tvar fzfIn bytes.Buffer\n\t\tfor _, file := range allFiles {\n\t\t\tfzfIn.WriteString(file)\n\t\t\tfzfIn.WriteByte(0)\n\t\t}\n\n\t\tcmdFzf.Stdin = &fzfIn\n\t\tvar fzfOut bytes.Buffer\n\t\tvar fzfErr bytes.Buffer\n\t\tcmdFzf.Stdout = &fzfOut\n\t\tcmdFzf.Stderr = &fzfErr\n\n\t\tif err := cmdFzf.Run(); err != nil {\n\t\t\tif exitErr, ok := err.(*exec.ExitError); ok && exitErr.ExitCode() == 1 {\n\t\t\t\treturn []string{}, nil\n\t\t\t}\n\t\t\treturn nil, fmt.Errorf(\"fzf command failed: %w\\nStderr: %s\", err, fzfErr.String())\n\t\t}\n\n\t\tmatches = processNullTerminatedOutput(fzfOut.Bytes())\n\n\t\t// Case 4: Fallback to doublestar with fuzzy match\n\t} else {\n\t\tlogging.Debug(\"Using doublestar with fuzzy match for file completions\")\n\t\tallFiles, _, err := fileutil.GlobWithDoublestar(\"**/*\", \".\", 0)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to glob files: %w\", err)\n\t\t}\n\n\t\tfilteredFiles := make([]string, 0, len(allFiles))\n\t\tfor _, file := range allFiles {\n\t\t\tif !fileutil.SkipHidden(file) {\n\t\t\t\tfilteredFiles = append(filteredFiles, file)\n\t\t\t}\n\t\t}\n\n\t\tmatches = fuzzy.Find(query, filteredFiles)\n\t}\n\n\treturn matches, nil\n}\n\nfunc (cg *filesAndFoldersContextGroup) GetChildEntries(query string) ([]dialog.CompletionItemI, error) {\n\tmatches, err := cg.getFiles(query)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\titems := make([]dialog.CompletionItemI, 0, len(matches))\n\tfor _, file := range matches {\n\t\titem := dialog.NewCompletionItem(dialog.CompletionItem{\n\t\t\tTitle: file,\n\t\t\tValue: file,\n\t\t})\n\t\titems = append(items, item)\n\t}\n\n\treturn items, nil\n}\n\nfunc NewFileAndFolderContextGroup() dialog.CompletionProvider {\n\treturn &filesAndFoldersContextGroup{\n\t\tprefix: \"file\",\n\t}\n}\n"], ["/opencode/internal/tui/layout/split.go", "package layout\n\nimport (\n\t\"github.com/charmbracelet/bubbles/key\"\n\ttea \"github.com/charmbracelet/bubbletea\"\n\t\"github.com/charmbracelet/lipgloss\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n)\n\ntype SplitPaneLayout interface {\n\ttea.Model\n\tSizeable\n\tBindings\n\tSetLeftPanel(panel Container) tea.Cmd\n\tSetRightPanel(panel Container) tea.Cmd\n\tSetBottomPanel(panel Container) tea.Cmd\n\n\tClearLeftPanel() tea.Cmd\n\tClearRightPanel() tea.Cmd\n\tClearBottomPanel() tea.Cmd\n}\n\ntype splitPaneLayout struct {\n\twidth int\n\theight int\n\tratio float64\n\tverticalRatio float64\n\n\trightPanel Container\n\tleftPanel Container\n\tbottomPanel Container\n}\n\ntype SplitPaneOption func(*splitPaneLayout)\n\nfunc (s *splitPaneLayout) Init() tea.Cmd {\n\tvar cmds []tea.Cmd\n\n\tif s.leftPanel != nil {\n\t\tcmds = append(cmds, s.leftPanel.Init())\n\t}\n\n\tif s.rightPanel != nil {\n\t\tcmds = append(cmds, s.rightPanel.Init())\n\t}\n\n\tif s.bottomPanel != nil {\n\t\tcmds = append(cmds, s.bottomPanel.Init())\n\t}\n\n\treturn tea.Batch(cmds...)\n}\n\nfunc (s *splitPaneLayout) Update(msg tea.Msg) (tea.Model, tea.Cmd) {\n\tvar cmds []tea.Cmd\n\tswitch msg := msg.(type) {\n\tcase tea.WindowSizeMsg:\n\t\treturn s, s.SetSize(msg.Width, msg.Height)\n\t}\n\n\tif s.rightPanel != nil {\n\t\tu, cmd := s.rightPanel.Update(msg)\n\t\ts.rightPanel = u.(Container)\n\t\tif cmd != nil {\n\t\t\tcmds = append(cmds, cmd)\n\t\t}\n\t}\n\n\tif s.leftPanel != nil {\n\t\tu, cmd := s.leftPanel.Update(msg)\n\t\ts.leftPanel = u.(Container)\n\t\tif cmd != nil {\n\t\t\tcmds = append(cmds, cmd)\n\t\t}\n\t}\n\n\tif s.bottomPanel != nil {\n\t\tu, cmd := s.bottomPanel.Update(msg)\n\t\ts.bottomPanel = u.(Container)\n\t\tif cmd != nil {\n\t\t\tcmds = append(cmds, cmd)\n\t\t}\n\t}\n\n\treturn s, tea.Batch(cmds...)\n}\n\nfunc (s *splitPaneLayout) View() string {\n\tvar topSection string\n\n\tif s.leftPanel != nil && s.rightPanel != nil {\n\t\tleftView := s.leftPanel.View()\n\t\trightView := s.rightPanel.View()\n\t\ttopSection = lipgloss.JoinHorizontal(lipgloss.Top, leftView, rightView)\n\t} else if s.leftPanel != nil {\n\t\ttopSection = s.leftPanel.View()\n\t} else if s.rightPanel != nil {\n\t\ttopSection = s.rightPanel.View()\n\t} else {\n\t\ttopSection = \"\"\n\t}\n\n\tvar finalView string\n\n\tif s.bottomPanel != nil && topSection != \"\" {\n\t\tbottomView := s.bottomPanel.View()\n\t\tfinalView = lipgloss.JoinVertical(lipgloss.Left, topSection, bottomView)\n\t} else if s.bottomPanel != nil {\n\t\tfinalView = s.bottomPanel.View()\n\t} else {\n\t\tfinalView = topSection\n\t}\n\n\tif finalView != \"\" {\n\t\tt := theme.CurrentTheme()\n\n\t\tstyle := lipgloss.NewStyle().\n\t\t\tWidth(s.width).\n\t\t\tHeight(s.height).\n\t\t\tBackground(t.Background())\n\n\t\treturn style.Render(finalView)\n\t}\n\n\treturn finalView\n}\n\nfunc (s *splitPaneLayout) SetSize(width, height int) tea.Cmd {\n\ts.width = width\n\ts.height = height\n\n\tvar topHeight, bottomHeight int\n\tif s.bottomPanel != nil {\n\t\ttopHeight = int(float64(height) * s.verticalRatio)\n\t\tbottomHeight = height - topHeight\n\t} else {\n\t\ttopHeight = height\n\t\tbottomHeight = 0\n\t}\n\n\tvar leftWidth, rightWidth int\n\tif s.leftPanel != nil && s.rightPanel != nil {\n\t\tleftWidth = int(float64(width) * s.ratio)\n\t\trightWidth = width - leftWidth\n\t} else if s.leftPanel != nil {\n\t\tleftWidth = width\n\t\trightWidth = 0\n\t} else if s.rightPanel != nil {\n\t\tleftWidth = 0\n\t\trightWidth = width\n\t}\n\n\tvar cmds []tea.Cmd\n\tif s.leftPanel != nil {\n\t\tcmd := s.leftPanel.SetSize(leftWidth, topHeight)\n\t\tcmds = append(cmds, cmd)\n\t}\n\n\tif s.rightPanel != nil {\n\t\tcmd := s.rightPanel.SetSize(rightWidth, topHeight)\n\t\tcmds = append(cmds, cmd)\n\t}\n\n\tif s.bottomPanel != nil {\n\t\tcmd := s.bottomPanel.SetSize(width, bottomHeight)\n\t\tcmds = append(cmds, cmd)\n\t}\n\treturn tea.Batch(cmds...)\n}\n\nfunc (s *splitPaneLayout) GetSize() (int, int) {\n\treturn s.width, s.height\n}\n\nfunc (s *splitPaneLayout) SetLeftPanel(panel Container) tea.Cmd {\n\ts.leftPanel = panel\n\tif s.width > 0 && s.height > 0 {\n\t\treturn s.SetSize(s.width, s.height)\n\t}\n\treturn nil\n}\n\nfunc (s *splitPaneLayout) SetRightPanel(panel Container) tea.Cmd {\n\ts.rightPanel = panel\n\tif s.width > 0 && s.height > 0 {\n\t\treturn s.SetSize(s.width, s.height)\n\t}\n\treturn nil\n}\n\nfunc (s *splitPaneLayout) SetBottomPanel(panel Container) tea.Cmd {\n\ts.bottomPanel = panel\n\tif s.width > 0 && s.height > 0 {\n\t\treturn s.SetSize(s.width, s.height)\n\t}\n\treturn nil\n}\n\nfunc (s *splitPaneLayout) ClearLeftPanel() tea.Cmd {\n\ts.leftPanel = nil\n\tif s.width > 0 && s.height > 0 {\n\t\treturn s.SetSize(s.width, s.height)\n\t}\n\treturn nil\n}\n\nfunc (s *splitPaneLayout) ClearRightPanel() tea.Cmd {\n\ts.rightPanel = nil\n\tif s.width > 0 && s.height > 0 {\n\t\treturn s.SetSize(s.width, s.height)\n\t}\n\treturn nil\n}\n\nfunc (s *splitPaneLayout) ClearBottomPanel() tea.Cmd {\n\ts.bottomPanel = nil\n\tif s.width > 0 && s.height > 0 {\n\t\treturn s.SetSize(s.width, s.height)\n\t}\n\treturn nil\n}\n\nfunc (s *splitPaneLayout) BindingKeys() []key.Binding {\n\tkeys := []key.Binding{}\n\tif s.leftPanel != nil {\n\t\tif b, ok := s.leftPanel.(Bindings); ok {\n\t\t\tkeys = append(keys, b.BindingKeys()...)\n\t\t}\n\t}\n\tif s.rightPanel != nil {\n\t\tif b, ok := s.rightPanel.(Bindings); ok {\n\t\t\tkeys = append(keys, b.BindingKeys()...)\n\t\t}\n\t}\n\tif s.bottomPanel != nil {\n\t\tif b, ok := s.bottomPanel.(Bindings); ok {\n\t\t\tkeys = append(keys, b.BindingKeys()...)\n\t\t}\n\t}\n\treturn keys\n}\n\nfunc NewSplitPane(options ...SplitPaneOption) SplitPaneLayout {\n\n\tlayout := &splitPaneLayout{\n\t\tratio: 0.7,\n\t\tverticalRatio: 0.9, // Default 90% for top section, 10% for bottom\n\t}\n\tfor _, option := range options {\n\t\toption(layout)\n\t}\n\treturn layout\n}\n\nfunc WithLeftPanel(panel Container) SplitPaneOption {\n\treturn func(s *splitPaneLayout) {\n\t\ts.leftPanel = panel\n\t}\n}\n\nfunc WithRightPanel(panel Container) SplitPaneOption {\n\treturn func(s *splitPaneLayout) {\n\t\ts.rightPanel = panel\n\t}\n}\n\nfunc WithRatio(ratio float64) SplitPaneOption {\n\treturn func(s *splitPaneLayout) {\n\t\ts.ratio = ratio\n\t}\n}\n\nfunc WithBottomPanel(panel Container) SplitPaneOption {\n\treturn func(s *splitPaneLayout) {\n\t\ts.bottomPanel = panel\n\t}\n}\n\nfunc WithVerticalRatio(ratio float64) SplitPaneOption {\n\treturn func(s *splitPaneLayout) {\n\t\ts.verticalRatio = ratio\n\t}\n}\n"], ["/opencode/internal/tui/styles/background.go", "package styles\n\nimport (\n\t\"fmt\"\n\t\"regexp\"\n\t\"strings\"\n\n\t\"github.com/charmbracelet/lipgloss\"\n)\n\nvar ansiEscape = regexp.MustCompile(\"\\x1b\\\\[[0-9;]*m\")\n\nfunc getColorRGB(c lipgloss.TerminalColor) (uint8, uint8, uint8) {\n\tr, g, b, a := c.RGBA()\n\n\t// Un-premultiply alpha if needed\n\tif a > 0 && a < 0xffff {\n\t\tr = (r * 0xffff) / a\n\t\tg = (g * 0xffff) / a\n\t\tb = (b * 0xffff) / a\n\t}\n\n\t// Convert from 16-bit to 8-bit color\n\treturn uint8(r >> 8), uint8(g >> 8), uint8(b >> 8)\n}\n\n// ForceReplaceBackgroundWithLipgloss replaces any ANSI background color codes\n// in `input` with a single 24‑bit background (48;2;R;G;B).\nfunc ForceReplaceBackgroundWithLipgloss(input string, newBgColor lipgloss.TerminalColor) string {\n\t// Precompute our new-bg sequence once\n\tr, g, b := getColorRGB(newBgColor)\n\tnewBg := fmt.Sprintf(\"48;2;%d;%d;%d\", r, g, b)\n\n\treturn ansiEscape.ReplaceAllStringFunc(input, func(seq string) string {\n\t\tconst (\n\t\t\tescPrefixLen = 2 // \"\\x1b[\"\n\t\t\tescSuffixLen = 1 // \"m\"\n\t\t)\n\n\t\traw := seq\n\t\tstart := escPrefixLen\n\t\tend := len(raw) - escSuffixLen\n\n\t\tvar sb strings.Builder\n\t\t// reserve enough space: original content minus bg codes + our newBg\n\t\tsb.Grow((end - start) + len(newBg) + 2)\n\n\t\t// scan from start..end, token by token\n\t\tfor i := start; i < end; {\n\t\t\t// find the next ';' or end\n\t\t\tj := i\n\t\t\tfor j < end && raw[j] != ';' {\n\t\t\t\tj++\n\t\t\t}\n\t\t\ttoken := raw[i:j]\n\n\t\t\t// fast‑path: skip \"48;5;N\" or \"48;2;R;G;B\"\n\t\t\tif len(token) == 2 && token[0] == '4' && token[1] == '8' {\n\t\t\t\tk := j + 1\n\t\t\t\tif k < end {\n\t\t\t\t\t// find next token\n\t\t\t\t\tl := k\n\t\t\t\t\tfor l < end && raw[l] != ';' {\n\t\t\t\t\t\tl++\n\t\t\t\t\t}\n\t\t\t\t\tnext := raw[k:l]\n\t\t\t\t\tif next == \"5\" {\n\t\t\t\t\t\t// skip \"48;5;N\"\n\t\t\t\t\t\tm := l + 1\n\t\t\t\t\t\tfor m < end && raw[m] != ';' {\n\t\t\t\t\t\t\tm++\n\t\t\t\t\t\t}\n\t\t\t\t\t\ti = m + 1\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t} else if next == \"2\" {\n\t\t\t\t\t\t// skip \"48;2;R;G;B\"\n\t\t\t\t\t\tm := l + 1\n\t\t\t\t\t\tfor count := 0; count < 3 && m < end; count++ {\n\t\t\t\t\t\t\tfor m < end && raw[m] != ';' {\n\t\t\t\t\t\t\t\tm++\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tm++\n\t\t\t\t\t\t}\n\t\t\t\t\t\ti = m\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// decide whether to keep this token\n\t\t\t// manually parse ASCII digits to int\n\t\t\tisNum := true\n\t\t\tval := 0\n\t\t\tfor p := i; p < j; p++ {\n\t\t\t\tc := raw[p]\n\t\t\t\tif c < '0' || c > '9' {\n\t\t\t\t\tisNum = false\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tval = val*10 + int(c-'0')\n\t\t\t}\n\t\t\tkeep := !isNum ||\n\t\t\t\t((val < 40 || val > 47) && (val < 100 || val > 107) && val != 49)\n\n\t\t\tif keep {\n\t\t\t\tif sb.Len() > 0 {\n\t\t\t\t\tsb.WriteByte(';')\n\t\t\t\t}\n\t\t\t\tsb.WriteString(token)\n\t\t\t}\n\t\t\t// advance past this token (and the semicolon)\n\t\t\ti = j + 1\n\t\t}\n\n\t\t// append our new background\n\t\tif sb.Len() > 0 {\n\t\t\tsb.WriteByte(';')\n\t\t}\n\t\tsb.WriteString(newBg)\n\n\t\treturn \"\\x1b[\" + sb.String() + \"m\"\n\t})\n}\n"], ["/opencode/internal/llm/models/local.go", "package models\n\nimport (\n\t\"cmp\"\n\t\"encoding/json\"\n\t\"net/http\"\n\t\"net/url\"\n\t\"os\"\n\t\"regexp\"\n\t\"strings\"\n\t\"unicode\"\n\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n\t\"github.com/spf13/viper\"\n)\n\nconst (\n\tProviderLocal ModelProvider = \"local\"\n\n\tlocalModelsPath = \"v1/models\"\n\tlmStudioBetaModelsPath = \"api/v0/models\"\n)\n\nfunc init() {\n\tif endpoint := os.Getenv(\"LOCAL_ENDPOINT\"); endpoint != \"\" {\n\t\tlocalEndpoint, err := url.Parse(endpoint)\n\t\tif err != nil {\n\t\t\tlogging.Debug(\"Failed to parse local endpoint\",\n\t\t\t\t\"error\", err,\n\t\t\t\t\"endpoint\", endpoint,\n\t\t\t)\n\t\t\treturn\n\t\t}\n\n\t\tload := func(url *url.URL, path string) []localModel {\n\t\t\turl.Path = path\n\t\t\treturn listLocalModels(url.String())\n\t\t}\n\n\t\tmodels := load(localEndpoint, lmStudioBetaModelsPath)\n\n\t\tif len(models) == 0 {\n\t\t\tmodels = load(localEndpoint, localModelsPath)\n\t\t}\n\n\t\tif len(models) == 0 {\n\t\t\tlogging.Debug(\"No local models found\",\n\t\t\t\t\"endpoint\", endpoint,\n\t\t\t)\n\t\t\treturn\n\t\t}\n\n\t\tloadLocalModels(models)\n\n\t\tviper.SetDefault(\"providers.local.apiKey\", \"dummy\")\n\t\tProviderPopularity[ProviderLocal] = 0\n\t}\n}\n\ntype localModelList struct {\n\tData []localModel `json:\"data\"`\n}\n\ntype localModel struct {\n\tID string `json:\"id\"`\n\tObject string `json:\"object\"`\n\tType string `json:\"type\"`\n\tPublisher string `json:\"publisher\"`\n\tArch string `json:\"arch\"`\n\tCompatibilityType string `json:\"compatibility_type\"`\n\tQuantization string `json:\"quantization\"`\n\tState string `json:\"state\"`\n\tMaxContextLength int64 `json:\"max_context_length\"`\n\tLoadedContextLength int64 `json:\"loaded_context_length\"`\n}\n\nfunc listLocalModels(modelsEndpoint string) []localModel {\n\tres, err := http.Get(modelsEndpoint)\n\tif err != nil {\n\t\tlogging.Debug(\"Failed to list local models\",\n\t\t\t\"error\", err,\n\t\t\t\"endpoint\", modelsEndpoint,\n\t\t)\n\t\treturn []localModel{}\n\t}\n\tdefer res.Body.Close()\n\n\tif res.StatusCode != http.StatusOK {\n\t\tlogging.Debug(\"Failed to list local models\",\n\t\t\t\"status\", res.StatusCode,\n\t\t\t\"endpoint\", modelsEndpoint,\n\t\t)\n\t\treturn []localModel{}\n\t}\n\n\tvar modelList localModelList\n\tif err = json.NewDecoder(res.Body).Decode(&modelList); err != nil {\n\t\tlogging.Debug(\"Failed to list local models\",\n\t\t\t\"error\", err,\n\t\t\t\"endpoint\", modelsEndpoint,\n\t\t)\n\t\treturn []localModel{}\n\t}\n\n\tvar supportedModels []localModel\n\tfor _, model := range modelList.Data {\n\t\tif strings.HasSuffix(modelsEndpoint, lmStudioBetaModelsPath) {\n\t\t\tif model.Object != \"model\" || model.Type != \"llm\" {\n\t\t\t\tlogging.Debug(\"Skipping unsupported LMStudio model\",\n\t\t\t\t\t\"endpoint\", modelsEndpoint,\n\t\t\t\t\t\"id\", model.ID,\n\t\t\t\t\t\"object\", model.Object,\n\t\t\t\t\t\"type\", model.Type,\n\t\t\t\t)\n\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\n\t\tsupportedModels = append(supportedModels, model)\n\t}\n\n\treturn supportedModels\n}\n\nfunc loadLocalModels(models []localModel) {\n\tfor i, m := range models {\n\t\tmodel := convertLocalModel(m)\n\t\tSupportedModels[model.ID] = model\n\n\t\tif i == 0 || m.State == \"loaded\" {\n\t\t\tviper.SetDefault(\"agents.coder.model\", model.ID)\n\t\t\tviper.SetDefault(\"agents.summarizer.model\", model.ID)\n\t\t\tviper.SetDefault(\"agents.task.model\", model.ID)\n\t\t\tviper.SetDefault(\"agents.title.model\", model.ID)\n\t\t}\n\t}\n}\n\nfunc convertLocalModel(model localModel) Model {\n\treturn Model{\n\t\tID: ModelID(\"local.\" + model.ID),\n\t\tName: friendlyModelName(model.ID),\n\t\tProvider: ProviderLocal,\n\t\tAPIModel: model.ID,\n\t\tContextWindow: cmp.Or(model.LoadedContextLength, 4096),\n\t\tDefaultMaxTokens: cmp.Or(model.LoadedContextLength, 4096),\n\t\tCanReason: true,\n\t\tSupportsAttachments: true,\n\t}\n}\n\nvar modelInfoRegex = regexp.MustCompile(`(?i)^([a-z0-9]+)(?:[-_]?([rv]?\\d[\\.\\d]*))?(?:[-_]?([a-z]+))?.*`)\n\nfunc friendlyModelName(modelID string) string {\n\tmainID := modelID\n\ttag := \"\"\n\n\tif slash := strings.LastIndex(mainID, \"/\"); slash != -1 {\n\t\tmainID = mainID[slash+1:]\n\t}\n\n\tif at := strings.Index(modelID, \"@\"); at != -1 {\n\t\tmainID = modelID[:at]\n\t\ttag = modelID[at+1:]\n\t}\n\n\tmatch := modelInfoRegex.FindStringSubmatch(mainID)\n\tif match == nil {\n\t\treturn modelID\n\t}\n\n\tcapitalize := func(s string) string {\n\t\tif s == \"\" {\n\t\t\treturn \"\"\n\t\t}\n\t\trunes := []rune(s)\n\t\trunes[0] = unicode.ToUpper(runes[0])\n\t\treturn string(runes)\n\t}\n\n\tfamily := capitalize(match[1])\n\tversion := \"\"\n\tlabel := \"\"\n\n\tif len(match) > 2 && match[2] != \"\" {\n\t\tversion = strings.ToUpper(match[2])\n\t}\n\n\tif len(match) > 3 && match[3] != \"\" {\n\t\tlabel = capitalize(match[3])\n\t}\n\n\tvar parts []string\n\tif family != \"\" {\n\t\tparts = append(parts, family)\n\t}\n\tif version != \"\" {\n\t\tparts = append(parts, version)\n\t}\n\tif label != \"\" {\n\t\tparts = append(parts, label)\n\t}\n\tif tag != \"\" {\n\t\tparts = append(parts, tag)\n\t}\n\n\treturn strings.Join(parts, \" \")\n}\n"], ["/opencode/internal/tui/theme/gruvbox.go", "package theme\n\nimport (\n\t\"github.com/charmbracelet/lipgloss\"\n)\n\n// Gruvbox color palette constants\nconst (\n\t// Dark theme colors\n\tgruvboxDarkBg0 = \"#282828\"\n\tgruvboxDarkBg0Soft = \"#32302f\"\n\tgruvboxDarkBg1 = \"#3c3836\"\n\tgruvboxDarkBg2 = \"#504945\"\n\tgruvboxDarkBg3 = \"#665c54\"\n\tgruvboxDarkBg4 = \"#7c6f64\"\n\tgruvboxDarkFg0 = \"#fbf1c7\"\n\tgruvboxDarkFg1 = \"#ebdbb2\"\n\tgruvboxDarkFg2 = \"#d5c4a1\"\n\tgruvboxDarkFg3 = \"#bdae93\"\n\tgruvboxDarkFg4 = \"#a89984\"\n\tgruvboxDarkGray = \"#928374\"\n\tgruvboxDarkRed = \"#cc241d\"\n\tgruvboxDarkRedBright = \"#fb4934\"\n\tgruvboxDarkGreen = \"#98971a\"\n\tgruvboxDarkGreenBright = \"#b8bb26\"\n\tgruvboxDarkYellow = \"#d79921\"\n\tgruvboxDarkYellowBright = \"#fabd2f\"\n\tgruvboxDarkBlue = \"#458588\"\n\tgruvboxDarkBlueBright = \"#83a598\"\n\tgruvboxDarkPurple = \"#b16286\"\n\tgruvboxDarkPurpleBright = \"#d3869b\"\n\tgruvboxDarkAqua = \"#689d6a\"\n\tgruvboxDarkAquaBright = \"#8ec07c\"\n\tgruvboxDarkOrange = \"#d65d0e\"\n\tgruvboxDarkOrangeBright = \"#fe8019\"\n\n\t// Light theme colors\n\tgruvboxLightBg0 = \"#fbf1c7\"\n\tgruvboxLightBg0Soft = \"#f2e5bc\"\n\tgruvboxLightBg1 = \"#ebdbb2\"\n\tgruvboxLightBg2 = \"#d5c4a1\"\n\tgruvboxLightBg3 = \"#bdae93\"\n\tgruvboxLightBg4 = \"#a89984\"\n\tgruvboxLightFg0 = \"#282828\"\n\tgruvboxLightFg1 = \"#3c3836\"\n\tgruvboxLightFg2 = \"#504945\"\n\tgruvboxLightFg3 = \"#665c54\"\n\tgruvboxLightFg4 = \"#7c6f64\"\n\tgruvboxLightGray = \"#928374\"\n\tgruvboxLightRed = \"#9d0006\"\n\tgruvboxLightRedBright = \"#cc241d\"\n\tgruvboxLightGreen = \"#79740e\"\n\tgruvboxLightGreenBright = \"#98971a\"\n\tgruvboxLightYellow = \"#b57614\"\n\tgruvboxLightYellowBright = \"#d79921\"\n\tgruvboxLightBlue = \"#076678\"\n\tgruvboxLightBlueBright = \"#458588\"\n\tgruvboxLightPurple = \"#8f3f71\"\n\tgruvboxLightPurpleBright = \"#b16286\"\n\tgruvboxLightAqua = \"#427b58\"\n\tgruvboxLightAquaBright = \"#689d6a\"\n\tgruvboxLightOrange = \"#af3a03\"\n\tgruvboxLightOrangeBright = \"#d65d0e\"\n)\n\n// GruvboxTheme implements the Theme interface with Gruvbox colors.\n// It provides both dark and light variants.\ntype GruvboxTheme struct {\n\tBaseTheme\n}\n\n// NewGruvboxTheme creates a new instance of the Gruvbox theme.\nfunc NewGruvboxTheme() *GruvboxTheme {\n\ttheme := &GruvboxTheme{}\n\n\t// Base colors\n\ttheme.PrimaryColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkBlueBright,\n\t\tLight: gruvboxLightBlueBright,\n\t}\n\ttheme.SecondaryColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkPurpleBright,\n\t\tLight: gruvboxLightPurpleBright,\n\t}\n\ttheme.AccentColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkOrangeBright,\n\t\tLight: gruvboxLightOrangeBright,\n\t}\n\n\t// Status colors\n\ttheme.ErrorColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkRedBright,\n\t\tLight: gruvboxLightRedBright,\n\t}\n\ttheme.WarningColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkYellowBright,\n\t\tLight: gruvboxLightYellowBright,\n\t}\n\ttheme.SuccessColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkGreenBright,\n\t\tLight: gruvboxLightGreenBright,\n\t}\n\ttheme.InfoColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkBlueBright,\n\t\tLight: gruvboxLightBlueBright,\n\t}\n\n\t// Text colors\n\ttheme.TextColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkFg1,\n\t\tLight: gruvboxLightFg1,\n\t}\n\ttheme.TextMutedColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkFg4,\n\t\tLight: gruvboxLightFg4,\n\t}\n\ttheme.TextEmphasizedColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkYellowBright,\n\t\tLight: gruvboxLightYellowBright,\n\t}\n\n\t// Background colors\n\ttheme.BackgroundColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkBg0,\n\t\tLight: gruvboxLightBg0,\n\t}\n\ttheme.BackgroundSecondaryColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkBg1,\n\t\tLight: gruvboxLightBg1,\n\t}\n\ttheme.BackgroundDarkerColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkBg0Soft,\n\t\tLight: gruvboxLightBg0Soft,\n\t}\n\n\t// Border colors\n\ttheme.BorderNormalColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkBg2,\n\t\tLight: gruvboxLightBg2,\n\t}\n\ttheme.BorderFocusedColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkBlueBright,\n\t\tLight: gruvboxLightBlueBright,\n\t}\n\ttheme.BorderDimColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkBg1,\n\t\tLight: gruvboxLightBg1,\n\t}\n\n\t// Diff view colors\n\ttheme.DiffAddedColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkGreenBright,\n\t\tLight: gruvboxLightGreenBright,\n\t}\n\ttheme.DiffRemovedColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkRedBright,\n\t\tLight: gruvboxLightRedBright,\n\t}\n\ttheme.DiffContextColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkFg4,\n\t\tLight: gruvboxLightFg4,\n\t}\n\ttheme.DiffHunkHeaderColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkFg3,\n\t\tLight: gruvboxLightFg3,\n\t}\n\ttheme.DiffHighlightAddedColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkGreenBright,\n\t\tLight: gruvboxLightGreenBright,\n\t}\n\ttheme.DiffHighlightRemovedColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkRedBright,\n\t\tLight: gruvboxLightRedBright,\n\t}\n\ttheme.DiffAddedBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#3C4C3C\", // Darker green background\n\t\tLight: \"#E8F5E9\", // Light green background\n\t}\n\ttheme.DiffRemovedBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#4C3C3C\", // Darker red background\n\t\tLight: \"#FFEBEE\", // Light red background\n\t}\n\ttheme.DiffContextBgColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkBg0,\n\t\tLight: gruvboxLightBg0,\n\t}\n\ttheme.DiffLineNumberColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkFg4,\n\t\tLight: gruvboxLightFg4,\n\t}\n\ttheme.DiffAddedLineNumberBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#32432F\", // Slightly darker green\n\t\tLight: \"#C8E6C9\", // Light green\n\t}\n\ttheme.DiffRemovedLineNumberBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#43322F\", // Slightly darker red\n\t\tLight: \"#FFCDD2\", // Light red\n\t}\n\n\t// Markdown colors\n\ttheme.MarkdownTextColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkFg1,\n\t\tLight: gruvboxLightFg1,\n\t}\n\ttheme.MarkdownHeadingColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkYellowBright,\n\t\tLight: gruvboxLightYellowBright,\n\t}\n\ttheme.MarkdownLinkColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkBlueBright,\n\t\tLight: gruvboxLightBlueBright,\n\t}\n\ttheme.MarkdownLinkTextColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkAquaBright,\n\t\tLight: gruvboxLightAquaBright,\n\t}\n\ttheme.MarkdownCodeColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkGreenBright,\n\t\tLight: gruvboxLightGreenBright,\n\t}\n\ttheme.MarkdownBlockQuoteColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkAquaBright,\n\t\tLight: gruvboxLightAquaBright,\n\t}\n\ttheme.MarkdownEmphColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkYellowBright,\n\t\tLight: gruvboxLightYellowBright,\n\t}\n\ttheme.MarkdownStrongColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkOrangeBright,\n\t\tLight: gruvboxLightOrangeBright,\n\t}\n\ttheme.MarkdownHorizontalRuleColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkBg3,\n\t\tLight: gruvboxLightBg3,\n\t}\n\ttheme.MarkdownListItemColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkBlueBright,\n\t\tLight: gruvboxLightBlueBright,\n\t}\n\ttheme.MarkdownListEnumerationColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkBlueBright,\n\t\tLight: gruvboxLightBlueBright,\n\t}\n\ttheme.MarkdownImageColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkPurpleBright,\n\t\tLight: gruvboxLightPurpleBright,\n\t}\n\ttheme.MarkdownImageTextColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkAquaBright,\n\t\tLight: gruvboxLightAquaBright,\n\t}\n\ttheme.MarkdownCodeBlockColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkFg1,\n\t\tLight: gruvboxLightFg1,\n\t}\n\n\t// Syntax highlighting colors\n\ttheme.SyntaxCommentColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkGray,\n\t\tLight: gruvboxLightGray,\n\t}\n\ttheme.SyntaxKeywordColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkRedBright,\n\t\tLight: gruvboxLightRedBright,\n\t}\n\ttheme.SyntaxFunctionColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkGreenBright,\n\t\tLight: gruvboxLightGreenBright,\n\t}\n\ttheme.SyntaxVariableColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkBlueBright,\n\t\tLight: gruvboxLightBlueBright,\n\t}\n\ttheme.SyntaxStringColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkYellowBright,\n\t\tLight: gruvboxLightYellowBright,\n\t}\n\ttheme.SyntaxNumberColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkPurpleBright,\n\t\tLight: gruvboxLightPurpleBright,\n\t}\n\ttheme.SyntaxTypeColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkYellow,\n\t\tLight: gruvboxLightYellow,\n\t}\n\ttheme.SyntaxOperatorColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkAquaBright,\n\t\tLight: gruvboxLightAquaBright,\n\t}\n\ttheme.SyntaxPunctuationColor = lipgloss.AdaptiveColor{\n\t\tDark: gruvboxDarkFg1,\n\t\tLight: gruvboxLightFg1,\n\t}\n\n\treturn theme\n}\n\nfunc init() {\n\t// Register the Gruvbox theme with the theme manager\n\tRegisterTheme(\"gruvbox\", NewGruvboxTheme())\n}"], ["/opencode/internal/tui/theme/opencode.go", "package theme\n\nimport (\n\t\"github.com/charmbracelet/lipgloss\"\n)\n\n// OpenCodeTheme implements the Theme interface with OpenCode brand colors.\n// It provides both dark and light variants.\ntype OpenCodeTheme struct {\n\tBaseTheme\n}\n\n// NewOpenCodeTheme creates a new instance of the OpenCode theme.\nfunc NewOpenCodeTheme() *OpenCodeTheme {\n\t// OpenCode color palette\n\t// Dark mode colors\n\tdarkBackground := \"#212121\"\n\tdarkCurrentLine := \"#252525\"\n\tdarkSelection := \"#303030\"\n\tdarkForeground := \"#e0e0e0\"\n\tdarkComment := \"#6a6a6a\"\n\tdarkPrimary := \"#fab283\" // Primary orange/gold\n\tdarkSecondary := \"#5c9cf5\" // Secondary blue\n\tdarkAccent := \"#9d7cd8\" // Accent purple\n\tdarkRed := \"#e06c75\" // Error red\n\tdarkOrange := \"#f5a742\" // Warning orange\n\tdarkGreen := \"#7fd88f\" // Success green\n\tdarkCyan := \"#56b6c2\" // Info cyan\n\tdarkYellow := \"#e5c07b\" // Emphasized text\n\tdarkBorder := \"#4b4c5c\" // Border color\n\n\t// Light mode colors\n\tlightBackground := \"#f8f8f8\"\n\tlightCurrentLine := \"#f0f0f0\"\n\tlightSelection := \"#e5e5e6\"\n\tlightForeground := \"#2a2a2a\"\n\tlightComment := \"#8a8a8a\"\n\tlightPrimary := \"#3b7dd8\" // Primary blue\n\tlightSecondary := \"#7b5bb6\" // Secondary purple\n\tlightAccent := \"#d68c27\" // Accent orange/gold\n\tlightRed := \"#d1383d\" // Error red\n\tlightOrange := \"#d68c27\" // Warning orange\n\tlightGreen := \"#3d9a57\" // Success green\n\tlightCyan := \"#318795\" // Info cyan\n\tlightYellow := \"#b0851f\" // Emphasized text\n\tlightBorder := \"#d3d3d3\" // Border color\n\n\ttheme := &OpenCodeTheme{}\n\n\t// Base colors\n\ttheme.PrimaryColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPrimary,\n\t\tLight: lightPrimary,\n\t}\n\ttheme.SecondaryColor = lipgloss.AdaptiveColor{\n\t\tDark: darkSecondary,\n\t\tLight: lightSecondary,\n\t}\n\ttheme.AccentColor = lipgloss.AdaptiveColor{\n\t\tDark: darkAccent,\n\t\tLight: lightAccent,\n\t}\n\n\t// Status colors\n\ttheme.ErrorColor = lipgloss.AdaptiveColor{\n\t\tDark: darkRed,\n\t\tLight: lightRed,\n\t}\n\ttheme.WarningColor = lipgloss.AdaptiveColor{\n\t\tDark: darkOrange,\n\t\tLight: lightOrange,\n\t}\n\ttheme.SuccessColor = lipgloss.AdaptiveColor{\n\t\tDark: darkGreen,\n\t\tLight: lightGreen,\n\t}\n\ttheme.InfoColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\n\t// Text colors\n\ttheme.TextColor = lipgloss.AdaptiveColor{\n\t\tDark: darkForeground,\n\t\tLight: lightForeground,\n\t}\n\ttheme.TextMutedColor = lipgloss.AdaptiveColor{\n\t\tDark: darkComment,\n\t\tLight: lightComment,\n\t}\n\ttheme.TextEmphasizedColor = lipgloss.AdaptiveColor{\n\t\tDark: darkYellow,\n\t\tLight: lightYellow,\n\t}\n\n\t// Background colors\n\ttheme.BackgroundColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBackground,\n\t\tLight: lightBackground,\n\t}\n\ttheme.BackgroundSecondaryColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCurrentLine,\n\t\tLight: lightCurrentLine,\n\t}\n\ttheme.BackgroundDarkerColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#121212\", // Slightly darker than background\n\t\tLight: \"#ffffff\", // Slightly lighter than background\n\t}\n\n\t// Border colors\n\ttheme.BorderNormalColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBorder,\n\t\tLight: lightBorder,\n\t}\n\ttheme.BorderFocusedColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPrimary,\n\t\tLight: lightPrimary,\n\t}\n\ttheme.BorderDimColor = lipgloss.AdaptiveColor{\n\t\tDark: darkSelection,\n\t\tLight: lightSelection,\n\t}\n\n\t// Diff view colors\n\ttheme.DiffAddedColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#478247\",\n\t\tLight: \"#2E7D32\",\n\t}\n\ttheme.DiffRemovedColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#7C4444\",\n\t\tLight: \"#C62828\",\n\t}\n\ttheme.DiffContextColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#a0a0a0\",\n\t\tLight: \"#757575\",\n\t}\n\ttheme.DiffHunkHeaderColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#a0a0a0\",\n\t\tLight: \"#757575\",\n\t}\n\ttheme.DiffHighlightAddedColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#DAFADA\",\n\t\tLight: \"#A5D6A7\",\n\t}\n\ttheme.DiffHighlightRemovedColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#FADADD\",\n\t\tLight: \"#EF9A9A\",\n\t}\n\ttheme.DiffAddedBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#303A30\",\n\t\tLight: \"#E8F5E9\",\n\t}\n\ttheme.DiffRemovedBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#3A3030\",\n\t\tLight: \"#FFEBEE\",\n\t}\n\ttheme.DiffContextBgColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBackground,\n\t\tLight: lightBackground,\n\t}\n\ttheme.DiffLineNumberColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#888888\",\n\t\tLight: \"#9E9E9E\",\n\t}\n\ttheme.DiffAddedLineNumberBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#293229\",\n\t\tLight: \"#C8E6C9\",\n\t}\n\ttheme.DiffRemovedLineNumberBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#332929\",\n\t\tLight: \"#FFCDD2\",\n\t}\n\n\t// Markdown colors\n\ttheme.MarkdownTextColor = lipgloss.AdaptiveColor{\n\t\tDark: darkForeground,\n\t\tLight: lightForeground,\n\t}\n\ttheme.MarkdownHeadingColor = lipgloss.AdaptiveColor{\n\t\tDark: darkSecondary,\n\t\tLight: lightSecondary,\n\t}\n\ttheme.MarkdownLinkColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPrimary,\n\t\tLight: lightPrimary,\n\t}\n\ttheme.MarkdownLinkTextColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.MarkdownCodeColor = lipgloss.AdaptiveColor{\n\t\tDark: darkGreen,\n\t\tLight: lightGreen,\n\t}\n\ttheme.MarkdownBlockQuoteColor = lipgloss.AdaptiveColor{\n\t\tDark: darkYellow,\n\t\tLight: lightYellow,\n\t}\n\ttheme.MarkdownEmphColor = lipgloss.AdaptiveColor{\n\t\tDark: darkYellow,\n\t\tLight: lightYellow,\n\t}\n\ttheme.MarkdownStrongColor = lipgloss.AdaptiveColor{\n\t\tDark: darkAccent,\n\t\tLight: lightAccent,\n\t}\n\ttheme.MarkdownHorizontalRuleColor = lipgloss.AdaptiveColor{\n\t\tDark: darkComment,\n\t\tLight: lightComment,\n\t}\n\ttheme.MarkdownListItemColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPrimary,\n\t\tLight: lightPrimary,\n\t}\n\ttheme.MarkdownListEnumerationColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.MarkdownImageColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPrimary,\n\t\tLight: lightPrimary,\n\t}\n\ttheme.MarkdownImageTextColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.MarkdownCodeBlockColor = lipgloss.AdaptiveColor{\n\t\tDark: darkForeground,\n\t\tLight: lightForeground,\n\t}\n\n\t// Syntax highlighting colors\n\ttheme.SyntaxCommentColor = lipgloss.AdaptiveColor{\n\t\tDark: darkComment,\n\t\tLight: lightComment,\n\t}\n\ttheme.SyntaxKeywordColor = lipgloss.AdaptiveColor{\n\t\tDark: darkSecondary,\n\t\tLight: lightSecondary,\n\t}\n\ttheme.SyntaxFunctionColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPrimary,\n\t\tLight: lightPrimary,\n\t}\n\ttheme.SyntaxVariableColor = lipgloss.AdaptiveColor{\n\t\tDark: darkRed,\n\t\tLight: lightRed,\n\t}\n\ttheme.SyntaxStringColor = lipgloss.AdaptiveColor{\n\t\tDark: darkGreen,\n\t\tLight: lightGreen,\n\t}\n\ttheme.SyntaxNumberColor = lipgloss.AdaptiveColor{\n\t\tDark: darkAccent,\n\t\tLight: lightAccent,\n\t}\n\ttheme.SyntaxTypeColor = lipgloss.AdaptiveColor{\n\t\tDark: darkYellow,\n\t\tLight: lightYellow,\n\t}\n\ttheme.SyntaxOperatorColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.SyntaxPunctuationColor = lipgloss.AdaptiveColor{\n\t\tDark: darkForeground,\n\t\tLight: lightForeground,\n\t}\n\n\treturn theme\n}\n\nfunc init() {\n\t// Register the OpenCode theme with the theme manager\n\tRegisterTheme(\"opencode\", NewOpenCodeTheme())\n}\n\n"], ["/opencode/internal/tui/theme/catppuccin.go", "package theme\n\nimport (\n\tcatppuccin \"github.com/catppuccin/go\"\n\t\"github.com/charmbracelet/lipgloss\"\n)\n\n// CatppuccinTheme implements the Theme interface with Catppuccin colors.\n// It provides both dark (Mocha) and light (Latte) variants.\ntype CatppuccinTheme struct {\n\tBaseTheme\n}\n\n// NewCatppuccinTheme creates a new instance of the Catppuccin theme.\nfunc NewCatppuccinTheme() *CatppuccinTheme {\n\t// Get the Catppuccin palettes\n\tmocha := catppuccin.Mocha\n\tlatte := catppuccin.Latte\n\n\ttheme := &CatppuccinTheme{}\n\n\t// Base colors\n\ttheme.PrimaryColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Blue().Hex,\n\t\tLight: latte.Blue().Hex,\n\t}\n\ttheme.SecondaryColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Mauve().Hex,\n\t\tLight: latte.Mauve().Hex,\n\t}\n\ttheme.AccentColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Peach().Hex,\n\t\tLight: latte.Peach().Hex,\n\t}\n\n\t// Status colors\n\ttheme.ErrorColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Red().Hex,\n\t\tLight: latte.Red().Hex,\n\t}\n\ttheme.WarningColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Peach().Hex,\n\t\tLight: latte.Peach().Hex,\n\t}\n\ttheme.SuccessColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Green().Hex,\n\t\tLight: latte.Green().Hex,\n\t}\n\ttheme.InfoColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Blue().Hex,\n\t\tLight: latte.Blue().Hex,\n\t}\n\n\t// Text colors\n\ttheme.TextColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Text().Hex,\n\t\tLight: latte.Text().Hex,\n\t}\n\ttheme.TextMutedColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Subtext0().Hex,\n\t\tLight: latte.Subtext0().Hex,\n\t}\n\ttheme.TextEmphasizedColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Lavender().Hex,\n\t\tLight: latte.Lavender().Hex,\n\t}\n\n\t// Background colors\n\ttheme.BackgroundColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#212121\", // From existing styles\n\t\tLight: \"#EEEEEE\", // Light equivalent\n\t}\n\ttheme.BackgroundSecondaryColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#2c2c2c\", // From existing styles\n\t\tLight: \"#E0E0E0\", // Light equivalent\n\t}\n\ttheme.BackgroundDarkerColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#181818\", // From existing styles\n\t\tLight: \"#F5F5F5\", // Light equivalent\n\t}\n\n\t// Border colors\n\ttheme.BorderNormalColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#4b4c5c\", // From existing styles\n\t\tLight: \"#BDBDBD\", // Light equivalent\n\t}\n\ttheme.BorderFocusedColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Blue().Hex,\n\t\tLight: latte.Blue().Hex,\n\t}\n\ttheme.BorderDimColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Surface0().Hex,\n\t\tLight: latte.Surface0().Hex,\n\t}\n\n\t// Diff view colors\n\ttheme.DiffAddedColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#478247\", // From existing diff.go\n\t\tLight: \"#2E7D32\", // Light equivalent\n\t}\n\ttheme.DiffRemovedColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#7C4444\", // From existing diff.go\n\t\tLight: \"#C62828\", // Light equivalent\n\t}\n\ttheme.DiffContextColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#a0a0a0\", // From existing diff.go\n\t\tLight: \"#757575\", // Light equivalent\n\t}\n\ttheme.DiffHunkHeaderColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#a0a0a0\", // From existing diff.go\n\t\tLight: \"#757575\", // Light equivalent\n\t}\n\ttheme.DiffHighlightAddedColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#DAFADA\", // From existing diff.go\n\t\tLight: \"#A5D6A7\", // Light equivalent\n\t}\n\ttheme.DiffHighlightRemovedColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#FADADD\", // From existing diff.go\n\t\tLight: \"#EF9A9A\", // Light equivalent\n\t}\n\ttheme.DiffAddedBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#303A30\", // From existing diff.go\n\t\tLight: \"#E8F5E9\", // Light equivalent\n\t}\n\ttheme.DiffRemovedBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#3A3030\", // From existing diff.go\n\t\tLight: \"#FFEBEE\", // Light equivalent\n\t}\n\ttheme.DiffContextBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#212121\", // From existing diff.go\n\t\tLight: \"#F5F5F5\", // Light equivalent\n\t}\n\ttheme.DiffLineNumberColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#888888\", // From existing diff.go\n\t\tLight: \"#9E9E9E\", // Light equivalent\n\t}\n\ttheme.DiffAddedLineNumberBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#293229\", // From existing diff.go\n\t\tLight: \"#C8E6C9\", // Light equivalent\n\t}\n\ttheme.DiffRemovedLineNumberBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#332929\", // From existing diff.go\n\t\tLight: \"#FFCDD2\", // Light equivalent\n\t}\n\n\t// Markdown colors\n\ttheme.MarkdownTextColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Text().Hex,\n\t\tLight: latte.Text().Hex,\n\t}\n\ttheme.MarkdownHeadingColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Mauve().Hex,\n\t\tLight: latte.Mauve().Hex,\n\t}\n\ttheme.MarkdownLinkColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Sky().Hex,\n\t\tLight: latte.Sky().Hex,\n\t}\n\ttheme.MarkdownLinkTextColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Pink().Hex,\n\t\tLight: latte.Pink().Hex,\n\t}\n\ttheme.MarkdownCodeColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Green().Hex,\n\t\tLight: latte.Green().Hex,\n\t}\n\ttheme.MarkdownBlockQuoteColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Yellow().Hex,\n\t\tLight: latte.Yellow().Hex,\n\t}\n\ttheme.MarkdownEmphColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Yellow().Hex,\n\t\tLight: latte.Yellow().Hex,\n\t}\n\ttheme.MarkdownStrongColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Peach().Hex,\n\t\tLight: latte.Peach().Hex,\n\t}\n\ttheme.MarkdownHorizontalRuleColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Overlay0().Hex,\n\t\tLight: latte.Overlay0().Hex,\n\t}\n\ttheme.MarkdownListItemColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Blue().Hex,\n\t\tLight: latte.Blue().Hex,\n\t}\n\ttheme.MarkdownListEnumerationColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Sky().Hex,\n\t\tLight: latte.Sky().Hex,\n\t}\n\ttheme.MarkdownImageColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Sapphire().Hex,\n\t\tLight: latte.Sapphire().Hex,\n\t}\n\ttheme.MarkdownImageTextColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Pink().Hex,\n\t\tLight: latte.Pink().Hex,\n\t}\n\ttheme.MarkdownCodeBlockColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Text().Hex,\n\t\tLight: latte.Text().Hex,\n\t}\n\n\t// Syntax highlighting colors\n\ttheme.SyntaxCommentColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Overlay1().Hex,\n\t\tLight: latte.Overlay1().Hex,\n\t}\n\ttheme.SyntaxKeywordColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Pink().Hex,\n\t\tLight: latte.Pink().Hex,\n\t}\n\ttheme.SyntaxFunctionColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Green().Hex,\n\t\tLight: latte.Green().Hex,\n\t}\n\ttheme.SyntaxVariableColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Sky().Hex,\n\t\tLight: latte.Sky().Hex,\n\t}\n\ttheme.SyntaxStringColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Yellow().Hex,\n\t\tLight: latte.Yellow().Hex,\n\t}\n\ttheme.SyntaxNumberColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Teal().Hex,\n\t\tLight: latte.Teal().Hex,\n\t}\n\ttheme.SyntaxTypeColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Sky().Hex,\n\t\tLight: latte.Sky().Hex,\n\t}\n\ttheme.SyntaxOperatorColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Pink().Hex,\n\t\tLight: latte.Pink().Hex,\n\t}\n\ttheme.SyntaxPunctuationColor = lipgloss.AdaptiveColor{\n\t\tDark: mocha.Text().Hex,\n\t\tLight: latte.Text().Hex,\n\t}\n\n\treturn theme\n}\n\nfunc init() {\n\t// Register the Catppuccin theme with the theme manager\n\tRegisterTheme(\"catppuccin\", NewCatppuccinTheme())\n}"], ["/opencode/internal/tui/theme/onedark.go", "package theme\n\nimport (\n\t\"github.com/charmbracelet/lipgloss\"\n)\n\n// OneDarkTheme implements the Theme interface with Atom's One Dark colors.\n// It provides both dark and light variants.\ntype OneDarkTheme struct {\n\tBaseTheme\n}\n\n// NewOneDarkTheme creates a new instance of the One Dark theme.\nfunc NewOneDarkTheme() *OneDarkTheme {\n\t// One Dark color palette\n\t// Dark mode colors from Atom One Dark\n\tdarkBackground := \"#282c34\"\n\tdarkCurrentLine := \"#2c313c\"\n\tdarkSelection := \"#3e4451\"\n\tdarkForeground := \"#abb2bf\"\n\tdarkComment := \"#5c6370\"\n\tdarkRed := \"#e06c75\"\n\tdarkOrange := \"#d19a66\"\n\tdarkYellow := \"#e5c07b\"\n\tdarkGreen := \"#98c379\"\n\tdarkCyan := \"#56b6c2\"\n\tdarkBlue := \"#61afef\"\n\tdarkPurple := \"#c678dd\"\n\tdarkBorder := \"#3b4048\"\n\n\t// Light mode colors from Atom One Light\n\tlightBackground := \"#fafafa\"\n\tlightCurrentLine := \"#f0f0f0\"\n\tlightSelection := \"#e5e5e6\"\n\tlightForeground := \"#383a42\"\n\tlightComment := \"#a0a1a7\"\n\tlightRed := \"#e45649\"\n\tlightOrange := \"#da8548\"\n\tlightYellow := \"#c18401\"\n\tlightGreen := \"#50a14f\"\n\tlightCyan := \"#0184bc\"\n\tlightBlue := \"#4078f2\"\n\tlightPurple := \"#a626a4\"\n\tlightBorder := \"#d3d3d3\"\n\n\ttheme := &OneDarkTheme{}\n\n\t// Base colors\n\ttheme.PrimaryColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBlue,\n\t\tLight: lightBlue,\n\t}\n\ttheme.SecondaryColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPurple,\n\t\tLight: lightPurple,\n\t}\n\ttheme.AccentColor = lipgloss.AdaptiveColor{\n\t\tDark: darkOrange,\n\t\tLight: lightOrange,\n\t}\n\n\t// Status colors\n\ttheme.ErrorColor = lipgloss.AdaptiveColor{\n\t\tDark: darkRed,\n\t\tLight: lightRed,\n\t}\n\ttheme.WarningColor = lipgloss.AdaptiveColor{\n\t\tDark: darkOrange,\n\t\tLight: lightOrange,\n\t}\n\ttheme.SuccessColor = lipgloss.AdaptiveColor{\n\t\tDark: darkGreen,\n\t\tLight: lightGreen,\n\t}\n\ttheme.InfoColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBlue,\n\t\tLight: lightBlue,\n\t}\n\n\t// Text colors\n\ttheme.TextColor = lipgloss.AdaptiveColor{\n\t\tDark: darkForeground,\n\t\tLight: lightForeground,\n\t}\n\ttheme.TextMutedColor = lipgloss.AdaptiveColor{\n\t\tDark: darkComment,\n\t\tLight: lightComment,\n\t}\n\ttheme.TextEmphasizedColor = lipgloss.AdaptiveColor{\n\t\tDark: darkYellow,\n\t\tLight: lightYellow,\n\t}\n\n\t// Background colors\n\ttheme.BackgroundColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBackground,\n\t\tLight: lightBackground,\n\t}\n\ttheme.BackgroundSecondaryColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCurrentLine,\n\t\tLight: lightCurrentLine,\n\t}\n\ttheme.BackgroundDarkerColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#21252b\", // Slightly darker than background\n\t\tLight: \"#ffffff\", // Slightly lighter than background\n\t}\n\n\t// Border colors\n\ttheme.BorderNormalColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBorder,\n\t\tLight: lightBorder,\n\t}\n\ttheme.BorderFocusedColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBlue,\n\t\tLight: lightBlue,\n\t}\n\ttheme.BorderDimColor = lipgloss.AdaptiveColor{\n\t\tDark: darkSelection,\n\t\tLight: lightSelection,\n\t}\n\n\t// Diff view colors\n\ttheme.DiffAddedColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#478247\",\n\t\tLight: \"#2E7D32\",\n\t}\n\ttheme.DiffRemovedColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#7C4444\",\n\t\tLight: \"#C62828\",\n\t}\n\ttheme.DiffContextColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#a0a0a0\",\n\t\tLight: \"#757575\",\n\t}\n\ttheme.DiffHunkHeaderColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#a0a0a0\",\n\t\tLight: \"#757575\",\n\t}\n\ttheme.DiffHighlightAddedColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#DAFADA\",\n\t\tLight: \"#A5D6A7\",\n\t}\n\ttheme.DiffHighlightRemovedColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#FADADD\",\n\t\tLight: \"#EF9A9A\",\n\t}\n\ttheme.DiffAddedBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#303A30\",\n\t\tLight: \"#E8F5E9\",\n\t}\n\ttheme.DiffRemovedBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#3A3030\",\n\t\tLight: \"#FFEBEE\",\n\t}\n\ttheme.DiffContextBgColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBackground,\n\t\tLight: lightBackground,\n\t}\n\ttheme.DiffLineNumberColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#888888\",\n\t\tLight: \"#9E9E9E\",\n\t}\n\ttheme.DiffAddedLineNumberBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#293229\",\n\t\tLight: \"#C8E6C9\",\n\t}\n\ttheme.DiffRemovedLineNumberBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#332929\",\n\t\tLight: \"#FFCDD2\",\n\t}\n\n\t// Markdown colors\n\ttheme.MarkdownTextColor = lipgloss.AdaptiveColor{\n\t\tDark: darkForeground,\n\t\tLight: lightForeground,\n\t}\n\ttheme.MarkdownHeadingColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPurple,\n\t\tLight: lightPurple,\n\t}\n\ttheme.MarkdownLinkColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBlue,\n\t\tLight: lightBlue,\n\t}\n\ttheme.MarkdownLinkTextColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.MarkdownCodeColor = lipgloss.AdaptiveColor{\n\t\tDark: darkGreen,\n\t\tLight: lightGreen,\n\t}\n\ttheme.MarkdownBlockQuoteColor = lipgloss.AdaptiveColor{\n\t\tDark: darkYellow,\n\t\tLight: lightYellow,\n\t}\n\ttheme.MarkdownEmphColor = lipgloss.AdaptiveColor{\n\t\tDark: darkYellow,\n\t\tLight: lightYellow,\n\t}\n\ttheme.MarkdownStrongColor = lipgloss.AdaptiveColor{\n\t\tDark: darkOrange,\n\t\tLight: lightOrange,\n\t}\n\ttheme.MarkdownHorizontalRuleColor = lipgloss.AdaptiveColor{\n\t\tDark: darkComment,\n\t\tLight: lightComment,\n\t}\n\ttheme.MarkdownListItemColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBlue,\n\t\tLight: lightBlue,\n\t}\n\ttheme.MarkdownListEnumerationColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.MarkdownImageColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBlue,\n\t\tLight: lightBlue,\n\t}\n\ttheme.MarkdownImageTextColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.MarkdownCodeBlockColor = lipgloss.AdaptiveColor{\n\t\tDark: darkForeground,\n\t\tLight: lightForeground,\n\t}\n\n\t// Syntax highlighting colors\n\ttheme.SyntaxCommentColor = lipgloss.AdaptiveColor{\n\t\tDark: darkComment,\n\t\tLight: lightComment,\n\t}\n\ttheme.SyntaxKeywordColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPurple,\n\t\tLight: lightPurple,\n\t}\n\ttheme.SyntaxFunctionColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBlue,\n\t\tLight: lightBlue,\n\t}\n\ttheme.SyntaxVariableColor = lipgloss.AdaptiveColor{\n\t\tDark: darkRed,\n\t\tLight: lightRed,\n\t}\n\ttheme.SyntaxStringColor = lipgloss.AdaptiveColor{\n\t\tDark: darkGreen,\n\t\tLight: lightGreen,\n\t}\n\ttheme.SyntaxNumberColor = lipgloss.AdaptiveColor{\n\t\tDark: darkOrange,\n\t\tLight: lightOrange,\n\t}\n\ttheme.SyntaxTypeColor = lipgloss.AdaptiveColor{\n\t\tDark: darkYellow,\n\t\tLight: lightYellow,\n\t}\n\ttheme.SyntaxOperatorColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.SyntaxPunctuationColor = lipgloss.AdaptiveColor{\n\t\tDark: darkForeground,\n\t\tLight: lightForeground,\n\t}\n\n\treturn theme\n}\n\nfunc init() {\n\t// Register the One Dark theme with the theme manager\n\tRegisterTheme(\"onedark\", NewOneDarkTheme())\n}"], ["/opencode/internal/tui/theme/flexoki.go", "package theme\n\nimport (\n\t\"github.com/charmbracelet/lipgloss\"\n)\n\n// Flexoki color palette constants\nconst (\n\t// Base colors\n\tflexokiPaper = \"#FFFCF0\" // Paper (lightest)\n\tflexokiBase50 = \"#F2F0E5\" // bg-2 (light)\n\tflexokiBase100 = \"#E6E4D9\" // ui (light)\n\tflexokiBase150 = \"#DAD8CE\" // ui-2 (light)\n\tflexokiBase200 = \"#CECDC3\" // ui-3 (light)\n\tflexokiBase300 = \"#B7B5AC\" // tx-3 (light)\n\tflexokiBase500 = \"#878580\" // tx-2 (light)\n\tflexokiBase600 = \"#6F6E69\" // tx (light)\n\tflexokiBase700 = \"#575653\" // tx-3 (dark)\n\tflexokiBase800 = \"#403E3C\" // ui-3 (dark)\n\tflexokiBase850 = \"#343331\" // ui-2 (dark)\n\tflexokiBase900 = \"#282726\" // ui (dark)\n\tflexokiBase950 = \"#1C1B1A\" // bg-2 (dark)\n\tflexokiBlack = \"#100F0F\" // bg (darkest)\n\n\t// Accent colors - Light theme (600)\n\tflexokiRed600 = \"#AF3029\"\n\tflexokiOrange600 = \"#BC5215\"\n\tflexokiYellow600 = \"#AD8301\"\n\tflexokiGreen600 = \"#66800B\"\n\tflexokiCyan600 = \"#24837B\"\n\tflexokiBlue600 = \"#205EA6\"\n\tflexokiPurple600 = \"#5E409D\"\n\tflexokiMagenta600 = \"#A02F6F\"\n\n\t// Accent colors - Dark theme (400)\n\tflexokiRed400 = \"#D14D41\"\n\tflexokiOrange400 = \"#DA702C\"\n\tflexokiYellow400 = \"#D0A215\"\n\tflexokiGreen400 = \"#879A39\"\n\tflexokiCyan400 = \"#3AA99F\"\n\tflexokiBlue400 = \"#4385BE\"\n\tflexokiPurple400 = \"#8B7EC8\"\n\tflexokiMagenta400 = \"#CE5D97\"\n)\n\n// FlexokiTheme implements the Theme interface with Flexoki colors.\n// It provides both dark and light variants.\ntype FlexokiTheme struct {\n\tBaseTheme\n}\n\n// NewFlexokiTheme creates a new instance of the Flexoki theme.\nfunc NewFlexokiTheme() *FlexokiTheme {\n\ttheme := &FlexokiTheme{}\n\n\t// Base colors\n\ttheme.PrimaryColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiBlue400,\n\t\tLight: flexokiBlue600,\n\t}\n\ttheme.SecondaryColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiPurple400,\n\t\tLight: flexokiPurple600,\n\t}\n\ttheme.AccentColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiOrange400,\n\t\tLight: flexokiOrange600,\n\t}\n\n\t// Status colors\n\ttheme.ErrorColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiRed400,\n\t\tLight: flexokiRed600,\n\t}\n\ttheme.WarningColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiYellow400,\n\t\tLight: flexokiYellow600,\n\t}\n\ttheme.SuccessColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiGreen400,\n\t\tLight: flexokiGreen600,\n\t}\n\ttheme.InfoColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiCyan400,\n\t\tLight: flexokiCyan600,\n\t}\n\n\t// Text colors\n\ttheme.TextColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiBase300,\n\t\tLight: flexokiBase600,\n\t}\n\ttheme.TextMutedColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiBase700,\n\t\tLight: flexokiBase500,\n\t}\n\ttheme.TextEmphasizedColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiYellow400,\n\t\tLight: flexokiYellow600,\n\t}\n\n\t// Background colors\n\ttheme.BackgroundColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiBlack,\n\t\tLight: flexokiPaper,\n\t}\n\ttheme.BackgroundSecondaryColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiBase950,\n\t\tLight: flexokiBase50,\n\t}\n\ttheme.BackgroundDarkerColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiBase900,\n\t\tLight: flexokiBase100,\n\t}\n\n\t// Border colors\n\ttheme.BorderNormalColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiBase900,\n\t\tLight: flexokiBase100,\n\t}\n\ttheme.BorderFocusedColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiBlue400,\n\t\tLight: flexokiBlue600,\n\t}\n\ttheme.BorderDimColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiBase850,\n\t\tLight: flexokiBase150,\n\t}\n\n\t// Diff view colors\n\ttheme.DiffAddedColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiGreen400,\n\t\tLight: flexokiGreen600,\n\t}\n\ttheme.DiffRemovedColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiRed400,\n\t\tLight: flexokiRed600,\n\t}\n\ttheme.DiffContextColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiBase700,\n\t\tLight: flexokiBase500,\n\t}\n\ttheme.DiffHunkHeaderColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiBase700,\n\t\tLight: flexokiBase500,\n\t}\n\ttheme.DiffHighlightAddedColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiGreen400,\n\t\tLight: flexokiGreen600,\n\t}\n\ttheme.DiffHighlightRemovedColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiRed400,\n\t\tLight: flexokiRed600,\n\t}\n\ttheme.DiffAddedBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#1D2419\", // Darker green background\n\t\tLight: \"#EFF2E2\", // Light green background\n\t}\n\ttheme.DiffRemovedBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#241919\", // Darker red background\n\t\tLight: \"#F2E2E2\", // Light red background\n\t}\n\ttheme.DiffContextBgColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiBlack,\n\t\tLight: flexokiPaper,\n\t}\n\ttheme.DiffLineNumberColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiBase700,\n\t\tLight: flexokiBase500,\n\t}\n\ttheme.DiffAddedLineNumberBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#1A2017\", // Slightly darker green\n\t\tLight: \"#E5EBD9\", // Light green\n\t}\n\ttheme.DiffRemovedLineNumberBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#201717\", // Slightly darker red\n\t\tLight: \"#EBD9D9\", // Light red\n\t}\n\n\t// Markdown colors\n\ttheme.MarkdownTextColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiBase300,\n\t\tLight: flexokiBase600,\n\t}\n\ttheme.MarkdownHeadingColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiYellow400,\n\t\tLight: flexokiYellow600,\n\t}\n\ttheme.MarkdownLinkColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiCyan400,\n\t\tLight: flexokiCyan600,\n\t}\n\ttheme.MarkdownLinkTextColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiMagenta400,\n\t\tLight: flexokiMagenta600,\n\t}\n\ttheme.MarkdownCodeColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiGreen400,\n\t\tLight: flexokiGreen600,\n\t}\n\ttheme.MarkdownBlockQuoteColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiCyan400,\n\t\tLight: flexokiCyan600,\n\t}\n\ttheme.MarkdownEmphColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiYellow400,\n\t\tLight: flexokiYellow600,\n\t}\n\ttheme.MarkdownStrongColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiOrange400,\n\t\tLight: flexokiOrange600,\n\t}\n\ttheme.MarkdownHorizontalRuleColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiBase800,\n\t\tLight: flexokiBase200,\n\t}\n\ttheme.MarkdownListItemColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiBlue400,\n\t\tLight: flexokiBlue600,\n\t}\n\ttheme.MarkdownListEnumerationColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiBlue400,\n\t\tLight: flexokiBlue600,\n\t}\n\ttheme.MarkdownImageColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiPurple400,\n\t\tLight: flexokiPurple600,\n\t}\n\ttheme.MarkdownImageTextColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiMagenta400,\n\t\tLight: flexokiMagenta600,\n\t}\n\ttheme.MarkdownCodeBlockColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiBase300,\n\t\tLight: flexokiBase600,\n\t}\n\n\t// Syntax highlighting colors (based on Flexoki's mappings)\n\ttheme.SyntaxCommentColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiBase700, // tx-3\n\t\tLight: flexokiBase300, // tx-3\n\t}\n\ttheme.SyntaxKeywordColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiGreen400, // gr\n\t\tLight: flexokiGreen600, // gr\n\t}\n\ttheme.SyntaxFunctionColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiOrange400, // or\n\t\tLight: flexokiOrange600, // or\n\t}\n\ttheme.SyntaxVariableColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiBlue400, // bl\n\t\tLight: flexokiBlue600, // bl\n\t}\n\ttheme.SyntaxStringColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiCyan400, // cy\n\t\tLight: flexokiCyan600, // cy\n\t}\n\ttheme.SyntaxNumberColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiPurple400, // pu\n\t\tLight: flexokiPurple600, // pu\n\t}\n\ttheme.SyntaxTypeColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiYellow400, // ye\n\t\tLight: flexokiYellow600, // ye\n\t}\n\ttheme.SyntaxOperatorColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiBase500, // tx-2\n\t\tLight: flexokiBase500, // tx-2\n\t}\n\ttheme.SyntaxPunctuationColor = lipgloss.AdaptiveColor{\n\t\tDark: flexokiBase500, // tx-2\n\t\tLight: flexokiBase500, // tx-2\n\t}\n\n\treturn theme\n}\n\nfunc init() {\n\t// Register the Flexoki theme with the theme manager\n\tRegisterTheme(\"flexoki\", NewFlexokiTheme())\n}"], ["/opencode/internal/lsp/transport.go", "package lsp\n\nimport (\n\t\"bufio\"\n\t\"context\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"strings\"\n\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n)\n\n// Write writes an LSP message to the given writer\nfunc WriteMessage(w io.Writer, msg *Message) error {\n\tdata, err := json.Marshal(msg)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to marshal message: %w\", err)\n\t}\n\tcnf := config.Get()\n\n\tif cnf.DebugLSP {\n\t\tlogging.Debug(\"Sending message to server\", \"method\", msg.Method, \"id\", msg.ID)\n\t}\n\n\t_, err = fmt.Fprintf(w, \"Content-Length: %d\\r\\n\\r\\n\", len(data))\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to write header: %w\", err)\n\t}\n\n\t_, err = w.Write(data)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to write message: %w\", err)\n\t}\n\n\treturn nil\n}\n\n// ReadMessage reads a single LSP message from the given reader\nfunc ReadMessage(r *bufio.Reader) (*Message, error) {\n\tcnf := config.Get()\n\t// Read headers\n\tvar contentLength int\n\tfor {\n\t\tline, err := r.ReadString('\\n')\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to read header: %w\", err)\n\t\t}\n\t\tline = strings.TrimSpace(line)\n\n\t\tif cnf.DebugLSP {\n\t\t\tlogging.Debug(\"Received header\", \"line\", line)\n\t\t}\n\n\t\tif line == \"\" {\n\t\t\tbreak // End of headers\n\t\t}\n\n\t\tif strings.HasPrefix(line, \"Content-Length: \") {\n\t\t\t_, err := fmt.Sscanf(line, \"Content-Length: %d\", &contentLength)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"invalid Content-Length: %w\", err)\n\t\t\t}\n\t\t}\n\t}\n\n\tif cnf.DebugLSP {\n\t\tlogging.Debug(\"Content-Length\", \"length\", contentLength)\n\t}\n\n\t// Read content\n\tcontent := make([]byte, contentLength)\n\t_, err := io.ReadFull(r, content)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to read content: %w\", err)\n\t}\n\n\tif cnf.DebugLSP {\n\t\tlogging.Debug(\"Received content\", \"content\", string(content))\n\t}\n\n\t// Parse message\n\tvar msg Message\n\tif err := json.Unmarshal(content, &msg); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to unmarshal message: %w\", err)\n\t}\n\n\treturn &msg, nil\n}\n\n// handleMessages reads and dispatches messages in a loop\nfunc (c *Client) handleMessages() {\n\tcnf := config.Get()\n\tfor {\n\t\tmsg, err := ReadMessage(c.stdout)\n\t\tif err != nil {\n\t\t\tif cnf.DebugLSP {\n\t\t\t\tlogging.Error(\"Error reading message\", \"error\", err)\n\t\t\t}\n\t\t\treturn\n\t\t}\n\n\t\t// Handle server->client request (has both Method and ID)\n\t\tif msg.Method != \"\" && msg.ID != 0 {\n\t\t\tif cnf.DebugLSP {\n\t\t\t\tlogging.Debug(\"Received request from server\", \"method\", msg.Method, \"id\", msg.ID)\n\t\t\t}\n\n\t\t\tresponse := &Message{\n\t\t\t\tJSONRPC: \"2.0\",\n\t\t\t\tID: msg.ID,\n\t\t\t}\n\n\t\t\t// Look up handler for this method\n\t\t\tc.serverHandlersMu.RLock()\n\t\t\thandler, ok := c.serverRequestHandlers[msg.Method]\n\t\t\tc.serverHandlersMu.RUnlock()\n\n\t\t\tif ok {\n\t\t\t\tresult, err := handler(msg.Params)\n\t\t\t\tif err != nil {\n\t\t\t\t\tresponse.Error = &ResponseError{\n\t\t\t\t\t\tCode: -32603,\n\t\t\t\t\t\tMessage: err.Error(),\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\trawJSON, err := json.Marshal(result)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tresponse.Error = &ResponseError{\n\t\t\t\t\t\t\tCode: -32603,\n\t\t\t\t\t\t\tMessage: fmt.Sprintf(\"failed to marshal response: %v\", err),\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tresponse.Result = rawJSON\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tresponse.Error = &ResponseError{\n\t\t\t\t\tCode: -32601,\n\t\t\t\t\tMessage: fmt.Sprintf(\"method not found: %s\", msg.Method),\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Send response back to server\n\t\t\tif err := WriteMessage(c.stdin, response); err != nil {\n\t\t\t\tlogging.Error(\"Error sending response to server\", \"error\", err)\n\t\t\t}\n\n\t\t\tcontinue\n\t\t}\n\n\t\t// Handle notification (has Method but no ID)\n\t\tif msg.Method != \"\" && msg.ID == 0 {\n\t\t\tc.notificationMu.RLock()\n\t\t\thandler, ok := c.notificationHandlers[msg.Method]\n\t\t\tc.notificationMu.RUnlock()\n\n\t\t\tif ok {\n\t\t\t\tif cnf.DebugLSP {\n\t\t\t\t\tlogging.Debug(\"Handling notification\", \"method\", msg.Method)\n\t\t\t\t}\n\t\t\t\tgo handler(msg.Params)\n\t\t\t} else if cnf.DebugLSP {\n\t\t\t\tlogging.Debug(\"No handler for notification\", \"method\", msg.Method)\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\t// Handle response to our request (has ID but no Method)\n\t\tif msg.ID != 0 && msg.Method == \"\" {\n\t\t\tc.handlersMu.RLock()\n\t\t\tch, ok := c.handlers[msg.ID]\n\t\t\tc.handlersMu.RUnlock()\n\n\t\t\tif ok {\n\t\t\t\tif cnf.DebugLSP {\n\t\t\t\t\tlogging.Debug(\"Received response for request\", \"id\", msg.ID)\n\t\t\t\t}\n\t\t\t\tch <- msg\n\t\t\t\tclose(ch)\n\t\t\t} else if cnf.DebugLSP {\n\t\t\t\tlogging.Debug(\"No handler for response\", \"id\", msg.ID)\n\t\t\t}\n\t\t}\n\t}\n}\n\n// Call makes a request and waits for the response\nfunc (c *Client) Call(ctx context.Context, method string, params any, result any) error {\n\tcnf := config.Get()\n\tid := c.nextID.Add(1)\n\n\tif cnf.DebugLSP {\n\t\tlogging.Debug(\"Making call\", \"method\", method, \"id\", id)\n\t}\n\n\tmsg, err := NewRequest(id, method, params)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to create request: %w\", err)\n\t}\n\n\t// Create response channel\n\tch := make(chan *Message, 1)\n\tc.handlersMu.Lock()\n\tc.handlers[id] = ch\n\tc.handlersMu.Unlock()\n\n\tdefer func() {\n\t\tc.handlersMu.Lock()\n\t\tdelete(c.handlers, id)\n\t\tc.handlersMu.Unlock()\n\t}()\n\n\t// Send request\n\tif err := WriteMessage(c.stdin, msg); err != nil {\n\t\treturn fmt.Errorf(\"failed to send request: %w\", err)\n\t}\n\n\tif cnf.DebugLSP {\n\t\tlogging.Debug(\"Request sent\", \"method\", method, \"id\", id)\n\t}\n\n\t// Wait for response\n\tresp := <-ch\n\n\tif cnf.DebugLSP {\n\t\tlogging.Debug(\"Received response\", \"id\", id)\n\t}\n\n\tif resp.Error != nil {\n\t\treturn fmt.Errorf(\"request failed: %s (code: %d)\", resp.Error.Message, resp.Error.Code)\n\t}\n\n\tif result != nil {\n\t\t// If result is a json.RawMessage, just copy the raw bytes\n\t\tif rawMsg, ok := result.(*json.RawMessage); ok {\n\t\t\t*rawMsg = resp.Result\n\t\t\treturn nil\n\t\t}\n\t\t// Otherwise unmarshal into the provided type\n\t\tif err := json.Unmarshal(resp.Result, result); err != nil {\n\t\t\treturn fmt.Errorf(\"failed to unmarshal result: %w\", err)\n\t\t}\n\t}\n\n\treturn nil\n}\n\n// Notify sends a notification (a request without an ID that doesn't expect a response)\nfunc (c *Client) Notify(ctx context.Context, method string, params any) error {\n\tcnf := config.Get()\n\tif cnf.DebugLSP {\n\t\tlogging.Debug(\"Sending notification\", \"method\", method)\n\t}\n\n\tmsg, err := NewNotification(method, params)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to create notification: %w\", err)\n\t}\n\n\tif err := WriteMessage(c.stdin, msg); err != nil {\n\t\treturn fmt.Errorf(\"failed to send notification: %w\", err)\n\t}\n\n\treturn nil\n}\n\ntype (\n\tNotificationHandler func(params json.RawMessage)\n\tServerRequestHandler func(params json.RawMessage) (any, error)\n)\n"], ["/opencode/internal/tui/components/chat/chat.go", "package chat\n\nimport (\n\t\"fmt\"\n\t\"sort\"\n\n\t\"github.com/charmbracelet/lipgloss\"\n\t\"github.com/charmbracelet/x/ansi\"\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/message\"\n\t\"github.com/opencode-ai/opencode/internal/session\"\n\t\"github.com/opencode-ai/opencode/internal/tui/styles\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n\t\"github.com/opencode-ai/opencode/internal/version\"\n)\n\ntype SendMsg struct {\n\tText string\n\tAttachments []message.Attachment\n}\n\ntype SessionSelectedMsg = session.Session\n\ntype SessionClearedMsg struct{}\n\ntype EditorFocusMsg bool\n\nfunc header(width int) string {\n\treturn lipgloss.JoinVertical(\n\t\tlipgloss.Top,\n\t\tlogo(width),\n\t\trepo(width),\n\t\t\"\",\n\t\tcwd(width),\n\t)\n}\n\nfunc lspsConfigured(width int) string {\n\tcfg := config.Get()\n\ttitle := \"LSP Configuration\"\n\ttitle = ansi.Truncate(title, width, \"…\")\n\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\n\tlsps := baseStyle.\n\t\tWidth(width).\n\t\tForeground(t.Primary()).\n\t\tBold(true).\n\t\tRender(title)\n\n\t// Get LSP names and sort them for consistent ordering\n\tvar lspNames []string\n\tfor name := range cfg.LSP {\n\t\tlspNames = append(lspNames, name)\n\t}\n\tsort.Strings(lspNames)\n\n\tvar lspViews []string\n\tfor _, name := range lspNames {\n\t\tlsp := cfg.LSP[name]\n\t\tlspName := baseStyle.\n\t\t\tForeground(t.Text()).\n\t\t\tRender(fmt.Sprintf(\"• %s\", name))\n\n\t\tcmd := lsp.Command\n\t\tcmd = ansi.Truncate(cmd, width-lipgloss.Width(lspName)-3, \"…\")\n\n\t\tlspPath := baseStyle.\n\t\t\tForeground(t.TextMuted()).\n\t\t\tRender(fmt.Sprintf(\" (%s)\", cmd))\n\n\t\tlspViews = append(lspViews,\n\t\t\tbaseStyle.\n\t\t\t\tWidth(width).\n\t\t\t\tRender(\n\t\t\t\t\tlipgloss.JoinHorizontal(\n\t\t\t\t\t\tlipgloss.Left,\n\t\t\t\t\t\tlspName,\n\t\t\t\t\t\tlspPath,\n\t\t\t\t\t),\n\t\t\t\t),\n\t\t)\n\t}\n\n\treturn baseStyle.\n\t\tWidth(width).\n\t\tRender(\n\t\t\tlipgloss.JoinVertical(\n\t\t\t\tlipgloss.Left,\n\t\t\t\tlsps,\n\t\t\t\tlipgloss.JoinVertical(\n\t\t\t\t\tlipgloss.Left,\n\t\t\t\t\tlspViews...,\n\t\t\t\t),\n\t\t\t),\n\t\t)\n}\n\nfunc logo(width int) string {\n\tlogo := fmt.Sprintf(\"%s %s\", styles.OpenCodeIcon, \"OpenCode\")\n\tt := theme.CurrentTheme()\n\tbaseStyle := styles.BaseStyle()\n\n\tversionText := baseStyle.\n\t\tForeground(t.TextMuted()).\n\t\tRender(version.Version)\n\n\treturn baseStyle.\n\t\tBold(true).\n\t\tWidth(width).\n\t\tRender(\n\t\t\tlipgloss.JoinHorizontal(\n\t\t\t\tlipgloss.Left,\n\t\t\t\tlogo,\n\t\t\t\t\" \",\n\t\t\t\tversionText,\n\t\t\t),\n\t\t)\n}\n\nfunc repo(width int) string {\n\trepo := \"https://github.com/opencode-ai/opencode\"\n\tt := theme.CurrentTheme()\n\n\treturn styles.BaseStyle().\n\t\tForeground(t.TextMuted()).\n\t\tWidth(width).\n\t\tRender(repo)\n}\n\nfunc cwd(width int) string {\n\tcwd := fmt.Sprintf(\"cwd: %s\", config.WorkingDirectory())\n\tt := theme.CurrentTheme()\n\n\treturn styles.BaseStyle().\n\t\tForeground(t.TextMuted()).\n\t\tWidth(width).\n\t\tRender(cwd)\n}\n\n"], ["/opencode/internal/db/connect.go", "package db\n\nimport (\n\t\"database/sql\"\n\t\"fmt\"\n\t\"os\"\n\t\"path/filepath\"\n\n\t_ \"github.com/ncruces/go-sqlite3/driver\"\n\t_ \"github.com/ncruces/go-sqlite3/embed\"\n\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n\n\t\"github.com/pressly/goose/v3\"\n)\n\nfunc Connect() (*sql.DB, error) {\n\tdataDir := config.Get().Data.Directory\n\tif dataDir == \"\" {\n\t\treturn nil, fmt.Errorf(\"data.dir is not set\")\n\t}\n\tif err := os.MkdirAll(dataDir, 0o700); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to create data directory: %w\", err)\n\t}\n\tdbPath := filepath.Join(dataDir, \"opencode.db\")\n\t// Open the SQLite database\n\tdb, err := sql.Open(\"sqlite3\", dbPath)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to open database: %w\", err)\n\t}\n\n\t// Verify connection\n\tif err = db.Ping(); err != nil {\n\t\tdb.Close()\n\t\treturn nil, fmt.Errorf(\"failed to connect to database: %w\", err)\n\t}\n\n\t// Set pragmas for better performance\n\tpragmas := []string{\n\t\t\"PRAGMA foreign_keys = ON;\",\n\t\t\"PRAGMA journal_mode = WAL;\",\n\t\t\"PRAGMA page_size = 4096;\",\n\t\t\"PRAGMA cache_size = -8000;\",\n\t\t\"PRAGMA synchronous = NORMAL;\",\n\t}\n\n\tfor _, pragma := range pragmas {\n\t\tif _, err = db.Exec(pragma); err != nil {\n\t\t\tlogging.Error(\"Failed to set pragma\", pragma, err)\n\t\t} else {\n\t\t\tlogging.Debug(\"Set pragma\", \"pragma\", pragma)\n\t\t}\n\t}\n\n\tgoose.SetBaseFS(FS)\n\n\tif err := goose.SetDialect(\"sqlite3\"); err != nil {\n\t\tlogging.Error(\"Failed to set dialect\", \"error\", err)\n\t\treturn nil, fmt.Errorf(\"failed to set dialect: %w\", err)\n\t}\n\n\tif err := goose.Up(db, \"migrations\"); err != nil {\n\t\tlogging.Error(\"Failed to apply migrations\", \"error\", err)\n\t\treturn nil, fmt.Errorf(\"failed to apply migrations: %w\", err)\n\t}\n\treturn db, nil\n}\n"], ["/opencode/internal/llm/agent/agent-tool.go", "package agent\n\nimport (\n\t\"context\"\n\t\"encoding/json\"\n\t\"fmt\"\n\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/llm/tools\"\n\t\"github.com/opencode-ai/opencode/internal/lsp\"\n\t\"github.com/opencode-ai/opencode/internal/message\"\n\t\"github.com/opencode-ai/opencode/internal/session\"\n)\n\ntype agentTool struct {\n\tsessions session.Service\n\tmessages message.Service\n\tlspClients map[string]*lsp.Client\n}\n\nconst (\n\tAgentToolName = \"agent\"\n)\n\ntype AgentParams struct {\n\tPrompt string `json:\"prompt\"`\n}\n\nfunc (b *agentTool) Info() tools.ToolInfo {\n\treturn tools.ToolInfo{\n\t\tName: AgentToolName,\n\t\tDescription: \"Launch a new agent that has access to the following tools: GlobTool, GrepTool, LS, View. When you are searching for a keyword or file and are not confident that you will find the right match on the first try, use the Agent tool to perform the search for you. For example:\\n\\n- If you are searching for a keyword like \\\"config\\\" or \\\"logger\\\", or for questions like \\\"which file does X?\\\", the Agent tool is strongly recommended\\n- If you want to read a specific file path, use the View or GlobTool tool instead of the Agent tool, to find the match more quickly\\n- If you are searching for a specific class definition like \\\"class Foo\\\", use the GlobTool tool instead, to find the match more quickly\\n\\nUsage notes:\\n1. Launch multiple agents concurrently whenever possible, to maximize performance; to do that, use a single message with multiple tool uses\\n2. When the agent is done, it will return a single message back to you. The result returned by the agent is not visible to the user. To show the user the result, you should send a text message back to the user with a concise summary of the result.\\n3. Each agent invocation is stateless. You will not be able to send additional messages to the agent, nor will the agent be able to communicate with you outside of its final report. Therefore, your prompt should contain a highly detailed task description for the agent to perform autonomously and you should specify exactly what information the agent should return back to you in its final and only message to you.\\n4. The agent's outputs should generally be trusted\\n5. IMPORTANT: The agent can not use Bash, Replace, Edit, so can not modify files. If you want to use these tools, use them directly instead of going through the agent.\",\n\t\tParameters: map[string]any{\n\t\t\t\"prompt\": map[string]any{\n\t\t\t\t\"type\": \"string\",\n\t\t\t\t\"description\": \"The task for the agent to perform\",\n\t\t\t},\n\t\t},\n\t\tRequired: []string{\"prompt\"},\n\t}\n}\n\nfunc (b *agentTool) Run(ctx context.Context, call tools.ToolCall) (tools.ToolResponse, error) {\n\tvar params AgentParams\n\tif err := json.Unmarshal([]byte(call.Input), ¶ms); err != nil {\n\t\treturn tools.NewTextErrorResponse(fmt.Sprintf(\"error parsing parameters: %s\", err)), nil\n\t}\n\tif params.Prompt == \"\" {\n\t\treturn tools.NewTextErrorResponse(\"prompt is required\"), nil\n\t}\n\n\tsessionID, messageID := tools.GetContextValues(ctx)\n\tif sessionID == \"\" || messageID == \"\" {\n\t\treturn tools.ToolResponse{}, fmt.Errorf(\"session_id and message_id are required\")\n\t}\n\n\tagent, err := NewAgent(config.AgentTask, b.sessions, b.messages, TaskAgentTools(b.lspClients))\n\tif err != nil {\n\t\treturn tools.ToolResponse{}, fmt.Errorf(\"error creating agent: %s\", err)\n\t}\n\n\tsession, err := b.sessions.CreateTaskSession(ctx, call.ID, sessionID, \"New Agent Session\")\n\tif err != nil {\n\t\treturn tools.ToolResponse{}, fmt.Errorf(\"error creating session: %s\", err)\n\t}\n\n\tdone, err := agent.Run(ctx, session.ID, params.Prompt)\n\tif err != nil {\n\t\treturn tools.ToolResponse{}, fmt.Errorf(\"error generating agent: %s\", err)\n\t}\n\tresult := <-done\n\tif result.Error != nil {\n\t\treturn tools.ToolResponse{}, fmt.Errorf(\"error generating agent: %s\", result.Error)\n\t}\n\n\tresponse := result.Message\n\tif response.Role != message.Assistant {\n\t\treturn tools.NewTextErrorResponse(\"no response\"), nil\n\t}\n\n\tupdatedSession, err := b.sessions.Get(ctx, session.ID)\n\tif err != nil {\n\t\treturn tools.ToolResponse{}, fmt.Errorf(\"error getting session: %s\", err)\n\t}\n\tparentSession, err := b.sessions.Get(ctx, sessionID)\n\tif err != nil {\n\t\treturn tools.ToolResponse{}, fmt.Errorf(\"error getting parent session: %s\", err)\n\t}\n\n\tparentSession.Cost += updatedSession.Cost\n\n\t_, err = b.sessions.Save(ctx, parentSession)\n\tif err != nil {\n\t\treturn tools.ToolResponse{}, fmt.Errorf(\"error saving parent session: %s\", err)\n\t}\n\treturn tools.NewTextResponse(response.Content().String()), nil\n}\n\nfunc NewAgentTool(\n\tSessions session.Service,\n\tMessages message.Service,\n\tLspClients map[string]*lsp.Client,\n) tools.BaseTool {\n\treturn &agentTool{\n\t\tsessions: Sessions,\n\t\tmessages: Messages,\n\t\tlspClients: LspClients,\n\t}\n}\n"], ["/opencode/internal/tui/theme/tokyonight.go", "package theme\n\nimport (\n\t\"github.com/charmbracelet/lipgloss\"\n)\n\n// TokyoNightTheme implements the Theme interface with Tokyo Night colors.\n// It provides both dark and light variants.\ntype TokyoNightTheme struct {\n\tBaseTheme\n}\n\n// NewTokyoNightTheme creates a new instance of the Tokyo Night theme.\nfunc NewTokyoNightTheme() *TokyoNightTheme {\n\t// Tokyo Night color palette\n\t// Dark mode colors\n\tdarkBackground := \"#222436\"\n\tdarkCurrentLine := \"#1e2030\"\n\tdarkSelection := \"#2f334d\"\n\tdarkForeground := \"#c8d3f5\"\n\tdarkComment := \"#636da6\"\n\tdarkRed := \"#ff757f\"\n\tdarkOrange := \"#ff966c\"\n\tdarkYellow := \"#ffc777\"\n\tdarkGreen := \"#c3e88d\"\n\tdarkCyan := \"#86e1fc\"\n\tdarkBlue := \"#82aaff\"\n\tdarkPurple := \"#c099ff\"\n\tdarkBorder := \"#3b4261\"\n\n\t// Light mode colors (Tokyo Night Day)\n\tlightBackground := \"#e1e2e7\"\n\tlightCurrentLine := \"#d5d6db\"\n\tlightSelection := \"#c8c9ce\"\n\tlightForeground := \"#3760bf\"\n\tlightComment := \"#848cb5\"\n\tlightRed := \"#f52a65\"\n\tlightOrange := \"#b15c00\"\n\tlightYellow := \"#8c6c3e\"\n\tlightGreen := \"#587539\"\n\tlightCyan := \"#007197\"\n\tlightBlue := \"#2e7de9\"\n\tlightPurple := \"#9854f1\"\n\tlightBorder := \"#a8aecb\"\n\n\ttheme := &TokyoNightTheme{}\n\n\t// Base colors\n\ttheme.PrimaryColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBlue,\n\t\tLight: lightBlue,\n\t}\n\ttheme.SecondaryColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPurple,\n\t\tLight: lightPurple,\n\t}\n\ttheme.AccentColor = lipgloss.AdaptiveColor{\n\t\tDark: darkOrange,\n\t\tLight: lightOrange,\n\t}\n\n\t// Status colors\n\ttheme.ErrorColor = lipgloss.AdaptiveColor{\n\t\tDark: darkRed,\n\t\tLight: lightRed,\n\t}\n\ttheme.WarningColor = lipgloss.AdaptiveColor{\n\t\tDark: darkOrange,\n\t\tLight: lightOrange,\n\t}\n\ttheme.SuccessColor = lipgloss.AdaptiveColor{\n\t\tDark: darkGreen,\n\t\tLight: lightGreen,\n\t}\n\ttheme.InfoColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBlue,\n\t\tLight: lightBlue,\n\t}\n\n\t// Text colors\n\ttheme.TextColor = lipgloss.AdaptiveColor{\n\t\tDark: darkForeground,\n\t\tLight: lightForeground,\n\t}\n\ttheme.TextMutedColor = lipgloss.AdaptiveColor{\n\t\tDark: darkComment,\n\t\tLight: lightComment,\n\t}\n\ttheme.TextEmphasizedColor = lipgloss.AdaptiveColor{\n\t\tDark: darkYellow,\n\t\tLight: lightYellow,\n\t}\n\n\t// Background colors\n\ttheme.BackgroundColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBackground,\n\t\tLight: lightBackground,\n\t}\n\ttheme.BackgroundSecondaryColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCurrentLine,\n\t\tLight: lightCurrentLine,\n\t}\n\ttheme.BackgroundDarkerColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#191B29\", // Darker background from palette\n\t\tLight: \"#f0f0f5\", // Slightly lighter than background\n\t}\n\n\t// Border colors\n\ttheme.BorderNormalColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBorder,\n\t\tLight: lightBorder,\n\t}\n\ttheme.BorderFocusedColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBlue,\n\t\tLight: lightBlue,\n\t}\n\ttheme.BorderDimColor = lipgloss.AdaptiveColor{\n\t\tDark: darkSelection,\n\t\tLight: lightSelection,\n\t}\n\n\t// Diff view colors\n\ttheme.DiffAddedColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#4fd6be\", // teal from palette\n\t\tLight: \"#1e725c\",\n\t}\n\ttheme.DiffRemovedColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#c53b53\", // red1 from palette\n\t\tLight: \"#c53b53\",\n\t}\n\ttheme.DiffContextColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#828bb8\", // fg_dark from palette\n\t\tLight: \"#7086b5\",\n\t}\n\ttheme.DiffHunkHeaderColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#828bb8\", // fg_dark from palette\n\t\tLight: \"#7086b5\",\n\t}\n\ttheme.DiffHighlightAddedColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#b8db87\", // git.add from palette\n\t\tLight: \"#4db380\",\n\t}\n\ttheme.DiffHighlightRemovedColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#e26a75\", // git.delete from palette\n\t\tLight: \"#f52a65\",\n\t}\n\ttheme.DiffAddedBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#20303b\",\n\t\tLight: \"#d5e5d5\",\n\t}\n\ttheme.DiffRemovedBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#37222c\",\n\t\tLight: \"#f7d8db\",\n\t}\n\ttheme.DiffContextBgColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBackground,\n\t\tLight: lightBackground,\n\t}\n\ttheme.DiffLineNumberColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#545c7e\", // dark3 from palette\n\t\tLight: \"#848cb5\",\n\t}\n\ttheme.DiffAddedLineNumberBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#1b2b34\",\n\t\tLight: \"#c5d5c5\",\n\t}\n\ttheme.DiffRemovedLineNumberBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#2d1f26\",\n\t\tLight: \"#e7c8cb\",\n\t}\n\n\t// Markdown colors\n\ttheme.MarkdownTextColor = lipgloss.AdaptiveColor{\n\t\tDark: darkForeground,\n\t\tLight: lightForeground,\n\t}\n\ttheme.MarkdownHeadingColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPurple,\n\t\tLight: lightPurple,\n\t}\n\ttheme.MarkdownLinkColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBlue,\n\t\tLight: lightBlue,\n\t}\n\ttheme.MarkdownLinkTextColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.MarkdownCodeColor = lipgloss.AdaptiveColor{\n\t\tDark: darkGreen,\n\t\tLight: lightGreen,\n\t}\n\ttheme.MarkdownBlockQuoteColor = lipgloss.AdaptiveColor{\n\t\tDark: darkYellow,\n\t\tLight: lightYellow,\n\t}\n\ttheme.MarkdownEmphColor = lipgloss.AdaptiveColor{\n\t\tDark: darkYellow,\n\t\tLight: lightYellow,\n\t}\n\ttheme.MarkdownStrongColor = lipgloss.AdaptiveColor{\n\t\tDark: darkOrange,\n\t\tLight: lightOrange,\n\t}\n\ttheme.MarkdownHorizontalRuleColor = lipgloss.AdaptiveColor{\n\t\tDark: darkComment,\n\t\tLight: lightComment,\n\t}\n\ttheme.MarkdownListItemColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBlue,\n\t\tLight: lightBlue,\n\t}\n\ttheme.MarkdownListEnumerationColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.MarkdownImageColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBlue,\n\t\tLight: lightBlue,\n\t}\n\ttheme.MarkdownImageTextColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.MarkdownCodeBlockColor = lipgloss.AdaptiveColor{\n\t\tDark: darkForeground,\n\t\tLight: lightForeground,\n\t}\n\n\t// Syntax highlighting colors\n\ttheme.SyntaxCommentColor = lipgloss.AdaptiveColor{\n\t\tDark: darkComment,\n\t\tLight: lightComment,\n\t}\n\ttheme.SyntaxKeywordColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPurple,\n\t\tLight: lightPurple,\n\t}\n\ttheme.SyntaxFunctionColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBlue,\n\t\tLight: lightBlue,\n\t}\n\ttheme.SyntaxVariableColor = lipgloss.AdaptiveColor{\n\t\tDark: darkRed,\n\t\tLight: lightRed,\n\t}\n\ttheme.SyntaxStringColor = lipgloss.AdaptiveColor{\n\t\tDark: darkGreen,\n\t\tLight: lightGreen,\n\t}\n\ttheme.SyntaxNumberColor = lipgloss.AdaptiveColor{\n\t\tDark: darkOrange,\n\t\tLight: lightOrange,\n\t}\n\ttheme.SyntaxTypeColor = lipgloss.AdaptiveColor{\n\t\tDark: darkYellow,\n\t\tLight: lightYellow,\n\t}\n\ttheme.SyntaxOperatorColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.SyntaxPunctuationColor = lipgloss.AdaptiveColor{\n\t\tDark: darkForeground,\n\t\tLight: lightForeground,\n\t}\n\n\treturn theme\n}\n\nfunc init() {\n\t// Register the Tokyo Night theme with the theme manager\n\tRegisterTheme(\"tokyonight\", NewTokyoNightTheme())\n}"], ["/opencode/internal/app/app.go", "package app\n\nimport (\n\t\"context\"\n\t\"database/sql\"\n\t\"errors\"\n\t\"fmt\"\n\t\"maps\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/db\"\n\t\"github.com/opencode-ai/opencode/internal/format\"\n\t\"github.com/opencode-ai/opencode/internal/history\"\n\t\"github.com/opencode-ai/opencode/internal/llm/agent\"\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n\t\"github.com/opencode-ai/opencode/internal/lsp\"\n\t\"github.com/opencode-ai/opencode/internal/message\"\n\t\"github.com/opencode-ai/opencode/internal/permission\"\n\t\"github.com/opencode-ai/opencode/internal/session\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n)\n\ntype App struct {\n\tSessions session.Service\n\tMessages message.Service\n\tHistory history.Service\n\tPermissions permission.Service\n\n\tCoderAgent agent.Service\n\n\tLSPClients map[string]*lsp.Client\n\n\tclientsMutex sync.RWMutex\n\n\twatcherCancelFuncs []context.CancelFunc\n\tcancelFuncsMutex sync.Mutex\n\twatcherWG sync.WaitGroup\n}\n\nfunc New(ctx context.Context, conn *sql.DB) (*App, error) {\n\tq := db.New(conn)\n\tsessions := session.NewService(q)\n\tmessages := message.NewService(q)\n\tfiles := history.NewService(q, conn)\n\n\tapp := &App{\n\t\tSessions: sessions,\n\t\tMessages: messages,\n\t\tHistory: files,\n\t\tPermissions: permission.NewPermissionService(),\n\t\tLSPClients: make(map[string]*lsp.Client),\n\t}\n\n\t// Initialize theme based on configuration\n\tapp.initTheme()\n\n\t// Initialize LSP clients in the background\n\tgo app.initLSPClients(ctx)\n\n\tvar err error\n\tapp.CoderAgent, err = agent.NewAgent(\n\t\tconfig.AgentCoder,\n\t\tapp.Sessions,\n\t\tapp.Messages,\n\t\tagent.CoderAgentTools(\n\t\t\tapp.Permissions,\n\t\t\tapp.Sessions,\n\t\t\tapp.Messages,\n\t\t\tapp.History,\n\t\t\tapp.LSPClients,\n\t\t),\n\t)\n\tif err != nil {\n\t\tlogging.Error(\"Failed to create coder agent\", err)\n\t\treturn nil, err\n\t}\n\n\treturn app, nil\n}\n\n// initTheme sets the application theme based on the configuration\nfunc (app *App) initTheme() {\n\tcfg := config.Get()\n\tif cfg == nil || cfg.TUI.Theme == \"\" {\n\t\treturn // Use default theme\n\t}\n\n\t// Try to set the theme from config\n\terr := theme.SetTheme(cfg.TUI.Theme)\n\tif err != nil {\n\t\tlogging.Warn(\"Failed to set theme from config, using default theme\", \"theme\", cfg.TUI.Theme, \"error\", err)\n\t} else {\n\t\tlogging.Debug(\"Set theme from config\", \"theme\", cfg.TUI.Theme)\n\t}\n}\n\n// RunNonInteractive handles the execution flow when a prompt is provided via CLI flag.\nfunc (a *App) RunNonInteractive(ctx context.Context, prompt string, outputFormat string, quiet bool) error {\n\tlogging.Info(\"Running in non-interactive mode\")\n\n\t// Start spinner if not in quiet mode\n\tvar spinner *format.Spinner\n\tif !quiet {\n\t\tspinner = format.NewSpinner(\"Thinking...\")\n\t\tspinner.Start()\n\t\tdefer spinner.Stop()\n\t}\n\n\tconst maxPromptLengthForTitle = 100\n\ttitlePrefix := \"Non-interactive: \"\n\tvar titleSuffix string\n\n\tif len(prompt) > maxPromptLengthForTitle {\n\t\ttitleSuffix = prompt[:maxPromptLengthForTitle] + \"...\"\n\t} else {\n\t\ttitleSuffix = prompt\n\t}\n\ttitle := titlePrefix + titleSuffix\n\n\tsess, err := a.Sessions.Create(ctx, title)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to create session for non-interactive mode: %w\", err)\n\t}\n\tlogging.Info(\"Created session for non-interactive run\", \"session_id\", sess.ID)\n\n\t// Automatically approve all permission requests for this non-interactive session\n\ta.Permissions.AutoApproveSession(sess.ID)\n\n\tdone, err := a.CoderAgent.Run(ctx, sess.ID, prompt)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to start agent processing stream: %w\", err)\n\t}\n\n\tresult := <-done\n\tif result.Error != nil {\n\t\tif errors.Is(result.Error, context.Canceled) || errors.Is(result.Error, agent.ErrRequestCancelled) {\n\t\t\tlogging.Info(\"Agent processing cancelled\", \"session_id\", sess.ID)\n\t\t\treturn nil\n\t\t}\n\t\treturn fmt.Errorf(\"agent processing failed: %w\", result.Error)\n\t}\n\n\t// Stop spinner before printing output\n\tif !quiet && spinner != nil {\n\t\tspinner.Stop()\n\t}\n\n\t// Get the text content from the response\n\tcontent := \"No content available\"\n\tif result.Message.Content().String() != \"\" {\n\t\tcontent = result.Message.Content().String()\n\t}\n\n\tfmt.Println(format.FormatOutput(content, outputFormat))\n\n\tlogging.Info(\"Non-interactive run completed\", \"session_id\", sess.ID)\n\n\treturn nil\n}\n\n// Shutdown performs a clean shutdown of the application\nfunc (app *App) Shutdown() {\n\t// Cancel all watcher goroutines\n\tapp.cancelFuncsMutex.Lock()\n\tfor _, cancel := range app.watcherCancelFuncs {\n\t\tcancel()\n\t}\n\tapp.cancelFuncsMutex.Unlock()\n\tapp.watcherWG.Wait()\n\n\t// Perform additional cleanup for LSP clients\n\tapp.clientsMutex.RLock()\n\tclients := make(map[string]*lsp.Client, len(app.LSPClients))\n\tmaps.Copy(clients, app.LSPClients)\n\tapp.clientsMutex.RUnlock()\n\n\tfor name, client := range clients {\n\t\tshutdownCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)\n\t\tif err := client.Shutdown(shutdownCtx); err != nil {\n\t\t\tlogging.Error(\"Failed to shutdown LSP client\", \"name\", name, \"error\", err)\n\t\t}\n\t\tcancel()\n\t}\n}\n"], ["/opencode/internal/tui/theme/tron.go", "package theme\n\nimport (\n\t\"github.com/charmbracelet/lipgloss\"\n)\n\n// TronTheme implements the Theme interface with Tron-inspired colors.\n// It provides both dark and light variants, though Tron is primarily a dark theme.\ntype TronTheme struct {\n\tBaseTheme\n}\n\n// NewTronTheme creates a new instance of the Tron theme.\nfunc NewTronTheme() *TronTheme {\n\t// Tron color palette\n\t// Inspired by the Tron movie's neon aesthetic\n\tdarkBackground := \"#0c141f\"\n\tdarkCurrentLine := \"#1a2633\"\n\tdarkSelection := \"#1a2633\"\n\tdarkForeground := \"#caf0ff\"\n\tdarkComment := \"#4d6b87\"\n\tdarkCyan := \"#00d9ff\"\n\tdarkBlue := \"#007fff\"\n\tdarkOrange := \"#ff9000\"\n\tdarkPink := \"#ff00a0\"\n\tdarkPurple := \"#b73fff\"\n\tdarkRed := \"#ff3333\"\n\tdarkYellow := \"#ffcc00\"\n\tdarkGreen := \"#00ff8f\"\n\tdarkBorder := \"#1a2633\"\n\n\t// Light mode approximation\n\tlightBackground := \"#f0f8ff\"\n\tlightCurrentLine := \"#e0f0ff\"\n\tlightSelection := \"#d0e8ff\"\n\tlightForeground := \"#0c141f\"\n\tlightComment := \"#4d6b87\"\n\tlightCyan := \"#0097b3\"\n\tlightBlue := \"#0066cc\"\n\tlightOrange := \"#cc7300\"\n\tlightPink := \"#cc0080\"\n\tlightPurple := \"#9932cc\"\n\tlightRed := \"#cc2929\"\n\tlightYellow := \"#cc9900\"\n\tlightGreen := \"#00cc72\"\n\tlightBorder := \"#d0e8ff\"\n\n\ttheme := &TronTheme{}\n\n\t// Base colors\n\ttheme.PrimaryColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.SecondaryColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBlue,\n\t\tLight: lightBlue,\n\t}\n\ttheme.AccentColor = lipgloss.AdaptiveColor{\n\t\tDark: darkOrange,\n\t\tLight: lightOrange,\n\t}\n\n\t// Status colors\n\ttheme.ErrorColor = lipgloss.AdaptiveColor{\n\t\tDark: darkRed,\n\t\tLight: lightRed,\n\t}\n\ttheme.WarningColor = lipgloss.AdaptiveColor{\n\t\tDark: darkOrange,\n\t\tLight: lightOrange,\n\t}\n\ttheme.SuccessColor = lipgloss.AdaptiveColor{\n\t\tDark: darkGreen,\n\t\tLight: lightGreen,\n\t}\n\ttheme.InfoColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\n\t// Text colors\n\ttheme.TextColor = lipgloss.AdaptiveColor{\n\t\tDark: darkForeground,\n\t\tLight: lightForeground,\n\t}\n\ttheme.TextMutedColor = lipgloss.AdaptiveColor{\n\t\tDark: darkComment,\n\t\tLight: lightComment,\n\t}\n\ttheme.TextEmphasizedColor = lipgloss.AdaptiveColor{\n\t\tDark: darkYellow,\n\t\tLight: lightYellow,\n\t}\n\n\t// Background colors\n\ttheme.BackgroundColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBackground,\n\t\tLight: lightBackground,\n\t}\n\ttheme.BackgroundSecondaryColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCurrentLine,\n\t\tLight: lightCurrentLine,\n\t}\n\ttheme.BackgroundDarkerColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#070d14\", // Slightly darker than background\n\t\tLight: \"#ffffff\", // Slightly lighter than background\n\t}\n\n\t// Border colors\n\ttheme.BorderNormalColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBorder,\n\t\tLight: lightBorder,\n\t}\n\ttheme.BorderFocusedColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.BorderDimColor = lipgloss.AdaptiveColor{\n\t\tDark: darkSelection,\n\t\tLight: lightSelection,\n\t}\n\n\t// Diff view colors\n\ttheme.DiffAddedColor = lipgloss.AdaptiveColor{\n\t\tDark: darkGreen,\n\t\tLight: lightGreen,\n\t}\n\ttheme.DiffRemovedColor = lipgloss.AdaptiveColor{\n\t\tDark: darkRed,\n\t\tLight: lightRed,\n\t}\n\ttheme.DiffContextColor = lipgloss.AdaptiveColor{\n\t\tDark: darkComment,\n\t\tLight: lightComment,\n\t}\n\ttheme.DiffHunkHeaderColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBlue,\n\t\tLight: lightBlue,\n\t}\n\ttheme.DiffHighlightAddedColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#00ff8f\",\n\t\tLight: \"#a5d6a7\",\n\t}\n\ttheme.DiffHighlightRemovedColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#ff3333\",\n\t\tLight: \"#ef9a9a\",\n\t}\n\ttheme.DiffAddedBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#0a2a1a\",\n\t\tLight: \"#e8f5e9\",\n\t}\n\ttheme.DiffRemovedBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#2a0a0a\",\n\t\tLight: \"#ffebee\",\n\t}\n\ttheme.DiffContextBgColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBackground,\n\t\tLight: lightBackground,\n\t}\n\ttheme.DiffLineNumberColor = lipgloss.AdaptiveColor{\n\t\tDark: darkComment,\n\t\tLight: lightComment,\n\t}\n\ttheme.DiffAddedLineNumberBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#082015\",\n\t\tLight: \"#c8e6c9\",\n\t}\n\ttheme.DiffRemovedLineNumberBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#200808\",\n\t\tLight: \"#ffcdd2\",\n\t}\n\n\t// Markdown colors\n\ttheme.MarkdownTextColor = lipgloss.AdaptiveColor{\n\t\tDark: darkForeground,\n\t\tLight: lightForeground,\n\t}\n\ttheme.MarkdownHeadingColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.MarkdownLinkColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBlue,\n\t\tLight: lightBlue,\n\t}\n\ttheme.MarkdownLinkTextColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.MarkdownCodeColor = lipgloss.AdaptiveColor{\n\t\tDark: darkGreen,\n\t\tLight: lightGreen,\n\t}\n\ttheme.MarkdownBlockQuoteColor = lipgloss.AdaptiveColor{\n\t\tDark: darkYellow,\n\t\tLight: lightYellow,\n\t}\n\ttheme.MarkdownEmphColor = lipgloss.AdaptiveColor{\n\t\tDark: darkYellow,\n\t\tLight: lightYellow,\n\t}\n\ttheme.MarkdownStrongColor = lipgloss.AdaptiveColor{\n\t\tDark: darkOrange,\n\t\tLight: lightOrange,\n\t}\n\ttheme.MarkdownHorizontalRuleColor = lipgloss.AdaptiveColor{\n\t\tDark: darkComment,\n\t\tLight: lightComment,\n\t}\n\ttheme.MarkdownListItemColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBlue,\n\t\tLight: lightBlue,\n\t}\n\ttheme.MarkdownListEnumerationColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.MarkdownImageColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBlue,\n\t\tLight: lightBlue,\n\t}\n\ttheme.MarkdownImageTextColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.MarkdownCodeBlockColor = lipgloss.AdaptiveColor{\n\t\tDark: darkForeground,\n\t\tLight: lightForeground,\n\t}\n\n\t// Syntax highlighting colors\n\ttheme.SyntaxCommentColor = lipgloss.AdaptiveColor{\n\t\tDark: darkComment,\n\t\tLight: lightComment,\n\t}\n\ttheme.SyntaxKeywordColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.SyntaxFunctionColor = lipgloss.AdaptiveColor{\n\t\tDark: darkGreen,\n\t\tLight: lightGreen,\n\t}\n\ttheme.SyntaxVariableColor = lipgloss.AdaptiveColor{\n\t\tDark: darkOrange,\n\t\tLight: lightOrange,\n\t}\n\ttheme.SyntaxStringColor = lipgloss.AdaptiveColor{\n\t\tDark: darkYellow,\n\t\tLight: lightYellow,\n\t}\n\ttheme.SyntaxNumberColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBlue,\n\t\tLight: lightBlue,\n\t}\n\ttheme.SyntaxTypeColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPurple,\n\t\tLight: lightPurple,\n\t}\n\ttheme.SyntaxOperatorColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPink,\n\t\tLight: lightPink,\n\t}\n\ttheme.SyntaxPunctuationColor = lipgloss.AdaptiveColor{\n\t\tDark: darkForeground,\n\t\tLight: lightForeground,\n\t}\n\n\treturn theme\n}\n\nfunc init() {\n\t// Register the Tron theme with the theme manager\n\tRegisterTheme(\"tron\", NewTronTheme())\n}"], ["/opencode/internal/tui/theme/monokai.go", "package theme\n\nimport (\n\t\"github.com/charmbracelet/lipgloss\"\n)\n\n// MonokaiProTheme implements the Theme interface with Monokai Pro colors.\n// It provides both dark and light variants.\ntype MonokaiProTheme struct {\n\tBaseTheme\n}\n\n// NewMonokaiProTheme creates a new instance of the Monokai Pro theme.\nfunc NewMonokaiProTheme() *MonokaiProTheme {\n\t// Monokai Pro color palette (dark mode)\n\tdarkBackground := \"#2d2a2e\"\n\tdarkCurrentLine := \"#403e41\"\n\tdarkSelection := \"#5b595c\"\n\tdarkForeground := \"#fcfcfa\"\n\tdarkComment := \"#727072\"\n\tdarkRed := \"#ff6188\"\n\tdarkOrange := \"#fc9867\"\n\tdarkYellow := \"#ffd866\"\n\tdarkGreen := \"#a9dc76\"\n\tdarkCyan := \"#78dce8\"\n\tdarkBlue := \"#ab9df2\"\n\tdarkPurple := \"#ab9df2\"\n\tdarkBorder := \"#403e41\"\n\n\t// Light mode colors (adapted from dark)\n\tlightBackground := \"#fafafa\"\n\tlightCurrentLine := \"#f0f0f0\"\n\tlightSelection := \"#e5e5e6\"\n\tlightForeground := \"#2d2a2e\"\n\tlightComment := \"#939293\"\n\tlightRed := \"#f92672\"\n\tlightOrange := \"#fd971f\"\n\tlightYellow := \"#e6db74\"\n\tlightGreen := \"#9bca65\"\n\tlightCyan := \"#66d9ef\"\n\tlightBlue := \"#7e75db\"\n\tlightPurple := \"#ae81ff\"\n\tlightBorder := \"#d3d3d3\"\n\n\ttheme := &MonokaiProTheme{}\n\n\t// Base colors\n\ttheme.PrimaryColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.SecondaryColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPurple,\n\t\tLight: lightPurple,\n\t}\n\ttheme.AccentColor = lipgloss.AdaptiveColor{\n\t\tDark: darkOrange,\n\t\tLight: lightOrange,\n\t}\n\n\t// Status colors\n\ttheme.ErrorColor = lipgloss.AdaptiveColor{\n\t\tDark: darkRed,\n\t\tLight: lightRed,\n\t}\n\ttheme.WarningColor = lipgloss.AdaptiveColor{\n\t\tDark: darkOrange,\n\t\tLight: lightOrange,\n\t}\n\ttheme.SuccessColor = lipgloss.AdaptiveColor{\n\t\tDark: darkGreen,\n\t\tLight: lightGreen,\n\t}\n\ttheme.InfoColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBlue,\n\t\tLight: lightBlue,\n\t}\n\n\t// Text colors\n\ttheme.TextColor = lipgloss.AdaptiveColor{\n\t\tDark: darkForeground,\n\t\tLight: lightForeground,\n\t}\n\ttheme.TextMutedColor = lipgloss.AdaptiveColor{\n\t\tDark: darkComment,\n\t\tLight: lightComment,\n\t}\n\ttheme.TextEmphasizedColor = lipgloss.AdaptiveColor{\n\t\tDark: darkYellow,\n\t\tLight: lightYellow,\n\t}\n\n\t// Background colors\n\ttheme.BackgroundColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBackground,\n\t\tLight: lightBackground,\n\t}\n\ttheme.BackgroundSecondaryColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCurrentLine,\n\t\tLight: lightCurrentLine,\n\t}\n\ttheme.BackgroundDarkerColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#221f22\", // Slightly darker than background\n\t\tLight: \"#ffffff\", // Slightly lighter than background\n\t}\n\n\t// Border colors\n\ttheme.BorderNormalColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBorder,\n\t\tLight: lightBorder,\n\t}\n\ttheme.BorderFocusedColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.BorderDimColor = lipgloss.AdaptiveColor{\n\t\tDark: darkSelection,\n\t\tLight: lightSelection,\n\t}\n\n\t// Diff view colors\n\ttheme.DiffAddedColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#a9dc76\",\n\t\tLight: \"#9bca65\",\n\t}\n\ttheme.DiffRemovedColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#ff6188\",\n\t\tLight: \"#f92672\",\n\t}\n\ttheme.DiffContextColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#a0a0a0\",\n\t\tLight: \"#757575\",\n\t}\n\ttheme.DiffHunkHeaderColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#a0a0a0\",\n\t\tLight: \"#757575\",\n\t}\n\ttheme.DiffHighlightAddedColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#c2e7a9\",\n\t\tLight: \"#c5e0b4\",\n\t}\n\ttheme.DiffHighlightRemovedColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#ff8ca6\",\n\t\tLight: \"#ffb3c8\",\n\t}\n\ttheme.DiffAddedBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#3a4a35\",\n\t\tLight: \"#e8f5e9\",\n\t}\n\ttheme.DiffRemovedBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#4a3439\",\n\t\tLight: \"#ffebee\",\n\t}\n\ttheme.DiffContextBgColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBackground,\n\t\tLight: lightBackground,\n\t}\n\ttheme.DiffLineNumberColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#888888\",\n\t\tLight: \"#9e9e9e\",\n\t}\n\ttheme.DiffAddedLineNumberBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#2d3a28\",\n\t\tLight: \"#c8e6c9\",\n\t}\n\ttheme.DiffRemovedLineNumberBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#3d2a2e\",\n\t\tLight: \"#ffcdd2\",\n\t}\n\n\t// Markdown colors\n\ttheme.MarkdownTextColor = lipgloss.AdaptiveColor{\n\t\tDark: darkForeground,\n\t\tLight: lightForeground,\n\t}\n\ttheme.MarkdownHeadingColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPurple,\n\t\tLight: lightPurple,\n\t}\n\ttheme.MarkdownLinkColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.MarkdownLinkTextColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBlue,\n\t\tLight: lightBlue,\n\t}\n\ttheme.MarkdownCodeColor = lipgloss.AdaptiveColor{\n\t\tDark: darkGreen,\n\t\tLight: lightGreen,\n\t}\n\ttheme.MarkdownBlockQuoteColor = lipgloss.AdaptiveColor{\n\t\tDark: darkYellow,\n\t\tLight: lightYellow,\n\t}\n\ttheme.MarkdownEmphColor = lipgloss.AdaptiveColor{\n\t\tDark: darkYellow,\n\t\tLight: lightYellow,\n\t}\n\ttheme.MarkdownStrongColor = lipgloss.AdaptiveColor{\n\t\tDark: darkOrange,\n\t\tLight: lightOrange,\n\t}\n\ttheme.MarkdownHorizontalRuleColor = lipgloss.AdaptiveColor{\n\t\tDark: darkComment,\n\t\tLight: lightComment,\n\t}\n\ttheme.MarkdownListItemColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.MarkdownListEnumerationColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBlue,\n\t\tLight: lightBlue,\n\t}\n\ttheme.MarkdownImageColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.MarkdownImageTextColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBlue,\n\t\tLight: lightBlue,\n\t}\n\ttheme.MarkdownCodeBlockColor = lipgloss.AdaptiveColor{\n\t\tDark: darkForeground,\n\t\tLight: lightForeground,\n\t}\n\n\t// Syntax highlighting colors\n\ttheme.SyntaxCommentColor = lipgloss.AdaptiveColor{\n\t\tDark: darkComment,\n\t\tLight: lightComment,\n\t}\n\ttheme.SyntaxKeywordColor = lipgloss.AdaptiveColor{\n\t\tDark: darkRed,\n\t\tLight: lightRed,\n\t}\n\ttheme.SyntaxFunctionColor = lipgloss.AdaptiveColor{\n\t\tDark: darkGreen,\n\t\tLight: lightGreen,\n\t}\n\ttheme.SyntaxVariableColor = lipgloss.AdaptiveColor{\n\t\tDark: darkForeground,\n\t\tLight: lightForeground,\n\t}\n\ttheme.SyntaxStringColor = lipgloss.AdaptiveColor{\n\t\tDark: darkYellow,\n\t\tLight: lightYellow,\n\t}\n\ttheme.SyntaxNumberColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPurple,\n\t\tLight: lightPurple,\n\t}\n\ttheme.SyntaxTypeColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBlue,\n\t\tLight: lightBlue,\n\t}\n\ttheme.SyntaxOperatorColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.SyntaxPunctuationColor = lipgloss.AdaptiveColor{\n\t\tDark: darkForeground,\n\t\tLight: lightForeground,\n\t}\n\n\treturn theme\n}\n\nfunc init() {\n\t// Register the Monokai Pro theme with the theme manager\n\tRegisterTheme(\"monokai\", NewMonokaiProTheme())\n}"], ["/opencode/internal/app/lsp.go", "package app\n\nimport (\n\t\"context\"\n\t\"time\"\n\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n\t\"github.com/opencode-ai/opencode/internal/lsp\"\n\t\"github.com/opencode-ai/opencode/internal/lsp/watcher\"\n)\n\nfunc (app *App) initLSPClients(ctx context.Context) {\n\tcfg := config.Get()\n\n\t// Initialize LSP clients\n\tfor name, clientConfig := range cfg.LSP {\n\t\t// Start each client initialization in its own goroutine\n\t\tgo app.createAndStartLSPClient(ctx, name, clientConfig.Command, clientConfig.Args...)\n\t}\n\tlogging.Info(\"LSP clients initialization started in background\")\n}\n\n// createAndStartLSPClient creates a new LSP client, initializes it, and starts its workspace watcher\nfunc (app *App) createAndStartLSPClient(ctx context.Context, name string, command string, args ...string) {\n\t// Create a specific context for initialization with a timeout\n\tlogging.Info(\"Creating LSP client\", \"name\", name, \"command\", command, \"args\", args)\n\t\n\t// Create the LSP client\n\tlspClient, err := lsp.NewClient(ctx, command, args...)\n\tif err != nil {\n\t\tlogging.Error(\"Failed to create LSP client for\", name, err)\n\t\treturn\n\t}\n\n\t// Create a longer timeout for initialization (some servers take time to start)\n\tinitCtx, cancel := context.WithTimeout(ctx, 30*time.Second)\n\tdefer cancel()\n\t\n\t// Initialize with the initialization context\n\t_, err = lspClient.InitializeLSPClient(initCtx, config.WorkingDirectory())\n\tif err != nil {\n\t\tlogging.Error(\"Initialize failed\", \"name\", name, \"error\", err)\n\t\t// Clean up the client to prevent resource leaks\n\t\tlspClient.Close()\n\t\treturn\n\t}\n\n\t// Wait for the server to be ready\n\tif err := lspClient.WaitForServerReady(initCtx); err != nil {\n\t\tlogging.Error(\"Server failed to become ready\", \"name\", name, \"error\", err)\n\t\t// We'll continue anyway, as some functionality might still work\n\t\tlspClient.SetServerState(lsp.StateError)\n\t} else {\n\t\tlogging.Info(\"LSP server is ready\", \"name\", name)\n\t\tlspClient.SetServerState(lsp.StateReady)\n\t}\n\n\tlogging.Info(\"LSP client initialized\", \"name\", name)\n\t\n\t// Create a child context that can be canceled when the app is shutting down\n\twatchCtx, cancelFunc := context.WithCancel(ctx)\n\t\n\t// Create a context with the server name for better identification\n\twatchCtx = context.WithValue(watchCtx, \"serverName\", name)\n\t\n\t// Create the workspace watcher\n\tworkspaceWatcher := watcher.NewWorkspaceWatcher(lspClient)\n\n\t// Store the cancel function to be called during cleanup\n\tapp.cancelFuncsMutex.Lock()\n\tapp.watcherCancelFuncs = append(app.watcherCancelFuncs, cancelFunc)\n\tapp.cancelFuncsMutex.Unlock()\n\n\t// Add the watcher to a WaitGroup to track active goroutines\n\tapp.watcherWG.Add(1)\n\n\t// Add to map with mutex protection before starting goroutine\n\tapp.clientsMutex.Lock()\n\tapp.LSPClients[name] = lspClient\n\tapp.clientsMutex.Unlock()\n\n\tgo app.runWorkspaceWatcher(watchCtx, name, workspaceWatcher)\n}\n\n// runWorkspaceWatcher executes the workspace watcher for an LSP client\nfunc (app *App) runWorkspaceWatcher(ctx context.Context, name string, workspaceWatcher *watcher.WorkspaceWatcher) {\n\tdefer app.watcherWG.Done()\n\tdefer logging.RecoverPanic(\"LSP-\"+name, func() {\n\t\t// Try to restart the client\n\t\tapp.restartLSPClient(ctx, name)\n\t})\n\n\tworkspaceWatcher.WatchWorkspace(ctx, config.WorkingDirectory())\n\tlogging.Info(\"Workspace watcher stopped\", \"client\", name)\n}\n\n// restartLSPClient attempts to restart a crashed or failed LSP client\nfunc (app *App) restartLSPClient(ctx context.Context, name string) {\n\t// Get the original configuration\n\tcfg := config.Get()\n\tclientConfig, exists := cfg.LSP[name]\n\tif !exists {\n\t\tlogging.Error(\"Cannot restart client, configuration not found\", \"client\", name)\n\t\treturn\n\t}\n\n\t// Clean up the old client if it exists\n\tapp.clientsMutex.Lock()\n\toldClient, exists := app.LSPClients[name]\n\tif exists {\n\t\tdelete(app.LSPClients, name) // Remove from map before potentially slow shutdown\n\t}\n\tapp.clientsMutex.Unlock()\n\n\tif exists && oldClient != nil {\n\t\t// Try to shut it down gracefully, but don't block on errors\n\t\tshutdownCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)\n\t\t_ = oldClient.Shutdown(shutdownCtx)\n\t\tcancel()\n\t}\n\n\t// Create a new client using the shared function\n\tapp.createAndStartLSPClient(ctx, name, clientConfig.Command, clientConfig.Args...)\n\tlogging.Info(\"Successfully restarted LSP client\", \"client\", name)\n}\n"], ["/opencode/internal/config/init.go", "package config\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"path/filepath\"\n)\n\nconst (\n\t// InitFlagFilename is the name of the file that indicates whether the project has been initialized\n\tInitFlagFilename = \"init\"\n)\n\n// ProjectInitFlag represents the initialization status for a project directory\ntype ProjectInitFlag struct {\n\tInitialized bool `json:\"initialized\"`\n}\n\n// ShouldShowInitDialog checks if the initialization dialog should be shown for the current directory\nfunc ShouldShowInitDialog() (bool, error) {\n\tif cfg == nil {\n\t\treturn false, fmt.Errorf(\"config not loaded\")\n\t}\n\n\t// Create the flag file path\n\tflagFilePath := filepath.Join(cfg.Data.Directory, InitFlagFilename)\n\n\t// Check if the flag file exists\n\t_, err := os.Stat(flagFilePath)\n\tif err == nil {\n\t\t// File exists, don't show the dialog\n\t\treturn false, nil\n\t}\n\n\t// If the error is not \"file not found\", return the error\n\tif !os.IsNotExist(err) {\n\t\treturn false, fmt.Errorf(\"failed to check init flag file: %w\", err)\n\t}\n\n\t// File doesn't exist, show the dialog\n\treturn true, nil\n}\n\n// MarkProjectInitialized marks the current project as initialized\nfunc MarkProjectInitialized() error {\n\tif cfg == nil {\n\t\treturn fmt.Errorf(\"config not loaded\")\n\t}\n\t// Create the flag file path\n\tflagFilePath := filepath.Join(cfg.Data.Directory, InitFlagFilename)\n\n\t// Create an empty file to mark the project as initialized\n\tfile, err := os.Create(flagFilePath)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to create init flag file: %w\", err)\n\t}\n\tdefer file.Close()\n\n\treturn nil\n}\n\n"], ["/opencode/internal/tui/layout/overlay.go", "package layout\n\nimport (\n\t\"strings\"\n\n\t\"github.com/charmbracelet/lipgloss\"\n\tchAnsi \"github.com/charmbracelet/x/ansi\"\n\t\"github.com/muesli/ansi\"\n\t\"github.com/muesli/reflow/truncate\"\n\t\"github.com/muesli/termenv\"\n\t\"github.com/opencode-ai/opencode/internal/tui/styles\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n\t\"github.com/opencode-ai/opencode/internal/tui/util\"\n)\n\n// Most of this code is borrowed from\n// https://github.com/charmbracelet/lipgloss/pull/102\n// as well as the lipgloss library, with some modification for what I needed.\n\n// Split a string into lines, additionally returning the size of the widest\n// line.\nfunc getLines(s string) (lines []string, widest int) {\n\tlines = strings.Split(s, \"\\n\")\n\n\tfor _, l := range lines {\n\t\tw := ansi.PrintableRuneWidth(l)\n\t\tif widest < w {\n\t\t\twidest = w\n\t\t}\n\t}\n\n\treturn lines, widest\n}\n\n// PlaceOverlay places fg on top of bg.\nfunc PlaceOverlay(\n\tx, y int,\n\tfg, bg string,\n\tshadow bool, opts ...WhitespaceOption,\n) string {\n\tfgLines, fgWidth := getLines(fg)\n\tbgLines, bgWidth := getLines(bg)\n\tbgHeight := len(bgLines)\n\tfgHeight := len(fgLines)\n\n\tif shadow {\n\t\tt := theme.CurrentTheme()\n\t\tbaseStyle := styles.BaseStyle()\n\n\t\tvar shadowbg string = \"\"\n\t\tshadowchar := lipgloss.NewStyle().\n\t\t\tBackground(t.BackgroundDarker()).\n\t\t\tForeground(t.Background()).\n\t\t\tRender(\"░\")\n\t\tbgchar := baseStyle.Render(\" \")\n\t\tfor i := 0; i <= fgHeight; i++ {\n\t\t\tif i == 0 {\n\t\t\t\tshadowbg += bgchar + strings.Repeat(bgchar, fgWidth) + \"\\n\"\n\t\t\t} else {\n\t\t\t\tshadowbg += bgchar + strings.Repeat(shadowchar, fgWidth) + \"\\n\"\n\t\t\t}\n\t\t}\n\n\t\tfg = PlaceOverlay(0, 0, fg, shadowbg, false, opts...)\n\t\tfgLines, fgWidth = getLines(fg)\n\t\tfgHeight = len(fgLines)\n\t}\n\n\tif fgWidth >= bgWidth && fgHeight >= bgHeight {\n\t\t// FIXME: return fg or bg?\n\t\treturn fg\n\t}\n\t// TODO: allow placement outside of the bg box?\n\tx = util.Clamp(x, 0, bgWidth-fgWidth)\n\ty = util.Clamp(y, 0, bgHeight-fgHeight)\n\n\tws := &whitespace{}\n\tfor _, opt := range opts {\n\t\topt(ws)\n\t}\n\n\tvar b strings.Builder\n\tfor i, bgLine := range bgLines {\n\t\tif i > 0 {\n\t\t\tb.WriteByte('\\n')\n\t\t}\n\t\tif i < y || i >= y+fgHeight {\n\t\t\tb.WriteString(bgLine)\n\t\t\tcontinue\n\t\t}\n\n\t\tpos := 0\n\t\tif x > 0 {\n\t\t\tleft := truncate.String(bgLine, uint(x))\n\t\t\tpos = ansi.PrintableRuneWidth(left)\n\t\t\tb.WriteString(left)\n\t\t\tif pos < x {\n\t\t\t\tb.WriteString(ws.render(x - pos))\n\t\t\t\tpos = x\n\t\t\t}\n\t\t}\n\n\t\tfgLine := fgLines[i-y]\n\t\tb.WriteString(fgLine)\n\t\tpos += ansi.PrintableRuneWidth(fgLine)\n\n\t\tright := cutLeft(bgLine, pos)\n\t\tbgWidth := ansi.PrintableRuneWidth(bgLine)\n\t\trightWidth := ansi.PrintableRuneWidth(right)\n\t\tif rightWidth <= bgWidth-pos {\n\t\t\tb.WriteString(ws.render(bgWidth - rightWidth - pos))\n\t\t}\n\n\t\tb.WriteString(right)\n\t}\n\n\treturn b.String()\n}\n\n// cutLeft cuts printable characters from the left.\n// This function is heavily based on muesli's ansi and truncate packages.\nfunc cutLeft(s string, cutWidth int) string {\n\treturn chAnsi.Cut(s, cutWidth, lipgloss.Width(s))\n}\n\nfunc max(a, b int) int {\n\tif a > b {\n\t\treturn a\n\t}\n\treturn b\n}\n\ntype whitespace struct {\n\tstyle termenv.Style\n\tchars string\n}\n\n// Render whitespaces.\nfunc (w whitespace) render(width int) string {\n\tif w.chars == \"\" {\n\t\tw.chars = \" \"\n\t}\n\n\tr := []rune(w.chars)\n\tj := 0\n\tb := strings.Builder{}\n\n\t// Cycle through runes and print them into the whitespace.\n\tfor i := 0; i < width; {\n\t\tb.WriteRune(r[j])\n\t\tj++\n\t\tif j >= len(r) {\n\t\t\tj = 0\n\t\t}\n\t\ti += ansi.PrintableRuneWidth(string(r[j]))\n\t}\n\n\t// Fill any extra gaps white spaces. This might be necessary if any runes\n\t// are more than one cell wide, which could leave a one-rune gap.\n\tshort := width - ansi.PrintableRuneWidth(b.String())\n\tif short > 0 {\n\t\tb.WriteString(strings.Repeat(\" \", short))\n\t}\n\n\treturn w.style.Styled(b.String())\n}\n\n// WhitespaceOption sets a styling rule for rendering whitespace.\ntype WhitespaceOption func(*whitespace)\n"], ["/opencode/internal/history/file.go", "package history\n\nimport (\n\t\"context\"\n\t\"database/sql\"\n\t\"fmt\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/google/uuid\"\n\t\"github.com/opencode-ai/opencode/internal/db\"\n\t\"github.com/opencode-ai/opencode/internal/pubsub\"\n)\n\nconst (\n\tInitialVersion = \"initial\"\n)\n\ntype File struct {\n\tID string\n\tSessionID string\n\tPath string\n\tContent string\n\tVersion string\n\tCreatedAt int64\n\tUpdatedAt int64\n}\n\ntype Service interface {\n\tpubsub.Suscriber[File]\n\tCreate(ctx context.Context, sessionID, path, content string) (File, error)\n\tCreateVersion(ctx context.Context, sessionID, path, content string) (File, error)\n\tGet(ctx context.Context, id string) (File, error)\n\tGetByPathAndSession(ctx context.Context, path, sessionID string) (File, error)\n\tListBySession(ctx context.Context, sessionID string) ([]File, error)\n\tListLatestSessionFiles(ctx context.Context, sessionID string) ([]File, error)\n\tUpdate(ctx context.Context, file File) (File, error)\n\tDelete(ctx context.Context, id string) error\n\tDeleteSessionFiles(ctx context.Context, sessionID string) error\n}\n\ntype service struct {\n\t*pubsub.Broker[File]\n\tdb *sql.DB\n\tq *db.Queries\n}\n\nfunc NewService(q *db.Queries, db *sql.DB) Service {\n\treturn &service{\n\t\tBroker: pubsub.NewBroker[File](),\n\t\tq: q,\n\t\tdb: db,\n\t}\n}\n\nfunc (s *service) Create(ctx context.Context, sessionID, path, content string) (File, error) {\n\treturn s.createWithVersion(ctx, sessionID, path, content, InitialVersion)\n}\n\nfunc (s *service) CreateVersion(ctx context.Context, sessionID, path, content string) (File, error) {\n\t// Get the latest version for this path\n\tfiles, err := s.q.ListFilesByPath(ctx, path)\n\tif err != nil {\n\t\treturn File{}, err\n\t}\n\n\tif len(files) == 0 {\n\t\t// No previous versions, create initial\n\t\treturn s.Create(ctx, sessionID, path, content)\n\t}\n\n\t// Get the latest version\n\tlatestFile := files[0] // Files are ordered by created_at DESC\n\tlatestVersion := latestFile.Version\n\n\t// Generate the next version\n\tvar nextVersion string\n\tif latestVersion == InitialVersion {\n\t\tnextVersion = \"v1\"\n\t} else if strings.HasPrefix(latestVersion, \"v\") {\n\t\tversionNum, err := strconv.Atoi(latestVersion[1:])\n\t\tif err != nil {\n\t\t\t// If we can't parse the version, just use a timestamp-based version\n\t\t\tnextVersion = fmt.Sprintf(\"v%d\", latestFile.CreatedAt)\n\t\t} else {\n\t\t\tnextVersion = fmt.Sprintf(\"v%d\", versionNum+1)\n\t\t}\n\t} else {\n\t\t// If the version format is unexpected, use a timestamp-based version\n\t\tnextVersion = fmt.Sprintf(\"v%d\", latestFile.CreatedAt)\n\t}\n\n\treturn s.createWithVersion(ctx, sessionID, path, content, nextVersion)\n}\n\nfunc (s *service) createWithVersion(ctx context.Context, sessionID, path, content, version string) (File, error) {\n\t// Maximum number of retries for transaction conflicts\n\tconst maxRetries = 3\n\tvar file File\n\tvar err error\n\n\t// Retry loop for transaction conflicts\n\tfor attempt := range maxRetries {\n\t\t// Start a transaction\n\t\ttx, txErr := s.db.Begin()\n\t\tif txErr != nil {\n\t\t\treturn File{}, fmt.Errorf(\"failed to begin transaction: %w\", txErr)\n\t\t}\n\n\t\t// Create a new queries instance with the transaction\n\t\tqtx := s.q.WithTx(tx)\n\n\t\t// Try to create the file within the transaction\n\t\tdbFile, txErr := qtx.CreateFile(ctx, db.CreateFileParams{\n\t\t\tID: uuid.New().String(),\n\t\t\tSessionID: sessionID,\n\t\t\tPath: path,\n\t\t\tContent: content,\n\t\t\tVersion: version,\n\t\t})\n\t\tif txErr != nil {\n\t\t\t// Rollback the transaction\n\t\t\ttx.Rollback()\n\n\t\t\t// Check if this is a uniqueness constraint violation\n\t\t\tif strings.Contains(txErr.Error(), \"UNIQUE constraint failed\") {\n\t\t\t\tif attempt < maxRetries-1 {\n\t\t\t\t\t// If we have retries left, generate a new version and try again\n\t\t\t\t\tif strings.HasPrefix(version, \"v\") {\n\t\t\t\t\t\tversionNum, parseErr := strconv.Atoi(version[1:])\n\t\t\t\t\t\tif parseErr == nil {\n\t\t\t\t\t\t\tversion = fmt.Sprintf(\"v%d\", versionNum+1)\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t// If we can't parse the version, use a timestamp-based version\n\t\t\t\t\tversion = fmt.Sprintf(\"v%d\", time.Now().Unix())\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn File{}, txErr\n\t\t}\n\n\t\t// Commit the transaction\n\t\tif txErr = tx.Commit(); txErr != nil {\n\t\t\treturn File{}, fmt.Errorf(\"failed to commit transaction: %w\", txErr)\n\t\t}\n\n\t\tfile = s.fromDBItem(dbFile)\n\t\ts.Publish(pubsub.CreatedEvent, file)\n\t\treturn file, nil\n\t}\n\n\treturn file, err\n}\n\nfunc (s *service) Get(ctx context.Context, id string) (File, error) {\n\tdbFile, err := s.q.GetFile(ctx, id)\n\tif err != nil {\n\t\treturn File{}, err\n\t}\n\treturn s.fromDBItem(dbFile), nil\n}\n\nfunc (s *service) GetByPathAndSession(ctx context.Context, path, sessionID string) (File, error) {\n\tdbFile, err := s.q.GetFileByPathAndSession(ctx, db.GetFileByPathAndSessionParams{\n\t\tPath: path,\n\t\tSessionID: sessionID,\n\t})\n\tif err != nil {\n\t\treturn File{}, err\n\t}\n\treturn s.fromDBItem(dbFile), nil\n}\n\nfunc (s *service) ListBySession(ctx context.Context, sessionID string) ([]File, error) {\n\tdbFiles, err := s.q.ListFilesBySession(ctx, sessionID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfiles := make([]File, len(dbFiles))\n\tfor i, dbFile := range dbFiles {\n\t\tfiles[i] = s.fromDBItem(dbFile)\n\t}\n\treturn files, nil\n}\n\nfunc (s *service) ListLatestSessionFiles(ctx context.Context, sessionID string) ([]File, error) {\n\tdbFiles, err := s.q.ListLatestSessionFiles(ctx, sessionID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfiles := make([]File, len(dbFiles))\n\tfor i, dbFile := range dbFiles {\n\t\tfiles[i] = s.fromDBItem(dbFile)\n\t}\n\treturn files, nil\n}\n\nfunc (s *service) Update(ctx context.Context, file File) (File, error) {\n\tdbFile, err := s.q.UpdateFile(ctx, db.UpdateFileParams{\n\t\tID: file.ID,\n\t\tContent: file.Content,\n\t\tVersion: file.Version,\n\t})\n\tif err != nil {\n\t\treturn File{}, err\n\t}\n\tupdatedFile := s.fromDBItem(dbFile)\n\ts.Publish(pubsub.UpdatedEvent, updatedFile)\n\treturn updatedFile, nil\n}\n\nfunc (s *service) Delete(ctx context.Context, id string) error {\n\tfile, err := s.Get(ctx, id)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = s.q.DeleteFile(ctx, id)\n\tif err != nil {\n\t\treturn err\n\t}\n\ts.Publish(pubsub.DeletedEvent, file)\n\treturn nil\n}\n\nfunc (s *service) DeleteSessionFiles(ctx context.Context, sessionID string) error {\n\tfiles, err := s.ListBySession(ctx, sessionID)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor _, file := range files {\n\t\terr = s.Delete(ctx, file.ID)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (s *service) fromDBItem(item db.File) File {\n\treturn File{\n\t\tID: item.ID,\n\t\tSessionID: item.SessionID,\n\t\tPath: item.Path,\n\t\tContent: item.Content,\n\t\tVersion: item.Version,\n\t\tCreatedAt: item.CreatedAt,\n\t\tUpdatedAt: item.UpdatedAt,\n\t}\n}\n"], ["/opencode/internal/tui/theme/dracula.go", "package theme\n\nimport (\n\t\"github.com/charmbracelet/lipgloss\"\n)\n\n// DraculaTheme implements the Theme interface with Dracula colors.\n// It provides both dark and light variants, though Dracula is primarily a dark theme.\ntype DraculaTheme struct {\n\tBaseTheme\n}\n\n// NewDraculaTheme creates a new instance of the Dracula theme.\nfunc NewDraculaTheme() *DraculaTheme {\n\t// Dracula color palette\n\t// Official colors from https://draculatheme.com/\n\tdarkBackground := \"#282a36\"\n\tdarkCurrentLine := \"#44475a\"\n\tdarkSelection := \"#44475a\"\n\tdarkForeground := \"#f8f8f2\"\n\tdarkComment := \"#6272a4\"\n\tdarkCyan := \"#8be9fd\"\n\tdarkGreen := \"#50fa7b\"\n\tdarkOrange := \"#ffb86c\"\n\tdarkPink := \"#ff79c6\"\n\tdarkPurple := \"#bd93f9\"\n\tdarkRed := \"#ff5555\"\n\tdarkYellow := \"#f1fa8c\"\n\tdarkBorder := \"#44475a\"\n\n\t// Light mode approximation (Dracula is primarily a dark theme)\n\tlightBackground := \"#f8f8f2\"\n\tlightCurrentLine := \"#e6e6e6\"\n\tlightSelection := \"#d8d8d8\"\n\tlightForeground := \"#282a36\"\n\tlightComment := \"#6272a4\"\n\tlightCyan := \"#0097a7\"\n\tlightGreen := \"#388e3c\"\n\tlightOrange := \"#f57c00\"\n\tlightPink := \"#d81b60\"\n\tlightPurple := \"#7e57c2\"\n\tlightRed := \"#e53935\"\n\tlightYellow := \"#fbc02d\"\n\tlightBorder := \"#d8d8d8\"\n\n\ttheme := &DraculaTheme{}\n\n\t// Base colors\n\ttheme.PrimaryColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPurple,\n\t\tLight: lightPurple,\n\t}\n\ttheme.SecondaryColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPink,\n\t\tLight: lightPink,\n\t}\n\ttheme.AccentColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\n\t// Status colors\n\ttheme.ErrorColor = lipgloss.AdaptiveColor{\n\t\tDark: darkRed,\n\t\tLight: lightRed,\n\t}\n\ttheme.WarningColor = lipgloss.AdaptiveColor{\n\t\tDark: darkOrange,\n\t\tLight: lightOrange,\n\t}\n\ttheme.SuccessColor = lipgloss.AdaptiveColor{\n\t\tDark: darkGreen,\n\t\tLight: lightGreen,\n\t}\n\ttheme.InfoColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\n\t// Text colors\n\ttheme.TextColor = lipgloss.AdaptiveColor{\n\t\tDark: darkForeground,\n\t\tLight: lightForeground,\n\t}\n\ttheme.TextMutedColor = lipgloss.AdaptiveColor{\n\t\tDark: darkComment,\n\t\tLight: lightComment,\n\t}\n\ttheme.TextEmphasizedColor = lipgloss.AdaptiveColor{\n\t\tDark: darkYellow,\n\t\tLight: lightYellow,\n\t}\n\n\t// Background colors\n\ttheme.BackgroundColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBackground,\n\t\tLight: lightBackground,\n\t}\n\ttheme.BackgroundSecondaryColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCurrentLine,\n\t\tLight: lightCurrentLine,\n\t}\n\ttheme.BackgroundDarkerColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#21222c\", // Slightly darker than background\n\t\tLight: \"#ffffff\", // Slightly lighter than background\n\t}\n\n\t// Border colors\n\ttheme.BorderNormalColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBorder,\n\t\tLight: lightBorder,\n\t}\n\ttheme.BorderFocusedColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPurple,\n\t\tLight: lightPurple,\n\t}\n\ttheme.BorderDimColor = lipgloss.AdaptiveColor{\n\t\tDark: darkSelection,\n\t\tLight: lightSelection,\n\t}\n\n\t// Diff view colors\n\ttheme.DiffAddedColor = lipgloss.AdaptiveColor{\n\t\tDark: darkGreen,\n\t\tLight: lightGreen,\n\t}\n\ttheme.DiffRemovedColor = lipgloss.AdaptiveColor{\n\t\tDark: darkRed,\n\t\tLight: lightRed,\n\t}\n\ttheme.DiffContextColor = lipgloss.AdaptiveColor{\n\t\tDark: darkComment,\n\t\tLight: lightComment,\n\t}\n\ttheme.DiffHunkHeaderColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPurple,\n\t\tLight: lightPurple,\n\t}\n\ttheme.DiffHighlightAddedColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#50fa7b\",\n\t\tLight: \"#a5d6a7\",\n\t}\n\ttheme.DiffHighlightRemovedColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#ff5555\",\n\t\tLight: \"#ef9a9a\",\n\t}\n\ttheme.DiffAddedBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#2c3b2c\",\n\t\tLight: \"#e8f5e9\",\n\t}\n\ttheme.DiffRemovedBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#3b2c2c\",\n\t\tLight: \"#ffebee\",\n\t}\n\ttheme.DiffContextBgColor = lipgloss.AdaptiveColor{\n\t\tDark: darkBackground,\n\t\tLight: lightBackground,\n\t}\n\ttheme.DiffLineNumberColor = lipgloss.AdaptiveColor{\n\t\tDark: darkComment,\n\t\tLight: lightComment,\n\t}\n\ttheme.DiffAddedLineNumberBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#253025\",\n\t\tLight: \"#c8e6c9\",\n\t}\n\ttheme.DiffRemovedLineNumberBgColor = lipgloss.AdaptiveColor{\n\t\tDark: \"#302525\",\n\t\tLight: \"#ffcdd2\",\n\t}\n\n\t// Markdown colors\n\ttheme.MarkdownTextColor = lipgloss.AdaptiveColor{\n\t\tDark: darkForeground,\n\t\tLight: lightForeground,\n\t}\n\ttheme.MarkdownHeadingColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPink,\n\t\tLight: lightPink,\n\t}\n\ttheme.MarkdownLinkColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPurple,\n\t\tLight: lightPurple,\n\t}\n\ttheme.MarkdownLinkTextColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.MarkdownCodeColor = lipgloss.AdaptiveColor{\n\t\tDark: darkGreen,\n\t\tLight: lightGreen,\n\t}\n\ttheme.MarkdownBlockQuoteColor = lipgloss.AdaptiveColor{\n\t\tDark: darkYellow,\n\t\tLight: lightYellow,\n\t}\n\ttheme.MarkdownEmphColor = lipgloss.AdaptiveColor{\n\t\tDark: darkYellow,\n\t\tLight: lightYellow,\n\t}\n\ttheme.MarkdownStrongColor = lipgloss.AdaptiveColor{\n\t\tDark: darkOrange,\n\t\tLight: lightOrange,\n\t}\n\ttheme.MarkdownHorizontalRuleColor = lipgloss.AdaptiveColor{\n\t\tDark: darkComment,\n\t\tLight: lightComment,\n\t}\n\ttheme.MarkdownListItemColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPurple,\n\t\tLight: lightPurple,\n\t}\n\ttheme.MarkdownListEnumerationColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.MarkdownImageColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPurple,\n\t\tLight: lightPurple,\n\t}\n\ttheme.MarkdownImageTextColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.MarkdownCodeBlockColor = lipgloss.AdaptiveColor{\n\t\tDark: darkForeground,\n\t\tLight: lightForeground,\n\t}\n\n\t// Syntax highlighting colors\n\ttheme.SyntaxCommentColor = lipgloss.AdaptiveColor{\n\t\tDark: darkComment,\n\t\tLight: lightComment,\n\t}\n\ttheme.SyntaxKeywordColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPink,\n\t\tLight: lightPink,\n\t}\n\ttheme.SyntaxFunctionColor = lipgloss.AdaptiveColor{\n\t\tDark: darkGreen,\n\t\tLight: lightGreen,\n\t}\n\ttheme.SyntaxVariableColor = lipgloss.AdaptiveColor{\n\t\tDark: darkOrange,\n\t\tLight: lightOrange,\n\t}\n\ttheme.SyntaxStringColor = lipgloss.AdaptiveColor{\n\t\tDark: darkYellow,\n\t\tLight: lightYellow,\n\t}\n\ttheme.SyntaxNumberColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPurple,\n\t\tLight: lightPurple,\n\t}\n\ttheme.SyntaxTypeColor = lipgloss.AdaptiveColor{\n\t\tDark: darkCyan,\n\t\tLight: lightCyan,\n\t}\n\ttheme.SyntaxOperatorColor = lipgloss.AdaptiveColor{\n\t\tDark: darkPink,\n\t\tLight: lightPink,\n\t}\n\ttheme.SyntaxPunctuationColor = lipgloss.AdaptiveColor{\n\t\tDark: darkForeground,\n\t\tLight: lightForeground,\n\t}\n\n\treturn theme\n}\n\nfunc init() {\n\t// Register the Dracula theme with the theme manager\n\tRegisterTheme(\"dracula\", NewDraculaTheme())\n}"], ["/opencode/internal/logging/logger.go", "package logging\n\nimport (\n\t\"fmt\"\n\t\"log/slog\"\n\t\"os\"\n\t// \"path/filepath\"\n\t\"encoding/json\"\n\t\"runtime\"\n\t\"runtime/debug\"\n\t\"sync\"\n\t\"time\"\n)\n\nfunc getCaller() string {\n\tvar caller string\n\tif _, file, line, ok := runtime.Caller(2); ok {\n\t\t// caller = fmt.Sprintf(\"%s:%d\", filepath.Base(file), line)\n\t\tcaller = fmt.Sprintf(\"%s:%d\", file, line)\n\t} else {\n\t\tcaller = \"unknown\"\n\t}\n\treturn caller\n}\nfunc Info(msg string, args ...any) {\n\tsource := getCaller()\n\tslog.Info(msg, append([]any{\"source\", source}, args...)...)\n}\n\nfunc Debug(msg string, args ...any) {\n\t// slog.Debug(msg, args...)\n\tsource := getCaller()\n\tslog.Debug(msg, append([]any{\"source\", source}, args...)...)\n}\n\nfunc Warn(msg string, args ...any) {\n\tslog.Warn(msg, args...)\n}\n\nfunc Error(msg string, args ...any) {\n\tslog.Error(msg, args...)\n}\n\nfunc InfoPersist(msg string, args ...any) {\n\targs = append(args, persistKeyArg, true)\n\tslog.Info(msg, args...)\n}\n\nfunc DebugPersist(msg string, args ...any) {\n\targs = append(args, persistKeyArg, true)\n\tslog.Debug(msg, args...)\n}\n\nfunc WarnPersist(msg string, args ...any) {\n\targs = append(args, persistKeyArg, true)\n\tslog.Warn(msg, args...)\n}\n\nfunc ErrorPersist(msg string, args ...any) {\n\targs = append(args, persistKeyArg, true)\n\tslog.Error(msg, args...)\n}\n\n// RecoverPanic is a common function to handle panics gracefully.\n// It logs the error, creates a panic log file with stack trace,\n// and executes an optional cleanup function before returning.\nfunc RecoverPanic(name string, cleanup func()) {\n\tif r := recover(); r != nil {\n\t\t// Log the panic\n\t\tErrorPersist(fmt.Sprintf(\"Panic in %s: %v\", name, r))\n\n\t\t// Create a timestamped panic log file\n\t\ttimestamp := time.Now().Format(\"20060102-150405\")\n\t\tfilename := fmt.Sprintf(\"opencode-panic-%s-%s.log\", name, timestamp)\n\n\t\tfile, err := os.Create(filename)\n\t\tif err != nil {\n\t\t\tErrorPersist(fmt.Sprintf(\"Failed to create panic log: %v\", err))\n\t\t} else {\n\t\t\tdefer file.Close()\n\n\t\t\t// Write panic information and stack trace\n\t\t\tfmt.Fprintf(file, \"Panic in %s: %v\\n\\n\", name, r)\n\t\t\tfmt.Fprintf(file, \"Time: %s\\n\\n\", time.Now().Format(time.RFC3339))\n\t\t\tfmt.Fprintf(file, \"Stack Trace:\\n%s\\n\", debug.Stack())\n\n\t\t\tInfoPersist(fmt.Sprintf(\"Panic details written to %s\", filename))\n\t\t}\n\n\t\t// Execute cleanup function if provided\n\t\tif cleanup != nil {\n\t\t\tcleanup()\n\t\t}\n\t}\n}\n\n// Message Logging for Debug\nvar MessageDir string\n\nfunc GetSessionPrefix(sessionId string) string {\n\treturn sessionId[:8]\n}\n\nvar sessionLogMutex sync.Mutex\n\nfunc AppendToSessionLogFile(sessionId string, filename string, content string) string {\n\tif MessageDir == \"\" || sessionId == \"\" {\n\t\treturn \"\"\n\t}\n\tsessionPrefix := GetSessionPrefix(sessionId)\n\n\tsessionLogMutex.Lock()\n\tdefer sessionLogMutex.Unlock()\n\n\tsessionPath := fmt.Sprintf(\"%s/%s\", MessageDir, sessionPrefix)\n\tif _, err := os.Stat(sessionPath); os.IsNotExist(err) {\n\t\tif err := os.MkdirAll(sessionPath, 0o766); err != nil {\n\t\t\tError(\"Failed to create session directory\", \"dirpath\", sessionPath, \"error\", err)\n\t\t\treturn \"\"\n\t\t}\n\t}\n\n\tfilePath := fmt.Sprintf(\"%s/%s\", sessionPath, filename)\n\n\tf, err := os.OpenFile(filePath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)\n\tif err != nil {\n\t\tError(\"Failed to open session log file\", \"filepath\", filePath, \"error\", err)\n\t\treturn \"\"\n\t}\n\tdefer f.Close()\n\n\t// Append chunk to file\n\t_, err = f.WriteString(content)\n\tif err != nil {\n\t\tError(\"Failed to write chunk to session log file\", \"filepath\", filePath, \"error\", err)\n\t\treturn \"\"\n\t}\n\treturn filePath\n}\n\nfunc WriteRequestMessageJson(sessionId string, requestSeqId int, message any) string {\n\tif MessageDir == \"\" || sessionId == \"\" || requestSeqId <= 0 {\n\t\treturn \"\"\n\t}\n\tmsgJson, err := json.Marshal(message)\n\tif err != nil {\n\t\tError(\"Failed to marshal message\", \"session_id\", sessionId, \"request_seq_id\", requestSeqId, \"error\", err)\n\t\treturn \"\"\n\t}\n\treturn WriteRequestMessage(sessionId, requestSeqId, string(msgJson))\n}\n\nfunc WriteRequestMessage(sessionId string, requestSeqId int, message string) string {\n\tif MessageDir == \"\" || sessionId == \"\" || requestSeqId <= 0 {\n\t\treturn \"\"\n\t}\n\tfilename := fmt.Sprintf(\"%d_request.json\", requestSeqId)\n\n\treturn AppendToSessionLogFile(sessionId, filename, message)\n}\n\nfunc AppendToStreamSessionLogJson(sessionId string, requestSeqId int, jsonableChunk any) string {\n\tif MessageDir == \"\" || sessionId == \"\" || requestSeqId <= 0 {\n\t\treturn \"\"\n\t}\n\tchunkJson, err := json.Marshal(jsonableChunk)\n\tif err != nil {\n\t\tError(\"Failed to marshal message\", \"session_id\", sessionId, \"request_seq_id\", requestSeqId, \"error\", err)\n\t\treturn \"\"\n\t}\n\treturn AppendToStreamSessionLog(sessionId, requestSeqId, string(chunkJson))\n}\n\nfunc AppendToStreamSessionLog(sessionId string, requestSeqId int, chunk string) string {\n\tif MessageDir == \"\" || sessionId == \"\" || requestSeqId <= 0 {\n\t\treturn \"\"\n\t}\n\tfilename := fmt.Sprintf(\"%d_response_stream.log\", requestSeqId)\n\treturn AppendToSessionLogFile(sessionId, filename, chunk)\n}\n\nfunc WriteChatResponseJson(sessionId string, requestSeqId int, response any) string {\n\tif MessageDir == \"\" || sessionId == \"\" || requestSeqId <= 0 {\n\t\treturn \"\"\n\t}\n\tresponseJson, err := json.Marshal(response)\n\tif err != nil {\n\t\tError(\"Failed to marshal response\", \"session_id\", sessionId, \"request_seq_id\", requestSeqId, \"error\", err)\n\t\treturn \"\"\n\t}\n\tfilename := fmt.Sprintf(\"%d_response.json\", requestSeqId)\n\n\treturn AppendToSessionLogFile(sessionId, filename, string(responseJson))\n}\n\nfunc WriteToolResultsJson(sessionId string, requestSeqId int, toolResults any) string {\n\tif MessageDir == \"\" || sessionId == \"\" || requestSeqId <= 0 {\n\t\treturn \"\"\n\t}\n\ttoolResultsJson, err := json.Marshal(toolResults)\n\tif err != nil {\n\t\tError(\"Failed to marshal tool results\", \"session_id\", sessionId, \"request_seq_id\", requestSeqId, \"error\", err)\n\t\treturn \"\"\n\t}\n\tfilename := fmt.Sprintf(\"%d_tool_results.json\", requestSeqId)\n\treturn AppendToSessionLogFile(sessionId, filename, string(toolResultsJson))\n}\n"], ["/opencode/internal/tui/theme/manager.go", "package theme\n\nimport (\n\t\"fmt\"\n\t\"slices\"\n\t\"strings\"\n\t\"sync\"\n\n\t\"github.com/alecthomas/chroma/v2/styles\"\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n)\n\n// Manager handles theme registration, selection, and retrieval.\n// It maintains a registry of available themes and tracks the currently active theme.\ntype Manager struct {\n\tthemes map[string]Theme\n\tcurrentName string\n\tmu sync.RWMutex\n}\n\n// Global instance of the theme manager\nvar globalManager = &Manager{\n\tthemes: make(map[string]Theme),\n\tcurrentName: \"\",\n}\n\n// RegisterTheme adds a new theme to the registry.\n// If this is the first theme registered, it becomes the default.\nfunc RegisterTheme(name string, theme Theme) {\n\tglobalManager.mu.Lock()\n\tdefer globalManager.mu.Unlock()\n\n\tglobalManager.themes[name] = theme\n\n\t// If this is the first theme, make it the default\n\tif globalManager.currentName == \"\" {\n\t\tglobalManager.currentName = name\n\t}\n}\n\n// SetTheme changes the active theme to the one with the specified name.\n// Returns an error if the theme doesn't exist.\nfunc SetTheme(name string) error {\n\tglobalManager.mu.Lock()\n\tdefer globalManager.mu.Unlock()\n\n\tdelete(styles.Registry, \"charm\")\n\tif _, exists := globalManager.themes[name]; !exists {\n\t\treturn fmt.Errorf(\"theme '%s' not found\", name)\n\t}\n\n\tglobalManager.currentName = name\n\n\t// Update the config file using viper\n\tif err := updateConfigTheme(name); err != nil {\n\t\t// Log the error but don't fail the theme change\n\t\tlogging.Warn(\"Warning: Failed to update config file with new theme\", \"err\", err)\n\t}\n\n\treturn nil\n}\n\n// CurrentTheme returns the currently active theme.\n// If no theme is set, it returns nil.\nfunc CurrentTheme() Theme {\n\tglobalManager.mu.RLock()\n\tdefer globalManager.mu.RUnlock()\n\n\tif globalManager.currentName == \"\" {\n\t\treturn nil\n\t}\n\n\treturn globalManager.themes[globalManager.currentName]\n}\n\n// CurrentThemeName returns the name of the currently active theme.\nfunc CurrentThemeName() string {\n\tglobalManager.mu.RLock()\n\tdefer globalManager.mu.RUnlock()\n\n\treturn globalManager.currentName\n}\n\n// AvailableThemes returns a list of all registered theme names.\nfunc AvailableThemes() []string {\n\tglobalManager.mu.RLock()\n\tdefer globalManager.mu.RUnlock()\n\n\tnames := make([]string, 0, len(globalManager.themes))\n\tfor name := range globalManager.themes {\n\t\tnames = append(names, name)\n\t}\n\tslices.SortFunc(names, func(a, b string) int {\n\t\tif a == \"opencode\" {\n\t\t\treturn -1\n\t\t} else if b == \"opencode\" {\n\t\t\treturn 1\n\t\t}\n\t\treturn strings.Compare(a, b)\n\t})\n\treturn names\n}\n\n// GetTheme returns a specific theme by name.\n// Returns nil if the theme doesn't exist.\nfunc GetTheme(name string) Theme {\n\tglobalManager.mu.RLock()\n\tdefer globalManager.mu.RUnlock()\n\n\treturn globalManager.themes[name]\n}\n\n// updateConfigTheme updates the theme setting in the configuration file\nfunc updateConfigTheme(themeName string) error {\n\t// Use the config package to update the theme\n\treturn config.UpdateTheme(themeName)\n}\n"], ["/opencode/internal/message/content.go", "package message\n\nimport (\n\t\"encoding/base64\"\n\t\"slices\"\n\t\"time\"\n\n\t\"github.com/opencode-ai/opencode/internal/llm/models\"\n)\n\ntype MessageRole string\n\nconst (\n\tAssistant MessageRole = \"assistant\"\n\tUser MessageRole = \"user\"\n\tSystem MessageRole = \"system\"\n\tTool MessageRole = \"tool\"\n)\n\ntype FinishReason string\n\nconst (\n\tFinishReasonEndTurn FinishReason = \"end_turn\"\n\tFinishReasonMaxTokens FinishReason = \"max_tokens\"\n\tFinishReasonToolUse FinishReason = \"tool_use\"\n\tFinishReasonCanceled FinishReason = \"canceled\"\n\tFinishReasonError FinishReason = \"error\"\n\tFinishReasonPermissionDenied FinishReason = \"permission_denied\"\n\n\t// Should never happen\n\tFinishReasonUnknown FinishReason = \"unknown\"\n)\n\ntype ContentPart interface {\n\tisPart()\n}\n\ntype ReasoningContent struct {\n\tThinking string `json:\"thinking\"`\n}\n\nfunc (tc ReasoningContent) String() string {\n\treturn tc.Thinking\n}\nfunc (ReasoningContent) isPart() {}\n\ntype TextContent struct {\n\tText string `json:\"text\"`\n}\n\nfunc (tc TextContent) String() string {\n\treturn tc.Text\n}\n\nfunc (TextContent) isPart() {}\n\ntype ImageURLContent struct {\n\tURL string `json:\"url\"`\n\tDetail string `json:\"detail,omitempty\"`\n}\n\nfunc (iuc ImageURLContent) String() string {\n\treturn iuc.URL\n}\n\nfunc (ImageURLContent) isPart() {}\n\ntype BinaryContent struct {\n\tPath string\n\tMIMEType string\n\tData []byte\n}\n\nfunc (bc BinaryContent) String(provider models.ModelProvider) string {\n\tbase64Encoded := base64.StdEncoding.EncodeToString(bc.Data)\n\tif provider == models.ProviderOpenAI {\n\t\treturn \"data:\" + bc.MIMEType + \";base64,\" + base64Encoded\n\t}\n\treturn base64Encoded\n}\n\nfunc (BinaryContent) isPart() {}\n\ntype ToolCall struct {\n\tID string `json:\"id\"`\n\tName string `json:\"name\"`\n\tInput string `json:\"input\"`\n\tType string `json:\"type\"`\n\tFinished bool `json:\"finished\"`\n}\n\nfunc (ToolCall) isPart() {}\n\ntype ToolResult struct {\n\tToolCallID string `json:\"tool_call_id\"`\n\tName string `json:\"name\"`\n\tContent string `json:\"content\"`\n\tMetadata string `json:\"metadata\"`\n\tIsError bool `json:\"is_error\"`\n}\n\nfunc (ToolResult) isPart() {}\n\ntype Finish struct {\n\tReason FinishReason `json:\"reason\"`\n\tTime int64 `json:\"time\"`\n}\n\nfunc (Finish) isPart() {}\n\ntype Message struct {\n\tID string\n\tRole MessageRole\n\tSessionID string\n\tParts []ContentPart\n\tModel models.ModelID\n\tCreatedAt int64\n\tUpdatedAt int64\n}\n\nfunc (m *Message) Content() TextContent {\n\tfor _, part := range m.Parts {\n\t\tif c, ok := part.(TextContent); ok {\n\t\t\treturn c\n\t\t}\n\t}\n\treturn TextContent{}\n}\n\nfunc (m *Message) ReasoningContent() ReasoningContent {\n\tfor _, part := range m.Parts {\n\t\tif c, ok := part.(ReasoningContent); ok {\n\t\t\treturn c\n\t\t}\n\t}\n\treturn ReasoningContent{}\n}\n\nfunc (m *Message) ImageURLContent() []ImageURLContent {\n\timageURLContents := make([]ImageURLContent, 0)\n\tfor _, part := range m.Parts {\n\t\tif c, ok := part.(ImageURLContent); ok {\n\t\t\timageURLContents = append(imageURLContents, c)\n\t\t}\n\t}\n\treturn imageURLContents\n}\n\nfunc (m *Message) BinaryContent() []BinaryContent {\n\tbinaryContents := make([]BinaryContent, 0)\n\tfor _, part := range m.Parts {\n\t\tif c, ok := part.(BinaryContent); ok {\n\t\t\tbinaryContents = append(binaryContents, c)\n\t\t}\n\t}\n\treturn binaryContents\n}\n\nfunc (m *Message) ToolCalls() []ToolCall {\n\ttoolCalls := make([]ToolCall, 0)\n\tfor _, part := range m.Parts {\n\t\tif c, ok := part.(ToolCall); ok {\n\t\t\ttoolCalls = append(toolCalls, c)\n\t\t}\n\t}\n\treturn toolCalls\n}\n\nfunc (m *Message) ToolResults() []ToolResult {\n\ttoolResults := make([]ToolResult, 0)\n\tfor _, part := range m.Parts {\n\t\tif c, ok := part.(ToolResult); ok {\n\t\t\ttoolResults = append(toolResults, c)\n\t\t}\n\t}\n\treturn toolResults\n}\n\nfunc (m *Message) IsFinished() bool {\n\tfor _, part := range m.Parts {\n\t\tif _, ok := part.(Finish); ok {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc (m *Message) FinishPart() *Finish {\n\tfor _, part := range m.Parts {\n\t\tif c, ok := part.(Finish); ok {\n\t\t\treturn &c\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (m *Message) FinishReason() FinishReason {\n\tfor _, part := range m.Parts {\n\t\tif c, ok := part.(Finish); ok {\n\t\t\treturn c.Reason\n\t\t}\n\t}\n\treturn \"\"\n}\n\nfunc (m *Message) IsThinking() bool {\n\tif m.ReasoningContent().Thinking != \"\" && m.Content().Text == \"\" && !m.IsFinished() {\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc (m *Message) AppendContent(delta string) {\n\tfound := false\n\tfor i, part := range m.Parts {\n\t\tif c, ok := part.(TextContent); ok {\n\t\t\tm.Parts[i] = TextContent{Text: c.Text + delta}\n\t\t\tfound = true\n\t\t}\n\t}\n\tif !found {\n\t\tm.Parts = append(m.Parts, TextContent{Text: delta})\n\t}\n}\n\nfunc (m *Message) AppendReasoningContent(delta string) {\n\tfound := false\n\tfor i, part := range m.Parts {\n\t\tif c, ok := part.(ReasoningContent); ok {\n\t\t\tm.Parts[i] = ReasoningContent{Thinking: c.Thinking + delta}\n\t\t\tfound = true\n\t\t}\n\t}\n\tif !found {\n\t\tm.Parts = append(m.Parts, ReasoningContent{Thinking: delta})\n\t}\n}\n\nfunc (m *Message) FinishToolCall(toolCallID string) {\n\tfor i, part := range m.Parts {\n\t\tif c, ok := part.(ToolCall); ok {\n\t\t\tif c.ID == toolCallID {\n\t\t\t\tm.Parts[i] = ToolCall{\n\t\t\t\t\tID: c.ID,\n\t\t\t\t\tName: c.Name,\n\t\t\t\t\tInput: c.Input,\n\t\t\t\t\tType: c.Type,\n\t\t\t\t\tFinished: true,\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc (m *Message) AppendToolCallInput(toolCallID string, inputDelta string) {\n\tfor i, part := range m.Parts {\n\t\tif c, ok := part.(ToolCall); ok {\n\t\t\tif c.ID == toolCallID {\n\t\t\t\tm.Parts[i] = ToolCall{\n\t\t\t\t\tID: c.ID,\n\t\t\t\t\tName: c.Name,\n\t\t\t\t\tInput: c.Input + inputDelta,\n\t\t\t\t\tType: c.Type,\n\t\t\t\t\tFinished: c.Finished,\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc (m *Message) AddToolCall(tc ToolCall) {\n\tfor i, part := range m.Parts {\n\t\tif c, ok := part.(ToolCall); ok {\n\t\t\tif c.ID == tc.ID {\n\t\t\t\tm.Parts[i] = tc\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\tm.Parts = append(m.Parts, tc)\n}\n\nfunc (m *Message) SetToolCalls(tc []ToolCall) {\n\t// remove any existing tool call part it could have multiple\n\tparts := make([]ContentPart, 0)\n\tfor _, part := range m.Parts {\n\t\tif _, ok := part.(ToolCall); ok {\n\t\t\tcontinue\n\t\t}\n\t\tparts = append(parts, part)\n\t}\n\tm.Parts = parts\n\tfor _, toolCall := range tc {\n\t\tm.Parts = append(m.Parts, toolCall)\n\t}\n}\n\nfunc (m *Message) AddToolResult(tr ToolResult) {\n\tm.Parts = append(m.Parts, tr)\n}\n\nfunc (m *Message) SetToolResults(tr []ToolResult) {\n\tfor _, toolResult := range tr {\n\t\tm.Parts = append(m.Parts, toolResult)\n\t}\n}\n\nfunc (m *Message) AddFinish(reason FinishReason) {\n\t// remove any existing finish part\n\tfor i, part := range m.Parts {\n\t\tif _, ok := part.(Finish); ok {\n\t\t\tm.Parts = slices.Delete(m.Parts, i, i+1)\n\t\t\tbreak\n\t\t}\n\t}\n\tm.Parts = append(m.Parts, Finish{Reason: reason, Time: time.Now().Unix()})\n}\n\nfunc (m *Message) AddImageURL(url, detail string) {\n\tm.Parts = append(m.Parts, ImageURLContent{URL: url, Detail: detail})\n}\n\nfunc (m *Message) AddBinary(mimeType string, data []byte) {\n\tm.Parts = append(m.Parts, BinaryContent{MIMEType: mimeType, Data: data})\n}\n"], ["/opencode/internal/llm/provider/bedrock.go", "package provider\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"os\"\n\t\"strings\"\n\n\t\"github.com/opencode-ai/opencode/internal/llm/tools\"\n\t\"github.com/opencode-ai/opencode/internal/message\"\n)\n\ntype bedrockOptions struct {\n\t// Bedrock specific options can be added here\n}\n\ntype BedrockOption func(*bedrockOptions)\n\ntype bedrockClient struct {\n\tproviderOptions providerClientOptions\n\toptions bedrockOptions\n\tchildProvider ProviderClient\n}\n\ntype BedrockClient ProviderClient\n\nfunc newBedrockClient(opts providerClientOptions) BedrockClient {\n\tbedrockOpts := bedrockOptions{}\n\t// Apply bedrock specific options if they are added in the future\n\n\t// Get AWS region from environment\n\tregion := os.Getenv(\"AWS_REGION\")\n\tif region == \"\" {\n\t\tregion = os.Getenv(\"AWS_DEFAULT_REGION\")\n\t}\n\n\tif region == \"\" {\n\t\tregion = \"us-east-1\" // default region\n\t}\n\tif len(region) < 2 {\n\t\treturn &bedrockClient{\n\t\t\tproviderOptions: opts,\n\t\t\toptions: bedrockOpts,\n\t\t\tchildProvider: nil, // Will cause an error when used\n\t\t}\n\t}\n\n\t// Prefix the model name with region\n\tregionPrefix := region[:2]\n\tmodelName := opts.model.APIModel\n\topts.model.APIModel = fmt.Sprintf(\"%s.%s\", regionPrefix, modelName)\n\n\t// Determine which provider to use based on the model\n\tif strings.Contains(string(opts.model.APIModel), \"anthropic\") {\n\t\t// Create Anthropic client with Bedrock configuration\n\t\tanthropicOpts := opts\n\t\tanthropicOpts.anthropicOptions = append(anthropicOpts.anthropicOptions,\n\t\t\tWithAnthropicBedrock(true),\n\t\t\tWithAnthropicDisableCache(),\n\t\t)\n\t\treturn &bedrockClient{\n\t\t\tproviderOptions: opts,\n\t\t\toptions: bedrockOpts,\n\t\t\tchildProvider: newAnthropicClient(anthropicOpts),\n\t\t}\n\t}\n\n\t// Return client with nil childProvider if model is not supported\n\t// This will cause an error when used\n\treturn &bedrockClient{\n\t\tproviderOptions: opts,\n\t\toptions: bedrockOpts,\n\t\tchildProvider: nil,\n\t}\n}\n\nfunc (b *bedrockClient) send(ctx context.Context, messages []message.Message, tools []tools.BaseTool) (*ProviderResponse, error) {\n\tif b.childProvider == nil {\n\t\treturn nil, errors.New(\"unsupported model for bedrock provider\")\n\t}\n\treturn b.childProvider.send(ctx, messages, tools)\n}\n\nfunc (b *bedrockClient) stream(ctx context.Context, messages []message.Message, tools []tools.BaseTool) <-chan ProviderEvent {\n\teventChan := make(chan ProviderEvent)\n\n\tif b.childProvider == nil {\n\t\tgo func() {\n\t\t\teventChan <- ProviderEvent{\n\t\t\t\tType: EventError,\n\t\t\t\tError: errors.New(\"unsupported model for bedrock provider\"),\n\t\t\t}\n\t\t\tclose(eventChan)\n\t\t}()\n\t\treturn eventChan\n\t}\n\n\treturn b.childProvider.stream(ctx, messages, tools)\n}\n\n"], ["/opencode/internal/tui/image/images.go", "package image\n\nimport (\n\t\"fmt\"\n\t\"image\"\n\t\"os\"\n\t\"strings\"\n\n\t\"github.com/charmbracelet/lipgloss\"\n\t\"github.com/disintegration/imaging\"\n\t\"github.com/lucasb-eyer/go-colorful\"\n)\n\nfunc ValidateFileSize(filePath string, sizeLimit int64) (bool, error) {\n\tfileInfo, err := os.Stat(filePath)\n\tif err != nil {\n\t\treturn false, fmt.Errorf(\"error getting file info: %w\", err)\n\t}\n\n\tif fileInfo.Size() > sizeLimit {\n\t\treturn true, nil\n\t}\n\n\treturn false, nil\n}\n\nfunc ToString(width int, img image.Image) string {\n\timg = imaging.Resize(img, width, 0, imaging.Lanczos)\n\tb := img.Bounds()\n\timageWidth := b.Max.X\n\th := b.Max.Y\n\tstr := strings.Builder{}\n\n\tfor heightCounter := 0; heightCounter < h; heightCounter += 2 {\n\t\tfor x := range imageWidth {\n\t\t\tc1, _ := colorful.MakeColor(img.At(x, heightCounter))\n\t\t\tcolor1 := lipgloss.Color(c1.Hex())\n\n\t\t\tvar color2 lipgloss.Color\n\t\t\tif heightCounter+1 < h {\n\t\t\t\tc2, _ := colorful.MakeColor(img.At(x, heightCounter+1))\n\t\t\t\tcolor2 = lipgloss.Color(c2.Hex())\n\t\t\t} else {\n\t\t\t\tcolor2 = color1\n\t\t\t}\n\n\t\t\tstr.WriteString(lipgloss.NewStyle().Foreground(color1).\n\t\t\t\tBackground(color2).Render(\"▀\"))\n\t\t}\n\n\t\tstr.WriteString(\"\\n\")\n\t}\n\n\treturn str.String()\n}\n\nfunc ImagePreview(width int, filename string) (string, error) {\n\timageContent, err := os.Open(filename)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer imageContent.Close()\n\n\timg, _, err := image.Decode(imageContent)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\timageString := ToString(width, img)\n\n\treturn imageString, nil\n}\n"], ["/opencode/internal/tui/styles/styles.go", "package styles\n\nimport (\n\t\"github.com/charmbracelet/lipgloss\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n)\n\nvar (\n\tImageBakcground = \"#212121\"\n)\n\n// Style generation functions that use the current theme\n\n// BaseStyle returns the base style with background and foreground colors\nfunc BaseStyle() lipgloss.Style {\n\tt := theme.CurrentTheme()\n\treturn lipgloss.NewStyle().\n\t\tBackground(t.Background()).\n\t\tForeground(t.Text())\n}\n\n// Regular returns a basic unstyled lipgloss.Style\nfunc Regular() lipgloss.Style {\n\treturn lipgloss.NewStyle()\n}\n\n// Bold returns a bold style\nfunc Bold() lipgloss.Style {\n\treturn Regular().Bold(true)\n}\n\n// Padded returns a style with horizontal padding\nfunc Padded() lipgloss.Style {\n\treturn Regular().Padding(0, 1)\n}\n\n// Border returns a style with a normal border\nfunc Border() lipgloss.Style {\n\tt := theme.CurrentTheme()\n\treturn Regular().\n\t\tBorder(lipgloss.NormalBorder()).\n\t\tBorderForeground(t.BorderNormal())\n}\n\n// ThickBorder returns a style with a thick border\nfunc ThickBorder() lipgloss.Style {\n\tt := theme.CurrentTheme()\n\treturn Regular().\n\t\tBorder(lipgloss.ThickBorder()).\n\t\tBorderForeground(t.BorderNormal())\n}\n\n// DoubleBorder returns a style with a double border\nfunc DoubleBorder() lipgloss.Style {\n\tt := theme.CurrentTheme()\n\treturn Regular().\n\t\tBorder(lipgloss.DoubleBorder()).\n\t\tBorderForeground(t.BorderNormal())\n}\n\n// FocusedBorder returns a style with a border using the focused border color\nfunc FocusedBorder() lipgloss.Style {\n\tt := theme.CurrentTheme()\n\treturn Regular().\n\t\tBorder(lipgloss.NormalBorder()).\n\t\tBorderForeground(t.BorderFocused())\n}\n\n// DimBorder returns a style with a border using the dim border color\nfunc DimBorder() lipgloss.Style {\n\tt := theme.CurrentTheme()\n\treturn Regular().\n\t\tBorder(lipgloss.NormalBorder()).\n\t\tBorderForeground(t.BorderDim())\n}\n\n// PrimaryColor returns the primary color from the current theme\nfunc PrimaryColor() lipgloss.AdaptiveColor {\n\treturn theme.CurrentTheme().Primary()\n}\n\n// SecondaryColor returns the secondary color from the current theme\nfunc SecondaryColor() lipgloss.AdaptiveColor {\n\treturn theme.CurrentTheme().Secondary()\n}\n\n// AccentColor returns the accent color from the current theme\nfunc AccentColor() lipgloss.AdaptiveColor {\n\treturn theme.CurrentTheme().Accent()\n}\n\n// ErrorColor returns the error color from the current theme\nfunc ErrorColor() lipgloss.AdaptiveColor {\n\treturn theme.CurrentTheme().Error()\n}\n\n// WarningColor returns the warning color from the current theme\nfunc WarningColor() lipgloss.AdaptiveColor {\n\treturn theme.CurrentTheme().Warning()\n}\n\n// SuccessColor returns the success color from the current theme\nfunc SuccessColor() lipgloss.AdaptiveColor {\n\treturn theme.CurrentTheme().Success()\n}\n\n// InfoColor returns the info color from the current theme\nfunc InfoColor() lipgloss.AdaptiveColor {\n\treturn theme.CurrentTheme().Info()\n}\n\n// TextColor returns the text color from the current theme\nfunc TextColor() lipgloss.AdaptiveColor {\n\treturn theme.CurrentTheme().Text()\n}\n\n// TextMutedColor returns the muted text color from the current theme\nfunc TextMutedColor() lipgloss.AdaptiveColor {\n\treturn theme.CurrentTheme().TextMuted()\n}\n\n// TextEmphasizedColor returns the emphasized text color from the current theme\nfunc TextEmphasizedColor() lipgloss.AdaptiveColor {\n\treturn theme.CurrentTheme().TextEmphasized()\n}\n\n// BackgroundColor returns the background color from the current theme\nfunc BackgroundColor() lipgloss.AdaptiveColor {\n\treturn theme.CurrentTheme().Background()\n}\n\n// BackgroundSecondaryColor returns the secondary background color from the current theme\nfunc BackgroundSecondaryColor() lipgloss.AdaptiveColor {\n\treturn theme.CurrentTheme().BackgroundSecondary()\n}\n\n// BackgroundDarkerColor returns the darker background color from the current theme\nfunc BackgroundDarkerColor() lipgloss.AdaptiveColor {\n\treturn theme.CurrentTheme().BackgroundDarker()\n}\n\n// BorderNormalColor returns the normal border color from the current theme\nfunc BorderNormalColor() lipgloss.AdaptiveColor {\n\treturn theme.CurrentTheme().BorderNormal()\n}\n\n// BorderFocusedColor returns the focused border color from the current theme\nfunc BorderFocusedColor() lipgloss.AdaptiveColor {\n\treturn theme.CurrentTheme().BorderFocused()\n}\n\n// BorderDimColor returns the dim border color from the current theme\nfunc BorderDimColor() lipgloss.AdaptiveColor {\n\treturn theme.CurrentTheme().BorderDim()\n}\n"], ["/opencode/internal/llm/provider/vertexai.go", "package provider\n\nimport (\n\t\"context\"\n\t\"os\"\n\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n\t\"google.golang.org/genai\"\n)\n\ntype VertexAIClient ProviderClient\n\nfunc newVertexAIClient(opts providerClientOptions) VertexAIClient {\n\tgeminiOpts := geminiOptions{}\n\tfor _, o := range opts.geminiOptions {\n\t\to(&geminiOpts)\n\t}\n\n\tclient, err := genai.NewClient(context.Background(), &genai.ClientConfig{\n\t\tProject: os.Getenv(\"VERTEXAI_PROJECT\"),\n\t\tLocation: os.Getenv(\"VERTEXAI_LOCATION\"),\n\t\tBackend: genai.BackendVertexAI,\n\t})\n\tif err != nil {\n\t\tlogging.Error(\"Failed to create VertexAI client\", \"error\", err)\n\t\treturn nil\n\t}\n\n\treturn &geminiClient{\n\t\tproviderOptions: opts,\n\t\toptions: geminiOpts,\n\t\tclient: client,\n\t}\n}\n"], ["/opencode/internal/llm/agent/tools.go", "package agent\n\nimport (\n\t\"context\"\n\n\t\"github.com/opencode-ai/opencode/internal/history\"\n\t\"github.com/opencode-ai/opencode/internal/llm/tools\"\n\t\"github.com/opencode-ai/opencode/internal/lsp\"\n\t\"github.com/opencode-ai/opencode/internal/message\"\n\t\"github.com/opencode-ai/opencode/internal/permission\"\n\t\"github.com/opencode-ai/opencode/internal/session\"\n)\n\nfunc CoderAgentTools(\n\tpermissions permission.Service,\n\tsessions session.Service,\n\tmessages message.Service,\n\thistory history.Service,\n\tlspClients map[string]*lsp.Client,\n) []tools.BaseTool {\n\tctx := context.Background()\n\totherTools := GetMcpTools(ctx, permissions)\n\tif len(lspClients) > 0 {\n\t\totherTools = append(otherTools, tools.NewDiagnosticsTool(lspClients))\n\t}\n\treturn append(\n\t\t[]tools.BaseTool{\n\t\t\ttools.NewBashTool(permissions),\n\t\t\ttools.NewEditTool(lspClients, permissions, history),\n\t\t\ttools.NewFetchTool(permissions),\n\t\t\ttools.NewGlobTool(),\n\t\t\ttools.NewGrepTool(),\n\t\t\ttools.NewLsTool(),\n\t\t\ttools.NewSourcegraphTool(),\n\t\t\ttools.NewViewTool(lspClients),\n\t\t\ttools.NewPatchTool(lspClients, permissions, history),\n\t\t\ttools.NewWriteTool(lspClients, permissions, history),\n\t\t\tNewAgentTool(sessions, messages, lspClients),\n\t\t}, otherTools...,\n\t)\n}\n\nfunc TaskAgentTools(lspClients map[string]*lsp.Client) []tools.BaseTool {\n\treturn []tools.BaseTool{\n\t\ttools.NewGlobTool(),\n\t\ttools.NewGrepTool(),\n\t\ttools.NewLsTool(),\n\t\ttools.NewSourcegraphTool(),\n\t\ttools.NewViewTool(lspClients),\n\t}\n}\n"], ["/opencode/internal/tui/layout/container.go", "package layout\n\nimport (\n\t\"github.com/charmbracelet/bubbles/key\"\n\ttea \"github.com/charmbracelet/bubbletea\"\n\t\"github.com/charmbracelet/lipgloss\"\n\t\"github.com/opencode-ai/opencode/internal/tui/theme\"\n)\n\ntype Container interface {\n\ttea.Model\n\tSizeable\n\tBindings\n}\ntype container struct {\n\twidth int\n\theight int\n\n\tcontent tea.Model\n\n\t// Style options\n\tpaddingTop int\n\tpaddingRight int\n\tpaddingBottom int\n\tpaddingLeft int\n\n\tborderTop bool\n\tborderRight bool\n\tborderBottom bool\n\tborderLeft bool\n\tborderStyle lipgloss.Border\n}\n\nfunc (c *container) Init() tea.Cmd {\n\treturn c.content.Init()\n}\n\nfunc (c *container) Update(msg tea.Msg) (tea.Model, tea.Cmd) {\n\tu, cmd := c.content.Update(msg)\n\tc.content = u\n\treturn c, cmd\n}\n\nfunc (c *container) View() string {\n\tt := theme.CurrentTheme()\n\tstyle := lipgloss.NewStyle()\n\twidth := c.width\n\theight := c.height\n\n\tstyle = style.Background(t.Background())\n\n\t// Apply border if any side is enabled\n\tif c.borderTop || c.borderRight || c.borderBottom || c.borderLeft {\n\t\t// Adjust width and height for borders\n\t\tif c.borderTop {\n\t\t\theight--\n\t\t}\n\t\tif c.borderBottom {\n\t\t\theight--\n\t\t}\n\t\tif c.borderLeft {\n\t\t\twidth--\n\t\t}\n\t\tif c.borderRight {\n\t\t\twidth--\n\t\t}\n\t\tstyle = style.Border(c.borderStyle, c.borderTop, c.borderRight, c.borderBottom, c.borderLeft)\n\t\tstyle = style.BorderBackground(t.Background()).BorderForeground(t.BorderNormal())\n\t}\n\tstyle = style.\n\t\tWidth(width).\n\t\tHeight(height).\n\t\tPaddingTop(c.paddingTop).\n\t\tPaddingRight(c.paddingRight).\n\t\tPaddingBottom(c.paddingBottom).\n\t\tPaddingLeft(c.paddingLeft)\n\n\treturn style.Render(c.content.View())\n}\n\nfunc (c *container) SetSize(width, height int) tea.Cmd {\n\tc.width = width\n\tc.height = height\n\n\t// If the content implements Sizeable, adjust its size to account for padding and borders\n\tif sizeable, ok := c.content.(Sizeable); ok {\n\t\t// Calculate horizontal space taken by padding and borders\n\t\thorizontalSpace := c.paddingLeft + c.paddingRight\n\t\tif c.borderLeft {\n\t\t\thorizontalSpace++\n\t\t}\n\t\tif c.borderRight {\n\t\t\thorizontalSpace++\n\t\t}\n\n\t\t// Calculate vertical space taken by padding and borders\n\t\tverticalSpace := c.paddingTop + c.paddingBottom\n\t\tif c.borderTop {\n\t\t\tverticalSpace++\n\t\t}\n\t\tif c.borderBottom {\n\t\t\tverticalSpace++\n\t\t}\n\n\t\t// Set content size with adjusted dimensions\n\t\tcontentWidth := max(0, width-horizontalSpace)\n\t\tcontentHeight := max(0, height-verticalSpace)\n\t\treturn sizeable.SetSize(contentWidth, contentHeight)\n\t}\n\treturn nil\n}\n\nfunc (c *container) GetSize() (int, int) {\n\treturn c.width, c.height\n}\n\nfunc (c *container) BindingKeys() []key.Binding {\n\tif b, ok := c.content.(Bindings); ok {\n\t\treturn b.BindingKeys()\n\t}\n\treturn []key.Binding{}\n}\n\ntype ContainerOption func(*container)\n\nfunc NewContainer(content tea.Model, options ...ContainerOption) Container {\n\n\tc := &container{\n\t\tcontent: content,\n\t\tborderStyle: lipgloss.NormalBorder(),\n\t}\n\n\tfor _, option := range options {\n\t\toption(c)\n\t}\n\n\treturn c\n}\n\n// Padding options\nfunc WithPadding(top, right, bottom, left int) ContainerOption {\n\treturn func(c *container) {\n\t\tc.paddingTop = top\n\t\tc.paddingRight = right\n\t\tc.paddingBottom = bottom\n\t\tc.paddingLeft = left\n\t}\n}\n\nfunc WithPaddingAll(padding int) ContainerOption {\n\treturn WithPadding(padding, padding, padding, padding)\n}\n\nfunc WithPaddingHorizontal(padding int) ContainerOption {\n\treturn func(c *container) {\n\t\tc.paddingLeft = padding\n\t\tc.paddingRight = padding\n\t}\n}\n\nfunc WithPaddingVertical(padding int) ContainerOption {\n\treturn func(c *container) {\n\t\tc.paddingTop = padding\n\t\tc.paddingBottom = padding\n\t}\n}\n\nfunc WithBorder(top, right, bottom, left bool) ContainerOption {\n\treturn func(c *container) {\n\t\tc.borderTop = top\n\t\tc.borderRight = right\n\t\tc.borderBottom = bottom\n\t\tc.borderLeft = left\n\t}\n}\n\nfunc WithBorderAll() ContainerOption {\n\treturn WithBorder(true, true, true, true)\n}\n\nfunc WithBorderHorizontal() ContainerOption {\n\treturn WithBorder(true, false, true, false)\n}\n\nfunc WithBorderVertical() ContainerOption {\n\treturn WithBorder(false, true, false, true)\n}\n\nfunc WithBorderStyle(style lipgloss.Border) ContainerOption {\n\treturn func(c *container) {\n\t\tc.borderStyle = style\n\t}\n}\n\nfunc WithRoundedBorder() ContainerOption {\n\treturn WithBorderStyle(lipgloss.RoundedBorder())\n}\n\nfunc WithThickBorder() ContainerOption {\n\treturn WithBorderStyle(lipgloss.ThickBorder())\n}\n\nfunc WithDoubleBorder() ContainerOption {\n\treturn WithBorderStyle(lipgloss.DoubleBorder())\n}\n"], ["/opencode/internal/permission/permission.go", "package permission\n\nimport (\n\t\"errors\"\n\t\"path/filepath\"\n\t\"slices\"\n\t\"sync\"\n\n\t\"github.com/google/uuid\"\n\t\"github.com/opencode-ai/opencode/internal/config\"\n\t\"github.com/opencode-ai/opencode/internal/pubsub\"\n)\n\nvar ErrorPermissionDenied = errors.New(\"permission denied\")\n\ntype CreatePermissionRequest struct {\n\tSessionID string `json:\"session_id\"`\n\tToolName string `json:\"tool_name\"`\n\tDescription string `json:\"description\"`\n\tAction string `json:\"action\"`\n\tParams any `json:\"params\"`\n\tPath string `json:\"path\"`\n}\n\ntype PermissionRequest struct {\n\tID string `json:\"id\"`\n\tSessionID string `json:\"session_id\"`\n\tToolName string `json:\"tool_name\"`\n\tDescription string `json:\"description\"`\n\tAction string `json:\"action\"`\n\tParams any `json:\"params\"`\n\tPath string `json:\"path\"`\n}\n\ntype Service interface {\n\tpubsub.Suscriber[PermissionRequest]\n\tGrantPersistant(permission PermissionRequest)\n\tGrant(permission PermissionRequest)\n\tDeny(permission PermissionRequest)\n\tRequest(opts CreatePermissionRequest) bool\n\tAutoApproveSession(sessionID string)\n}\n\ntype permissionService struct {\n\t*pubsub.Broker[PermissionRequest]\n\n\tsessionPermissions []PermissionRequest\n\tpendingRequests sync.Map\n\tautoApproveSessions []string\n}\n\nfunc (s *permissionService) GrantPersistant(permission PermissionRequest) {\n\trespCh, ok := s.pendingRequests.Load(permission.ID)\n\tif ok {\n\t\trespCh.(chan bool) <- true\n\t}\n\ts.sessionPermissions = append(s.sessionPermissions, permission)\n}\n\nfunc (s *permissionService) Grant(permission PermissionRequest) {\n\trespCh, ok := s.pendingRequests.Load(permission.ID)\n\tif ok {\n\t\trespCh.(chan bool) <- true\n\t}\n}\n\nfunc (s *permissionService) Deny(permission PermissionRequest) {\n\trespCh, ok := s.pendingRequests.Load(permission.ID)\n\tif ok {\n\t\trespCh.(chan bool) <- false\n\t}\n}\n\nfunc (s *permissionService) Request(opts CreatePermissionRequest) bool {\n\tif slices.Contains(s.autoApproveSessions, opts.SessionID) {\n\t\treturn true\n\t}\n\tdir := filepath.Dir(opts.Path)\n\tif dir == \".\" {\n\t\tdir = config.WorkingDirectory()\n\t}\n\tpermission := PermissionRequest{\n\t\tID: uuid.New().String(),\n\t\tPath: dir,\n\t\tSessionID: opts.SessionID,\n\t\tToolName: opts.ToolName,\n\t\tDescription: opts.Description,\n\t\tAction: opts.Action,\n\t\tParams: opts.Params,\n\t}\n\n\tfor _, p := range s.sessionPermissions {\n\t\tif p.ToolName == permission.ToolName && p.Action == permission.Action && p.SessionID == permission.SessionID && p.Path == permission.Path {\n\t\t\treturn true\n\t\t}\n\t}\n\n\trespCh := make(chan bool, 1)\n\n\ts.pendingRequests.Store(permission.ID, respCh)\n\tdefer s.pendingRequests.Delete(permission.ID)\n\n\ts.Publish(pubsub.CreatedEvent, permission)\n\n\t// Wait for the response with a timeout\n\tresp := <-respCh\n\treturn resp\n}\n\nfunc (s *permissionService) AutoApproveSession(sessionID string) {\n\ts.autoApproveSessions = append(s.autoApproveSessions, sessionID)\n}\n\nfunc NewPermissionService() Service {\n\treturn &permissionService{\n\t\tBroker: pubsub.NewBroker[PermissionRequest](),\n\t\tsessionPermissions: make([]PermissionRequest, 0),\n\t}\n}\n"], ["/opencode/internal/version/version.go", "package version\n\nimport \"runtime/debug\"\n\n// Build-time parameters set via -ldflags\nvar Version = \"unknown\"\n\n// A user may install pug using `go install github.com/opencode-ai/opencode@latest`.\n// without -ldflags, in which case the version above is unset. As a workaround\n// we use the embedded build version that *is* set when using `go install` (and\n// is only set for `go install` and not for `go build`).\nfunc init() {\n\tinfo, ok := debug.ReadBuildInfo()\n\tif !ok {\n\t\t// < go v1.18\n\t\treturn\n\t}\n\tmainVersion := info.Main.Version\n\tif mainVersion == \"\" || mainVersion == \"(devel)\" {\n\t\t// bin not built using `go install`\n\t\treturn\n\t}\n\t// bin built using `go install`\n\tVersion = mainVersion\n}\n"], ["/opencode/internal/session/session.go", "package session\n\nimport (\n\t\"context\"\n\t\"database/sql\"\n\n\t\"github.com/google/uuid\"\n\t\"github.com/opencode-ai/opencode/internal/db\"\n\t\"github.com/opencode-ai/opencode/internal/pubsub\"\n)\n\ntype Session struct {\n\tID string\n\tParentSessionID string\n\tTitle string\n\tMessageCount int64\n\tPromptTokens int64\n\tCompletionTokens int64\n\tSummaryMessageID string\n\tCost float64\n\tCreatedAt int64\n\tUpdatedAt int64\n}\n\ntype Service interface {\n\tpubsub.Suscriber[Session]\n\tCreate(ctx context.Context, title string) (Session, error)\n\tCreateTitleSession(ctx context.Context, parentSessionID string) (Session, error)\n\tCreateTaskSession(ctx context.Context, toolCallID, parentSessionID, title string) (Session, error)\n\tGet(ctx context.Context, id string) (Session, error)\n\tList(ctx context.Context) ([]Session, error)\n\tSave(ctx context.Context, session Session) (Session, error)\n\tDelete(ctx context.Context, id string) error\n}\n\ntype service struct {\n\t*pubsub.Broker[Session]\n\tq db.Querier\n}\n\nfunc (s *service) Create(ctx context.Context, title string) (Session, error) {\n\tdbSession, err := s.q.CreateSession(ctx, db.CreateSessionParams{\n\t\tID: uuid.New().String(),\n\t\tTitle: title,\n\t})\n\tif err != nil {\n\t\treturn Session{}, err\n\t}\n\tsession := s.fromDBItem(dbSession)\n\ts.Publish(pubsub.CreatedEvent, session)\n\treturn session, nil\n}\n\nfunc (s *service) CreateTaskSession(ctx context.Context, toolCallID, parentSessionID, title string) (Session, error) {\n\tdbSession, err := s.q.CreateSession(ctx, db.CreateSessionParams{\n\t\tID: toolCallID,\n\t\tParentSessionID: sql.NullString{String: parentSessionID, Valid: true},\n\t\tTitle: title,\n\t})\n\tif err != nil {\n\t\treturn Session{}, err\n\t}\n\tsession := s.fromDBItem(dbSession)\n\ts.Publish(pubsub.CreatedEvent, session)\n\treturn session, nil\n}\n\nfunc (s *service) CreateTitleSession(ctx context.Context, parentSessionID string) (Session, error) {\n\tdbSession, err := s.q.CreateSession(ctx, db.CreateSessionParams{\n\t\tID: \"title-\" + parentSessionID,\n\t\tParentSessionID: sql.NullString{String: parentSessionID, Valid: true},\n\t\tTitle: \"Generate a title\",\n\t})\n\tif err != nil {\n\t\treturn Session{}, err\n\t}\n\tsession := s.fromDBItem(dbSession)\n\ts.Publish(pubsub.CreatedEvent, session)\n\treturn session, nil\n}\n\nfunc (s *service) Delete(ctx context.Context, id string) error {\n\tsession, err := s.Get(ctx, id)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = s.q.DeleteSession(ctx, session.ID)\n\tif err != nil {\n\t\treturn err\n\t}\n\ts.Publish(pubsub.DeletedEvent, session)\n\treturn nil\n}\n\nfunc (s *service) Get(ctx context.Context, id string) (Session, error) {\n\tdbSession, err := s.q.GetSessionByID(ctx, id)\n\tif err != nil {\n\t\treturn Session{}, err\n\t}\n\treturn s.fromDBItem(dbSession), nil\n}\n\nfunc (s *service) Save(ctx context.Context, session Session) (Session, error) {\n\tdbSession, err := s.q.UpdateSession(ctx, db.UpdateSessionParams{\n\t\tID: session.ID,\n\t\tTitle: session.Title,\n\t\tPromptTokens: session.PromptTokens,\n\t\tCompletionTokens: session.CompletionTokens,\n\t\tSummaryMessageID: sql.NullString{\n\t\t\tString: session.SummaryMessageID,\n\t\t\tValid: session.SummaryMessageID != \"\",\n\t\t},\n\t\tCost: session.Cost,\n\t})\n\tif err != nil {\n\t\treturn Session{}, err\n\t}\n\tsession = s.fromDBItem(dbSession)\n\ts.Publish(pubsub.UpdatedEvent, session)\n\treturn session, nil\n}\n\nfunc (s *service) List(ctx context.Context) ([]Session, error) {\n\tdbSessions, err := s.q.ListSessions(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsessions := make([]Session, len(dbSessions))\n\tfor i, dbSession := range dbSessions {\n\t\tsessions[i] = s.fromDBItem(dbSession)\n\t}\n\treturn sessions, nil\n}\n\nfunc (s service) fromDBItem(item db.Session) Session {\n\treturn Session{\n\t\tID: item.ID,\n\t\tParentSessionID: item.ParentSessionID.String,\n\t\tTitle: item.Title,\n\t\tMessageCount: item.MessageCount,\n\t\tPromptTokens: item.PromptTokens,\n\t\tCompletionTokens: item.CompletionTokens,\n\t\tSummaryMessageID: item.SummaryMessageID.String,\n\t\tCost: item.Cost,\n\t\tCreatedAt: item.CreatedAt,\n\t\tUpdatedAt: item.UpdatedAt,\n\t}\n}\n\nfunc NewService(q db.Querier) Service {\n\tbroker := pubsub.NewBroker[Session]()\n\treturn &service{\n\t\tbroker,\n\t\tq,\n\t}\n}\n"], ["/opencode/internal/llm/prompt/task.go", "package prompt\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/opencode-ai/opencode/internal/llm/models\"\n)\n\nfunc TaskPrompt(_ models.ModelProvider) string {\n\tagentPrompt := `You are an agent for OpenCode. Given the user's prompt, you should use the tools available to you to answer the user's question.\nNotes:\n1. IMPORTANT: You should be concise, direct, and to the point, since your responses will be displayed on a command line interface. Answer the user's question directly, without elaboration, explanation, or details. One word answers are best. Avoid introductions, conclusions, and explanations. You MUST avoid text before/after your response, such as \"The answer is .\", \"Here is the content of the file...\" or \"Based on the information provided, the answer is...\" or \"Here is what I will do next...\".\n2. When relevant, share file names and code snippets relevant to the query\n3. Any file paths you return in your final response MUST be absolute. DO NOT use relative paths.`\n\n\treturn fmt.Sprintf(\"%s\\n%s\\n\", agentPrompt, getEnvironmentInfo())\n}\n"], ["/opencode/internal/db/messages.sql.go", "// Code generated by sqlc. DO NOT EDIT.\n// versions:\n// sqlc v1.29.0\n// source: messages.sql\n\npackage db\n\nimport (\n\t\"context\"\n\t\"database/sql\"\n)\n\nconst createMessage = `-- name: CreateMessage :one\nINSERT INTO messages (\n id,\n session_id,\n role,\n parts,\n model,\n created_at,\n updated_at\n) VALUES (\n ?, ?, ?, ?, ?, strftime('%s', 'now'), strftime('%s', 'now')\n)\nRETURNING id, session_id, role, parts, model, created_at, updated_at, finished_at\n`\n\ntype CreateMessageParams struct {\n\tID string `json:\"id\"`\n\tSessionID string `json:\"session_id\"`\n\tRole string `json:\"role\"`\n\tParts string `json:\"parts\"`\n\tModel sql.NullString `json:\"model\"`\n}\n\nfunc (q *Queries) CreateMessage(ctx context.Context, arg CreateMessageParams) (Message, error) {\n\trow := q.queryRow(ctx, q.createMessageStmt, createMessage,\n\t\targ.ID,\n\t\targ.SessionID,\n\t\targ.Role,\n\t\targ.Parts,\n\t\targ.Model,\n\t)\n\tvar i Message\n\terr := row.Scan(\n\t\t&i.ID,\n\t\t&i.SessionID,\n\t\t&i.Role,\n\t\t&i.Parts,\n\t\t&i.Model,\n\t\t&i.CreatedAt,\n\t\t&i.UpdatedAt,\n\t\t&i.FinishedAt,\n\t)\n\treturn i, err\n}\n\nconst deleteMessage = `-- name: DeleteMessage :exec\nDELETE FROM messages\nWHERE id = ?\n`\n\nfunc (q *Queries) DeleteMessage(ctx context.Context, id string) error {\n\t_, err := q.exec(ctx, q.deleteMessageStmt, deleteMessage, id)\n\treturn err\n}\n\nconst deleteSessionMessages = `-- name: DeleteSessionMessages :exec\nDELETE FROM messages\nWHERE session_id = ?\n`\n\nfunc (q *Queries) DeleteSessionMessages(ctx context.Context, sessionID string) error {\n\t_, err := q.exec(ctx, q.deleteSessionMessagesStmt, deleteSessionMessages, sessionID)\n\treturn err\n}\n\nconst getMessage = `-- name: GetMessage :one\nSELECT id, session_id, role, parts, model, created_at, updated_at, finished_at\nFROM messages\nWHERE id = ? LIMIT 1\n`\n\nfunc (q *Queries) GetMessage(ctx context.Context, id string) (Message, error) {\n\trow := q.queryRow(ctx, q.getMessageStmt, getMessage, id)\n\tvar i Message\n\terr := row.Scan(\n\t\t&i.ID,\n\t\t&i.SessionID,\n\t\t&i.Role,\n\t\t&i.Parts,\n\t\t&i.Model,\n\t\t&i.CreatedAt,\n\t\t&i.UpdatedAt,\n\t\t&i.FinishedAt,\n\t)\n\treturn i, err\n}\n\nconst listMessagesBySession = `-- name: ListMessagesBySession :many\nSELECT id, session_id, role, parts, model, created_at, updated_at, finished_at\nFROM messages\nWHERE session_id = ?\nORDER BY created_at ASC\n`\n\nfunc (q *Queries) ListMessagesBySession(ctx context.Context, sessionID string) ([]Message, error) {\n\trows, err := q.query(ctx, q.listMessagesBySessionStmt, listMessagesBySession, sessionID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer rows.Close()\n\titems := []Message{}\n\tfor rows.Next() {\n\t\tvar i Message\n\t\tif err := rows.Scan(\n\t\t\t&i.ID,\n\t\t\t&i.SessionID,\n\t\t\t&i.Role,\n\t\t\t&i.Parts,\n\t\t\t&i.Model,\n\t\t\t&i.CreatedAt,\n\t\t\t&i.UpdatedAt,\n\t\t\t&i.FinishedAt,\n\t\t); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\titems = append(items, i)\n\t}\n\tif err := rows.Close(); err != nil {\n\t\treturn nil, err\n\t}\n\tif err := rows.Err(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn items, nil\n}\n\nconst updateMessage = `-- name: UpdateMessage :exec\nUPDATE messages\nSET\n parts = ?,\n finished_at = ?,\n updated_at = strftime('%s', 'now')\nWHERE id = ?\n`\n\ntype UpdateMessageParams struct {\n\tParts string `json:\"parts\"`\n\tFinishedAt sql.NullInt64 `json:\"finished_at\"`\n\tID string `json:\"id\"`\n}\n\nfunc (q *Queries) UpdateMessage(ctx context.Context, arg UpdateMessageParams) error {\n\t_, err := q.exec(ctx, q.updateMessageStmt, updateMessage, arg.Parts, arg.FinishedAt, arg.ID)\n\treturn err\n}\n"], ["/opencode/internal/db/sessions.sql.go", "// Code generated by sqlc. DO NOT EDIT.\n// versions:\n// sqlc v1.29.0\n// source: sessions.sql\n\npackage db\n\nimport (\n\t\"context\"\n\t\"database/sql\"\n)\n\nconst createSession = `-- name: CreateSession :one\nINSERT INTO sessions (\n id,\n parent_session_id,\n title,\n message_count,\n prompt_tokens,\n completion_tokens,\n cost,\n summary_message_id,\n updated_at,\n created_at\n) VALUES (\n ?,\n ?,\n ?,\n ?,\n ?,\n ?,\n ?,\n null,\n strftime('%s', 'now'),\n strftime('%s', 'now')\n) RETURNING id, parent_session_id, title, message_count, prompt_tokens, completion_tokens, cost, updated_at, created_at, summary_message_id\n`\n\ntype CreateSessionParams struct {\n\tID string `json:\"id\"`\n\tParentSessionID sql.NullString `json:\"parent_session_id\"`\n\tTitle string `json:\"title\"`\n\tMessageCount int64 `json:\"message_count\"`\n\tPromptTokens int64 `json:\"prompt_tokens\"`\n\tCompletionTokens int64 `json:\"completion_tokens\"`\n\tCost float64 `json:\"cost\"`\n}\n\nfunc (q *Queries) CreateSession(ctx context.Context, arg CreateSessionParams) (Session, error) {\n\trow := q.queryRow(ctx, q.createSessionStmt, createSession,\n\t\targ.ID,\n\t\targ.ParentSessionID,\n\t\targ.Title,\n\t\targ.MessageCount,\n\t\targ.PromptTokens,\n\t\targ.CompletionTokens,\n\t\targ.Cost,\n\t)\n\tvar i Session\n\terr := row.Scan(\n\t\t&i.ID,\n\t\t&i.ParentSessionID,\n\t\t&i.Title,\n\t\t&i.MessageCount,\n\t\t&i.PromptTokens,\n\t\t&i.CompletionTokens,\n\t\t&i.Cost,\n\t\t&i.UpdatedAt,\n\t\t&i.CreatedAt,\n\t\t&i.SummaryMessageID,\n\t)\n\treturn i, err\n}\n\nconst deleteSession = `-- name: DeleteSession :exec\nDELETE FROM sessions\nWHERE id = ?\n`\n\nfunc (q *Queries) DeleteSession(ctx context.Context, id string) error {\n\t_, err := q.exec(ctx, q.deleteSessionStmt, deleteSession, id)\n\treturn err\n}\n\nconst getSessionByID = `-- name: GetSessionByID :one\nSELECT id, parent_session_id, title, message_count, prompt_tokens, completion_tokens, cost, updated_at, created_at, summary_message_id\nFROM sessions\nWHERE id = ? LIMIT 1\n`\n\nfunc (q *Queries) GetSessionByID(ctx context.Context, id string) (Session, error) {\n\trow := q.queryRow(ctx, q.getSessionByIDStmt, getSessionByID, id)\n\tvar i Session\n\terr := row.Scan(\n\t\t&i.ID,\n\t\t&i.ParentSessionID,\n\t\t&i.Title,\n\t\t&i.MessageCount,\n\t\t&i.PromptTokens,\n\t\t&i.CompletionTokens,\n\t\t&i.Cost,\n\t\t&i.UpdatedAt,\n\t\t&i.CreatedAt,\n\t\t&i.SummaryMessageID,\n\t)\n\treturn i, err\n}\n\nconst listSessions = `-- name: ListSessions :many\nSELECT id, parent_session_id, title, message_count, prompt_tokens, completion_tokens, cost, updated_at, created_at, summary_message_id\nFROM sessions\nWHERE parent_session_id is NULL\nORDER BY created_at DESC\n`\n\nfunc (q *Queries) ListSessions(ctx context.Context) ([]Session, error) {\n\trows, err := q.query(ctx, q.listSessionsStmt, listSessions)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer rows.Close()\n\titems := []Session{}\n\tfor rows.Next() {\n\t\tvar i Session\n\t\tif err := rows.Scan(\n\t\t\t&i.ID,\n\t\t\t&i.ParentSessionID,\n\t\t\t&i.Title,\n\t\t\t&i.MessageCount,\n\t\t\t&i.PromptTokens,\n\t\t\t&i.CompletionTokens,\n\t\t\t&i.Cost,\n\t\t\t&i.UpdatedAt,\n\t\t\t&i.CreatedAt,\n\t\t\t&i.SummaryMessageID,\n\t\t); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\titems = append(items, i)\n\t}\n\tif err := rows.Close(); err != nil {\n\t\treturn nil, err\n\t}\n\tif err := rows.Err(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn items, nil\n}\n\nconst updateSession = `-- name: UpdateSession :one\nUPDATE sessions\nSET\n title = ?,\n prompt_tokens = ?,\n completion_tokens = ?,\n summary_message_id = ?,\n cost = ?\nWHERE id = ?\nRETURNING id, parent_session_id, title, message_count, prompt_tokens, completion_tokens, cost, updated_at, created_at, summary_message_id\n`\n\ntype UpdateSessionParams struct {\n\tTitle string `json:\"title\"`\n\tPromptTokens int64 `json:\"prompt_tokens\"`\n\tCompletionTokens int64 `json:\"completion_tokens\"`\n\tSummaryMessageID sql.NullString `json:\"summary_message_id\"`\n\tCost float64 `json:\"cost\"`\n\tID string `json:\"id\"`\n}\n\nfunc (q *Queries) UpdateSession(ctx context.Context, arg UpdateSessionParams) (Session, error) {\n\trow := q.queryRow(ctx, q.updateSessionStmt, updateSession,\n\t\targ.Title,\n\t\targ.PromptTokens,\n\t\targ.CompletionTokens,\n\t\targ.SummaryMessageID,\n\t\targ.Cost,\n\t\targ.ID,\n\t)\n\tvar i Session\n\terr := row.Scan(\n\t\t&i.ID,\n\t\t&i.ParentSessionID,\n\t\t&i.Title,\n\t\t&i.MessageCount,\n\t\t&i.PromptTokens,\n\t\t&i.CompletionTokens,\n\t\t&i.Cost,\n\t\t&i.UpdatedAt,\n\t\t&i.CreatedAt,\n\t\t&i.SummaryMessageID,\n\t)\n\treturn i, err\n}\n"], ["/opencode/internal/db/files.sql.go", "// Code generated by sqlc. DO NOT EDIT.\n// versions:\n// sqlc v1.29.0\n// source: files.sql\n\npackage db\n\nimport (\n\t\"context\"\n)\n\nconst createFile = `-- name: CreateFile :one\nINSERT INTO files (\n id,\n session_id,\n path,\n content,\n version,\n created_at,\n updated_at\n) VALUES (\n ?, ?, ?, ?, ?, strftime('%s', 'now'), strftime('%s', 'now')\n)\nRETURNING id, session_id, path, content, version, created_at, updated_at\n`\n\ntype CreateFileParams struct {\n\tID string `json:\"id\"`\n\tSessionID string `json:\"session_id\"`\n\tPath string `json:\"path\"`\n\tContent string `json:\"content\"`\n\tVersion string `json:\"version\"`\n}\n\nfunc (q *Queries) CreateFile(ctx context.Context, arg CreateFileParams) (File, error) {\n\trow := q.queryRow(ctx, q.createFileStmt, createFile,\n\t\targ.ID,\n\t\targ.SessionID,\n\t\targ.Path,\n\t\targ.Content,\n\t\targ.Version,\n\t)\n\tvar i File\n\terr := row.Scan(\n\t\t&i.ID,\n\t\t&i.SessionID,\n\t\t&i.Path,\n\t\t&i.Content,\n\t\t&i.Version,\n\t\t&i.CreatedAt,\n\t\t&i.UpdatedAt,\n\t)\n\treturn i, err\n}\n\nconst deleteFile = `-- name: DeleteFile :exec\nDELETE FROM files\nWHERE id = ?\n`\n\nfunc (q *Queries) DeleteFile(ctx context.Context, id string) error {\n\t_, err := q.exec(ctx, q.deleteFileStmt, deleteFile, id)\n\treturn err\n}\n\nconst deleteSessionFiles = `-- name: DeleteSessionFiles :exec\nDELETE FROM files\nWHERE session_id = ?\n`\n\nfunc (q *Queries) DeleteSessionFiles(ctx context.Context, sessionID string) error {\n\t_, err := q.exec(ctx, q.deleteSessionFilesStmt, deleteSessionFiles, sessionID)\n\treturn err\n}\n\nconst getFile = `-- name: GetFile :one\nSELECT id, session_id, path, content, version, created_at, updated_at\nFROM files\nWHERE id = ? LIMIT 1\n`\n\nfunc (q *Queries) GetFile(ctx context.Context, id string) (File, error) {\n\trow := q.queryRow(ctx, q.getFileStmt, getFile, id)\n\tvar i File\n\terr := row.Scan(\n\t\t&i.ID,\n\t\t&i.SessionID,\n\t\t&i.Path,\n\t\t&i.Content,\n\t\t&i.Version,\n\t\t&i.CreatedAt,\n\t\t&i.UpdatedAt,\n\t)\n\treturn i, err\n}\n\nconst getFileByPathAndSession = `-- name: GetFileByPathAndSession :one\nSELECT id, session_id, path, content, version, created_at, updated_at\nFROM files\nWHERE path = ? AND session_id = ?\nORDER BY created_at DESC\nLIMIT 1\n`\n\ntype GetFileByPathAndSessionParams struct {\n\tPath string `json:\"path\"`\n\tSessionID string `json:\"session_id\"`\n}\n\nfunc (q *Queries) GetFileByPathAndSession(ctx context.Context, arg GetFileByPathAndSessionParams) (File, error) {\n\trow := q.queryRow(ctx, q.getFileByPathAndSessionStmt, getFileByPathAndSession, arg.Path, arg.SessionID)\n\tvar i File\n\terr := row.Scan(\n\t\t&i.ID,\n\t\t&i.SessionID,\n\t\t&i.Path,\n\t\t&i.Content,\n\t\t&i.Version,\n\t\t&i.CreatedAt,\n\t\t&i.UpdatedAt,\n\t)\n\treturn i, err\n}\n\nconst listFilesByPath = `-- name: ListFilesByPath :many\nSELECT id, session_id, path, content, version, created_at, updated_at\nFROM files\nWHERE path = ?\nORDER BY created_at DESC\n`\n\nfunc (q *Queries) ListFilesByPath(ctx context.Context, path string) ([]File, error) {\n\trows, err := q.query(ctx, q.listFilesByPathStmt, listFilesByPath, path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer rows.Close()\n\titems := []File{}\n\tfor rows.Next() {\n\t\tvar i File\n\t\tif err := rows.Scan(\n\t\t\t&i.ID,\n\t\t\t&i.SessionID,\n\t\t\t&i.Path,\n\t\t\t&i.Content,\n\t\t\t&i.Version,\n\t\t\t&i.CreatedAt,\n\t\t\t&i.UpdatedAt,\n\t\t); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\titems = append(items, i)\n\t}\n\tif err := rows.Close(); err != nil {\n\t\treturn nil, err\n\t}\n\tif err := rows.Err(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn items, nil\n}\n\nconst listFilesBySession = `-- name: ListFilesBySession :many\nSELECT id, session_id, path, content, version, created_at, updated_at\nFROM files\nWHERE session_id = ?\nORDER BY created_at ASC\n`\n\nfunc (q *Queries) ListFilesBySession(ctx context.Context, sessionID string) ([]File, error) {\n\trows, err := q.query(ctx, q.listFilesBySessionStmt, listFilesBySession, sessionID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer rows.Close()\n\titems := []File{}\n\tfor rows.Next() {\n\t\tvar i File\n\t\tif err := rows.Scan(\n\t\t\t&i.ID,\n\t\t\t&i.SessionID,\n\t\t\t&i.Path,\n\t\t\t&i.Content,\n\t\t\t&i.Version,\n\t\t\t&i.CreatedAt,\n\t\t\t&i.UpdatedAt,\n\t\t); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\titems = append(items, i)\n\t}\n\tif err := rows.Close(); err != nil {\n\t\treturn nil, err\n\t}\n\tif err := rows.Err(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn items, nil\n}\n\nconst listLatestSessionFiles = `-- name: ListLatestSessionFiles :many\nSELECT f.id, f.session_id, f.path, f.content, f.version, f.created_at, f.updated_at\nFROM files f\nINNER JOIN (\n SELECT path, MAX(created_at) as max_created_at\n FROM files\n GROUP BY path\n) latest ON f.path = latest.path AND f.created_at = latest.max_created_at\nWHERE f.session_id = ?\nORDER BY f.path\n`\n\nfunc (q *Queries) ListLatestSessionFiles(ctx context.Context, sessionID string) ([]File, error) {\n\trows, err := q.query(ctx, q.listLatestSessionFilesStmt, listLatestSessionFiles, sessionID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer rows.Close()\n\titems := []File{}\n\tfor rows.Next() {\n\t\tvar i File\n\t\tif err := rows.Scan(\n\t\t\t&i.ID,\n\t\t\t&i.SessionID,\n\t\t\t&i.Path,\n\t\t\t&i.Content,\n\t\t\t&i.Version,\n\t\t\t&i.CreatedAt,\n\t\t\t&i.UpdatedAt,\n\t\t); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\titems = append(items, i)\n\t}\n\tif err := rows.Close(); err != nil {\n\t\treturn nil, err\n\t}\n\tif err := rows.Err(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn items, nil\n}\n\nconst listNewFiles = `-- name: ListNewFiles :many\nSELECT id, session_id, path, content, version, created_at, updated_at\nFROM files\nWHERE is_new = 1\nORDER BY created_at DESC\n`\n\nfunc (q *Queries) ListNewFiles(ctx context.Context) ([]File, error) {\n\trows, err := q.query(ctx, q.listNewFilesStmt, listNewFiles)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer rows.Close()\n\titems := []File{}\n\tfor rows.Next() {\n\t\tvar i File\n\t\tif err := rows.Scan(\n\t\t\t&i.ID,\n\t\t\t&i.SessionID,\n\t\t\t&i.Path,\n\t\t\t&i.Content,\n\t\t\t&i.Version,\n\t\t\t&i.CreatedAt,\n\t\t\t&i.UpdatedAt,\n\t\t); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\titems = append(items, i)\n\t}\n\tif err := rows.Close(); err != nil {\n\t\treturn nil, err\n\t}\n\tif err := rows.Err(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn items, nil\n}\n\nconst updateFile = `-- name: UpdateFile :one\nUPDATE files\nSET\n content = ?,\n version = ?,\n updated_at = strftime('%s', 'now')\nWHERE id = ?\nRETURNING id, session_id, path, content, version, created_at, updated_at\n`\n\ntype UpdateFileParams struct {\n\tContent string `json:\"content\"`\n\tVersion string `json:\"version\"`\n\tID string `json:\"id\"`\n}\n\nfunc (q *Queries) UpdateFile(ctx context.Context, arg UpdateFileParams) (File, error) {\n\trow := q.queryRow(ctx, q.updateFileStmt, updateFile, arg.Content, arg.Version, arg.ID)\n\tvar i File\n\terr := row.Scan(\n\t\t&i.ID,\n\t\t&i.SessionID,\n\t\t&i.Path,\n\t\t&i.Content,\n\t\t&i.Version,\n\t\t&i.CreatedAt,\n\t\t&i.UpdatedAt,\n\t)\n\treturn i, err\n}\n"], ["/opencode/internal/lsp/protocol.go", "package lsp\n\nimport (\n\t\"encoding/json\"\n)\n\n// Message represents a JSON-RPC 2.0 message\ntype Message struct {\n\tJSONRPC string `json:\"jsonrpc\"`\n\tID int32 `json:\"id,omitempty\"`\n\tMethod string `json:\"method,omitempty\"`\n\tParams json.RawMessage `json:\"params,omitempty\"`\n\tResult json.RawMessage `json:\"result,omitempty\"`\n\tError *ResponseError `json:\"error,omitempty\"`\n}\n\n// ResponseError represents a JSON-RPC 2.0 error\ntype ResponseError struct {\n\tCode int `json:\"code\"`\n\tMessage string `json:\"message\"`\n}\n\nfunc NewRequest(id int32, method string, params any) (*Message, error) {\n\tparamsJSON, err := json.Marshal(params)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Message{\n\t\tJSONRPC: \"2.0\",\n\t\tID: id,\n\t\tMethod: method,\n\t\tParams: paramsJSON,\n\t}, nil\n}\n\nfunc NewNotification(method string, params any) (*Message, error) {\n\tparamsJSON, err := json.Marshal(params)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Message{\n\t\tJSONRPC: \"2.0\",\n\t\tMethod: method,\n\t\tParams: paramsJSON,\n\t}, nil\n}\n"], ["/opencode/internal/tui/util/util.go", "package util\n\nimport (\n\t\"time\"\n\n\ttea \"github.com/charmbracelet/bubbletea\"\n)\n\nfunc CmdHandler(msg tea.Msg) tea.Cmd {\n\treturn func() tea.Msg {\n\t\treturn msg\n\t}\n}\n\nfunc ReportError(err error) tea.Cmd {\n\treturn CmdHandler(InfoMsg{\n\t\tType: InfoTypeError,\n\t\tMsg: err.Error(),\n\t})\n}\n\ntype InfoType int\n\nconst (\n\tInfoTypeInfo InfoType = iota\n\tInfoTypeWarn\n\tInfoTypeError\n)\n\nfunc ReportInfo(info string) tea.Cmd {\n\treturn CmdHandler(InfoMsg{\n\t\tType: InfoTypeInfo,\n\t\tMsg: info,\n\t})\n}\n\nfunc ReportWarn(warn string) tea.Cmd {\n\treturn CmdHandler(InfoMsg{\n\t\tType: InfoTypeWarn,\n\t\tMsg: warn,\n\t})\n}\n\ntype (\n\tInfoMsg struct {\n\t\tType InfoType\n\t\tMsg string\n\t\tTTL time.Duration\n\t}\n\tClearStatusMsg struct{}\n)\n\nfunc Clamp(v, low, high int) int {\n\tif high < low {\n\t\tlow, high = high, low\n\t}\n\treturn min(high, max(low, v))\n}\n"], ["/opencode/internal/llm/prompt/summarizer.go", "package prompt\n\nimport \"github.com/opencode-ai/opencode/internal/llm/models\"\n\nfunc SummarizerPrompt(_ models.ModelProvider) string {\n\treturn `You are a helpful AI assistant tasked with summarizing conversations.\n\nWhen asked to summarize, provide a detailed but concise summary of the conversation. \nFocus on information that would be helpful for continuing the conversation, including:\n- What was done\n- What is currently being worked on\n- Which files are being modified\n- What needs to be done next\n\nYour summary should be comprehensive enough to provide context but concise enough to be quickly understood.`\n}\n"], ["/opencode/internal/tui/theme/theme.go", "package theme\n\nimport (\n\t\"github.com/charmbracelet/lipgloss\"\n)\n\n// Theme defines the interface for all UI themes in the application.\n// All colors must be defined as lipgloss.AdaptiveColor to support\n// both light and dark terminal backgrounds.\ntype Theme interface {\n\t// Base colors\n\tPrimary() lipgloss.AdaptiveColor\n\tSecondary() lipgloss.AdaptiveColor\n\tAccent() lipgloss.AdaptiveColor\n\n\t// Status colors\n\tError() lipgloss.AdaptiveColor\n\tWarning() lipgloss.AdaptiveColor\n\tSuccess() lipgloss.AdaptiveColor\n\tInfo() lipgloss.AdaptiveColor\n\n\t// Text colors\n\tText() lipgloss.AdaptiveColor\n\tTextMuted() lipgloss.AdaptiveColor\n\tTextEmphasized() lipgloss.AdaptiveColor\n\n\t// Background colors\n\tBackground() lipgloss.AdaptiveColor\n\tBackgroundSecondary() lipgloss.AdaptiveColor\n\tBackgroundDarker() lipgloss.AdaptiveColor\n\n\t// Border colors\n\tBorderNormal() lipgloss.AdaptiveColor\n\tBorderFocused() lipgloss.AdaptiveColor\n\tBorderDim() lipgloss.AdaptiveColor\n\n\t// Diff view colors\n\tDiffAdded() lipgloss.AdaptiveColor\n\tDiffRemoved() lipgloss.AdaptiveColor\n\tDiffContext() lipgloss.AdaptiveColor\n\tDiffHunkHeader() lipgloss.AdaptiveColor\n\tDiffHighlightAdded() lipgloss.AdaptiveColor\n\tDiffHighlightRemoved() lipgloss.AdaptiveColor\n\tDiffAddedBg() lipgloss.AdaptiveColor\n\tDiffRemovedBg() lipgloss.AdaptiveColor\n\tDiffContextBg() lipgloss.AdaptiveColor\n\tDiffLineNumber() lipgloss.AdaptiveColor\n\tDiffAddedLineNumberBg() lipgloss.AdaptiveColor\n\tDiffRemovedLineNumberBg() lipgloss.AdaptiveColor\n\n\t// Markdown colors\n\tMarkdownText() lipgloss.AdaptiveColor\n\tMarkdownHeading() lipgloss.AdaptiveColor\n\tMarkdownLink() lipgloss.AdaptiveColor\n\tMarkdownLinkText() lipgloss.AdaptiveColor\n\tMarkdownCode() lipgloss.AdaptiveColor\n\tMarkdownBlockQuote() lipgloss.AdaptiveColor\n\tMarkdownEmph() lipgloss.AdaptiveColor\n\tMarkdownStrong() lipgloss.AdaptiveColor\n\tMarkdownHorizontalRule() lipgloss.AdaptiveColor\n\tMarkdownListItem() lipgloss.AdaptiveColor\n\tMarkdownListEnumeration() lipgloss.AdaptiveColor\n\tMarkdownImage() lipgloss.AdaptiveColor\n\tMarkdownImageText() lipgloss.AdaptiveColor\n\tMarkdownCodeBlock() lipgloss.AdaptiveColor\n\n\t// Syntax highlighting colors\n\tSyntaxComment() lipgloss.AdaptiveColor\n\tSyntaxKeyword() lipgloss.AdaptiveColor\n\tSyntaxFunction() lipgloss.AdaptiveColor\n\tSyntaxVariable() lipgloss.AdaptiveColor\n\tSyntaxString() lipgloss.AdaptiveColor\n\tSyntaxNumber() lipgloss.AdaptiveColor\n\tSyntaxType() lipgloss.AdaptiveColor\n\tSyntaxOperator() lipgloss.AdaptiveColor\n\tSyntaxPunctuation() lipgloss.AdaptiveColor\n}\n\n// BaseTheme provides a default implementation of the Theme interface\n// that can be embedded in concrete theme implementations.\ntype BaseTheme struct {\n\t// Base colors\n\tPrimaryColor lipgloss.AdaptiveColor\n\tSecondaryColor lipgloss.AdaptiveColor\n\tAccentColor lipgloss.AdaptiveColor\n\n\t// Status colors\n\tErrorColor lipgloss.AdaptiveColor\n\tWarningColor lipgloss.AdaptiveColor\n\tSuccessColor lipgloss.AdaptiveColor\n\tInfoColor lipgloss.AdaptiveColor\n\n\t// Text colors\n\tTextColor lipgloss.AdaptiveColor\n\tTextMutedColor lipgloss.AdaptiveColor\n\tTextEmphasizedColor lipgloss.AdaptiveColor\n\n\t// Background colors\n\tBackgroundColor lipgloss.AdaptiveColor\n\tBackgroundSecondaryColor lipgloss.AdaptiveColor\n\tBackgroundDarkerColor lipgloss.AdaptiveColor\n\n\t// Border colors\n\tBorderNormalColor lipgloss.AdaptiveColor\n\tBorderFocusedColor lipgloss.AdaptiveColor\n\tBorderDimColor lipgloss.AdaptiveColor\n\n\t// Diff view colors\n\tDiffAddedColor lipgloss.AdaptiveColor\n\tDiffRemovedColor lipgloss.AdaptiveColor\n\tDiffContextColor lipgloss.AdaptiveColor\n\tDiffHunkHeaderColor lipgloss.AdaptiveColor\n\tDiffHighlightAddedColor lipgloss.AdaptiveColor\n\tDiffHighlightRemovedColor lipgloss.AdaptiveColor\n\tDiffAddedBgColor lipgloss.AdaptiveColor\n\tDiffRemovedBgColor lipgloss.AdaptiveColor\n\tDiffContextBgColor lipgloss.AdaptiveColor\n\tDiffLineNumberColor lipgloss.AdaptiveColor\n\tDiffAddedLineNumberBgColor lipgloss.AdaptiveColor\n\tDiffRemovedLineNumberBgColor lipgloss.AdaptiveColor\n\n\t// Markdown colors\n\tMarkdownTextColor lipgloss.AdaptiveColor\n\tMarkdownHeadingColor lipgloss.AdaptiveColor\n\tMarkdownLinkColor lipgloss.AdaptiveColor\n\tMarkdownLinkTextColor lipgloss.AdaptiveColor\n\tMarkdownCodeColor lipgloss.AdaptiveColor\n\tMarkdownBlockQuoteColor lipgloss.AdaptiveColor\n\tMarkdownEmphColor lipgloss.AdaptiveColor\n\tMarkdownStrongColor lipgloss.AdaptiveColor\n\tMarkdownHorizontalRuleColor lipgloss.AdaptiveColor\n\tMarkdownListItemColor lipgloss.AdaptiveColor\n\tMarkdownListEnumerationColor lipgloss.AdaptiveColor\n\tMarkdownImageColor lipgloss.AdaptiveColor\n\tMarkdownImageTextColor lipgloss.AdaptiveColor\n\tMarkdownCodeBlockColor lipgloss.AdaptiveColor\n\n\t// Syntax highlighting colors\n\tSyntaxCommentColor lipgloss.AdaptiveColor\n\tSyntaxKeywordColor lipgloss.AdaptiveColor\n\tSyntaxFunctionColor lipgloss.AdaptiveColor\n\tSyntaxVariableColor lipgloss.AdaptiveColor\n\tSyntaxStringColor lipgloss.AdaptiveColor\n\tSyntaxNumberColor lipgloss.AdaptiveColor\n\tSyntaxTypeColor lipgloss.AdaptiveColor\n\tSyntaxOperatorColor lipgloss.AdaptiveColor\n\tSyntaxPunctuationColor lipgloss.AdaptiveColor\n}\n\n// Implement the Theme interface for BaseTheme\nfunc (t *BaseTheme) Primary() lipgloss.AdaptiveColor { return t.PrimaryColor }\nfunc (t *BaseTheme) Secondary() lipgloss.AdaptiveColor { return t.SecondaryColor }\nfunc (t *BaseTheme) Accent() lipgloss.AdaptiveColor { return t.AccentColor }\n\nfunc (t *BaseTheme) Error() lipgloss.AdaptiveColor { return t.ErrorColor }\nfunc (t *BaseTheme) Warning() lipgloss.AdaptiveColor { return t.WarningColor }\nfunc (t *BaseTheme) Success() lipgloss.AdaptiveColor { return t.SuccessColor }\nfunc (t *BaseTheme) Info() lipgloss.AdaptiveColor { return t.InfoColor }\n\nfunc (t *BaseTheme) Text() lipgloss.AdaptiveColor { return t.TextColor }\nfunc (t *BaseTheme) TextMuted() lipgloss.AdaptiveColor { return t.TextMutedColor }\nfunc (t *BaseTheme) TextEmphasized() lipgloss.AdaptiveColor { return t.TextEmphasizedColor }\n\nfunc (t *BaseTheme) Background() lipgloss.AdaptiveColor { return t.BackgroundColor }\nfunc (t *BaseTheme) BackgroundSecondary() lipgloss.AdaptiveColor { return t.BackgroundSecondaryColor }\nfunc (t *BaseTheme) BackgroundDarker() lipgloss.AdaptiveColor { return t.BackgroundDarkerColor }\n\nfunc (t *BaseTheme) BorderNormal() lipgloss.AdaptiveColor { return t.BorderNormalColor }\nfunc (t *BaseTheme) BorderFocused() lipgloss.AdaptiveColor { return t.BorderFocusedColor }\nfunc (t *BaseTheme) BorderDim() lipgloss.AdaptiveColor { return t.BorderDimColor }\n\nfunc (t *BaseTheme) DiffAdded() lipgloss.AdaptiveColor { return t.DiffAddedColor }\nfunc (t *BaseTheme) DiffRemoved() lipgloss.AdaptiveColor { return t.DiffRemovedColor }\nfunc (t *BaseTheme) DiffContext() lipgloss.AdaptiveColor { return t.DiffContextColor }\nfunc (t *BaseTheme) DiffHunkHeader() lipgloss.AdaptiveColor { return t.DiffHunkHeaderColor }\nfunc (t *BaseTheme) DiffHighlightAdded() lipgloss.AdaptiveColor { return t.DiffHighlightAddedColor }\nfunc (t *BaseTheme) DiffHighlightRemoved() lipgloss.AdaptiveColor { return t.DiffHighlightRemovedColor }\nfunc (t *BaseTheme) DiffAddedBg() lipgloss.AdaptiveColor { return t.DiffAddedBgColor }\nfunc (t *BaseTheme) DiffRemovedBg() lipgloss.AdaptiveColor { return t.DiffRemovedBgColor }\nfunc (t *BaseTheme) DiffContextBg() lipgloss.AdaptiveColor { return t.DiffContextBgColor }\nfunc (t *BaseTheme) DiffLineNumber() lipgloss.AdaptiveColor { return t.DiffLineNumberColor }\nfunc (t *BaseTheme) DiffAddedLineNumberBg() lipgloss.AdaptiveColor { return t.DiffAddedLineNumberBgColor }\nfunc (t *BaseTheme) DiffRemovedLineNumberBg() lipgloss.AdaptiveColor { return t.DiffRemovedLineNumberBgColor }\n\nfunc (t *BaseTheme) MarkdownText() lipgloss.AdaptiveColor { return t.MarkdownTextColor }\nfunc (t *BaseTheme) MarkdownHeading() lipgloss.AdaptiveColor { return t.MarkdownHeadingColor }\nfunc (t *BaseTheme) MarkdownLink() lipgloss.AdaptiveColor { return t.MarkdownLinkColor }\nfunc (t *BaseTheme) MarkdownLinkText() lipgloss.AdaptiveColor { return t.MarkdownLinkTextColor }\nfunc (t *BaseTheme) MarkdownCode() lipgloss.AdaptiveColor { return t.MarkdownCodeColor }\nfunc (t *BaseTheme) MarkdownBlockQuote() lipgloss.AdaptiveColor { return t.MarkdownBlockQuoteColor }\nfunc (t *BaseTheme) MarkdownEmph() lipgloss.AdaptiveColor { return t.MarkdownEmphColor }\nfunc (t *BaseTheme) MarkdownStrong() lipgloss.AdaptiveColor { return t.MarkdownStrongColor }\nfunc (t *BaseTheme) MarkdownHorizontalRule() lipgloss.AdaptiveColor { return t.MarkdownHorizontalRuleColor }\nfunc (t *BaseTheme) MarkdownListItem() lipgloss.AdaptiveColor { return t.MarkdownListItemColor }\nfunc (t *BaseTheme) MarkdownListEnumeration() lipgloss.AdaptiveColor { return t.MarkdownListEnumerationColor }\nfunc (t *BaseTheme) MarkdownImage() lipgloss.AdaptiveColor { return t.MarkdownImageColor }\nfunc (t *BaseTheme) MarkdownImageText() lipgloss.AdaptiveColor { return t.MarkdownImageTextColor }\nfunc (t *BaseTheme) MarkdownCodeBlock() lipgloss.AdaptiveColor { return t.MarkdownCodeBlockColor }\n\nfunc (t *BaseTheme) SyntaxComment() lipgloss.AdaptiveColor { return t.SyntaxCommentColor }\nfunc (t *BaseTheme) SyntaxKeyword() lipgloss.AdaptiveColor { return t.SyntaxKeywordColor }\nfunc (t *BaseTheme) SyntaxFunction() lipgloss.AdaptiveColor { return t.SyntaxFunctionColor }\nfunc (t *BaseTheme) SyntaxVariable() lipgloss.AdaptiveColor { return t.SyntaxVariableColor }\nfunc (t *BaseTheme) SyntaxString() lipgloss.AdaptiveColor { return t.SyntaxStringColor }\nfunc (t *BaseTheme) SyntaxNumber() lipgloss.AdaptiveColor { return t.SyntaxNumberColor }\nfunc (t *BaseTheme) SyntaxType() lipgloss.AdaptiveColor { return t.SyntaxTypeColor }\nfunc (t *BaseTheme) SyntaxOperator() lipgloss.AdaptiveColor { return t.SyntaxOperatorColor }\nfunc (t *BaseTheme) SyntaxPunctuation() lipgloss.AdaptiveColor { return t.SyntaxPunctuationColor }"], ["/opencode/internal/llm/provider/azure.go", "package provider\n\nimport (\n\t\"os\"\n\n\t\"github.com/Azure/azure-sdk-for-go/sdk/azidentity\"\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/azure\"\n\t\"github.com/openai/openai-go/option\"\n)\n\ntype azureClient struct {\n\t*openaiClient\n}\n\ntype AzureClient ProviderClient\n\nfunc newAzureClient(opts providerClientOptions) AzureClient {\n\n\tendpoint := os.Getenv(\"AZURE_OPENAI_ENDPOINT\") // ex: https://foo.openai.azure.com\n\tapiVersion := os.Getenv(\"AZURE_OPENAI_API_VERSION\") // ex: 2025-04-01-preview\n\n\tif endpoint == \"\" || apiVersion == \"\" {\n\t\treturn &azureClient{openaiClient: newOpenAIClient(opts).(*openaiClient)}\n\t}\n\n\treqOpts := []option.RequestOption{\n\t\tazure.WithEndpoint(endpoint, apiVersion),\n\t}\n\n\tif opts.apiKey != \"\" || os.Getenv(\"AZURE_OPENAI_API_KEY\") != \"\" {\n\t\tkey := opts.apiKey\n\t\tif key == \"\" {\n\t\t\tkey = os.Getenv(\"AZURE_OPENAI_API_KEY\")\n\t\t}\n\t\treqOpts = append(reqOpts, azure.WithAPIKey(key))\n\t} else if cred, err := azidentity.NewDefaultAzureCredential(nil); err == nil {\n\t\treqOpts = append(reqOpts, azure.WithTokenCredential(cred))\n\t}\n\n\tbase := &openaiClient{\n\t\tproviderOptions: opts,\n\t\tclient: openai.NewClient(reqOpts...),\n\t}\n\n\treturn &azureClient{openaiClient: base}\n}\n"], ["/opencode/internal/llm/models/groq.go", "package models\n\nconst (\n\tProviderGROQ ModelProvider = \"groq\"\n\n\t// GROQ\n\tQWENQwq ModelID = \"qwen-qwq\"\n\n\t// GROQ preview models\n\tLlama4Scout ModelID = \"meta-llama/llama-4-scout-17b-16e-instruct\"\n\tLlama4Maverick ModelID = \"meta-llama/llama-4-maverick-17b-128e-instruct\"\n\tLlama3_3_70BVersatile ModelID = \"llama-3.3-70b-versatile\"\n\tDeepseekR1DistillLlama70b ModelID = \"deepseek-r1-distill-llama-70b\"\n)\n\nvar GroqModels = map[ModelID]Model{\n\t//\n\t// GROQ\n\tQWENQwq: {\n\t\tID: QWENQwq,\n\t\tName: \"Qwen Qwq\",\n\t\tProvider: ProviderGROQ,\n\t\tAPIModel: \"qwen-qwq-32b\",\n\t\tCostPer1MIn: 0.29,\n\t\tCostPer1MInCached: 0.275,\n\t\tCostPer1MOutCached: 0.0,\n\t\tCostPer1MOut: 0.39,\n\t\tContextWindow: 128_000,\n\t\tDefaultMaxTokens: 50000,\n\t\t// for some reason, the groq api doesn't like the reasoningEffort parameter\n\t\tCanReason: false,\n\t\tSupportsAttachments: false,\n\t},\n\n\tLlama4Scout: {\n\t\tID: Llama4Scout,\n\t\tName: \"Llama4Scout\",\n\t\tProvider: ProviderGROQ,\n\t\tAPIModel: \"meta-llama/llama-4-scout-17b-16e-instruct\",\n\t\tCostPer1MIn: 0.11,\n\t\tCostPer1MInCached: 0,\n\t\tCostPer1MOutCached: 0,\n\t\tCostPer1MOut: 0.34,\n\t\tContextWindow: 128_000, // 10M when?\n\t\tSupportsAttachments: true,\n\t},\n\n\tLlama4Maverick: {\n\t\tID: Llama4Maverick,\n\t\tName: \"Llama4Maverick\",\n\t\tProvider: ProviderGROQ,\n\t\tAPIModel: \"meta-llama/llama-4-maverick-17b-128e-instruct\",\n\t\tCostPer1MIn: 0.20,\n\t\tCostPer1MInCached: 0,\n\t\tCostPer1MOutCached: 0,\n\t\tCostPer1MOut: 0.20,\n\t\tContextWindow: 128_000,\n\t\tSupportsAttachments: true,\n\t},\n\n\tLlama3_3_70BVersatile: {\n\t\tID: Llama3_3_70BVersatile,\n\t\tName: \"Llama3_3_70BVersatile\",\n\t\tProvider: ProviderGROQ,\n\t\tAPIModel: \"llama-3.3-70b-versatile\",\n\t\tCostPer1MIn: 0.59,\n\t\tCostPer1MInCached: 0,\n\t\tCostPer1MOutCached: 0,\n\t\tCostPer1MOut: 0.79,\n\t\tContextWindow: 128_000,\n\t\tSupportsAttachments: false,\n\t},\n\n\tDeepseekR1DistillLlama70b: {\n\t\tID: DeepseekR1DistillLlama70b,\n\t\tName: \"DeepseekR1DistillLlama70b\",\n\t\tProvider: ProviderGROQ,\n\t\tAPIModel: \"deepseek-r1-distill-llama-70b\",\n\t\tCostPer1MIn: 0.75,\n\t\tCostPer1MInCached: 0,\n\t\tCostPer1MOutCached: 0,\n\t\tCostPer1MOut: 0.99,\n\t\tContextWindow: 128_000,\n\t\tCanReason: true,\n\t\tSupportsAttachments: false,\n\t},\n}\n"], ["/opencode/internal/tui/layout/layout.go", "package layout\n\nimport (\n\t\"reflect\"\n\n\t\"github.com/charmbracelet/bubbles/key\"\n\ttea \"github.com/charmbracelet/bubbletea\"\n)\n\ntype Focusable interface {\n\tFocus() tea.Cmd\n\tBlur() tea.Cmd\n\tIsFocused() bool\n}\n\ntype Sizeable interface {\n\tSetSize(width, height int) tea.Cmd\n\tGetSize() (int, int)\n}\n\ntype Bindings interface {\n\tBindingKeys() []key.Binding\n}\n\nfunc KeyMapToSlice(t any) (bindings []key.Binding) {\n\ttyp := reflect.TypeOf(t)\n\tif typ.Kind() != reflect.Struct {\n\t\treturn nil\n\t}\n\tfor i := range typ.NumField() {\n\t\tv := reflect.ValueOf(t).Field(i)\n\t\tbindings = append(bindings, v.Interface().(key.Binding))\n\t}\n\treturn\n}\n"], ["/opencode/internal/llm/prompt/title.go", "package prompt\n\nimport \"github.com/opencode-ai/opencode/internal/llm/models\"\n\nfunc TitlePrompt(_ models.ModelProvider) string {\n\treturn `you will generate a short title based on the first message a user begins a conversation with\n- ensure it is not more than 50 characters long\n- the title should be a summary of the user's message\n- it should be one line long\n- do not use quotes or colons\n- the entire text you return will be used as the title\n- never return anything that is more than one sentence (one line) long`\n}\n"], ["/opencode/internal/llm/models/xai.go", "package models\n\nconst (\n\tProviderXAI ModelProvider = \"xai\"\n\n\tXAIGrok3Beta ModelID = \"grok-3-beta\"\n\tXAIGrok3MiniBeta ModelID = \"grok-3-mini-beta\"\n\tXAIGrok3FastBeta ModelID = \"grok-3-fast-beta\"\n\tXAiGrok3MiniFastBeta ModelID = \"grok-3-mini-fast-beta\"\n)\n\nvar XAIModels = map[ModelID]Model{\n\tXAIGrok3Beta: {\n\t\tID: XAIGrok3Beta,\n\t\tName: \"Grok3 Beta\",\n\t\tProvider: ProviderXAI,\n\t\tAPIModel: \"grok-3-beta\",\n\t\tCostPer1MIn: 3.0,\n\t\tCostPer1MInCached: 0,\n\t\tCostPer1MOut: 15,\n\t\tCostPer1MOutCached: 0,\n\t\tContextWindow: 131_072,\n\t\tDefaultMaxTokens: 20_000,\n\t},\n\tXAIGrok3MiniBeta: {\n\t\tID: XAIGrok3MiniBeta,\n\t\tName: \"Grok3 Mini Beta\",\n\t\tProvider: ProviderXAI,\n\t\tAPIModel: \"grok-3-mini-beta\",\n\t\tCostPer1MIn: 0.3,\n\t\tCostPer1MInCached: 0,\n\t\tCostPer1MOut: 0.5,\n\t\tCostPer1MOutCached: 0,\n\t\tContextWindow: 131_072,\n\t\tDefaultMaxTokens: 20_000,\n\t},\n\tXAIGrok3FastBeta: {\n\t\tID: XAIGrok3FastBeta,\n\t\tName: \"Grok3 Fast Beta\",\n\t\tProvider: ProviderXAI,\n\t\tAPIModel: \"grok-3-fast-beta\",\n\t\tCostPer1MIn: 5,\n\t\tCostPer1MInCached: 0,\n\t\tCostPer1MOut: 25,\n\t\tCostPer1MOutCached: 0,\n\t\tContextWindow: 131_072,\n\t\tDefaultMaxTokens: 20_000,\n\t},\n\tXAiGrok3MiniFastBeta: {\n\t\tID: XAiGrok3MiniFastBeta,\n\t\tName: \"Grok3 Mini Fast Beta\",\n\t\tProvider: ProviderXAI,\n\t\tAPIModel: \"grok-3-mini-fast-beta\",\n\t\tCostPer1MIn: 0.6,\n\t\tCostPer1MInCached: 0,\n\t\tCostPer1MOut: 4.0,\n\t\tCostPer1MOutCached: 0,\n\t\tContextWindow: 131_072,\n\t\tDefaultMaxTokens: 20_000,\n\t},\n}\n"], ["/opencode/internal/llm/models/models.go", "package models\n\nimport \"maps\"\n\ntype (\n\tModelID string\n\tModelProvider string\n)\n\ntype Model struct {\n\tID ModelID `json:\"id\"`\n\tName string `json:\"name\"`\n\tProvider ModelProvider `json:\"provider\"`\n\tAPIModel string `json:\"api_model\"`\n\tCostPer1MIn float64 `json:\"cost_per_1m_in\"`\n\tCostPer1MOut float64 `json:\"cost_per_1m_out\"`\n\tCostPer1MInCached float64 `json:\"cost_per_1m_in_cached\"`\n\tCostPer1MOutCached float64 `json:\"cost_per_1m_out_cached\"`\n\tContextWindow int64 `json:\"context_window\"`\n\tDefaultMaxTokens int64 `json:\"default_max_tokens\"`\n\tCanReason bool `json:\"can_reason\"`\n\tSupportsAttachments bool `json:\"supports_attachments\"`\n}\n\n// Model IDs\nconst ( // GEMINI\n\t// Bedrock\n\tBedrockClaude37Sonnet ModelID = \"bedrock.claude-3.7-sonnet\"\n)\n\nconst (\n\tProviderBedrock ModelProvider = \"bedrock\"\n\t// ForTests\n\tProviderMock ModelProvider = \"__mock\"\n)\n\n// Providers in order of popularity\nvar ProviderPopularity = map[ModelProvider]int{\n\tProviderCopilot: 1,\n\tProviderAnthropic: 2,\n\tProviderOpenAI: 3,\n\tProviderGemini: 4,\n\tProviderGROQ: 5,\n\tProviderOpenRouter: 6,\n\tProviderBedrock: 7,\n\tProviderAzure: 8,\n\tProviderVertexAI: 9,\n}\n\nvar SupportedModels = map[ModelID]Model{\n\t//\n\t// // GEMINI\n\t// GEMINI25: {\n\t// \tID: GEMINI25,\n\t// \tName: \"Gemini 2.5 Pro\",\n\t// \tProvider: ProviderGemini,\n\t// \tAPIModel: \"gemini-2.5-pro-exp-03-25\",\n\t// \tCostPer1MIn: 0,\n\t// \tCostPer1MInCached: 0,\n\t// \tCostPer1MOutCached: 0,\n\t// \tCostPer1MOut: 0,\n\t// },\n\t//\n\t// GRMINI20Flash: {\n\t// \tID: GRMINI20Flash,\n\t// \tName: \"Gemini 2.0 Flash\",\n\t// \tProvider: ProviderGemini,\n\t// \tAPIModel: \"gemini-2.0-flash\",\n\t// \tCostPer1MIn: 0.1,\n\t// \tCostPer1MInCached: 0,\n\t// \tCostPer1MOutCached: 0.025,\n\t// \tCostPer1MOut: 0.4,\n\t// },\n\t//\n\t// // Bedrock\n\tBedrockClaude37Sonnet: {\n\t\tID: BedrockClaude37Sonnet,\n\t\tName: \"Bedrock: Claude 3.7 Sonnet\",\n\t\tProvider: ProviderBedrock,\n\t\tAPIModel: \"anthropic.claude-3-7-sonnet-20250219-v1:0\",\n\t\tCostPer1MIn: 3.0,\n\t\tCostPer1MInCached: 3.75,\n\t\tCostPer1MOutCached: 0.30,\n\t\tCostPer1MOut: 15.0,\n\t},\n}\n\nfunc init() {\n\tmaps.Copy(SupportedModels, AnthropicModels)\n\tmaps.Copy(SupportedModels, OpenAIModels)\n\tmaps.Copy(SupportedModels, GeminiModels)\n\tmaps.Copy(SupportedModels, GroqModels)\n\tmaps.Copy(SupportedModels, AzureModels)\n\tmaps.Copy(SupportedModels, OpenRouterModels)\n\tmaps.Copy(SupportedModels, XAIModels)\n\tmaps.Copy(SupportedModels, VertexAIGeminiModels)\n\tmaps.Copy(SupportedModels, CopilotModels)\n}\n"], ["/opencode/main.go", "package main\n\nimport (\n\t\"github.com/opencode-ai/opencode/cmd\"\n\t\"github.com/opencode-ai/opencode/internal/logging\"\n)\n\nfunc main() {\n\tdefer logging.RecoverPanic(\"main\", func() {\n\t\tlogging.ErrorPersist(\"Application terminated due to unhandled panic\")\n\t})\n\n\tcmd.Execute()\n}\n"], ["/opencode/internal/llm/models/anthropic.go", "package models\n\nconst (\n\tProviderAnthropic ModelProvider = \"anthropic\"\n\n\t// Models\n\tClaude35Sonnet ModelID = \"claude-3.5-sonnet\"\n\tClaude3Haiku ModelID = \"claude-3-haiku\"\n\tClaude37Sonnet ModelID = \"claude-3.7-sonnet\"\n\tClaude35Haiku ModelID = \"claude-3.5-haiku\"\n\tClaude3Opus ModelID = \"claude-3-opus\"\n\tClaude4Opus ModelID = \"claude-4-opus\"\n\tClaude4Sonnet ModelID = \"claude-4-sonnet\"\n)\n\n// https://docs.anthropic.com/en/docs/about-claude/models/all-models\nvar AnthropicModels = map[ModelID]Model{\n\tClaude35Sonnet: {\n\t\tID: Claude35Sonnet,\n\t\tName: \"Claude 3.5 Sonnet\",\n\t\tProvider: ProviderAnthropic,\n\t\tAPIModel: \"claude-3-5-sonnet-latest\",\n\t\tCostPer1MIn: 3.0,\n\t\tCostPer1MInCached: 3.75,\n\t\tCostPer1MOutCached: 0.30,\n\t\tCostPer1MOut: 15.0,\n\t\tContextWindow: 200000,\n\t\tDefaultMaxTokens: 5000,\n\t\tSupportsAttachments: true,\n\t},\n\tClaude3Haiku: {\n\t\tID: Claude3Haiku,\n\t\tName: \"Claude 3 Haiku\",\n\t\tProvider: ProviderAnthropic,\n\t\tAPIModel: \"claude-3-haiku-20240307\", // doesn't support \"-latest\"\n\t\tCostPer1MIn: 0.25,\n\t\tCostPer1MInCached: 0.30,\n\t\tCostPer1MOutCached: 0.03,\n\t\tCostPer1MOut: 1.25,\n\t\tContextWindow: 200000,\n\t\tDefaultMaxTokens: 4096,\n\t\tSupportsAttachments: true,\n\t},\n\tClaude37Sonnet: {\n\t\tID: Claude37Sonnet,\n\t\tName: \"Claude 3.7 Sonnet\",\n\t\tProvider: ProviderAnthropic,\n\t\tAPIModel: \"claude-3-7-sonnet-latest\",\n\t\tCostPer1MIn: 3.0,\n\t\tCostPer1MInCached: 3.75,\n\t\tCostPer1MOutCached: 0.30,\n\t\tCostPer1MOut: 15.0,\n\t\tContextWindow: 200000,\n\t\tDefaultMaxTokens: 50000,\n\t\tCanReason: true,\n\t\tSupportsAttachments: true,\n\t},\n\tClaude35Haiku: {\n\t\tID: Claude35Haiku,\n\t\tName: \"Claude 3.5 Haiku\",\n\t\tProvider: ProviderAnthropic,\n\t\tAPIModel: \"claude-3-5-haiku-latest\",\n\t\tCostPer1MIn: 0.80,\n\t\tCostPer1MInCached: 1.0,\n\t\tCostPer1MOutCached: 0.08,\n\t\tCostPer1MOut: 4.0,\n\t\tContextWindow: 200000,\n\t\tDefaultMaxTokens: 4096,\n\t\tSupportsAttachments: true,\n\t},\n\tClaude3Opus: {\n\t\tID: Claude3Opus,\n\t\tName: \"Claude 3 Opus\",\n\t\tProvider: ProviderAnthropic,\n\t\tAPIModel: \"claude-3-opus-latest\",\n\t\tCostPer1MIn: 15.0,\n\t\tCostPer1MInCached: 18.75,\n\t\tCostPer1MOutCached: 1.50,\n\t\tCostPer1MOut: 75.0,\n\t\tContextWindow: 200000,\n\t\tDefaultMaxTokens: 4096,\n\t\tSupportsAttachments: true,\n\t},\n\tClaude4Sonnet: {\n\t\tID: Claude4Sonnet,\n\t\tName: \"Claude 4 Sonnet\",\n\t\tProvider: ProviderAnthropic,\n\t\tAPIModel: \"claude-sonnet-4-20250514\",\n\t\tCostPer1MIn: 3.0,\n\t\tCostPer1MInCached: 3.75,\n\t\tCostPer1MOutCached: 0.30,\n\t\tCostPer1MOut: 15.0,\n\t\tContextWindow: 200000,\n\t\tDefaultMaxTokens: 50000,\n\t\tCanReason: true,\n\t\tSupportsAttachments: true,\n\t},\n\tClaude4Opus: {\n\t\tID: Claude4Opus,\n\t\tName: \"Claude 4 Opus\",\n\t\tProvider: ProviderAnthropic,\n\t\tAPIModel: \"claude-opus-4-20250514\",\n\t\tCostPer1MIn: 15.0,\n\t\tCostPer1MInCached: 18.75,\n\t\tCostPer1MOutCached: 1.50,\n\t\tCostPer1MOut: 75.0,\n\t\tContextWindow: 200000,\n\t\tDefaultMaxTokens: 4096,\n\t\tSupportsAttachments: true,\n\t},\n}\n"], ["/opencode/internal/db/querier.go", "// Code generated by sqlc. DO NOT EDIT.\n// versions:\n// sqlc v1.29.0\n\npackage db\n\nimport (\n\t\"context\"\n)\n\ntype Querier interface {\n\tCreateFile(ctx context.Context, arg CreateFileParams) (File, error)\n\tCreateMessage(ctx context.Context, arg CreateMessageParams) (Message, error)\n\tCreateSession(ctx context.Context, arg CreateSessionParams) (Session, error)\n\tDeleteFile(ctx context.Context, id string) error\n\tDeleteMessage(ctx context.Context, id string) error\n\tDeleteSession(ctx context.Context, id string) error\n\tDeleteSessionFiles(ctx context.Context, sessionID string) error\n\tDeleteSessionMessages(ctx context.Context, sessionID string) error\n\tGetFile(ctx context.Context, id string) (File, error)\n\tGetFileByPathAndSession(ctx context.Context, arg GetFileByPathAndSessionParams) (File, error)\n\tGetMessage(ctx context.Context, id string) (Message, error)\n\tGetSessionByID(ctx context.Context, id string) (Session, error)\n\tListFilesByPath(ctx context.Context, path string) ([]File, error)\n\tListFilesBySession(ctx context.Context, sessionID string) ([]File, error)\n\tListLatestSessionFiles(ctx context.Context, sessionID string) ([]File, error)\n\tListMessagesBySession(ctx context.Context, sessionID string) ([]Message, error)\n\tListNewFiles(ctx context.Context) ([]File, error)\n\tListSessions(ctx context.Context) ([]Session, error)\n\tUpdateFile(ctx context.Context, arg UpdateFileParams) (File, error)\n\tUpdateMessage(ctx context.Context, arg UpdateMessageParams) error\n\tUpdateSession(ctx context.Context, arg UpdateSessionParams) (Session, error)\n}\n\nvar _ Querier = (*Queries)(nil)\n"], ["/opencode/internal/llm/models/copilot.go", "package models\n\nconst (\n\tProviderCopilot ModelProvider = \"copilot\"\n\n\t// GitHub Copilot models\n\tCopilotGTP35Turbo ModelID = \"copilot.gpt-3.5-turbo\"\n\tCopilotGPT4o ModelID = \"copilot.gpt-4o\"\n\tCopilotGPT4oMini ModelID = \"copilot.gpt-4o-mini\"\n\tCopilotGPT41 ModelID = \"copilot.gpt-4.1\"\n\tCopilotClaude35 ModelID = \"copilot.claude-3.5-sonnet\"\n\tCopilotClaude37 ModelID = \"copilot.claude-3.7-sonnet\"\n\tCopilotClaude4 ModelID = \"copilot.claude-sonnet-4\"\n\tCopilotO1 ModelID = \"copilot.o1\"\n\tCopilotO3Mini ModelID = \"copilot.o3-mini\"\n\tCopilotO4Mini ModelID = \"copilot.o4-mini\"\n\tCopilotGemini20 ModelID = \"copilot.gemini-2.0-flash\"\n\tCopilotGemini25 ModelID = \"copilot.gemini-2.5-pro\"\n\tCopilotGPT4 ModelID = \"copilot.gpt-4\"\n\tCopilotClaude37Thought ModelID = \"copilot.claude-3.7-sonnet-thought\"\n)\n\nvar CopilotAnthropicModels = []ModelID{\n\tCopilotClaude35,\n\tCopilotClaude37,\n\tCopilotClaude37Thought,\n\tCopilotClaude4,\n}\n\n// GitHub Copilot models available through GitHub's API\nvar CopilotModels = map[ModelID]Model{\n\tCopilotGTP35Turbo: {\n\t\tID: CopilotGTP35Turbo,\n\t\tName: \"GitHub Copilot GPT-3.5-turbo\",\n\t\tProvider: ProviderCopilot,\n\t\tAPIModel: \"gpt-3.5-turbo\",\n\t\tCostPer1MIn: 0.0, // Included in GitHub Copilot subscription\n\t\tCostPer1MInCached: 0.0,\n\t\tCostPer1MOutCached: 0.0,\n\t\tCostPer1MOut: 0.0,\n\t\tContextWindow: 16_384,\n\t\tDefaultMaxTokens: 4096,\n\t\tSupportsAttachments: true,\n\t},\n\tCopilotGPT4o: {\n\t\tID: CopilotGPT4o,\n\t\tName: \"GitHub Copilot GPT-4o\",\n\t\tProvider: ProviderCopilot,\n\t\tAPIModel: \"gpt-4o\",\n\t\tCostPer1MIn: 0.0, // Included in GitHub Copilot subscription\n\t\tCostPer1MInCached: 0.0,\n\t\tCostPer1MOutCached: 0.0,\n\t\tCostPer1MOut: 0.0,\n\t\tContextWindow: 128_000,\n\t\tDefaultMaxTokens: 16384,\n\t\tSupportsAttachments: true,\n\t},\n\tCopilotGPT4oMini: {\n\t\tID: CopilotGPT4oMini,\n\t\tName: \"GitHub Copilot GPT-4o Mini\",\n\t\tProvider: ProviderCopilot,\n\t\tAPIModel: \"gpt-4o-mini\",\n\t\tCostPer1MIn: 0.0, // Included in GitHub Copilot subscription\n\t\tCostPer1MInCached: 0.0,\n\t\tCostPer1MOutCached: 0.0,\n\t\tCostPer1MOut: 0.0,\n\t\tContextWindow: 128_000,\n\t\tDefaultMaxTokens: 4096,\n\t\tSupportsAttachments: true,\n\t},\n\tCopilotGPT41: {\n\t\tID: CopilotGPT41,\n\t\tName: \"GitHub Copilot GPT-4.1\",\n\t\tProvider: ProviderCopilot,\n\t\tAPIModel: \"gpt-4.1\",\n\t\tCostPer1MIn: 0.0, // Included in GitHub Copilot subscription\n\t\tCostPer1MInCached: 0.0,\n\t\tCostPer1MOutCached: 0.0,\n\t\tCostPer1MOut: 0.0,\n\t\tContextWindow: 128_000,\n\t\tDefaultMaxTokens: 16384,\n\t\tCanReason: true,\n\t\tSupportsAttachments: true,\n\t},\n\tCopilotClaude35: {\n\t\tID: CopilotClaude35,\n\t\tName: \"GitHub Copilot Claude 3.5 Sonnet\",\n\t\tProvider: ProviderCopilot,\n\t\tAPIModel: \"claude-3.5-sonnet\",\n\t\tCostPer1MIn: 0.0, // Included in GitHub Copilot subscription\n\t\tCostPer1MInCached: 0.0,\n\t\tCostPer1MOutCached: 0.0,\n\t\tCostPer1MOut: 0.0,\n\t\tContextWindow: 90_000,\n\t\tDefaultMaxTokens: 8192,\n\t\tSupportsAttachments: true,\n\t},\n\tCopilotClaude37: {\n\t\tID: CopilotClaude37,\n\t\tName: \"GitHub Copilot Claude 3.7 Sonnet\",\n\t\tProvider: ProviderCopilot,\n\t\tAPIModel: \"claude-3.7-sonnet\",\n\t\tCostPer1MIn: 0.0, // Included in GitHub Copilot subscription\n\t\tCostPer1MInCached: 0.0,\n\t\tCostPer1MOutCached: 0.0,\n\t\tCostPer1MOut: 0.0,\n\t\tContextWindow: 200_000,\n\t\tDefaultMaxTokens: 16384,\n\t\tSupportsAttachments: true,\n\t},\n\tCopilotClaude4: {\n\t\tID: CopilotClaude4,\n\t\tName: \"GitHub Copilot Claude Sonnet 4\",\n\t\tProvider: ProviderCopilot,\n\t\tAPIModel: \"claude-sonnet-4\",\n\t\tCostPer1MIn: 0.0, // Included in GitHub Copilot subscription\n\t\tCostPer1MInCached: 0.0,\n\t\tCostPer1MOutCached: 0.0,\n\t\tCostPer1MOut: 0.0,\n\t\tContextWindow: 128_000,\n\t\tDefaultMaxTokens: 16000,\n\t\tSupportsAttachments: true,\n\t},\n\tCopilotO1: {\n\t\tID: CopilotO1,\n\t\tName: \"GitHub Copilot o1\",\n\t\tProvider: ProviderCopilot,\n\t\tAPIModel: \"o1\",\n\t\tCostPer1MIn: 0.0, // Included in GitHub Copilot subscription\n\t\tCostPer1MInCached: 0.0,\n\t\tCostPer1MOutCached: 0.0,\n\t\tCostPer1MOut: 0.0,\n\t\tContextWindow: 200_000,\n\t\tDefaultMaxTokens: 100_000,\n\t\tCanReason: true,\n\t\tSupportsAttachments: false,\n\t},\n\tCopilotO3Mini: {\n\t\tID: CopilotO3Mini,\n\t\tName: \"GitHub Copilot o3-mini\",\n\t\tProvider: ProviderCopilot,\n\t\tAPIModel: \"o3-mini\",\n\t\tCostPer1MIn: 0.0, // Included in GitHub Copilot subscription\n\t\tCostPer1MInCached: 0.0,\n\t\tCostPer1MOutCached: 0.0,\n\t\tCostPer1MOut: 0.0,\n\t\tContextWindow: 200_000,\n\t\tDefaultMaxTokens: 100_000,\n\t\tCanReason: true,\n\t\tSupportsAttachments: false,\n\t},\n\tCopilotO4Mini: {\n\t\tID: CopilotO4Mini,\n\t\tName: \"GitHub Copilot o4-mini\",\n\t\tProvider: ProviderCopilot,\n\t\tAPIModel: \"o4-mini\",\n\t\tCostPer1MIn: 0.0, // Included in GitHub Copilot subscription\n\t\tCostPer1MInCached: 0.0,\n\t\tCostPer1MOutCached: 0.0,\n\t\tCostPer1MOut: 0.0,\n\t\tContextWindow: 128_000,\n\t\tDefaultMaxTokens: 16_384,\n\t\tCanReason: true,\n\t\tSupportsAttachments: true,\n\t},\n\tCopilotGemini20: {\n\t\tID: CopilotGemini20,\n\t\tName: \"GitHub Copilot Gemini 2.0 Flash\",\n\t\tProvider: ProviderCopilot,\n\t\tAPIModel: \"gemini-2.0-flash-001\",\n\t\tCostPer1MIn: 0.0, // Included in GitHub Copilot subscription\n\t\tCostPer1MInCached: 0.0,\n\t\tCostPer1MOutCached: 0.0,\n\t\tCostPer1MOut: 0.0,\n\t\tContextWindow: 1_000_000,\n\t\tDefaultMaxTokens: 8192,\n\t\tSupportsAttachments: true,\n\t},\n\tCopilotGemini25: {\n\t\tID: CopilotGemini25,\n\t\tName: \"GitHub Copilot Gemini 2.5 Pro\",\n\t\tProvider: ProviderCopilot,\n\t\tAPIModel: \"gemini-2.5-pro\",\n\t\tCostPer1MIn: 0.0, // Included in GitHub Copilot subscription\n\t\tCostPer1MInCached: 0.0,\n\t\tCostPer1MOutCached: 0.0,\n\t\tCostPer1MOut: 0.0,\n\t\tContextWindow: 128_000,\n\t\tDefaultMaxTokens: 64000,\n\t\tSupportsAttachments: true,\n\t},\n\tCopilotGPT4: {\n\t\tID: CopilotGPT4,\n\t\tName: \"GitHub Copilot GPT-4\",\n\t\tProvider: ProviderCopilot,\n\t\tAPIModel: \"gpt-4\",\n\t\tCostPer1MIn: 0.0, // Included in GitHub Copilot subscription\n\t\tCostPer1MInCached: 0.0,\n\t\tCostPer1MOutCached: 0.0,\n\t\tCostPer1MOut: 0.0,\n\t\tContextWindow: 32_768,\n\t\tDefaultMaxTokens: 4096,\n\t\tSupportsAttachments: true,\n\t},\n\tCopilotClaude37Thought: {\n\t\tID: CopilotClaude37Thought,\n\t\tName: \"GitHub Copilot Claude 3.7 Sonnet Thinking\",\n\t\tProvider: ProviderCopilot,\n\t\tAPIModel: \"claude-3.7-sonnet-thought\",\n\t\tCostPer1MIn: 0.0, // Included in GitHub Copilot subscription\n\t\tCostPer1MInCached: 0.0,\n\t\tCostPer1MOutCached: 0.0,\n\t\tCostPer1MOut: 0.0,\n\t\tContextWindow: 200_000,\n\t\tDefaultMaxTokens: 16384,\n\t\tCanReason: true,\n\t\tSupportsAttachments: true,\n\t},\n}\n"], ["/opencode/internal/llm/models/openrouter.go", "package models\n\nconst (\n\tProviderOpenRouter ModelProvider = \"openrouter\"\n\n\tOpenRouterGPT41 ModelID = \"openrouter.gpt-4.1\"\n\tOpenRouterGPT41Mini ModelID = \"openrouter.gpt-4.1-mini\"\n\tOpenRouterGPT41Nano ModelID = \"openrouter.gpt-4.1-nano\"\n\tOpenRouterGPT45Preview ModelID = \"openrouter.gpt-4.5-preview\"\n\tOpenRouterGPT4o ModelID = \"openrouter.gpt-4o\"\n\tOpenRouterGPT4oMini ModelID = \"openrouter.gpt-4o-mini\"\n\tOpenRouterO1 ModelID = \"openrouter.o1\"\n\tOpenRouterO1Pro ModelID = \"openrouter.o1-pro\"\n\tOpenRouterO1Mini ModelID = \"openrouter.o1-mini\"\n\tOpenRouterO3 ModelID = \"openrouter.o3\"\n\tOpenRouterO3Mini ModelID = \"openrouter.o3-mini\"\n\tOpenRouterO4Mini ModelID = \"openrouter.o4-mini\"\n\tOpenRouterGemini25Flash ModelID = \"openrouter.gemini-2.5-flash\"\n\tOpenRouterGemini25 ModelID = \"openrouter.gemini-2.5\"\n\tOpenRouterClaude35Sonnet ModelID = \"openrouter.claude-3.5-sonnet\"\n\tOpenRouterClaude3Haiku ModelID = \"openrouter.claude-3-haiku\"\n\tOpenRouterClaude37Sonnet ModelID = \"openrouter.claude-3.7-sonnet\"\n\tOpenRouterClaude35Haiku ModelID = \"openrouter.claude-3.5-haiku\"\n\tOpenRouterClaude3Opus ModelID = \"openrouter.claude-3-opus\"\n\tOpenRouterDeepSeekR1Free ModelID = \"openrouter.deepseek-r1-free\"\n)\n\nvar OpenRouterModels = map[ModelID]Model{\n\tOpenRouterGPT41: {\n\t\tID: OpenRouterGPT41,\n\t\tName: \"OpenRouter – GPT 4.1\",\n\t\tProvider: ProviderOpenRouter,\n\t\tAPIModel: \"openai/gpt-4.1\",\n\t\tCostPer1MIn: OpenAIModels[GPT41].CostPer1MIn,\n\t\tCostPer1MInCached: OpenAIModels[GPT41].CostPer1MInCached,\n\t\tCostPer1MOut: OpenAIModels[GPT41].CostPer1MOut,\n\t\tCostPer1MOutCached: OpenAIModels[GPT41].CostPer1MOutCached,\n\t\tContextWindow: OpenAIModels[GPT41].ContextWindow,\n\t\tDefaultMaxTokens: OpenAIModels[GPT41].DefaultMaxTokens,\n\t},\n\tOpenRouterGPT41Mini: {\n\t\tID: OpenRouterGPT41Mini,\n\t\tName: \"OpenRouter – GPT 4.1 mini\",\n\t\tProvider: ProviderOpenRouter,\n\t\tAPIModel: \"openai/gpt-4.1-mini\",\n\t\tCostPer1MIn: OpenAIModels[GPT41Mini].CostPer1MIn,\n\t\tCostPer1MInCached: OpenAIModels[GPT41Mini].CostPer1MInCached,\n\t\tCostPer1MOut: OpenAIModels[GPT41Mini].CostPer1MOut,\n\t\tCostPer1MOutCached: OpenAIModels[GPT41Mini].CostPer1MOutCached,\n\t\tContextWindow: OpenAIModels[GPT41Mini].ContextWindow,\n\t\tDefaultMaxTokens: OpenAIModels[GPT41Mini].DefaultMaxTokens,\n\t},\n\tOpenRouterGPT41Nano: {\n\t\tID: OpenRouterGPT41Nano,\n\t\tName: \"OpenRouter – GPT 4.1 nano\",\n\t\tProvider: ProviderOpenRouter,\n\t\tAPIModel: \"openai/gpt-4.1-nano\",\n\t\tCostPer1MIn: OpenAIModels[GPT41Nano].CostPer1MIn,\n\t\tCostPer1MInCached: OpenAIModels[GPT41Nano].CostPer1MInCached,\n\t\tCostPer1MOut: OpenAIModels[GPT41Nano].CostPer1MOut,\n\t\tCostPer1MOutCached: OpenAIModels[GPT41Nano].CostPer1MOutCached,\n\t\tContextWindow: OpenAIModels[GPT41Nano].ContextWindow,\n\t\tDefaultMaxTokens: OpenAIModels[GPT41Nano].DefaultMaxTokens,\n\t},\n\tOpenRouterGPT45Preview: {\n\t\tID: OpenRouterGPT45Preview,\n\t\tName: \"OpenRouter – GPT 4.5 preview\",\n\t\tProvider: ProviderOpenRouter,\n\t\tAPIModel: \"openai/gpt-4.5-preview\",\n\t\tCostPer1MIn: OpenAIModels[GPT45Preview].CostPer1MIn,\n\t\tCostPer1MInCached: OpenAIModels[GPT45Preview].CostPer1MInCached,\n\t\tCostPer1MOut: OpenAIModels[GPT45Preview].CostPer1MOut,\n\t\tCostPer1MOutCached: OpenAIModels[GPT45Preview].CostPer1MOutCached,\n\t\tContextWindow: OpenAIModels[GPT45Preview].ContextWindow,\n\t\tDefaultMaxTokens: OpenAIModels[GPT45Preview].DefaultMaxTokens,\n\t},\n\tOpenRouterGPT4o: {\n\t\tID: OpenRouterGPT4o,\n\t\tName: \"OpenRouter – GPT 4o\",\n\t\tProvider: ProviderOpenRouter,\n\t\tAPIModel: \"openai/gpt-4o\",\n\t\tCostPer1MIn: OpenAIModels[GPT4o].CostPer1MIn,\n\t\tCostPer1MInCached: OpenAIModels[GPT4o].CostPer1MInCached,\n\t\tCostPer1MOut: OpenAIModels[GPT4o].CostPer1MOut,\n\t\tCostPer1MOutCached: OpenAIModels[GPT4o].CostPer1MOutCached,\n\t\tContextWindow: OpenAIModels[GPT4o].ContextWindow,\n\t\tDefaultMaxTokens: OpenAIModels[GPT4o].DefaultMaxTokens,\n\t},\n\tOpenRouterGPT4oMini: {\n\t\tID: OpenRouterGPT4oMini,\n\t\tName: \"OpenRouter – GPT 4o mini\",\n\t\tProvider: ProviderOpenRouter,\n\t\tAPIModel: \"openai/gpt-4o-mini\",\n\t\tCostPer1MIn: OpenAIModels[GPT4oMini].CostPer1MIn,\n\t\tCostPer1MInCached: OpenAIModels[GPT4oMini].CostPer1MInCached,\n\t\tCostPer1MOut: OpenAIModels[GPT4oMini].CostPer1MOut,\n\t\tCostPer1MOutCached: OpenAIModels[GPT4oMini].CostPer1MOutCached,\n\t\tContextWindow: OpenAIModels[GPT4oMini].ContextWindow,\n\t},\n\tOpenRouterO1: {\n\t\tID: OpenRouterO1,\n\t\tName: \"OpenRouter – O1\",\n\t\tProvider: ProviderOpenRouter,\n\t\tAPIModel: \"openai/o1\",\n\t\tCostPer1MIn: OpenAIModels[O1].CostPer1MIn,\n\t\tCostPer1MInCached: OpenAIModels[O1].CostPer1MInCached,\n\t\tCostPer1MOut: OpenAIModels[O1].CostPer1MOut,\n\t\tCostPer1MOutCached: OpenAIModels[O1].CostPer1MOutCached,\n\t\tContextWindow: OpenAIModels[O1].ContextWindow,\n\t\tDefaultMaxTokens: OpenAIModels[O1].DefaultMaxTokens,\n\t\tCanReason: OpenAIModels[O1].CanReason,\n\t},\n\tOpenRouterO1Pro: {\n\t\tID: OpenRouterO1Pro,\n\t\tName: \"OpenRouter – o1 pro\",\n\t\tProvider: ProviderOpenRouter,\n\t\tAPIModel: \"openai/o1-pro\",\n\t\tCostPer1MIn: OpenAIModels[O1Pro].CostPer1MIn,\n\t\tCostPer1MInCached: OpenAIModels[O1Pro].CostPer1MInCached,\n\t\tCostPer1MOut: OpenAIModels[O1Pro].CostPer1MOut,\n\t\tCostPer1MOutCached: OpenAIModels[O1Pro].CostPer1MOutCached,\n\t\tContextWindow: OpenAIModels[O1Pro].ContextWindow,\n\t\tDefaultMaxTokens: OpenAIModels[O1Pro].DefaultMaxTokens,\n\t\tCanReason: OpenAIModels[O1Pro].CanReason,\n\t},\n\tOpenRouterO1Mini: {\n\t\tID: OpenRouterO1Mini,\n\t\tName: \"OpenRouter – o1 mini\",\n\t\tProvider: ProviderOpenRouter,\n\t\tAPIModel: \"openai/o1-mini\",\n\t\tCostPer1MIn: OpenAIModels[O1Mini].CostPer1MIn,\n\t\tCostPer1MInCached: OpenAIModels[O1Mini].CostPer1MInCached,\n\t\tCostPer1MOut: OpenAIModels[O1Mini].CostPer1MOut,\n\t\tCostPer1MOutCached: OpenAIModels[O1Mini].CostPer1MOutCached,\n\t\tContextWindow: OpenAIModels[O1Mini].ContextWindow,\n\t\tDefaultMaxTokens: OpenAIModels[O1Mini].DefaultMaxTokens,\n\t\tCanReason: OpenAIModels[O1Mini].CanReason,\n\t},\n\tOpenRouterO3: {\n\t\tID: OpenRouterO3,\n\t\tName: \"OpenRouter – o3\",\n\t\tProvider: ProviderOpenRouter,\n\t\tAPIModel: \"openai/o3\",\n\t\tCostPer1MIn: OpenAIModels[O3].CostPer1MIn,\n\t\tCostPer1MInCached: OpenAIModels[O3].CostPer1MInCached,\n\t\tCostPer1MOut: OpenAIModels[O3].CostPer1MOut,\n\t\tCostPer1MOutCached: OpenAIModels[O3].CostPer1MOutCached,\n\t\tContextWindow: OpenAIModels[O3].ContextWindow,\n\t\tDefaultMaxTokens: OpenAIModels[O3].DefaultMaxTokens,\n\t\tCanReason: OpenAIModels[O3].CanReason,\n\t},\n\tOpenRouterO3Mini: {\n\t\tID: OpenRouterO3Mini,\n\t\tName: \"OpenRouter – o3 mini\",\n\t\tProvider: ProviderOpenRouter,\n\t\tAPIModel: \"openai/o3-mini-high\",\n\t\tCostPer1MIn: OpenAIModels[O3Mini].CostPer1MIn,\n\t\tCostPer1MInCached: OpenAIModels[O3Mini].CostPer1MInCached,\n\t\tCostPer1MOut: OpenAIModels[O3Mini].CostPer1MOut,\n\t\tCostPer1MOutCached: OpenAIModels[O3Mini].CostPer1MOutCached,\n\t\tContextWindow: OpenAIModels[O3Mini].ContextWindow,\n\t\tDefaultMaxTokens: OpenAIModels[O3Mini].DefaultMaxTokens,\n\t\tCanReason: OpenAIModels[O3Mini].CanReason,\n\t},\n\tOpenRouterO4Mini: {\n\t\tID: OpenRouterO4Mini,\n\t\tName: \"OpenRouter – o4 mini\",\n\t\tProvider: ProviderOpenRouter,\n\t\tAPIModel: \"openai/o4-mini-high\",\n\t\tCostPer1MIn: OpenAIModels[O4Mini].CostPer1MIn,\n\t\tCostPer1MInCached: OpenAIModels[O4Mini].CostPer1MInCached,\n\t\tCostPer1MOut: OpenAIModels[O4Mini].CostPer1MOut,\n\t\tCostPer1MOutCached: OpenAIModels[O4Mini].CostPer1MOutCached,\n\t\tContextWindow: OpenAIModels[O4Mini].ContextWindow,\n\t\tDefaultMaxTokens: OpenAIModels[O4Mini].DefaultMaxTokens,\n\t\tCanReason: OpenAIModels[O4Mini].CanReason,\n\t},\n\tOpenRouterGemini25Flash: {\n\t\tID: OpenRouterGemini25Flash,\n\t\tName: \"OpenRouter – Gemini 2.5 Flash\",\n\t\tProvider: ProviderOpenRouter,\n\t\tAPIModel: \"google/gemini-2.5-flash-preview:thinking\",\n\t\tCostPer1MIn: GeminiModels[Gemini25Flash].CostPer1MIn,\n\t\tCostPer1MInCached: GeminiModels[Gemini25Flash].CostPer1MInCached,\n\t\tCostPer1MOut: GeminiModels[Gemini25Flash].CostPer1MOut,\n\t\tCostPer1MOutCached: GeminiModels[Gemini25Flash].CostPer1MOutCached,\n\t\tContextWindow: GeminiModels[Gemini25Flash].ContextWindow,\n\t\tDefaultMaxTokens: GeminiModels[Gemini25Flash].DefaultMaxTokens,\n\t},\n\tOpenRouterGemini25: {\n\t\tID: OpenRouterGemini25,\n\t\tName: \"OpenRouter – Gemini 2.5 Pro\",\n\t\tProvider: ProviderOpenRouter,\n\t\tAPIModel: \"google/gemini-2.5-pro-preview-03-25\",\n\t\tCostPer1MIn: GeminiModels[Gemini25].CostPer1MIn,\n\t\tCostPer1MInCached: GeminiModels[Gemini25].CostPer1MInCached,\n\t\tCostPer1MOut: GeminiModels[Gemini25].CostPer1MOut,\n\t\tCostPer1MOutCached: GeminiModels[Gemini25].CostPer1MOutCached,\n\t\tContextWindow: GeminiModels[Gemini25].ContextWindow,\n\t\tDefaultMaxTokens: GeminiModels[Gemini25].DefaultMaxTokens,\n\t},\n\tOpenRouterClaude35Sonnet: {\n\t\tID: OpenRouterClaude35Sonnet,\n\t\tName: \"OpenRouter – Claude 3.5 Sonnet\",\n\t\tProvider: ProviderOpenRouter,\n\t\tAPIModel: \"anthropic/claude-3.5-sonnet\",\n\t\tCostPer1MIn: AnthropicModels[Claude35Sonnet].CostPer1MIn,\n\t\tCostPer1MInCached: AnthropicModels[Claude35Sonnet].CostPer1MInCached,\n\t\tCostPer1MOut: AnthropicModels[Claude35Sonnet].CostPer1MOut,\n\t\tCostPer1MOutCached: AnthropicModels[Claude35Sonnet].CostPer1MOutCached,\n\t\tContextWindow: AnthropicModels[Claude35Sonnet].ContextWindow,\n\t\tDefaultMaxTokens: AnthropicModels[Claude35Sonnet].DefaultMaxTokens,\n\t},\n\tOpenRouterClaude3Haiku: {\n\t\tID: OpenRouterClaude3Haiku,\n\t\tName: \"OpenRouter – Claude 3 Haiku\",\n\t\tProvider: ProviderOpenRouter,\n\t\tAPIModel: \"anthropic/claude-3-haiku\",\n\t\tCostPer1MIn: AnthropicModels[Claude3Haiku].CostPer1MIn,\n\t\tCostPer1MInCached: AnthropicModels[Claude3Haiku].CostPer1MInCached,\n\t\tCostPer1MOut: AnthropicModels[Claude3Haiku].CostPer1MOut,\n\t\tCostPer1MOutCached: AnthropicModels[Claude3Haiku].CostPer1MOutCached,\n\t\tContextWindow: AnthropicModels[Claude3Haiku].ContextWindow,\n\t\tDefaultMaxTokens: AnthropicModels[Claude3Haiku].DefaultMaxTokens,\n\t},\n\tOpenRouterClaude37Sonnet: {\n\t\tID: OpenRouterClaude37Sonnet,\n\t\tName: \"OpenRouter – Claude 3.7 Sonnet\",\n\t\tProvider: ProviderOpenRouter,\n\t\tAPIModel: \"anthropic/claude-3.7-sonnet\",\n\t\tCostPer1MIn: AnthropicModels[Claude37Sonnet].CostPer1MIn,\n\t\tCostPer1MInCached: AnthropicModels[Claude37Sonnet].CostPer1MInCached,\n\t\tCostPer1MOut: AnthropicModels[Claude37Sonnet].CostPer1MOut,\n\t\tCostPer1MOutCached: AnthropicModels[Claude37Sonnet].CostPer1MOutCached,\n\t\tContextWindow: AnthropicModels[Claude37Sonnet].ContextWindow,\n\t\tDefaultMaxTokens: AnthropicModels[Claude37Sonnet].DefaultMaxTokens,\n\t\tCanReason: AnthropicModels[Claude37Sonnet].CanReason,\n\t},\n\tOpenRouterClaude35Haiku: {\n\t\tID: OpenRouterClaude35Haiku,\n\t\tName: \"OpenRouter – Claude 3.5 Haiku\",\n\t\tProvider: ProviderOpenRouter,\n\t\tAPIModel: \"anthropic/claude-3.5-haiku\",\n\t\tCostPer1MIn: AnthropicModels[Claude35Haiku].CostPer1MIn,\n\t\tCostPer1MInCached: AnthropicModels[Claude35Haiku].CostPer1MInCached,\n\t\tCostPer1MOut: AnthropicModels[Claude35Haiku].CostPer1MOut,\n\t\tCostPer1MOutCached: AnthropicModels[Claude35Haiku].CostPer1MOutCached,\n\t\tContextWindow: AnthropicModels[Claude35Haiku].ContextWindow,\n\t\tDefaultMaxTokens: AnthropicModels[Claude35Haiku].DefaultMaxTokens,\n\t},\n\tOpenRouterClaude3Opus: {\n\t\tID: OpenRouterClaude3Opus,\n\t\tName: \"OpenRouter – Claude 3 Opus\",\n\t\tProvider: ProviderOpenRouter,\n\t\tAPIModel: \"anthropic/claude-3-opus\",\n\t\tCostPer1MIn: AnthropicModels[Claude3Opus].CostPer1MIn,\n\t\tCostPer1MInCached: AnthropicModels[Claude3Opus].CostPer1MInCached,\n\t\tCostPer1MOut: AnthropicModels[Claude3Opus].CostPer1MOut,\n\t\tCostPer1MOutCached: AnthropicModels[Claude3Opus].CostPer1MOutCached,\n\t\tContextWindow: AnthropicModels[Claude3Opus].ContextWindow,\n\t\tDefaultMaxTokens: AnthropicModels[Claude3Opus].DefaultMaxTokens,\n\t},\n\n\tOpenRouterDeepSeekR1Free: {\n\t\tID: OpenRouterDeepSeekR1Free,\n\t\tName: \"OpenRouter – DeepSeek R1 Free\",\n\t\tProvider: ProviderOpenRouter,\n\t\tAPIModel: \"deepseek/deepseek-r1-0528:free\",\n\t\tCostPer1MIn: 0,\n\t\tCostPer1MInCached: 0,\n\t\tCostPer1MOut: 0,\n\t\tCostPer1MOutCached: 0,\n\t\tContextWindow: 163_840,\n\t\tDefaultMaxTokens: 10000,\n\t},\n}\n"], ["/opencode/internal/llm/models/gemini.go", "package models\n\nconst (\n\tProviderGemini ModelProvider = \"gemini\"\n\n\t// Models\n\tGemini25Flash ModelID = \"gemini-2.5-flash\"\n\tGemini25 ModelID = \"gemini-2.5\"\n\tGemini20Flash ModelID = \"gemini-2.0-flash\"\n\tGemini20FlashLite ModelID = \"gemini-2.0-flash-lite\"\n)\n\nvar GeminiModels = map[ModelID]Model{\n\tGemini25Flash: {\n\t\tID: Gemini25Flash,\n\t\tName: \"Gemini 2.5 Flash\",\n\t\tProvider: ProviderGemini,\n\t\tAPIModel: \"gemini-2.5-flash-preview-04-17\",\n\t\tCostPer1MIn: 0.15,\n\t\tCostPer1MInCached: 0,\n\t\tCostPer1MOutCached: 0,\n\t\tCostPer1MOut: 0.60,\n\t\tContextWindow: 1000000,\n\t\tDefaultMaxTokens: 50000,\n\t\tSupportsAttachments: true,\n\t},\n\tGemini25: {\n\t\tID: Gemini25,\n\t\tName: \"Gemini 2.5 Pro\",\n\t\tProvider: ProviderGemini,\n\t\tAPIModel: \"gemini-2.5-pro-preview-05-06\",\n\t\tCostPer1MIn: 1.25,\n\t\tCostPer1MInCached: 0,\n\t\tCostPer1MOutCached: 0,\n\t\tCostPer1MOut: 10,\n\t\tContextWindow: 1000000,\n\t\tDefaultMaxTokens: 50000,\n\t\tSupportsAttachments: true,\n\t},\n\n\tGemini20Flash: {\n\t\tID: Gemini20Flash,\n\t\tName: \"Gemini 2.0 Flash\",\n\t\tProvider: ProviderGemini,\n\t\tAPIModel: \"gemini-2.0-flash\",\n\t\tCostPer1MIn: 0.10,\n\t\tCostPer1MInCached: 0,\n\t\tCostPer1MOutCached: 0,\n\t\tCostPer1MOut: 0.40,\n\t\tContextWindow: 1000000,\n\t\tDefaultMaxTokens: 6000,\n\t\tSupportsAttachments: true,\n\t},\n\tGemini20FlashLite: {\n\t\tID: Gemini20FlashLite,\n\t\tName: \"Gemini 2.0 Flash Lite\",\n\t\tProvider: ProviderGemini,\n\t\tAPIModel: \"gemini-2.0-flash-lite\",\n\t\tCostPer1MIn: 0.05,\n\t\tCostPer1MInCached: 0,\n\t\tCostPer1MOutCached: 0,\n\t\tCostPer1MOut: 0.30,\n\t\tContextWindow: 1000000,\n\t\tDefaultMaxTokens: 6000,\n\t\tSupportsAttachments: true,\n\t},\n}\n"], ["/opencode/internal/llm/models/vertexai.go", "package models\n\nconst (\n\tProviderVertexAI ModelProvider = \"vertexai\"\n\n\t// Models\n\tVertexAIGemini25Flash ModelID = \"vertexai.gemini-2.5-flash\"\n\tVertexAIGemini25 ModelID = \"vertexai.gemini-2.5\"\n)\n\nvar VertexAIGeminiModels = map[ModelID]Model{\n\tVertexAIGemini25Flash: {\n\t\tID: VertexAIGemini25Flash,\n\t\tName: \"VertexAI: Gemini 2.5 Flash\",\n\t\tProvider: ProviderVertexAI,\n\t\tAPIModel: \"gemini-2.5-flash-preview-04-17\",\n\t\tCostPer1MIn: GeminiModels[Gemini25Flash].CostPer1MIn,\n\t\tCostPer1MInCached: GeminiModels[Gemini25Flash].CostPer1MInCached,\n\t\tCostPer1MOut: GeminiModels[Gemini25Flash].CostPer1MOut,\n\t\tCostPer1MOutCached: GeminiModels[Gemini25Flash].CostPer1MOutCached,\n\t\tContextWindow: GeminiModels[Gemini25Flash].ContextWindow,\n\t\tDefaultMaxTokens: GeminiModels[Gemini25Flash].DefaultMaxTokens,\n\t\tSupportsAttachments: true,\n\t},\n\tVertexAIGemini25: {\n\t\tID: VertexAIGemini25,\n\t\tName: \"VertexAI: Gemini 2.5 Pro\",\n\t\tProvider: ProviderVertexAI,\n\t\tAPIModel: \"gemini-2.5-pro-preview-03-25\",\n\t\tCostPer1MIn: GeminiModels[Gemini25].CostPer1MIn,\n\t\tCostPer1MInCached: GeminiModels[Gemini25].CostPer1MInCached,\n\t\tCostPer1MOut: GeminiModels[Gemini25].CostPer1MOut,\n\t\tCostPer1MOutCached: GeminiModels[Gemini25].CostPer1MOutCached,\n\t\tContextWindow: GeminiModels[Gemini25].ContextWindow,\n\t\tDefaultMaxTokens: GeminiModels[Gemini25].DefaultMaxTokens,\n\t\tSupportsAttachments: true,\n\t},\n}\n"], ["/opencode/internal/db/embed.go", "package db\n\nimport \"embed\"\n\n//go:embed migrations/*.sql\nvar FS embed.FS\n"], ["/opencode/internal/pubsub/events.go", "package pubsub\n\nimport \"context\"\n\nconst (\n\tCreatedEvent EventType = \"created\"\n\tUpdatedEvent EventType = \"updated\"\n\tDeletedEvent EventType = \"deleted\"\n)\n\ntype Suscriber[T any] interface {\n\tSubscribe(context.Context) <-chan Event[T]\n}\n\ntype (\n\t// EventType identifies the type of event\n\tEventType string\n\n\t// Event represents an event in the lifecycle of a resource\n\tEvent[T any] struct {\n\t\tType EventType\n\t\tPayload T\n\t}\n\n\tPublisher[T any] interface {\n\t\tPublish(EventType, T)\n\t}\n)\n"], ["/opencode/internal/db/models.go", "// Code generated by sqlc. DO NOT EDIT.\n// versions:\n// sqlc v1.29.0\n\npackage db\n\nimport (\n\t\"database/sql\"\n)\n\ntype File struct {\n\tID string `json:\"id\"`\n\tSessionID string `json:\"session_id\"`\n\tPath string `json:\"path\"`\n\tContent string `json:\"content\"`\n\tVersion string `json:\"version\"`\n\tCreatedAt int64 `json:\"created_at\"`\n\tUpdatedAt int64 `json:\"updated_at\"`\n}\n\ntype Message struct {\n\tID string `json:\"id\"`\n\tSessionID string `json:\"session_id\"`\n\tRole string `json:\"role\"`\n\tParts string `json:\"parts\"`\n\tModel sql.NullString `json:\"model\"`\n\tCreatedAt int64 `json:\"created_at\"`\n\tUpdatedAt int64 `json:\"updated_at\"`\n\tFinishedAt sql.NullInt64 `json:\"finished_at\"`\n}\n\ntype Session struct {\n\tID string `json:\"id\"`\n\tParentSessionID sql.NullString `json:\"parent_session_id\"`\n\tTitle string `json:\"title\"`\n\tMessageCount int64 `json:\"message_count\"`\n\tPromptTokens int64 `json:\"prompt_tokens\"`\n\tCompletionTokens int64 `json:\"completion_tokens\"`\n\tCost float64 `json:\"cost\"`\n\tUpdatedAt int64 `json:\"updated_at\"`\n\tCreatedAt int64 `json:\"created_at\"`\n\tSummaryMessageID sql.NullString `json:\"summary_message_id\"`\n}\n"], ["/opencode/internal/logging/message.go", "package logging\n\nimport (\n\t\"time\"\n)\n\n// LogMessage is the event payload for a log message\ntype LogMessage struct {\n\tID string\n\tTime time.Time\n\tLevel string\n\tPersist bool // used when we want to show the mesage in the status bar\n\tPersistTime time.Duration // used when we want to show the mesage in the status bar\n\tMessage string `json:\"msg\"`\n\tAttributes []Attr\n}\n\ntype Attr struct {\n\tKey string\n\tValue string\n}\n"], ["/opencode/internal/message/attachment.go", "package message\n\ntype Attachment struct {\n\tFilePath string\n\tFileName string\n\tMimeType string\n\tContent []byte\n}\n"], ["/opencode/internal/llm/models/openai.go", "package models\n\nconst (\n\tProviderOpenAI ModelProvider = \"openai\"\n\n\tGPT41 ModelID = \"gpt-4.1\"\n\tGPT41Mini ModelID = \"gpt-4.1-mini\"\n\tGPT41Nano ModelID = \"gpt-4.1-nano\"\n\tGPT45Preview ModelID = \"gpt-4.5-preview\"\n\tGPT4o ModelID = \"gpt-4o\"\n\tGPT4oMini ModelID = \"gpt-4o-mini\"\n\tO1 ModelID = \"o1\"\n\tO1Pro ModelID = \"o1-pro\"\n\tO1Mini ModelID = \"o1-mini\"\n\tO3 ModelID = \"o3\"\n\tO3Mini ModelID = \"o3-mini\"\n\tO4Mini ModelID = \"o4-mini\"\n)\n\nvar OpenAIModels = map[ModelID]Model{\n\tGPT41: {\n\t\tID: GPT41,\n\t\tName: \"GPT 4.1\",\n\t\tProvider: ProviderOpenAI,\n\t\tAPIModel: \"gpt-4.1\",\n\t\tCostPer1MIn: 2.00,\n\t\tCostPer1MInCached: 0.50,\n\t\tCostPer1MOutCached: 0.0,\n\t\tCostPer1MOut: 8.00,\n\t\tContextWindow: 1_047_576,\n\t\tDefaultMaxTokens: 20000,\n\t\tSupportsAttachments: true,\n\t},\n\tGPT41Mini: {\n\t\tID: GPT41Mini,\n\t\tName: \"GPT 4.1 mini\",\n\t\tProvider: ProviderOpenAI,\n\t\tAPIModel: \"gpt-4.1\",\n\t\tCostPer1MIn: 0.40,\n\t\tCostPer1MInCached: 0.10,\n\t\tCostPer1MOutCached: 0.0,\n\t\tCostPer1MOut: 1.60,\n\t\tContextWindow: 200_000,\n\t\tDefaultMaxTokens: 20000,\n\t\tSupportsAttachments: true,\n\t},\n\tGPT41Nano: {\n\t\tID: GPT41Nano,\n\t\tName: \"GPT 4.1 nano\",\n\t\tProvider: ProviderOpenAI,\n\t\tAPIModel: \"gpt-4.1-nano\",\n\t\tCostPer1MIn: 0.10,\n\t\tCostPer1MInCached: 0.025,\n\t\tCostPer1MOutCached: 0.0,\n\t\tCostPer1MOut: 0.40,\n\t\tContextWindow: 1_047_576,\n\t\tDefaultMaxTokens: 20000,\n\t\tSupportsAttachments: true,\n\t},\n\tGPT45Preview: {\n\t\tID: GPT45Preview,\n\t\tName: \"GPT 4.5 preview\",\n\t\tProvider: ProviderOpenAI,\n\t\tAPIModel: \"gpt-4.5-preview\",\n\t\tCostPer1MIn: 75.00,\n\t\tCostPer1MInCached: 37.50,\n\t\tCostPer1MOutCached: 0.0,\n\t\tCostPer1MOut: 150.00,\n\t\tContextWindow: 128_000,\n\t\tDefaultMaxTokens: 15000,\n\t\tSupportsAttachments: true,\n\t},\n\tGPT4o: {\n\t\tID: GPT4o,\n\t\tName: \"GPT 4o\",\n\t\tProvider: ProviderOpenAI,\n\t\tAPIModel: \"gpt-4o\",\n\t\tCostPer1MIn: 2.50,\n\t\tCostPer1MInCached: 1.25,\n\t\tCostPer1MOutCached: 0.0,\n\t\tCostPer1MOut: 10.00,\n\t\tContextWindow: 128_000,\n\t\tDefaultMaxTokens: 4096,\n\t\tSupportsAttachments: true,\n\t},\n\tGPT4oMini: {\n\t\tID: GPT4oMini,\n\t\tName: \"GPT 4o mini\",\n\t\tProvider: ProviderOpenAI,\n\t\tAPIModel: \"gpt-4o-mini\",\n\t\tCostPer1MIn: 0.15,\n\t\tCostPer1MInCached: 0.075,\n\t\tCostPer1MOutCached: 0.0,\n\t\tCostPer1MOut: 0.60,\n\t\tContextWindow: 128_000,\n\t\tSupportsAttachments: true,\n\t},\n\tO1: {\n\t\tID: O1,\n\t\tName: \"O1\",\n\t\tProvider: ProviderOpenAI,\n\t\tAPIModel: \"o1\",\n\t\tCostPer1MIn: 15.00,\n\t\tCostPer1MInCached: 7.50,\n\t\tCostPer1MOutCached: 0.0,\n\t\tCostPer1MOut: 60.00,\n\t\tContextWindow: 200_000,\n\t\tDefaultMaxTokens: 50000,\n\t\tCanReason: true,\n\t\tSupportsAttachments: true,\n\t},\n\tO1Pro: {\n\t\tID: O1Pro,\n\t\tName: \"o1 pro\",\n\t\tProvider: ProviderOpenAI,\n\t\tAPIModel: \"o1-pro\",\n\t\tCostPer1MIn: 150.00,\n\t\tCostPer1MInCached: 0.0,\n\t\tCostPer1MOutCached: 0.0,\n\t\tCostPer1MOut: 600.00,\n\t\tContextWindow: 200_000,\n\t\tDefaultMaxTokens: 50000,\n\t\tCanReason: true,\n\t\tSupportsAttachments: true,\n\t},\n\tO1Mini: {\n\t\tID: O1Mini,\n\t\tName: \"o1 mini\",\n\t\tProvider: ProviderOpenAI,\n\t\tAPIModel: \"o1-mini\",\n\t\tCostPer1MIn: 1.10,\n\t\tCostPer1MInCached: 0.55,\n\t\tCostPer1MOutCached: 0.0,\n\t\tCostPer1MOut: 4.40,\n\t\tContextWindow: 128_000,\n\t\tDefaultMaxTokens: 50000,\n\t\tCanReason: true,\n\t\tSupportsAttachments: true,\n\t},\n\tO3: {\n\t\tID: O3,\n\t\tName: \"o3\",\n\t\tProvider: ProviderOpenAI,\n\t\tAPIModel: \"o3\",\n\t\tCostPer1MIn: 10.00,\n\t\tCostPer1MInCached: 2.50,\n\t\tCostPer1MOutCached: 0.0,\n\t\tCostPer1MOut: 40.00,\n\t\tContextWindow: 200_000,\n\t\tCanReason: true,\n\t\tSupportsAttachments: true,\n\t},\n\tO3Mini: {\n\t\tID: O3Mini,\n\t\tName: \"o3 mini\",\n\t\tProvider: ProviderOpenAI,\n\t\tAPIModel: \"o3-mini\",\n\t\tCostPer1MIn: 1.10,\n\t\tCostPer1MInCached: 0.55,\n\t\tCostPer1MOutCached: 0.0,\n\t\tCostPer1MOut: 4.40,\n\t\tContextWindow: 200_000,\n\t\tDefaultMaxTokens: 50000,\n\t\tCanReason: true,\n\t\tSupportsAttachments: false,\n\t},\n\tO4Mini: {\n\t\tID: O4Mini,\n\t\tName: \"o4 mini\",\n\t\tProvider: ProviderOpenAI,\n\t\tAPIModel: \"o4-mini\",\n\t\tCostPer1MIn: 1.10,\n\t\tCostPer1MInCached: 0.275,\n\t\tCostPer1MOutCached: 0.0,\n\t\tCostPer1MOut: 4.40,\n\t\tContextWindow: 128_000,\n\t\tDefaultMaxTokens: 50000,\n\t\tCanReason: true,\n\t\tSupportsAttachments: true,\n\t},\n}\n"], ["/opencode/internal/llm/models/azure.go", "package models\n\nconst ProviderAzure ModelProvider = \"azure\"\n\nconst (\n\tAzureGPT41 ModelID = \"azure.gpt-4.1\"\n\tAzureGPT41Mini ModelID = \"azure.gpt-4.1-mini\"\n\tAzureGPT41Nano ModelID = \"azure.gpt-4.1-nano\"\n\tAzureGPT45Preview ModelID = \"azure.gpt-4.5-preview\"\n\tAzureGPT4o ModelID = \"azure.gpt-4o\"\n\tAzureGPT4oMini ModelID = \"azure.gpt-4o-mini\"\n\tAzureO1 ModelID = \"azure.o1\"\n\tAzureO1Mini ModelID = \"azure.o1-mini\"\n\tAzureO3 ModelID = \"azure.o3\"\n\tAzureO3Mini ModelID = \"azure.o3-mini\"\n\tAzureO4Mini ModelID = \"azure.o4-mini\"\n)\n\nvar AzureModels = map[ModelID]Model{\n\tAzureGPT41: {\n\t\tID: AzureGPT41,\n\t\tName: \"Azure OpenAI – GPT 4.1\",\n\t\tProvider: ProviderAzure,\n\t\tAPIModel: \"gpt-4.1\",\n\t\tCostPer1MIn: OpenAIModels[GPT41].CostPer1MIn,\n\t\tCostPer1MInCached: OpenAIModels[GPT41].CostPer1MInCached,\n\t\tCostPer1MOut: OpenAIModels[GPT41].CostPer1MOut,\n\t\tCostPer1MOutCached: OpenAIModels[GPT41].CostPer1MOutCached,\n\t\tContextWindow: OpenAIModels[GPT41].ContextWindow,\n\t\tDefaultMaxTokens: OpenAIModels[GPT41].DefaultMaxTokens,\n\t\tSupportsAttachments: true,\n\t},\n\tAzureGPT41Mini: {\n\t\tID: AzureGPT41Mini,\n\t\tName: \"Azure OpenAI – GPT 4.1 mini\",\n\t\tProvider: ProviderAzure,\n\t\tAPIModel: \"gpt-4.1-mini\",\n\t\tCostPer1MIn: OpenAIModels[GPT41Mini].CostPer1MIn,\n\t\tCostPer1MInCached: OpenAIModels[GPT41Mini].CostPer1MInCached,\n\t\tCostPer1MOut: OpenAIModels[GPT41Mini].CostPer1MOut,\n\t\tCostPer1MOutCached: OpenAIModels[GPT41Mini].CostPer1MOutCached,\n\t\tContextWindow: OpenAIModels[GPT41Mini].ContextWindow,\n\t\tDefaultMaxTokens: OpenAIModels[GPT41Mini].DefaultMaxTokens,\n\t\tSupportsAttachments: true,\n\t},\n\tAzureGPT41Nano: {\n\t\tID: AzureGPT41Nano,\n\t\tName: \"Azure OpenAI – GPT 4.1 nano\",\n\t\tProvider: ProviderAzure,\n\t\tAPIModel: \"gpt-4.1-nano\",\n\t\tCostPer1MIn: OpenAIModels[GPT41Nano].CostPer1MIn,\n\t\tCostPer1MInCached: OpenAIModels[GPT41Nano].CostPer1MInCached,\n\t\tCostPer1MOut: OpenAIModels[GPT41Nano].CostPer1MOut,\n\t\tCostPer1MOutCached: OpenAIModels[GPT41Nano].CostPer1MOutCached,\n\t\tContextWindow: OpenAIModels[GPT41Nano].ContextWindow,\n\t\tDefaultMaxTokens: OpenAIModels[GPT41Nano].DefaultMaxTokens,\n\t\tSupportsAttachments: true,\n\t},\n\tAzureGPT45Preview: {\n\t\tID: AzureGPT45Preview,\n\t\tName: \"Azure OpenAI – GPT 4.5 preview\",\n\t\tProvider: ProviderAzure,\n\t\tAPIModel: \"gpt-4.5-preview\",\n\t\tCostPer1MIn: OpenAIModels[GPT45Preview].CostPer1MIn,\n\t\tCostPer1MInCached: OpenAIModels[GPT45Preview].CostPer1MInCached,\n\t\tCostPer1MOut: OpenAIModels[GPT45Preview].CostPer1MOut,\n\t\tCostPer1MOutCached: OpenAIModels[GPT45Preview].CostPer1MOutCached,\n\t\tContextWindow: OpenAIModels[GPT45Preview].ContextWindow,\n\t\tDefaultMaxTokens: OpenAIModels[GPT45Preview].DefaultMaxTokens,\n\t\tSupportsAttachments: true,\n\t},\n\tAzureGPT4o: {\n\t\tID: AzureGPT4o,\n\t\tName: \"Azure OpenAI – GPT-4o\",\n\t\tProvider: ProviderAzure,\n\t\tAPIModel: \"gpt-4o\",\n\t\tCostPer1MIn: OpenAIModels[GPT4o].CostPer1MIn,\n\t\tCostPer1MInCached: OpenAIModels[GPT4o].CostPer1MInCached,\n\t\tCostPer1MOut: OpenAIModels[GPT4o].CostPer1MOut,\n\t\tCostPer1MOutCached: OpenAIModels[GPT4o].CostPer1MOutCached,\n\t\tContextWindow: OpenAIModels[GPT4o].ContextWindow,\n\t\tDefaultMaxTokens: OpenAIModels[GPT4o].DefaultMaxTokens,\n\t\tSupportsAttachments: true,\n\t},\n\tAzureGPT4oMini: {\n\t\tID: AzureGPT4oMini,\n\t\tName: \"Azure OpenAI – GPT-4o mini\",\n\t\tProvider: ProviderAzure,\n\t\tAPIModel: \"gpt-4o-mini\",\n\t\tCostPer1MIn: OpenAIModels[GPT4oMini].CostPer1MIn,\n\t\tCostPer1MInCached: OpenAIModels[GPT4oMini].CostPer1MInCached,\n\t\tCostPer1MOut: OpenAIModels[GPT4oMini].CostPer1MOut,\n\t\tCostPer1MOutCached: OpenAIModels[GPT4oMini].CostPer1MOutCached,\n\t\tContextWindow: OpenAIModels[GPT4oMini].ContextWindow,\n\t\tDefaultMaxTokens: OpenAIModels[GPT4oMini].DefaultMaxTokens,\n\t\tSupportsAttachments: true,\n\t},\n\tAzureO1: {\n\t\tID: AzureO1,\n\t\tName: \"Azure OpenAI – O1\",\n\t\tProvider: ProviderAzure,\n\t\tAPIModel: \"o1\",\n\t\tCostPer1MIn: OpenAIModels[O1].CostPer1MIn,\n\t\tCostPer1MInCached: OpenAIModels[O1].CostPer1MInCached,\n\t\tCostPer1MOut: OpenAIModels[O1].CostPer1MOut,\n\t\tCostPer1MOutCached: OpenAIModels[O1].CostPer1MOutCached,\n\t\tContextWindow: OpenAIModels[O1].ContextWindow,\n\t\tDefaultMaxTokens: OpenAIModels[O1].DefaultMaxTokens,\n\t\tCanReason: OpenAIModels[O1].CanReason,\n\t\tSupportsAttachments: true,\n\t},\n\tAzureO1Mini: {\n\t\tID: AzureO1Mini,\n\t\tName: \"Azure OpenAI – O1 mini\",\n\t\tProvider: ProviderAzure,\n\t\tAPIModel: \"o1-mini\",\n\t\tCostPer1MIn: OpenAIModels[O1Mini].CostPer1MIn,\n\t\tCostPer1MInCached: OpenAIModels[O1Mini].CostPer1MInCached,\n\t\tCostPer1MOut: OpenAIModels[O1Mini].CostPer1MOut,\n\t\tCostPer1MOutCached: OpenAIModels[O1Mini].CostPer1MOutCached,\n\t\tContextWindow: OpenAIModels[O1Mini].ContextWindow,\n\t\tDefaultMaxTokens: OpenAIModels[O1Mini].DefaultMaxTokens,\n\t\tCanReason: OpenAIModels[O1Mini].CanReason,\n\t\tSupportsAttachments: true,\n\t},\n\tAzureO3: {\n\t\tID: AzureO3,\n\t\tName: \"Azure OpenAI – O3\",\n\t\tProvider: ProviderAzure,\n\t\tAPIModel: \"o3\",\n\t\tCostPer1MIn: OpenAIModels[O3].CostPer1MIn,\n\t\tCostPer1MInCached: OpenAIModels[O3].CostPer1MInCached,\n\t\tCostPer1MOut: OpenAIModels[O3].CostPer1MOut,\n\t\tCostPer1MOutCached: OpenAIModels[O3].CostPer1MOutCached,\n\t\tContextWindow: OpenAIModels[O3].ContextWindow,\n\t\tDefaultMaxTokens: OpenAIModels[O3].DefaultMaxTokens,\n\t\tCanReason: OpenAIModels[O3].CanReason,\n\t\tSupportsAttachments: true,\n\t},\n\tAzureO3Mini: {\n\t\tID: AzureO3Mini,\n\t\tName: \"Azure OpenAI – O3 mini\",\n\t\tProvider: ProviderAzure,\n\t\tAPIModel: \"o3-mini\",\n\t\tCostPer1MIn: OpenAIModels[O3Mini].CostPer1MIn,\n\t\tCostPer1MInCached: OpenAIModels[O3Mini].CostPer1MInCached,\n\t\tCostPer1MOut: OpenAIModels[O3Mini].CostPer1MOut,\n\t\tCostPer1MOutCached: OpenAIModels[O3Mini].CostPer1MOutCached,\n\t\tContextWindow: OpenAIModels[O3Mini].ContextWindow,\n\t\tDefaultMaxTokens: OpenAIModels[O3Mini].DefaultMaxTokens,\n\t\tCanReason: OpenAIModels[O3Mini].CanReason,\n\t\tSupportsAttachments: false,\n\t},\n\tAzureO4Mini: {\n\t\tID: AzureO4Mini,\n\t\tName: \"Azure OpenAI – O4 mini\",\n\t\tProvider: ProviderAzure,\n\t\tAPIModel: \"o4-mini\",\n\t\tCostPer1MIn: OpenAIModels[O4Mini].CostPer1MIn,\n\t\tCostPer1MInCached: OpenAIModels[O4Mini].CostPer1MInCached,\n\t\tCostPer1MOut: OpenAIModels[O4Mini].CostPer1MOut,\n\t\tCostPer1MOutCached: OpenAIModels[O4Mini].CostPer1MOutCached,\n\t\tContextWindow: OpenAIModels[O4Mini].ContextWindow,\n\t\tDefaultMaxTokens: OpenAIModels[O4Mini].DefaultMaxTokens,\n\t\tCanReason: OpenAIModels[O4Mini].CanReason,\n\t\tSupportsAttachments: true,\n\t},\n}\n"], ["/opencode/internal/tui/page/page.go", "package page\n\ntype PageID string\n\n// PageChangeMsg is used to change the current page\ntype PageChangeMsg struct {\n\tID PageID\n}\n"], ["/opencode/internal/tui/styles/icons.go", "package styles\n\nconst (\n\tOpenCodeIcon string = \"⌬\"\n\n\tCheckIcon string = \"✓\"\n\tErrorIcon string = \"✖\"\n\tWarningIcon string = \"⚠\"\n\tInfoIcon string = \"\"\n\tHintIcon string = \"i\"\n\tSpinnerIcon string = \"...\"\n\tLoadingIcon string = \"⟳\"\n\tDocumentIcon string = \"🖼\"\n)\n"]], "task_instance_info": {"created_time": "2025-08-20 20:58:37", "created_task_model": "DeepSeek-R1", "function_skeleton": "func DetectLanguageID (uri string) protocol.LanguageKind {}", "code_description": "This code segment functions to: Map file extensions from a given path to standardized language identifiers using a predefined categorization structure, enabling type-specific processing based on filename patterns."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```go\n[TASK_BEGIN]\nfunc DetectLanguageID(uri string) protocol.LanguageKind {\n\text := strings.ToLower(strings.TrimPrefix(filepath.Ext(uri), \".\"))\n\tswitch ext {\n\tcase \"go\":\n\t\treturn protocol.LanguageKindGo\n\tcase \"py\":\n\t\treturn protocol.LanguageKindPython\n\tcase \"js\":\n\t\treturn protocol.LanguageKindJavaScript\n\tcase \"ts\":\n\t\treturn protocol.LanguageKindTypeScript\n\tcase \"java\":\n\t\treturn protocol.LanguageKindJava\n\tcase \"c\", \"h\":\n\t\treturn protocol.LanguageKindC\n\tcase \"cpp\", \"cc\", \"hpp\":\n\t\treturn protocol.LanguageKindCPP\n\tcase \"cs\":\n\t\treturn protocol.LanguageKindCSharp\n\tcase \"html\":\n\t\treturn protocol.LanguageKindHTML\n\tcase \"css\":\n\t\treturn protocol.LanguageKindCSS\n\tcase \"php\":\n\t\treturn protocol.LanguageKindPHP\n\tcase \"rb\":\n\t\treturn protocol.LanguageKindRuby\n\tcase \"swift\":\n\t\treturn protocol.LanguageKindSwift\n\tdefault:\n\t\treturn protocol.LanguageKindUnknown\n\t}\n}\n[TASK_END]\n```", "inference_time": "2025-08-20 20-59-11"}, "editdistance_info": {"edit_distance": 15.0198, "calculate_time": "2025-08-20 20:59:11", "true_code_clean": "func DetectLanguageID(uri string) protocol.LanguageKind {\n\text := strings.ToLower(filepath.Ext(uri))\n\tswitch ext {\n\tcase \".abap\":\n\t\treturn protocol.LangABAP\n\tcase \".bat\":\n\t\treturn protocol.LangWindowsBat\n\tcase \".bib\", \".bibtex\":\n\t\treturn protocol.LangBibTeX\n\tcase \".clj\":\n\t\treturn protocol.LangClojure\n\tcase \".coffee\":\n\t\treturn protocol.LangCoffeescript\n\tcase \".c\":\n\t\treturn protocol.LangC\n\tcase \".cpp\", \".cxx\", \".cc\", \".c++\":\n\t\treturn protocol.LangCPP\n\tcase \".cs\":\n\t\treturn protocol.LangCSharp\n\tcase \".css\":\n\t\treturn protocol.LangCSS\n\tcase \".d\":\n\t\treturn protocol.LangD\n\tcase \".pas\", \".pascal\":\n\t\treturn protocol.LangDelphi\n\tcase \".diff\", \".patch\":\n\t\treturn protocol.LangDiff\n\tcase \".dart\":\n\t\treturn protocol.LangDart\n\tcase \".dockerfile\":\n\t\treturn protocol.LangDockerfile\n\tcase \".ex\", \".exs\":\n\t\treturn protocol.LangElixir\n\tcase \".erl\", \".hrl\":\n\t\treturn protocol.LangErlang\n\tcase \".fs\", \".fsi\", \".fsx\", \".fsscript\":\n\t\treturn protocol.LangFSharp\n\tcase \".gitcommit\":\n\t\treturn protocol.LangGitCommit\n\tcase \".gitrebase\":\n\t\treturn protocol.LangGitRebase\n\tcase \".go\":\n\t\treturn protocol.LangGo\n\tcase \".groovy\":\n\t\treturn protocol.LangGroovy\n\tcase \".hbs\", \".handlebars\":\n\t\treturn protocol.LangHandlebars\n\tcase \".hs\":\n\t\treturn protocol.LangHaskell\n\tcase \".html\", \".htm\":\n\t\treturn protocol.LangHTML\n\tcase \".ini\":\n\t\treturn protocol.LangIni\n\tcase \".java\":\n\t\treturn protocol.LangJava\n\tcase \".js\":\n\t\treturn protocol.LangJavaScript\n\tcase \".jsx\":\n\t\treturn protocol.LangJavaScriptReact\n\tcase \".json\":\n\t\treturn protocol.LangJSON\n\tcase \".tex\", \".latex\":\n\t\treturn protocol.LangLaTeX\n\tcase \".less\":\n\t\treturn protocol.LangLess\n\tcase \".lua\":\n\t\treturn protocol.LangLua\n\tcase \".makefile\", \"makefile\":\n\t\treturn protocol.LangMakefile\n\tcase \".md\", \".markdown\":\n\t\treturn protocol.LangMarkdown\n\tcase \".m\":\n\t\treturn protocol.LangObjectiveC\n\tcase \".mm\":\n\t\treturn protocol.LangObjectiveCPP\n\tcase \".pl\":\n\t\treturn protocol.LangPerl\n\tcase \".pm\":\n\t\treturn protocol.LangPerl6\n\tcase \".php\":\n\t\treturn protocol.LangPHP\n\tcase \".ps1\", \".psm1\":\n\t\treturn protocol.LangPowershell\n\tcase \".pug\", \".jade\":\n\t\treturn protocol.LangPug\n\tcase \".py\":\n\t\treturn protocol.LangPython\n\tcase \".r\":\n\t\treturn protocol.LangR\n\tcase \".cshtml\", \".razor\":\n\t\treturn protocol.LangRazor\n\tcase \".rb\":\n\t\treturn protocol.LangRuby\n\tcase \".rs\":\n\t\treturn protocol.LangRust\n\tcase \".scss\":\n\t\treturn protocol.LangSCSS\n\tcase \".sass\":\n\t\treturn protocol.LangSASS\n\tcase \".scala\":\n\t\treturn protocol.LangScala\n\tcase \".shader\":\n\t\treturn protocol.LangShaderLab\n\tcase \".sh\", \".bash\", \".zsh\", \".ksh\":\n\t\treturn protocol.LangShellScript\n\tcase \".sql\":\n\t\treturn protocol.LangSQL\n\tcase \".swift\":\n\t\treturn protocol.LangSwift\n\tcase \".ts\":\n\t\treturn protocol.LangTypeScript\n\tcase \".tsx\":\n\t\treturn protocol.LangTypeScriptReact\n\tcase \".xml\":\n\t\treturn protocol.LangXML\n\tcase \".xsl\":\n\t\treturn protocol.LangXSL\n\tcase \".yaml\", \".yml\":\n\t\treturn protocol.LangYAML\n\tdefault:\n\t\treturn protocol.LanguageKind(\"\") \n\t}\n}", "predict_code_clean": "func DetectLanguageID(uri string) protocol.LanguageKind {\n\text := strings.ToLower(strings.TrimPrefix(filepath.Ext(uri), \".\"))\n\tswitch ext {\n\tcase \"go\":\n\t\treturn protocol.LanguageKindGo\n\tcase \"py\":\n\t\treturn protocol.LanguageKindPython\n\tcase \"js\":\n\t\treturn protocol.LanguageKindJavaScript\n\tcase \"ts\":\n\t\treturn protocol.LanguageKindTypeScript\n\tcase \"java\":\n\t\treturn protocol.LanguageKindJava\n\tcase \"c\", \"h\":\n\t\treturn protocol.LanguageKindC\n\tcase \"cpp\", \"cc\", \"hpp\":\n\t\treturn protocol.LanguageKindCPP\n\tcase \"cs\":\n\t\treturn protocol.LanguageKindCSharp\n\tcase \"html\":\n\t\treturn protocol.LanguageKindHTML\n\tcase \"css\":\n\t\treturn protocol.LanguageKindCSS\n\tcase \"php\":\n\t\treturn protocol.LanguageKindPHP\n\tcase \"rb\":\n\t\treturn protocol.LanguageKindRuby\n\tcase \"swift\":\n\t\treturn protocol.LanguageKindSwift\n\tdefault:\n\t\treturn protocol.LanguageKindUnknown\n\t}\n}"}}