Truncate a path-like string to the given display width, keeping leading and trailing segments
where possible and inserting a single Unicode ellipsis between them. If an individual segment
cannot fit, it is front-truncated with an ellipsis.
Truncate a tool result to fit within the given height and width. If the text is valid JSON, we format it in a compact way before truncating.
This is a best-effort approach that may not work perfectly for text where 1 grapheme is rendered as multiple terminal cells.
Format JSON text in a compact single-line format with spaces for better Ratatui wrapping.
Ex: {"a":"b",c:["d","e"]} -> {"a": "b", "c": ["d", "e"]}
Returns the formatted JSON string if the input is valid JSON, otherwise returns None.
This is a little complicated, but it’s necessary because Ratatui’s wrapping is very limited
and can only do line breaks at whitespace. If we use the default serde_json format, we get lines
without spaces that Ratatui can’t wrap nicely. If we use the serde_json pretty format as-is,
it’s much too sparse and uses too many terminal rows.
Relevant issue: https://github.com/ratatui/ratatui/issues/293