tool.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865
  1. package messages
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "path/filepath"
  6. "strings"
  7. "time"
  8. "github.com/atotto/clipboard"
  9. "github.com/charmbracelet/bubbles/v2/key"
  10. tea "github.com/charmbracelet/bubbletea/v2"
  11. "github.com/charmbracelet/crush/internal/agent"
  12. "github.com/charmbracelet/crush/internal/agent/tools"
  13. "github.com/charmbracelet/crush/internal/diff"
  14. "github.com/charmbracelet/crush/internal/fsext"
  15. "github.com/charmbracelet/crush/internal/message"
  16. "github.com/charmbracelet/crush/internal/permission"
  17. "github.com/charmbracelet/crush/internal/tui/components/anim"
  18. "github.com/charmbracelet/crush/internal/tui/components/core/layout"
  19. "github.com/charmbracelet/crush/internal/tui/styles"
  20. "github.com/charmbracelet/crush/internal/tui/util"
  21. "github.com/charmbracelet/lipgloss/v2"
  22. "github.com/charmbracelet/x/ansi"
  23. )
  24. // ToolCallCmp defines the interface for tool call components in the chat interface.
  25. // It manages the display of tool execution including pending states, results, and errors.
  26. type ToolCallCmp interface {
  27. util.Model // Basic Bubble util.Model interface
  28. layout.Sizeable // Width/height management
  29. layout.Focusable // Focus state management
  30. GetToolCall() message.ToolCall // Access to tool call data
  31. GetToolResult() message.ToolResult // Access to tool result data
  32. SetToolResult(message.ToolResult) // Update tool result
  33. SetToolCall(message.ToolCall) // Update tool call
  34. SetCancelled() // Mark as cancelled
  35. ParentMessageID() string // Get parent message ID
  36. Spinning() bool // Animation state for pending tools
  37. GetNestedToolCalls() []ToolCallCmp // Get nested tool calls
  38. SetNestedToolCalls([]ToolCallCmp) // Set nested tool calls
  39. SetIsNested(bool) // Set whether this tool call is nested
  40. ID() string
  41. SetPermissionRequested() // Mark permission request
  42. SetPermissionGranted() // Mark permission granted
  43. }
  44. // toolCallCmp implements the ToolCallCmp interface for displaying tool calls.
  45. // It handles rendering of tool execution states including pending, completed, and error states.
  46. type toolCallCmp struct {
  47. width int // Component width for text wrapping
  48. focused bool // Focus state for border styling
  49. isNested bool // Whether this tool call is nested within another
  50. // Tool call data and state
  51. parentMessageID string // ID of the message that initiated this tool call
  52. call message.ToolCall // The tool call being executed
  53. result message.ToolResult // The result of the tool execution
  54. cancelled bool // Whether the tool call was cancelled
  55. permissionRequested bool
  56. permissionGranted bool
  57. // Animation state for pending tool calls
  58. spinning bool // Whether to show loading animation
  59. anim util.Model // Animation component for pending states
  60. nestedToolCalls []ToolCallCmp // Nested tool calls for hierarchical display
  61. }
  62. // ToolCallOption provides functional options for configuring tool call components
  63. type ToolCallOption func(*toolCallCmp)
  64. // WithToolCallCancelled marks the tool call as cancelled
  65. func WithToolCallCancelled() ToolCallOption {
  66. return func(m *toolCallCmp) {
  67. m.cancelled = true
  68. }
  69. }
  70. // WithToolCallResult sets the initial tool result
  71. func WithToolCallResult(result message.ToolResult) ToolCallOption {
  72. return func(m *toolCallCmp) {
  73. m.result = result
  74. }
  75. }
  76. func WithToolCallNested(isNested bool) ToolCallOption {
  77. return func(m *toolCallCmp) {
  78. m.isNested = isNested
  79. }
  80. }
  81. func WithToolCallNestedCalls(calls []ToolCallCmp) ToolCallOption {
  82. return func(m *toolCallCmp) {
  83. m.nestedToolCalls = calls
  84. }
  85. }
  86. func WithToolPermissionRequested() ToolCallOption {
  87. return func(m *toolCallCmp) {
  88. m.permissionRequested = true
  89. }
  90. }
  91. func WithToolPermissionGranted() ToolCallOption {
  92. return func(m *toolCallCmp) {
  93. m.permissionGranted = true
  94. }
  95. }
  96. // NewToolCallCmp creates a new tool call component with the given parent message ID,
  97. // tool call, and optional configuration
  98. func NewToolCallCmp(parentMessageID string, tc message.ToolCall, permissions permission.Service, opts ...ToolCallOption) ToolCallCmp {
  99. m := &toolCallCmp{
  100. call: tc,
  101. parentMessageID: parentMessageID,
  102. }
  103. for _, opt := range opts {
  104. opt(m)
  105. }
  106. t := styles.CurrentTheme()
  107. m.anim = anim.New(anim.Settings{
  108. Size: 15,
  109. Label: "Working",
  110. GradColorA: t.Primary,
  111. GradColorB: t.Secondary,
  112. LabelColor: t.FgBase,
  113. CycleColors: true,
  114. })
  115. if m.isNested {
  116. m.anim = anim.New(anim.Settings{
  117. Size: 10,
  118. GradColorA: t.Primary,
  119. GradColorB: t.Secondary,
  120. CycleColors: true,
  121. })
  122. }
  123. return m
  124. }
  125. // Init initializes the tool call component and starts animations if needed.
  126. // Returns a command to start the animation for pending tool calls.
  127. func (m *toolCallCmp) Init() tea.Cmd {
  128. m.spinning = m.shouldSpin()
  129. return m.anim.Init()
  130. }
  131. // Update handles incoming messages and updates the component state.
  132. // Manages animation updates for pending tool calls.
  133. func (m *toolCallCmp) Update(msg tea.Msg) (util.Model, tea.Cmd) {
  134. switch msg := msg.(type) {
  135. case anim.StepMsg:
  136. var cmds []tea.Cmd
  137. for i, nested := range m.nestedToolCalls {
  138. if nested.Spinning() {
  139. u, cmd := nested.Update(msg)
  140. m.nestedToolCalls[i] = u.(ToolCallCmp)
  141. cmds = append(cmds, cmd)
  142. }
  143. }
  144. if m.spinning {
  145. u, cmd := m.anim.Update(msg)
  146. m.anim = u
  147. cmds = append(cmds, cmd)
  148. }
  149. return m, tea.Batch(cmds...)
  150. case tea.KeyPressMsg:
  151. if key.Matches(msg, CopyKey) {
  152. return m, m.copyTool()
  153. }
  154. }
  155. return m, nil
  156. }
  157. // View renders the tool call component based on its current state.
  158. // Shows either a pending animation or the tool-specific rendered result.
  159. func (m *toolCallCmp) View() string {
  160. box := m.style()
  161. if !m.call.Finished && !m.cancelled {
  162. return box.Render(m.renderPending())
  163. }
  164. r := registry.lookup(m.call.Name)
  165. if m.isNested {
  166. return box.Render(r.Render(m))
  167. }
  168. return box.Render(r.Render(m))
  169. }
  170. // State management methods
  171. // SetCancelled marks the tool call as cancelled
  172. func (m *toolCallCmp) SetCancelled() {
  173. m.cancelled = true
  174. }
  175. func (m *toolCallCmp) copyTool() tea.Cmd {
  176. content := m.formatToolForCopy()
  177. return tea.Sequence(
  178. tea.SetClipboard(content),
  179. func() tea.Msg {
  180. _ = clipboard.WriteAll(content)
  181. return nil
  182. },
  183. util.ReportInfo("Tool content copied to clipboard"),
  184. )
  185. }
  186. func (m *toolCallCmp) formatToolForCopy() string {
  187. var parts []string
  188. toolName := prettifyToolName(m.call.Name)
  189. parts = append(parts, fmt.Sprintf("## %s Tool Call", toolName))
  190. if m.call.Input != "" {
  191. params := m.formatParametersForCopy()
  192. if params != "" {
  193. parts = append(parts, "### Parameters:")
  194. parts = append(parts, params)
  195. }
  196. }
  197. if m.result.ToolCallID != "" {
  198. if m.result.IsError {
  199. parts = append(parts, "### Error:")
  200. parts = append(parts, m.result.Content)
  201. } else {
  202. parts = append(parts, "### Result:")
  203. content := m.formatResultForCopy()
  204. if content != "" {
  205. parts = append(parts, content)
  206. }
  207. }
  208. } else if m.cancelled {
  209. parts = append(parts, "### Status:")
  210. parts = append(parts, "Cancelled")
  211. } else {
  212. parts = append(parts, "### Status:")
  213. parts = append(parts, "Pending...")
  214. }
  215. return strings.Join(parts, "\n\n")
  216. }
  217. func (m *toolCallCmp) formatParametersForCopy() string {
  218. switch m.call.Name {
  219. case tools.BashToolName:
  220. var params tools.BashParams
  221. if json.Unmarshal([]byte(m.call.Input), &params) == nil {
  222. cmd := strings.ReplaceAll(params.Command, "\n", " ")
  223. cmd = strings.ReplaceAll(cmd, "\t", " ")
  224. return fmt.Sprintf("**Command:** %s", cmd)
  225. }
  226. case tools.ViewToolName:
  227. var params tools.ViewParams
  228. if json.Unmarshal([]byte(m.call.Input), &params) == nil {
  229. var parts []string
  230. parts = append(parts, fmt.Sprintf("**File:** %s", fsext.PrettyPath(params.FilePath)))
  231. if params.Limit > 0 {
  232. parts = append(parts, fmt.Sprintf("**Limit:** %d", params.Limit))
  233. }
  234. if params.Offset > 0 {
  235. parts = append(parts, fmt.Sprintf("**Offset:** %d", params.Offset))
  236. }
  237. return strings.Join(parts, "\n")
  238. }
  239. case tools.EditToolName:
  240. var params tools.EditParams
  241. if json.Unmarshal([]byte(m.call.Input), &params) == nil {
  242. return fmt.Sprintf("**File:** %s", fsext.PrettyPath(params.FilePath))
  243. }
  244. case tools.MultiEditToolName:
  245. var params tools.MultiEditParams
  246. if json.Unmarshal([]byte(m.call.Input), &params) == nil {
  247. var parts []string
  248. parts = append(parts, fmt.Sprintf("**File:** %s", fsext.PrettyPath(params.FilePath)))
  249. parts = append(parts, fmt.Sprintf("**Edits:** %d", len(params.Edits)))
  250. return strings.Join(parts, "\n")
  251. }
  252. case tools.WriteToolName:
  253. var params tools.WriteParams
  254. if json.Unmarshal([]byte(m.call.Input), &params) == nil {
  255. return fmt.Sprintf("**File:** %s", fsext.PrettyPath(params.FilePath))
  256. }
  257. case tools.FetchToolName:
  258. var params tools.FetchParams
  259. if json.Unmarshal([]byte(m.call.Input), &params) == nil {
  260. var parts []string
  261. parts = append(parts, fmt.Sprintf("**URL:** %s", params.URL))
  262. if params.Format != "" {
  263. parts = append(parts, fmt.Sprintf("**Format:** %s", params.Format))
  264. }
  265. if params.Timeout > 0 {
  266. parts = append(parts, fmt.Sprintf("**Timeout:** %ds", params.Timeout))
  267. }
  268. return strings.Join(parts, "\n")
  269. }
  270. case tools.AgenticFetchToolName:
  271. var params tools.AgenticFetchParams
  272. if json.Unmarshal([]byte(m.call.Input), &params) == nil {
  273. var parts []string
  274. parts = append(parts, fmt.Sprintf("**URL:** %s", params.URL))
  275. if params.Prompt != "" {
  276. parts = append(parts, fmt.Sprintf("**Prompt:** %s", params.Prompt))
  277. }
  278. return strings.Join(parts, "\n")
  279. }
  280. case tools.WebFetchToolName:
  281. var params tools.WebFetchParams
  282. if json.Unmarshal([]byte(m.call.Input), &params) == nil {
  283. return fmt.Sprintf("**URL:** %s", params.URL)
  284. }
  285. case tools.GrepToolName:
  286. var params tools.GrepParams
  287. if json.Unmarshal([]byte(m.call.Input), &params) == nil {
  288. var parts []string
  289. parts = append(parts, fmt.Sprintf("**Pattern:** %s", params.Pattern))
  290. if params.Path != "" {
  291. parts = append(parts, fmt.Sprintf("**Path:** %s", params.Path))
  292. }
  293. if params.Include != "" {
  294. parts = append(parts, fmt.Sprintf("**Include:** %s", params.Include))
  295. }
  296. if params.LiteralText {
  297. parts = append(parts, "**Literal:** true")
  298. }
  299. return strings.Join(parts, "\n")
  300. }
  301. case tools.GlobToolName:
  302. var params tools.GlobParams
  303. if json.Unmarshal([]byte(m.call.Input), &params) == nil {
  304. var parts []string
  305. parts = append(parts, fmt.Sprintf("**Pattern:** %s", params.Pattern))
  306. if params.Path != "" {
  307. parts = append(parts, fmt.Sprintf("**Path:** %s", params.Path))
  308. }
  309. return strings.Join(parts, "\n")
  310. }
  311. case tools.LSToolName:
  312. var params tools.LSParams
  313. if json.Unmarshal([]byte(m.call.Input), &params) == nil {
  314. path := params.Path
  315. if path == "" {
  316. path = "."
  317. }
  318. return fmt.Sprintf("**Path:** %s", fsext.PrettyPath(path))
  319. }
  320. case tools.DownloadToolName:
  321. var params tools.DownloadParams
  322. if json.Unmarshal([]byte(m.call.Input), &params) == nil {
  323. var parts []string
  324. parts = append(parts, fmt.Sprintf("**URL:** %s", params.URL))
  325. parts = append(parts, fmt.Sprintf("**File Path:** %s", fsext.PrettyPath(params.FilePath)))
  326. if params.Timeout > 0 {
  327. parts = append(parts, fmt.Sprintf("**Timeout:** %s", (time.Duration(params.Timeout)*time.Second).String()))
  328. }
  329. return strings.Join(parts, "\n")
  330. }
  331. case tools.SourcegraphToolName:
  332. var params tools.SourcegraphParams
  333. if json.Unmarshal([]byte(m.call.Input), &params) == nil {
  334. var parts []string
  335. parts = append(parts, fmt.Sprintf("**Query:** %s", params.Query))
  336. if params.Count > 0 {
  337. parts = append(parts, fmt.Sprintf("**Count:** %d", params.Count))
  338. }
  339. if params.ContextWindow > 0 {
  340. parts = append(parts, fmt.Sprintf("**Context:** %d", params.ContextWindow))
  341. }
  342. return strings.Join(parts, "\n")
  343. }
  344. case tools.DiagnosticsToolName:
  345. return "**Project:** diagnostics"
  346. case agent.AgentToolName:
  347. var params agent.AgentParams
  348. if json.Unmarshal([]byte(m.call.Input), &params) == nil {
  349. return fmt.Sprintf("**Task:**\n%s", params.Prompt)
  350. }
  351. }
  352. var params map[string]any
  353. if json.Unmarshal([]byte(m.call.Input), &params) == nil {
  354. var parts []string
  355. for key, value := range params {
  356. displayKey := strings.ReplaceAll(key, "_", " ")
  357. if len(displayKey) > 0 {
  358. displayKey = strings.ToUpper(displayKey[:1]) + displayKey[1:]
  359. }
  360. parts = append(parts, fmt.Sprintf("**%s:** %v", displayKey, value))
  361. }
  362. return strings.Join(parts, "\n")
  363. }
  364. return ""
  365. }
  366. func (m *toolCallCmp) formatResultForCopy() string {
  367. switch m.call.Name {
  368. case tools.BashToolName:
  369. return m.formatBashResultForCopy()
  370. case tools.ViewToolName:
  371. return m.formatViewResultForCopy()
  372. case tools.EditToolName:
  373. return m.formatEditResultForCopy()
  374. case tools.MultiEditToolName:
  375. return m.formatMultiEditResultForCopy()
  376. case tools.WriteToolName:
  377. return m.formatWriteResultForCopy()
  378. case tools.FetchToolName:
  379. return m.formatFetchResultForCopy()
  380. case tools.AgenticFetchToolName:
  381. return m.formatAgenticFetchResultForCopy()
  382. case tools.WebFetchToolName:
  383. return m.formatWebFetchResultForCopy()
  384. case agent.AgentToolName:
  385. return m.formatAgentResultForCopy()
  386. case tools.DownloadToolName, tools.GrepToolName, tools.GlobToolName, tools.LSToolName, tools.SourcegraphToolName, tools.DiagnosticsToolName:
  387. return fmt.Sprintf("```\n%s\n```", m.result.Content)
  388. default:
  389. return m.result.Content
  390. }
  391. }
  392. func (m *toolCallCmp) formatBashResultForCopy() string {
  393. var meta tools.BashResponseMetadata
  394. if m.result.Metadata != "" {
  395. json.Unmarshal([]byte(m.result.Metadata), &meta)
  396. }
  397. output := meta.Output
  398. if output == "" && m.result.Content != tools.BashNoOutput {
  399. output = m.result.Content
  400. }
  401. if output == "" {
  402. return ""
  403. }
  404. return fmt.Sprintf("```bash\n%s\n```", output)
  405. }
  406. func (m *toolCallCmp) formatViewResultForCopy() string {
  407. var meta tools.ViewResponseMetadata
  408. if m.result.Metadata != "" {
  409. json.Unmarshal([]byte(m.result.Metadata), &meta)
  410. }
  411. if meta.Content == "" {
  412. return m.result.Content
  413. }
  414. lang := ""
  415. if meta.FilePath != "" {
  416. ext := strings.ToLower(filepath.Ext(meta.FilePath))
  417. switch ext {
  418. case ".go":
  419. lang = "go"
  420. case ".js", ".mjs":
  421. lang = "javascript"
  422. case ".ts":
  423. lang = "typescript"
  424. case ".py":
  425. lang = "python"
  426. case ".rs":
  427. lang = "rust"
  428. case ".java":
  429. lang = "java"
  430. case ".c":
  431. lang = "c"
  432. case ".cpp", ".cc", ".cxx":
  433. lang = "cpp"
  434. case ".sh", ".bash":
  435. lang = "bash"
  436. case ".json":
  437. lang = "json"
  438. case ".yaml", ".yml":
  439. lang = "yaml"
  440. case ".xml":
  441. lang = "xml"
  442. case ".html":
  443. lang = "html"
  444. case ".css":
  445. lang = "css"
  446. case ".md":
  447. lang = "markdown"
  448. }
  449. }
  450. var result strings.Builder
  451. if lang != "" {
  452. result.WriteString(fmt.Sprintf("```%s\n", lang))
  453. } else {
  454. result.WriteString("```\n")
  455. }
  456. result.WriteString(meta.Content)
  457. result.WriteString("\n```")
  458. return result.String()
  459. }
  460. func (m *toolCallCmp) formatEditResultForCopy() string {
  461. var meta tools.EditResponseMetadata
  462. if m.result.Metadata == "" {
  463. return m.result.Content
  464. }
  465. if json.Unmarshal([]byte(m.result.Metadata), &meta) != nil {
  466. return m.result.Content
  467. }
  468. var params tools.EditParams
  469. json.Unmarshal([]byte(m.call.Input), &params)
  470. var result strings.Builder
  471. if meta.OldContent != "" || meta.NewContent != "" {
  472. fileName := params.FilePath
  473. if fileName != "" {
  474. fileName = fsext.PrettyPath(fileName)
  475. }
  476. diffContent, additions, removals := diff.GenerateDiff(meta.OldContent, meta.NewContent, fileName)
  477. result.WriteString(fmt.Sprintf("Changes: +%d -%d\n", additions, removals))
  478. result.WriteString("```diff\n")
  479. result.WriteString(diffContent)
  480. result.WriteString("\n```")
  481. }
  482. return result.String()
  483. }
  484. func (m *toolCallCmp) formatMultiEditResultForCopy() string {
  485. var meta tools.MultiEditResponseMetadata
  486. if m.result.Metadata == "" {
  487. return m.result.Content
  488. }
  489. if json.Unmarshal([]byte(m.result.Metadata), &meta) != nil {
  490. return m.result.Content
  491. }
  492. var params tools.MultiEditParams
  493. json.Unmarshal([]byte(m.call.Input), &params)
  494. var result strings.Builder
  495. if meta.OldContent != "" || meta.NewContent != "" {
  496. fileName := params.FilePath
  497. if fileName != "" {
  498. fileName = fsext.PrettyPath(fileName)
  499. }
  500. diffContent, additions, removals := diff.GenerateDiff(meta.OldContent, meta.NewContent, fileName)
  501. result.WriteString(fmt.Sprintf("Changes: +%d -%d\n", additions, removals))
  502. result.WriteString("```diff\n")
  503. result.WriteString(diffContent)
  504. result.WriteString("\n```")
  505. }
  506. return result.String()
  507. }
  508. func (m *toolCallCmp) formatWriteResultForCopy() string {
  509. var params tools.WriteParams
  510. if json.Unmarshal([]byte(m.call.Input), &params) != nil {
  511. return m.result.Content
  512. }
  513. lang := ""
  514. if params.FilePath != "" {
  515. ext := strings.ToLower(filepath.Ext(params.FilePath))
  516. switch ext {
  517. case ".go":
  518. lang = "go"
  519. case ".js", ".mjs":
  520. lang = "javascript"
  521. case ".ts":
  522. lang = "typescript"
  523. case ".py":
  524. lang = "python"
  525. case ".rs":
  526. lang = "rust"
  527. case ".java":
  528. lang = "java"
  529. case ".c":
  530. lang = "c"
  531. case ".cpp", ".cc", ".cxx":
  532. lang = "cpp"
  533. case ".sh", ".bash":
  534. lang = "bash"
  535. case ".json":
  536. lang = "json"
  537. case ".yaml", ".yml":
  538. lang = "yaml"
  539. case ".xml":
  540. lang = "xml"
  541. case ".html":
  542. lang = "html"
  543. case ".css":
  544. lang = "css"
  545. case ".md":
  546. lang = "markdown"
  547. }
  548. }
  549. var result strings.Builder
  550. result.WriteString(fmt.Sprintf("File: %s\n", fsext.PrettyPath(params.FilePath)))
  551. if lang != "" {
  552. result.WriteString(fmt.Sprintf("```%s\n", lang))
  553. } else {
  554. result.WriteString("```\n")
  555. }
  556. result.WriteString(params.Content)
  557. result.WriteString("\n```")
  558. return result.String()
  559. }
  560. func (m *toolCallCmp) formatFetchResultForCopy() string {
  561. var params tools.FetchParams
  562. if json.Unmarshal([]byte(m.call.Input), &params) != nil {
  563. return m.result.Content
  564. }
  565. var result strings.Builder
  566. if params.URL != "" {
  567. result.WriteString(fmt.Sprintf("URL: %s\n", params.URL))
  568. }
  569. if params.Format != "" {
  570. result.WriteString(fmt.Sprintf("Format: %s\n", params.Format))
  571. }
  572. if params.Timeout > 0 {
  573. result.WriteString(fmt.Sprintf("Timeout: %ds\n", params.Timeout))
  574. }
  575. result.WriteString("\n")
  576. result.WriteString(m.result.Content)
  577. return result.String()
  578. }
  579. func (m *toolCallCmp) formatAgenticFetchResultForCopy() string {
  580. var params tools.AgenticFetchParams
  581. if json.Unmarshal([]byte(m.call.Input), &params) != nil {
  582. return m.result.Content
  583. }
  584. var result strings.Builder
  585. if params.URL != "" {
  586. result.WriteString(fmt.Sprintf("URL: %s\n", params.URL))
  587. }
  588. if params.Prompt != "" {
  589. result.WriteString(fmt.Sprintf("Prompt: %s\n\n", params.Prompt))
  590. }
  591. result.WriteString("```markdown\n")
  592. result.WriteString(m.result.Content)
  593. result.WriteString("\n```")
  594. return result.String()
  595. }
  596. func (m *toolCallCmp) formatWebFetchResultForCopy() string {
  597. var params tools.WebFetchParams
  598. if json.Unmarshal([]byte(m.call.Input), &params) != nil {
  599. return m.result.Content
  600. }
  601. var result strings.Builder
  602. result.WriteString(fmt.Sprintf("URL: %s\n\n", params.URL))
  603. result.WriteString("```markdown\n")
  604. result.WriteString(m.result.Content)
  605. result.WriteString("\n```")
  606. return result.String()
  607. }
  608. func (m *toolCallCmp) formatAgentResultForCopy() string {
  609. var result strings.Builder
  610. if len(m.nestedToolCalls) > 0 {
  611. result.WriteString("### Nested Tool Calls:\n")
  612. for i, nestedCall := range m.nestedToolCalls {
  613. nestedContent := nestedCall.(*toolCallCmp).formatToolForCopy()
  614. indentedContent := strings.ReplaceAll(nestedContent, "\n", "\n ")
  615. result.WriteString(fmt.Sprintf("%d. %s\n", i+1, indentedContent))
  616. if i < len(m.nestedToolCalls)-1 {
  617. result.WriteString("\n")
  618. }
  619. }
  620. if m.result.Content != "" {
  621. result.WriteString("\n### Final Result:\n")
  622. }
  623. }
  624. if m.result.Content != "" {
  625. result.WriteString(fmt.Sprintf("```markdown\n%s\n```", m.result.Content))
  626. }
  627. return result.String()
  628. }
  629. // SetToolCall updates the tool call data and stops spinning if finished
  630. func (m *toolCallCmp) SetToolCall(call message.ToolCall) {
  631. m.call = call
  632. if m.call.Finished {
  633. m.spinning = false
  634. }
  635. }
  636. // ParentMessageID returns the ID of the message that initiated this tool call
  637. func (m *toolCallCmp) ParentMessageID() string {
  638. return m.parentMessageID
  639. }
  640. // SetToolResult updates the tool result and stops the spinning animation
  641. func (m *toolCallCmp) SetToolResult(result message.ToolResult) {
  642. m.result = result
  643. m.spinning = false
  644. }
  645. // GetToolCall returns the current tool call data
  646. func (m *toolCallCmp) GetToolCall() message.ToolCall {
  647. return m.call
  648. }
  649. // GetToolResult returns the current tool result data
  650. func (m *toolCallCmp) GetToolResult() message.ToolResult {
  651. return m.result
  652. }
  653. // GetNestedToolCalls returns the nested tool calls
  654. func (m *toolCallCmp) GetNestedToolCalls() []ToolCallCmp {
  655. return m.nestedToolCalls
  656. }
  657. // SetNestedToolCalls sets the nested tool calls
  658. func (m *toolCallCmp) SetNestedToolCalls(calls []ToolCallCmp) {
  659. m.nestedToolCalls = calls
  660. for _, nested := range m.nestedToolCalls {
  661. nested.SetSize(m.width, 0)
  662. }
  663. }
  664. // SetIsNested sets whether this tool call is nested within another
  665. func (m *toolCallCmp) SetIsNested(isNested bool) {
  666. m.isNested = isNested
  667. }
  668. // Rendering methods
  669. // renderPending displays the tool name with a loading animation for pending tool calls
  670. func (m *toolCallCmp) renderPending() string {
  671. t := styles.CurrentTheme()
  672. icon := t.S().Base.Foreground(t.GreenDark).Render(styles.ToolPending)
  673. if m.isNested {
  674. tool := t.S().Base.Foreground(t.FgHalfMuted).Render(prettifyToolName(m.call.Name))
  675. return fmt.Sprintf("%s %s %s", icon, tool, m.anim.View())
  676. }
  677. tool := t.S().Base.Foreground(t.Blue).Render(prettifyToolName(m.call.Name))
  678. return fmt.Sprintf("%s %s %s", icon, tool, m.anim.View())
  679. }
  680. // style returns the lipgloss style for the tool call component.
  681. // Applies muted colors and focus-dependent border styles.
  682. func (m *toolCallCmp) style() lipgloss.Style {
  683. t := styles.CurrentTheme()
  684. if m.isNested {
  685. return t.S().Muted
  686. }
  687. style := t.S().Muted.PaddingLeft(2)
  688. if m.focused {
  689. style = style.PaddingLeft(1).BorderStyle(focusedMessageBorder).BorderLeft(true).BorderForeground(t.GreenDark)
  690. }
  691. return style
  692. }
  693. // textWidth calculates the available width for text content,
  694. // accounting for borders and padding
  695. func (m *toolCallCmp) textWidth() int {
  696. if m.isNested {
  697. return m.width - 6
  698. }
  699. return m.width - 5 // take into account the border and PaddingLeft
  700. }
  701. // fit truncates content to fit within the specified width with ellipsis
  702. func (m *toolCallCmp) fit(content string, width int) string {
  703. t := styles.CurrentTheme()
  704. lineStyle := t.S().Muted
  705. dots := lineStyle.Render("…")
  706. return ansi.Truncate(content, width, dots)
  707. }
  708. // Focus management methods
  709. // Blur removes focus from the tool call component
  710. func (m *toolCallCmp) Blur() tea.Cmd {
  711. m.focused = false
  712. return nil
  713. }
  714. // Focus sets focus on the tool call component
  715. func (m *toolCallCmp) Focus() tea.Cmd {
  716. m.focused = true
  717. return nil
  718. }
  719. // IsFocused returns whether the tool call component is currently focused
  720. func (m *toolCallCmp) IsFocused() bool {
  721. return m.focused
  722. }
  723. // Size management methods
  724. // GetSize returns the current dimensions of the tool call component
  725. func (m *toolCallCmp) GetSize() (int, int) {
  726. return m.width, 0
  727. }
  728. // SetSize updates the width of the tool call component for text wrapping
  729. func (m *toolCallCmp) SetSize(width int, height int) tea.Cmd {
  730. m.width = width
  731. for _, nested := range m.nestedToolCalls {
  732. nested.SetSize(width, height)
  733. }
  734. return nil
  735. }
  736. // shouldSpin determines whether the tool call should show a loading animation.
  737. // Returns true if the tool call is not finished or if the result doesn't match the call ID.
  738. func (m *toolCallCmp) shouldSpin() bool {
  739. return !m.call.Finished && !m.cancelled
  740. }
  741. // Spinning returns whether the tool call is currently showing a loading animation
  742. func (m *toolCallCmp) Spinning() bool {
  743. if m.spinning {
  744. return true
  745. }
  746. for _, nested := range m.nestedToolCalls {
  747. if nested.Spinning() {
  748. return true
  749. }
  750. }
  751. return m.spinning
  752. }
  753. func (m *toolCallCmp) ID() string {
  754. return m.call.ID
  755. }
  756. // SetPermissionRequested marks that a permission request was made for this tool call
  757. func (m *toolCallCmp) SetPermissionRequested() {
  758. m.permissionRequested = true
  759. }
  760. // SetPermissionGranted marks that permission was granted for this tool call
  761. func (m *toolCallCmp) SetPermissionGranted() {
  762. m.permissionGranted = true
  763. }