session.go

  1package cmd
  2
  3import (
  4	"context"
  5	"encoding/json"
  6	"errors"
  7	"fmt"
  8	"io"
  9	"os"
 10	"os/exec"
 11	"runtime"
 12	"sort"
 13	"strings"
 14	"syscall"
 15	"time"
 16
 17	"charm.land/lipgloss/v2"
 18	"github.com/charmbracelet/colorprofile"
 19	"github.com/charmbracelet/crush/internal/agent/tools"
 20	"github.com/charmbracelet/crush/internal/config"
 21	"github.com/charmbracelet/crush/internal/db"
 22	"github.com/charmbracelet/crush/internal/event"
 23	"github.com/charmbracelet/crush/internal/message"
 24	"github.com/charmbracelet/crush/internal/session"
 25	"github.com/charmbracelet/crush/internal/ui/chat"
 26	"github.com/charmbracelet/crush/internal/ui/styles"
 27	"github.com/charmbracelet/x/ansi"
 28	"github.com/charmbracelet/x/exp/charmtone"
 29	"github.com/charmbracelet/x/term"
 30	"github.com/spf13/cobra"
 31)
 32
 33var sessionCmd = &cobra.Command{
 34	Use:     "session",
 35	Aliases: []string{"sessions", "s"},
 36	Short:   "Manage sessions",
 37	Long:    "Manage Crush sessions. Agents can use --json for machine-readable output.",
 38}
 39
 40var (
 41	sessionListJSON   bool
 42	sessionShowJSON   bool
 43	sessionLastJSON   bool
 44	sessionDeleteJSON bool
 45	sessionRenameJSON bool
 46)
 47
 48var sessionListCmd = &cobra.Command{
 49	Use:     "list",
 50	Aliases: []string{"ls"},
 51	Short:   "List all sessions",
 52	Long:    "List all sessions. Use --json for machine-readable output.",
 53	RunE:    runSessionList,
 54}
 55
 56var sessionShowCmd = &cobra.Command{
 57	Use:   "show <id>",
 58	Short: "Show session details",
 59	Long:  "Show session details. Use --json for machine-readable output. ID can be a UUID, full hash, or hash prefix.",
 60	Args:  cobra.ExactArgs(1),
 61	RunE:  runSessionShow,
 62}
 63
 64var sessionLastCmd = &cobra.Command{
 65	Use:   "last",
 66	Short: "Show most recent session",
 67	Long:  "Show the last updated session. Use --json for machine-readable output.",
 68	RunE:  runSessionLast,
 69}
 70
 71var sessionDeleteCmd = &cobra.Command{
 72	Use:     "delete <id>",
 73	Aliases: []string{"rm"},
 74	Short:   "Delete a session",
 75	Long:    "Delete a session by ID. Use --json for machine-readable output. ID can be a UUID, full hash, or hash prefix.",
 76	Args:    cobra.ExactArgs(1),
 77	RunE:    runSessionDelete,
 78}
 79
 80var sessionRenameCmd = &cobra.Command{
 81	Use:   "rename <id> <title>",
 82	Short: "Rename a session",
 83	Long:  "Rename a session by ID. Use --json for machine-readable output. ID can be a UUID, full hash, or hash prefix.",
 84	Args:  cobra.MinimumNArgs(2),
 85	RunE:  runSessionRename,
 86}
 87
 88func init() {
 89	sessionListCmd.Flags().BoolVar(&sessionListJSON, "json", false, "output in JSON format")
 90	sessionShowCmd.Flags().BoolVar(&sessionShowJSON, "json", false, "output in JSON format")
 91	sessionLastCmd.Flags().BoolVar(&sessionLastJSON, "json", false, "output in JSON format")
 92	sessionDeleteCmd.Flags().BoolVar(&sessionDeleteJSON, "json", false, "output in JSON format")
 93	sessionRenameCmd.Flags().BoolVar(&sessionRenameJSON, "json", false, "output in JSON format")
 94	sessionCmd.AddCommand(sessionListCmd)
 95	sessionCmd.AddCommand(sessionShowCmd)
 96	sessionCmd.AddCommand(sessionLastCmd)
 97	sessionCmd.AddCommand(sessionDeleteCmd)
 98	sessionCmd.AddCommand(sessionRenameCmd)
 99}
100
101type sessionServices struct {
102	sessions session.Service
103	messages message.Service
104}
105
106func sessionSetup(cmd *cobra.Command) (context.Context, *sessionServices, func(), error) {
107	dataDir, _ := cmd.Flags().GetString("data-dir")
108	ctx := cmd.Context()
109
110	if dataDir == "" {
111		cfg, err := config.Init("", "", false)
112		if err != nil {
113			return nil, nil, nil, fmt.Errorf("failed to initialize config: %w", err)
114		}
115		dataDir = cfg.Config().Options.DataDirectory
116	}
117
118	conn, err := db.Connect(ctx, dataDir)
119	if err != nil {
120		return nil, nil, nil, fmt.Errorf("failed to connect to database: %w", err)
121	}
122
123	queries := db.New(conn)
124	svc := &sessionServices{
125		sessions: session.NewService(queries, conn),
126		messages: message.NewService(queries),
127	}
128	return ctx, svc, func() { conn.Close() }, nil
129}
130
131func runSessionList(cmd *cobra.Command, _ []string) error {
132	event.SetNonInteractive(true)
133	event.SessionListed(sessionListJSON)
134
135	ctx, svc, cleanup, err := sessionSetup(cmd)
136	if err != nil {
137		return err
138	}
139	defer cleanup()
140
141	list, err := svc.sessions.List(ctx)
142	if err != nil {
143		return fmt.Errorf("failed to list sessions: %w", err)
144	}
145
146	if sessionListJSON {
147		out := cmd.OutOrStdout()
148		output := make([]sessionJSON, len(list))
149		for i, s := range list {
150			output[i] = sessionJSON{
151				ID:       session.HashID(s.ID),
152				UUID:     s.ID,
153				Title:    s.Title,
154				Created:  time.Unix(s.CreatedAt, 0).Format(time.RFC3339),
155				Modified: time.Unix(s.UpdatedAt, 0).Format(time.RFC3339),
156			}
157		}
158		enc := json.NewEncoder(out)
159		enc.SetEscapeHTML(false)
160		return enc.Encode(output)
161	}
162
163	w, cleanup, usingPager := sessionWriter(ctx, len(list))
164	defer cleanup()
165
166	hashStyle := lipgloss.NewStyle().Foreground(charmtone.Malibu)
167	dateStyle := lipgloss.NewStyle().Foreground(charmtone.Damson)
168
169	width := sessionOutputWidth
170	if tw, _, err := term.GetSize(os.Stdout.Fd()); err == nil && tw > 0 {
171		width = tw
172	}
173	// 7 (hash) + 1 (space) + 25 (RFC3339 date) + 1 (space) = 34 chars prefix.
174	titleWidth := max(width-34, 10)
175
176	var writeErr error
177	for _, s := range list {
178		hash := session.HashID(s.ID)[:7]
179		date := time.Unix(s.CreatedAt, 0).Format(time.RFC3339)
180		title := strings.ReplaceAll(s.Title, "\n", " ")
181		title = ansi.Truncate(title, titleWidth, "…")
182		_, writeErr = fmt.Fprintln(w, hashStyle.Render(hash), dateStyle.Render(date), title)
183		if writeErr != nil {
184			break
185		}
186	}
187	if writeErr != nil && usingPager && isBrokenPipe(writeErr) {
188		return nil
189	}
190	return writeErr
191}
192
193type sessionJSON struct {
194	ID       string `json:"id"`
195	UUID     string `json:"uuid"`
196	Title    string `json:"title"`
197	Created  string `json:"created"`
198	Modified string `json:"modified"`
199}
200
201type sessionMutationResult struct {
202	ID      string `json:"id"`
203	UUID    string `json:"uuid"`
204	Title   string `json:"title"`
205	Deleted bool   `json:"deleted,omitempty"`
206	Renamed bool   `json:"renamed,omitempty"`
207}
208
209// resolveSessionID resolves a session ID that can be a UUID, full hash, or hash prefix.
210// Returns an error if the prefix is ambiguous (matches multiple sessions).
211func resolveSessionID(ctx context.Context, svc session.Service, id string) (session.Session, error) {
212	// Try direct UUID lookup first
213	if s, err := svc.Get(ctx, id); err == nil {
214		return s, nil
215	}
216
217	// List all sessions and check for hash matches
218	sessions, err := svc.List(ctx)
219	if err != nil {
220		return session.Session{}, err
221	}
222
223	var matches []session.Session
224	for _, s := range sessions {
225		hash := session.HashID(s.ID)
226		if hash == id || strings.HasPrefix(hash, id) {
227			matches = append(matches, s)
228		}
229	}
230
231	if len(matches) == 0 {
232		return session.Session{}, fmt.Errorf("session not found: %s", id)
233	}
234
235	if len(matches) == 1 {
236		return matches[0], nil
237	}
238
239	// Ambiguous - show matches like Git does
240	var sb strings.Builder
241	fmt.Fprintf(&sb, "session ID '%s' is ambiguous. Matches:\n\n", id)
242	for _, m := range matches {
243		hash := session.HashID(m.ID)
244		created := time.Unix(m.CreatedAt, 0).Format("2006-01-02")
245		// Keep title on one line by replacing newlines with spaces, and truncate.
246		title := strings.ReplaceAll(m.Title, "\n", " ")
247		title = ansi.Truncate(title, 50, "…")
248		fmt.Fprintf(&sb, "  %s... %q (created %s)\n", hash[:12], title, created)
249	}
250	sb.WriteString("\nUse more characters or the full hash")
251	return session.Session{}, errors.New(sb.String())
252}
253
254func runSessionShow(cmd *cobra.Command, args []string) error {
255	event.SetNonInteractive(true)
256	event.SessionShown(sessionShowJSON)
257
258	ctx, svc, cleanup, err := sessionSetup(cmd)
259	if err != nil {
260		return err
261	}
262	defer cleanup()
263
264	sess, err := resolveSessionID(ctx, svc.sessions, args[0])
265	if err != nil {
266		return err
267	}
268
269	msgs, err := svc.messages.List(ctx, sess.ID)
270	if err != nil {
271		return fmt.Errorf("failed to list messages: %w", err)
272	}
273
274	msgPtrs := messagePtrs(msgs)
275	if sessionShowJSON {
276		return outputSessionJSON(cmd.OutOrStdout(), sess, msgPtrs)
277	}
278	return outputSessionHuman(ctx, sess, msgPtrs)
279}
280
281func runSessionDelete(cmd *cobra.Command, args []string) error {
282	event.SetNonInteractive(true)
283	event.SessionDeletedCommand(sessionDeleteJSON)
284
285	ctx, svc, cleanup, err := sessionSetup(cmd)
286	if err != nil {
287		return err
288	}
289	defer cleanup()
290
291	sess, err := resolveSessionID(ctx, svc.sessions, args[0])
292	if err != nil {
293		return err
294	}
295
296	if err := svc.sessions.Delete(ctx, sess.ID); err != nil {
297		return fmt.Errorf("failed to delete session: %w", err)
298	}
299
300	out := cmd.OutOrStdout()
301	if sessionDeleteJSON {
302		enc := json.NewEncoder(out)
303		enc.SetEscapeHTML(false)
304		return enc.Encode(sessionMutationResult{
305			ID:      session.HashID(sess.ID),
306			UUID:    sess.ID,
307			Title:   sess.Title,
308			Deleted: true,
309		})
310	}
311
312	fmt.Fprintf(out, "Deleted session %s\n", session.HashID(sess.ID)[:12])
313	return nil
314}
315
316func runSessionRename(cmd *cobra.Command, args []string) error {
317	event.SetNonInteractive(true)
318	event.SessionRenamed(sessionRenameJSON)
319
320	ctx, svc, cleanup, err := sessionSetup(cmd)
321	if err != nil {
322		return err
323	}
324	defer cleanup()
325
326	sess, err := resolveSessionID(ctx, svc.sessions, args[0])
327	if err != nil {
328		return err
329	}
330
331	newTitle := strings.Join(args[1:], " ")
332	if err := svc.sessions.Rename(ctx, sess.ID, newTitle); err != nil {
333		return fmt.Errorf("failed to rename session: %w", err)
334	}
335
336	out := cmd.OutOrStdout()
337	if sessionRenameJSON {
338		enc := json.NewEncoder(out)
339		enc.SetEscapeHTML(false)
340		return enc.Encode(sessionMutationResult{
341			ID:      session.HashID(sess.ID),
342			UUID:    sess.ID,
343			Title:   newTitle,
344			Renamed: true,
345		})
346	}
347
348	fmt.Fprintf(out, "Renamed session %s to %q\n", session.HashID(sess.ID)[:12], newTitle)
349	return nil
350}
351
352func runSessionLast(cmd *cobra.Command, _ []string) error {
353	event.SetNonInteractive(true)
354	event.SessionLastShown(sessionLastJSON)
355
356	ctx, svc, cleanup, err := sessionSetup(cmd)
357	if err != nil {
358		return err
359	}
360	defer cleanup()
361
362	list, err := svc.sessions.List(ctx)
363	if err != nil {
364		return fmt.Errorf("failed to list sessions: %w", err)
365	}
366
367	if len(list) == 0 {
368		return fmt.Errorf("no sessions found")
369	}
370
371	sess := list[0]
372
373	msgs, err := svc.messages.List(ctx, sess.ID)
374	if err != nil {
375		return fmt.Errorf("failed to list messages: %w", err)
376	}
377
378	msgPtrs := messagePtrs(msgs)
379	if sessionLastJSON {
380		return outputSessionJSON(cmd.OutOrStdout(), sess, msgPtrs)
381	}
382	return outputSessionHuman(ctx, sess, msgPtrs)
383}
384
385const (
386	sessionOutputWidth     = 80
387	sessionMaxContentWidth = 120
388)
389
390func messagePtrs(msgs []message.Message) []*message.Message {
391	ptrs := make([]*message.Message, len(msgs))
392	for i := range msgs {
393		ptrs[i] = &msgs[i]
394	}
395	return ptrs
396}
397
398func outputSessionJSON(w io.Writer, sess session.Session, msgs []*message.Message) error {
399	skills := extractSkillsFromMessages(msgs)
400	output := sessionShowOutput{
401		Meta: sessionShowMeta{
402			ID:               session.HashID(sess.ID),
403			UUID:             sess.ID,
404			Title:            sess.Title,
405			Created:          time.Unix(sess.CreatedAt, 0).Format(time.RFC3339),
406			Modified:         time.Unix(sess.UpdatedAt, 0).Format(time.RFC3339),
407			Cost:             sess.Cost,
408			PromptTokens:     sess.PromptTokens,
409			CompletionTokens: sess.CompletionTokens,
410			TotalTokens:      sess.PromptTokens + sess.CompletionTokens,
411			Skills:           skills,
412		},
413		Messages: make([]sessionShowMessage, len(msgs)),
414	}
415
416	for i, msg := range msgs {
417		output.Messages[i] = sessionShowMessage{
418			ID:       msg.ID,
419			Role:     string(msg.Role),
420			Created:  time.Unix(msg.CreatedAt, 0).Format(time.RFC3339),
421			Model:    msg.Model,
422			Provider: msg.Provider,
423			Parts:    convertParts(msg.Parts),
424		}
425	}
426
427	enc := json.NewEncoder(w)
428	enc.SetEscapeHTML(false)
429	return enc.Encode(output)
430}
431
432func outputSessionHuman(ctx context.Context, sess session.Session, msgs []*message.Message) error {
433	sty := styles.DefaultStyles()
434	toolResults := chat.BuildToolResultMap(msgs)
435
436	width := sessionOutputWidth
437	if w, _, err := term.GetSize(os.Stdout.Fd()); err == nil && w > 0 {
438		width = w
439	}
440	contentWidth := min(width, sessionMaxContentWidth)
441
442	keyStyle := lipgloss.NewStyle().Foreground(charmtone.Damson)
443	valStyle := lipgloss.NewStyle().Foreground(charmtone.Malibu)
444
445	hash := session.HashID(sess.ID)[:12]
446	created := time.Unix(sess.CreatedAt, 0).Format("Mon Jan 2 15:04:05 2006 -0700")
447
448	skills := extractSkillsFromMessages(msgs)
449
450	// Render to buffer to determine actual height
451	var buf strings.Builder
452
453	fmt.Fprintln(&buf, keyStyle.Render("ID:    ")+valStyle.Render(hash))
454	fmt.Fprintln(&buf, keyStyle.Render("UUID:  ")+valStyle.Render(sess.ID))
455	fmt.Fprintln(&buf, keyStyle.Render("Title: ")+valStyle.Render(sess.Title))
456	fmt.Fprintln(&buf, keyStyle.Render("Date:  ")+valStyle.Render(created))
457	if len(skills) > 0 {
458		skillNames := make([]string, len(skills))
459		for i, s := range skills {
460			timestamp := time.Unix(sess.CreatedAt, 0).Format("15:04:05 -0700")
461			if s.LoadedAt != "" {
462				if t, err := time.Parse(time.RFC3339, s.LoadedAt); err == nil {
463					timestamp = t.Format("15:04:05 -0700")
464				}
465			}
466			skillNames[i] = fmt.Sprintf("%s (%s)", s.Name, timestamp)
467		}
468		fmt.Fprintln(&buf, keyStyle.Render("Skills: ")+valStyle.Render(strings.Join(skillNames, ", ")))
469	}
470	fmt.Fprintln(&buf)
471
472	first := true
473	for _, msg := range msgs {
474		items := chat.ExtractMessageItems(&sty, msg, toolResults)
475		for _, item := range items {
476			if !first {
477				fmt.Fprintln(&buf)
478			}
479			first = false
480			fmt.Fprintln(&buf, item.Render(contentWidth))
481		}
482	}
483	fmt.Fprintln(&buf)
484
485	contentHeight := strings.Count(buf.String(), "\n")
486	w, cleanup, usingPager := sessionWriter(ctx, contentHeight)
487	defer cleanup()
488
489	_, err := io.WriteString(w, buf.String())
490	// Ignore broken pipe errors when using a pager. This happens when the user
491	// exits the pager early (e.g., pressing 'q' in less), which closes the pipe
492	// and causes subsequent writes to fail. These errors are expected user behavior.
493	if err != nil && usingPager && isBrokenPipe(err) {
494		return nil
495	}
496	return err
497}
498
499func isBrokenPipe(err error) bool {
500	if err == nil {
501		return false
502	}
503	// Check for syscall.EPIPE (broken pipe)
504	if errors.Is(err, syscall.EPIPE) {
505		return true
506	}
507	// Also check for "broken pipe" in the error message
508	return strings.Contains(err.Error(), "broken pipe")
509}
510
511// sessionWriter returns a writer, cleanup function, and a bool indicating if a pager is used.
512// When the content fits within the terminal (or stdout is not a TTY), it returns
513// a colorprofile.Writer wrapping stdout. When content exceeds terminal height,
514// it starts a pager process (respecting $PAGER, defaulting to "less -R").
515func sessionWriter(ctx context.Context, contentHeight int) (io.Writer, func(), bool) {
516	// Use NewWriter which automatically detects TTY and strips ANSI when redirected
517	if runtime.GOOS == "windows" || !term.IsTerminal(os.Stdout.Fd()) {
518		return colorprofile.NewWriter(os.Stdout, os.Environ()), func() {}, false
519	}
520
521	_, termHeight, err := term.GetSize(os.Stdout.Fd())
522	if err != nil || contentHeight <= termHeight {
523		return colorprofile.NewWriter(os.Stdout, os.Environ()), func() {}, false
524	}
525
526	// Detect color profile from stderr since stdout is piped to the pager.
527	profile := colorprofile.Detect(os.Stderr, os.Environ())
528
529	pager := os.Getenv("PAGER")
530	if pager == "" {
531		pager = "less -R"
532	}
533
534	parts := strings.Fields(pager)
535	cmd := exec.CommandContext(ctx, parts[0], parts[1:]...) //nolint:gosec
536	cmd.Stdout = os.Stdout
537	cmd.Stderr = os.Stderr
538
539	pipe, err := cmd.StdinPipe()
540	if err != nil {
541		return colorprofile.NewWriter(os.Stdout, os.Environ()), func() {}, false
542	}
543
544	if err := cmd.Start(); err != nil {
545		return colorprofile.NewWriter(os.Stdout, os.Environ()), func() {}, false
546	}
547
548	return &colorprofile.Writer{
549			Forward: pipe,
550			Profile: profile,
551		}, func() {
552			pipe.Close()
553			_ = cmd.Wait()
554		}, true
555}
556
557type sessionShowMeta struct {
558	ID               string             `json:"id"`
559	UUID             string             `json:"uuid"`
560	Title            string             `json:"title"`
561	Created          string             `json:"created"`
562	Modified         string             `json:"modified"`
563	Cost             float64            `json:"cost"`
564	PromptTokens     int64              `json:"prompt_tokens"`
565	CompletionTokens int64              `json:"completion_tokens"`
566	TotalTokens      int64              `json:"total_tokens"`
567	Skills           []sessionShowSkill `json:"skills,omitempty"`
568}
569
570type sessionShowSkill struct {
571	Name        string `json:"name"`
572	Description string `json:"description"`
573	LoadedAt    string `json:"loaded_at"`
574}
575
576type sessionShowMessage struct {
577	ID       string            `json:"id"`
578	Role     string            `json:"role"`
579	Created  string            `json:"created"`
580	Model    string            `json:"model,omitempty"`
581	Provider string            `json:"provider,omitempty"`
582	Parts    []sessionShowPart `json:"parts"`
583}
584
585type sessionShowPart struct {
586	Type string `json:"type"`
587
588	// Text content
589	Text string `json:"text,omitempty"`
590
591	// Reasoning
592	Thinking   string `json:"thinking,omitempty"`
593	StartedAt  int64  `json:"started_at,omitempty"`
594	FinishedAt int64  `json:"finished_at,omitempty"`
595
596	// Tool call
597	ToolCallID string `json:"tool_call_id,omitempty"`
598	Name       string `json:"name,omitempty"`
599	Input      string `json:"input,omitempty"`
600
601	// Tool result
602	Content  string `json:"content,omitempty"`
603	IsError  bool   `json:"is_error,omitempty"`
604	MIMEType string `json:"mime_type,omitempty"`
605
606	// Binary
607	Size int64 `json:"size,omitempty"`
608
609	// Image URL
610	URL    string `json:"url,omitempty"`
611	Detail string `json:"detail,omitempty"`
612
613	// Finish
614	Reason string `json:"reason,omitempty"`
615	Time   int64  `json:"time,omitempty"`
616}
617
618func extractSkillsFromMessages(msgs []*message.Message) []sessionShowSkill {
619	var skills []sessionShowSkill
620	seen := make(map[string]bool)
621
622	for _, msg := range msgs {
623		for _, part := range msg.Parts {
624			if tr, ok := part.(message.ToolResult); ok && tr.Metadata != "" {
625				var meta tools.ViewResponseMetadata
626				if err := json.Unmarshal([]byte(tr.Metadata), &meta); err == nil {
627					if meta.ResourceType == tools.ViewResourceSkill && meta.ResourceName != "" {
628						if !seen[meta.ResourceName] {
629							seen[meta.ResourceName] = true
630							skills = append(skills, sessionShowSkill{
631								Name:        meta.ResourceName,
632								Description: meta.ResourceDescription,
633								LoadedAt:    time.Unix(msg.CreatedAt, 0).Format(time.RFC3339),
634							})
635						}
636					}
637				}
638			}
639		}
640	}
641
642	sort.Slice(skills, func(i, j int) bool {
643		if skills[i].LoadedAt == skills[j].LoadedAt {
644			return skills[i].Name < skills[j].Name
645		}
646		return skills[i].LoadedAt < skills[j].LoadedAt
647	})
648
649	return skills
650}
651
652func convertParts(parts []message.ContentPart) []sessionShowPart {
653	result := make([]sessionShowPart, 0, len(parts))
654	for _, part := range parts {
655		switch p := part.(type) {
656		case message.TextContent:
657			result = append(result, sessionShowPart{
658				Type: "text",
659				Text: p.Text,
660			})
661		case message.ReasoningContent:
662			result = append(result, sessionShowPart{
663				Type:       "reasoning",
664				Thinking:   p.Thinking,
665				StartedAt:  p.StartedAt,
666				FinishedAt: p.FinishedAt,
667			})
668		case message.ToolCall:
669			result = append(result, sessionShowPart{
670				Type:       "tool_call",
671				ToolCallID: p.ID,
672				Name:       p.Name,
673				Input:      p.Input,
674			})
675		case message.ToolResult:
676			result = append(result, sessionShowPart{
677				Type:       "tool_result",
678				ToolCallID: p.ToolCallID,
679				Name:       p.Name,
680				Content:    p.Content,
681				IsError:    p.IsError,
682				MIMEType:   p.MIMEType,
683			})
684		case message.BinaryContent:
685			result = append(result, sessionShowPart{
686				Type:     "binary",
687				MIMEType: p.MIMEType,
688				Size:     int64(len(p.Data)),
689			})
690		case message.ImageURLContent:
691			result = append(result, sessionShowPart{
692				Type:   "image_url",
693				URL:    p.URL,
694				Detail: p.Detail,
695			})
696		case message.Finish:
697			result = append(result, sessionShowPart{
698				Type:   "finish",
699				Reason: string(p.Reason),
700				Time:   p.Time,
701			})
702		default:
703			result = append(result, sessionShowPart{
704				Type: "unknown",
705			})
706		}
707	}
708	return result
709}
710
711type sessionShowOutput struct {
712	Meta     sessionShowMeta      `json:"meta"`
713	Messages []sessionShowMessage `json:"messages"`
714}