package claude import ( "context" "errors" "fmt" "git.a-wan.net/alan/pipelines/internal/protocol" ) // defaultMode is Claude Code's own ask-for-permission mode. The CLI flag has no // spelling for it, so a process in this mode is started without the flag; the // control request accepts it by name. const defaultMode = "default" // chatModes are the Claude Code permission modes a chat can run in, in the // order the CLI cycles them. dontAsk is left out: it silently denies anything // not pre-approved, which a chat on a phone cannot recover from. var chatModes = []protocol.ChatMode{ {ID: defaultMode, Name: "Ask for permission", Description: "Ask before edits and commands."}, {ID: "acceptEdits", Name: "Accept edits", Description: "Make file edits without asking; ask for other actions."}, {ID: "plan", Name: "Plan", Description: "Explore and plan without changing anything."}, {ID: "auto", Name: "Auto", Description: "Act without asking, with Claude Code's safety checks."}, {ID: "bypassPermissions", Name: "Bypass permissions", Description: "Never ask. Everything runs without checks."}, } // Modes lists the permission modes a Claude chat can switch to. func (c *Chat) Modes(context.Context, string) ([]protocol.ChatMode, error) { return append([]protocol.ChatMode(nil), chatModes...), nil } func knownMode(mode string) bool { for _, known := range chatModes { if known.ID == mode { return true } } return false } // SetMode records the session's permission mode and applies it to a running // CLI at once; a later process starts in it. func (c *Chat) SetMode(ctx context.Context, id, mode string) error { if !knownMode(mode) { return fmt.Errorf("unknown Claude permission mode %q", mode) } s := c.session(id) if s == nil { meta, ok := transcriptSession(id) if !ok { return errors.New("unknown Claude session " + id) } s = c.sessionFor(id, meta.Directory) } s.mu.Lock() previous := s.mode s.mode = mode proc := s.proc s.mu.Unlock() if proc == nil { return nil } if err := s.applyMode(ctx, proc); err != nil { s.mu.Lock() s.mode = previous s.mu.Unlock() return err } return nil } // applyMode tells a running CLI the session's mode when it runs in another. func (s *session) applyMode(ctx context.Context, proc *process) error { s.mu.Lock() requested, current := s.mode, proc.mode s.mu.Unlock() if requested == "" || requested == current || (current == "" && requested == defaultMode) { return nil } setCtx, cancel := context.WithTimeout(ctx, controlRequestTimeout) defer cancel() if _, err := proc.request(setCtx, "set_permission_mode", map[string]any{"mode": requested}); err != nil { return fmt.Errorf("switch Claude permission mode: %w", err) } s.mu.Lock() proc.mode = requested s.mu.Unlock() return nil }