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"
33var sessionCmd = &cobra.Command{
35 Aliases: []string{"sessions", "s"},
36 Short: "Manage sessions",
37 Long: "Manage Crush sessions. Agents can use --json for machine-readable output.",
44 sessionDeleteJSON bool
45 sessionRenameJSON bool
48var sessionListCmd = &cobra.Command{
50 Aliases: []string{"ls"},
51 Short: "List all sessions",
52 Long: "List all sessions. Use --json for machine-readable output.",
56var sessionShowCmd = &cobra.Command{
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),
64var sessionLastCmd = &cobra.Command{
66 Short: "Show most recent session",
67 Long: "Show the last updated session. Use --json for machine-readable output.",
71var sessionDeleteCmd = &cobra.Command{
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,
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,
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)
101type sessionServices struct {
102 sessions session.Service
103 messages message.Service
104 cfg *config.ConfigStore
107func sessionSetup(cmd *cobra.Command) (context.Context, *sessionServices, func(), error) {
108 dataDir, _ := cmd.Flags().GetString("data-dir")
111 cfg, err := config.Init("", dataDir, false)
113 return nil, nil, nil, fmt.Errorf("failed to initialize config: %w", err)
116 dataDir = cfg.Config().Options.DataDirectory
118 if shouldEnableMetrics(cfg.Config()) {
122 conn, err := db.Connect(ctx, dataDir)
124 return nil, nil, nil, fmt.Errorf("failed to connect to database: %w", err)
127 queries := db.New(conn)
128 svc := &sessionServices{
129 sessions: session.NewService(queries, conn),
130 messages: message.NewService(queries),
133 return ctx, svc, func() { conn.Close() }, nil
136func runSessionList(cmd *cobra.Command, _ []string) error {
137 event.SetNonInteractive(true)
139 ctx, svc, cleanup, err := sessionSetup(cmd)
145 event.SessionListed(sessionListJSON)
147 list, err := svc.sessions.List(ctx)
149 return fmt.Errorf("failed to list sessions: %w", err)
153 out := cmd.OutOrStdout()
154 output := make([]sessionJSON, len(list))
155 for i, s := range list {
156 output[i] = sessionJSON{
157 ID: session.HashID(s.ID),
160 Created: time.Unix(s.CreatedAt, 0).Format(time.RFC3339),
161 Modified: time.Unix(s.UpdatedAt, 0).Format(time.RFC3339),
164 enc := json.NewEncoder(out)
165 enc.SetEscapeHTML(false)
166 return enc.Encode(output)
169 w, cleanup, usingPager := sessionWriter(ctx, len(list))
172 hashStyle := lipgloss.NewStyle().Foreground(charmtone.Malibu)
173 dateStyle := lipgloss.NewStyle().Foreground(charmtone.Damson)
175 width := sessionOutputWidth
176 if tw, _, err := term.GetSize(os.Stdout.Fd()); err == nil && tw > 0 {
179 // 7 (hash) + 1 (space) + 25 (RFC3339 date) + 1 (space) = 34 chars prefix.
180 titleWidth := max(width-34, 10)
183 for _, s := range list {
184 hash := session.HashID(s.ID)[:7]
185 date := time.Unix(s.CreatedAt, 0).Format(time.RFC3339)
186 title := strings.ReplaceAll(s.Title, "\n", " ")
187 title = ansi.Truncate(title, titleWidth, "…")
188 _, writeErr = fmt.Fprintln(w, hashStyle.Render(hash), dateStyle.Render(date), title)
193 if writeErr != nil && usingPager && isBrokenPipe(writeErr) {
199type sessionJSON struct {
200 ID string `json:"id"`
201 UUID string `json:"uuid"`
202 Title string `json:"title"`
203 Created string `json:"created"`
204 Modified string `json:"modified"`
207type sessionMutationResult struct {
208 ID string `json:"id"`
209 UUID string `json:"uuid"`
210 Title string `json:"title"`
211 Deleted bool `json:"deleted,omitempty"`
212 Renamed bool `json:"renamed,omitempty"`
215// resolveSessionID resolves a session ID that can be a UUID, full hash, or hash prefix.
216// Returns an error if the prefix is ambiguous (matches multiple sessions).
217func resolveSessionID(ctx context.Context, svc session.Service, id string) (session.Session, error) {
218 // Try direct UUID lookup first
219 if s, err := svc.Get(ctx, id); err == nil {
223 // List all sessions and check for hash matches
224 sessions, err := svc.List(ctx)
226 return session.Session{}, err
229 var matches []session.Session
230 for _, s := range sessions {
231 hash := session.HashID(s.ID)
232 if hash == id || strings.HasPrefix(hash, id) {
233 matches = append(matches, s)
237 if len(matches) == 0 {
238 return session.Session{}, fmt.Errorf("session not found: %s", id)
241 if len(matches) == 1 {
242 return matches[0], nil
245 // Ambiguous - show matches like Git does
246 var sb strings.Builder
247 fmt.Fprintf(&sb, "session ID '%s' is ambiguous. Matches:\n\n", id)
248 for _, m := range matches {
249 hash := session.HashID(m.ID)
250 created := time.Unix(m.CreatedAt, 0).Format("2006-01-02")
251 // Keep title on one line by replacing newlines with spaces, and truncate.
252 title := strings.ReplaceAll(m.Title, "\n", " ")
253 title = ansi.Truncate(title, 50, "…")
254 fmt.Fprintf(&sb, " %s... %q (created %s)\n", hash[:12], title, created)
256 sb.WriteString("\nUse more characters or the full hash")
257 return session.Session{}, errors.New(sb.String())
260func runSessionShow(cmd *cobra.Command, args []string) error {
261 event.SetNonInteractive(true)
263 ctx, svc, cleanup, err := sessionSetup(cmd)
269 event.SessionShown(sessionShowJSON)
271 sess, err := resolveSessionID(ctx, svc.sessions, args[0])
276 msgs, err := svc.messages.List(ctx, sess.ID)
278 return fmt.Errorf("failed to list messages: %w", err)
281 msgPtrs := messagePtrs(msgs)
283 return outputSessionJSON(cmd.OutOrStdout(), sess, msgPtrs)
285 return outputSessionHuman(ctx, svc.cfg, sess, msgPtrs)
288func runSessionDelete(cmd *cobra.Command, args []string) error {
289 event.SetNonInteractive(true)
291 ctx, svc, cleanup, err := sessionSetup(cmd)
297 event.SessionDeletedCommand(sessionDeleteJSON)
299 sess, err := resolveSessionID(ctx, svc.sessions, args[0])
304 if err := svc.sessions.Delete(ctx, sess.ID); err != nil {
305 return fmt.Errorf("failed to delete session: %w", err)
308 out := cmd.OutOrStdout()
309 if sessionDeleteJSON {
310 enc := json.NewEncoder(out)
311 enc.SetEscapeHTML(false)
312 return enc.Encode(sessionMutationResult{
313 ID: session.HashID(sess.ID),
320 fmt.Fprintf(out, "Deleted session %s\n", session.HashID(sess.ID)[:12])
324func runSessionRename(cmd *cobra.Command, args []string) error {
325 event.SetNonInteractive(true)
327 ctx, svc, cleanup, err := sessionSetup(cmd)
333 event.SessionRenamed(sessionRenameJSON)
335 sess, err := resolveSessionID(ctx, svc.sessions, args[0])
340 newTitle := strings.Join(args[1:], " ")
341 if err := svc.sessions.Rename(ctx, sess.ID, newTitle); err != nil {
342 return fmt.Errorf("failed to rename session: %w", err)
345 out := cmd.OutOrStdout()
346 if sessionRenameJSON {
347 enc := json.NewEncoder(out)
348 enc.SetEscapeHTML(false)
349 return enc.Encode(sessionMutationResult{
350 ID: session.HashID(sess.ID),
357 fmt.Fprintf(out, "Renamed session %s to %q\n", session.HashID(sess.ID)[:12], newTitle)
361func runSessionLast(cmd *cobra.Command, _ []string) error {
362 event.SetNonInteractive(true)
364 ctx, svc, cleanup, err := sessionSetup(cmd)
370 event.SessionLastShown(sessionLastJSON)
372 list, err := svc.sessions.List(ctx)
374 return fmt.Errorf("failed to list sessions: %w", err)
378 return fmt.Errorf("no sessions found")
383 msgs, err := svc.messages.List(ctx, sess.ID)
385 return fmt.Errorf("failed to list messages: %w", err)
388 msgPtrs := messagePtrs(msgs)
390 return outputSessionJSON(cmd.OutOrStdout(), sess, msgPtrs)
392 return outputSessionHuman(ctx, svc.cfg, sess, msgPtrs)
396 sessionOutputWidth = 80
397 sessionMaxContentWidth = 120
400func messagePtrs(msgs []message.Message) []*message.Message {
401 ptrs := make([]*message.Message, len(msgs))
402 for i := range msgs {
408func outputSessionJSON(w io.Writer, sess session.Session, msgs []*message.Message) error {
409 skills := extractSkillsFromMessages(msgs)
410 output := sessionShowOutput{
411 Meta: sessionShowMeta{
412 ID: session.HashID(sess.ID),
415 Created: time.Unix(sess.CreatedAt, 0).Format(time.RFC3339),
416 Modified: time.Unix(sess.UpdatedAt, 0).Format(time.RFC3339),
418 PromptTokens: sess.PromptTokens,
419 CompletionTokens: sess.CompletionTokens,
420 TotalTokens: sess.PromptTokens + sess.CompletionTokens,
423 Messages: make([]sessionShowMessage, len(msgs)),
426 for i, msg := range msgs {
427 output.Messages[i] = sessionShowMessage{
429 Role: string(msg.Role),
430 Created: time.Unix(msg.CreatedAt, 0).Format(time.RFC3339),
432 Provider: msg.Provider,
433 Parts: convertParts(msg.Parts),
437 enc := json.NewEncoder(w)
438 enc.SetEscapeHTML(false)
439 return enc.Encode(output)
442func outputSessionHuman(ctx context.Context, cfg *config.ConfigStore, sess session.Session, msgs []*message.Message) error {
443 var providerID string
445 providerID = cfg.Config().Models[config.SelectedModelTypeLarge].Provider
447 styles := styles.ThemeForProvider(providerID)
448 toolResults := chat.BuildToolResultMap(msgs)
450 width := sessionOutputWidth
451 if w, _, err := term.GetSize(os.Stdout.Fd()); err == nil && w > 0 {
454 contentWidth := min(width, sessionMaxContentWidth)
456 keyStyle := lipgloss.NewStyle().Foreground(charmtone.Damson)
457 valStyle := lipgloss.NewStyle().Foreground(charmtone.Malibu)
459 hash := session.HashID(sess.ID)[:12]
460 created := time.Unix(sess.CreatedAt, 0).Format("Mon Jan 2 15:04:05 2006 -0700")
462 skills := extractSkillsFromMessages(msgs)
464 // Render to buffer to determine actual height
465 var buf strings.Builder
467 fmt.Fprintln(&buf, keyStyle.Render("ID: ")+valStyle.Render(hash))
468 fmt.Fprintln(&buf, keyStyle.Render("UUID: ")+valStyle.Render(sess.ID))
469 fmt.Fprintln(&buf, keyStyle.Render("Title: ")+valStyle.Render(sess.Title))
470 fmt.Fprintln(&buf, keyStyle.Render("Date: ")+valStyle.Render(created))
472 skillNames := make([]string, len(skills))
473 for i, s := range skills {
474 timestamp := time.Unix(sess.CreatedAt, 0).Format("15:04:05 -0700")
475 if s.LoadedAt != "" {
476 if t, err := time.Parse(time.RFC3339, s.LoadedAt); err == nil {
477 timestamp = t.Format("15:04:05 -0700")
480 skillNames[i] = fmt.Sprintf("%s (%s)", s.Name, timestamp)
482 fmt.Fprintln(&buf, keyStyle.Render("Skills: ")+valStyle.Render(strings.Join(skillNames, ", ")))
487 for _, msg := range msgs {
488 items := chat.ExtractMessageItems(&styles, msg, toolResults)
489 for _, item := range items {
494 fmt.Fprintln(&buf, item.Render(contentWidth))
499 contentHeight := strings.Count(buf.String(), "\n")
500 w, cleanup, usingPager := sessionWriter(ctx, contentHeight)
503 _, err := io.WriteString(w, buf.String())
504 // Ignore broken pipe errors when using a pager. This happens when the user
505 // exits the pager early (e.g., pressing 'q' in less), which closes the pipe
506 // and causes subsequent writes to fail. These errors are expected user behavior.
507 if err != nil && usingPager && isBrokenPipe(err) {
513func isBrokenPipe(err error) bool {
517 // Check for syscall.EPIPE (broken pipe)
518 if errors.Is(err, syscall.EPIPE) {
521 // Also check for "broken pipe" in the error message
522 return strings.Contains(err.Error(), "broken pipe")
525// sessionWriter returns a writer, cleanup function, and a bool indicating if a pager is used.
526// When the content fits within the terminal (or stdout is not a TTY), it returns
527// a colorprofile.Writer wrapping stdout. When content exceeds terminal height,
528// it starts a pager process (respecting $PAGER, defaulting to "less -R").
529func sessionWriter(ctx context.Context, contentHeight int) (io.Writer, func(), bool) {
530 // Use NewWriter which automatically detects TTY and strips ANSI when redirected
531 if runtime.GOOS == "windows" || !term.IsTerminal(os.Stdout.Fd()) {
532 return colorprofile.NewWriter(os.Stdout, os.Environ()), func() {}, false
535 _, termHeight, err := term.GetSize(os.Stdout.Fd())
536 if err != nil || contentHeight <= termHeight {
537 return colorprofile.NewWriter(os.Stdout, os.Environ()), func() {}, false
540 // Detect color profile from stderr since stdout is piped to the pager.
541 profile := colorprofile.Detect(os.Stderr, os.Environ())
543 pager := os.Getenv("PAGER")
548 parts := strings.Fields(pager)
549 cmd := exec.CommandContext(ctx, parts[0], parts[1:]...) //nolint:gosec
550 cmd.Stdout = os.Stdout
551 cmd.Stderr = os.Stderr
553 pipe, err := cmd.StdinPipe()
555 return colorprofile.NewWriter(os.Stdout, os.Environ()), func() {}, false
558 if err := cmd.Start(); err != nil {
559 return colorprofile.NewWriter(os.Stdout, os.Environ()), func() {}, false
562 return &colorprofile.Writer{
571type sessionShowMeta struct {
572 ID string `json:"id"`
573 UUID string `json:"uuid"`
574 Title string `json:"title"`
575 Created string `json:"created"`
576 Modified string `json:"modified"`
577 Cost float64 `json:"cost"`
578 PromptTokens int64 `json:"prompt_tokens"`
579 CompletionTokens int64 `json:"completion_tokens"`
580 TotalTokens int64 `json:"total_tokens"`
581 Skills []sessionShowSkill `json:"skills,omitempty"`
584type sessionShowSkill struct {
585 Name string `json:"name"`
586 Description string `json:"description"`
587 LoadedAt string `json:"loaded_at"`
590type sessionShowMessage struct {
591 ID string `json:"id"`
592 Role string `json:"role"`
593 Created string `json:"created"`
594 Model string `json:"model,omitempty"`
595 Provider string `json:"provider,omitempty"`
596 Parts []sessionShowPart `json:"parts"`
599type sessionShowPart struct {
600 Type string `json:"type"`
603 Text string `json:"text,omitempty"`
606 Thinking string `json:"thinking,omitempty"`
607 StartedAt int64 `json:"started_at,omitempty"`
608 FinishedAt int64 `json:"finished_at,omitempty"`
611 ToolCallID string `json:"tool_call_id,omitempty"`
612 Name string `json:"name,omitempty"`
613 Input string `json:"input,omitempty"`
616 Content string `json:"content,omitempty"`
617 IsError bool `json:"is_error,omitempty"`
618 MIMEType string `json:"mime_type,omitempty"`
621 Size int64 `json:"size,omitempty"`
624 URL string `json:"url,omitempty"`
625 Detail string `json:"detail,omitempty"`
628 Reason string `json:"reason,omitempty"`
629 Time int64 `json:"time,omitempty"`
632func extractSkillsFromMessages(msgs []*message.Message) []sessionShowSkill {
633 var skills []sessionShowSkill
634 seen := make(map[string]bool)
636 for _, msg := range msgs {
637 for _, part := range msg.Parts {
638 if tr, ok := part.(message.ToolResult); ok && tr.Metadata != "" {
639 var meta tools.ViewResponseMetadata
640 if err := json.Unmarshal([]byte(tr.Metadata), &meta); err == nil {
641 if meta.ResourceType == tools.ViewResourceSkill && meta.ResourceName != "" {
642 if !seen[meta.ResourceName] {
643 seen[meta.ResourceName] = true
644 skills = append(skills, sessionShowSkill{
645 Name: meta.ResourceName,
646 Description: meta.ResourceDescription,
647 LoadedAt: time.Unix(msg.CreatedAt, 0).Format(time.RFC3339),
656 sort.Slice(skills, func(i, j int) bool {
657 if skills[i].LoadedAt == skills[j].LoadedAt {
658 return skills[i].Name < skills[j].Name
660 return skills[i].LoadedAt < skills[j].LoadedAt
666func convertParts(parts []message.ContentPart) []sessionShowPart {
667 result := make([]sessionShowPart, 0, len(parts))
668 for _, part := range parts {
669 switch p := part.(type) {
670 case message.TextContent:
671 result = append(result, sessionShowPart{
675 case message.ReasoningContent:
676 result = append(result, sessionShowPart{
678 Thinking: p.Thinking,
679 StartedAt: p.StartedAt,
680 FinishedAt: p.FinishedAt,
682 case message.ToolCall:
683 result = append(result, sessionShowPart{
689 case message.ToolResult:
690 result = append(result, sessionShowPart{
692 ToolCallID: p.ToolCallID,
696 MIMEType: p.MIMEType,
698 case message.BinaryContent:
699 result = append(result, sessionShowPart{
701 MIMEType: p.MIMEType,
702 Size: int64(len(p.Data)),
704 case message.ImageURLContent:
705 result = append(result, sessionShowPart{
711 result = append(result, sessionShowPart{
713 Reason: string(p.Reason),
717 result = append(result, sessionShowPart{
725type sessionShowOutput struct {
726 Meta sessionShowMeta `json:"meta"`
727 Messages []sessionShowMessage `json:"messages"`
keysesc to close
- j k
- move down, up
- enter
- open
- esc
- back, or up a level
- 1 2 3 4
- readme, files, commits, refs
- /
- filter
- y
- copy the clone command
- c
- compare the chosen commit with another (or shift-click both)
- ?
- show or hide this list