package server import ( "context" "errors" "log" "strconv" "strings" "time" "git.a-wan.net/alan/pipelines/internal/claude" "git.a-wan.net/alan/pipelines/internal/protocol" ) // When Claude Code refuses an operator chat's turn for a usage limit and the // server did not continue it on another account (chat_auto_switch.go), the // server queues a durable prompt into the chat to send a minute after the // limit resets: the refused operator message again when the turn was that // message and did no work, else "continue". It is marked as sent // automatically and waits in the queue as "Scheduled", where the operator can // remove it. Its operation id, auto-continue-, is the one // the app used when it scheduled the prompt itself, so a refusal is continued // once however many devices and servers saw it. It honours the operator's // "Auto-continue when limits reset" choice (on by default), kept per Claude // home, or by this server for a chat without one. A refusal that names no // reset is not continued. const ( // chatAutoContinueMargin is how long after the reset the prompt is sent, // so it does not race the quota coming back. chatAutoContinueMargin = time.Minute // chatAutoContinueText is sent when there is no refused message to send // again. chatAutoContinueText = "continue" // chatAutoContinueSetting is the server_settings key of the choice for // chats without a Claude home of their own. chatAutoContinueSetting = "chat.auto_continue" ) // chatAutoContinueHome keeps the choice per Claude home (*claude.Chat, and // chatManager routing to it). It reports claude.ErrNoConfigDir for a chat // whose directory selects no Claude home. type chatAutoContinueHome interface { AutoContinue(ctx context.Context, sessionID, directory string) (bool, error) SetAutoContinue(ctx context.Context, sessionID, directory string, on bool) error } // chatServerSettings is the server's own settings table; *pipeline.Store // implements it. type chatServerSettings interface { ServerSetting(ctx context.Context, key string) (string, bool, error) SetServerSetting(ctx context.Context, key, value string) error } // AutoContinue routes the Claude-home choice to the Claude harness. func (m *chatManager) AutoContinue(ctx context.Context, sessionID, directory string) (bool, error) { home, err := m.autoContinueHome(ctx, sessionID) if err != nil { return false, err } return home.AutoContinue(ctx, sessionID, directory) } // SetAutoContinue routes the Claude-home choice to the Claude harness. func (m *chatManager) SetAutoContinue(ctx context.Context, sessionID, directory string, on bool) error { home, err := m.autoContinueHome(ctx, sessionID) if err != nil { return err } return home.SetAutoContinue(ctx, sessionID, directory, on) } func (m *chatManager) autoContinueHome(ctx context.Context, sessionID string) (chatAutoContinueHome, error) { if m.backendFor(ctx, sessionID) != claude.Backend { return nil, errNotClaudeChat } home, ok := m.attached(claude.Backend).(chatAutoContinueHome) if !ok { return nil, errNotClaudeChat } return home, nil } // serverSettings is the hub's settings table, or nil. func (h *chatHub) serverSettings() chatServerSettings { store, _ := h.settings.(chatServerSettings) return store } // autoContinue reads the choice that applies to sessionID and where it is // kept. func (h *chatHub) autoContinue(ctx context.Context, broker chatBroker, sessionID, directory string) (bool, string, error) { if home, ok := broker.(chatAutoContinueHome); ok { on, err := home.AutoContinue(ctx, sessionID, directory) if err == nil { return on, protocol.ChatAutoContinueClaudeHome, nil } if !errors.Is(err, claude.ErrNoConfigDir) && !errors.Is(err, errNotClaudeChat) { return false, "", err } } store := h.serverSettings() if store == nil { return true, protocol.ChatAutoContinueServer, nil } value, found, err := store.ServerSetting(ctx, chatAutoContinueSetting) if err != nil { return false, "", err } on := true if found { on, _ = strconv.ParseBool(value) } return on, protocol.ChatAutoContinueServer, nil } // setAutoContinue records the choice where autoContinue reads it. func (h *chatHub) setAutoContinue(ctx context.Context, broker chatBroker, sessionID, directory string, on bool) (string, error) { if home, ok := broker.(chatAutoContinueHome); ok { err := home.SetAutoContinue(ctx, sessionID, directory, on) if err == nil { return protocol.ChatAutoContinueClaudeHome, nil } if !errors.Is(err, claude.ErrNoConfigDir) && !errors.Is(err, errNotClaudeChat) { return "", err } } store := h.serverSettings() if store == nil { return "", errors.New("auto-continue cannot be changed: this server keeps no settings") } return protocol.ChatAutoContinueServer, store.SetServerSetting(ctx, chatAutoContinueSetting, strconv.FormatBool(on)) } // continueAtReset queues refusal's auto-continue prompt (see the file // comment). The caller already claimed the refusal. func (h *chatHub) continueAtReset(ctx context.Context, broker chatBroker, refusal claude.UsageRefusal) { if refusal.ResetsAt.IsZero() { return } on, _, err := h.autoContinue(ctx, broker, refusal.SessionID, refusal.Directory) if err != nil { log.Printf("claude auto-continue session=%s: read the setting: %v", refusal.SessionID, err) return } if !on { return } operationID := chatAutoContinuePrefix + refusalKey(refusal) if h.autoContinueSuperseded(refusal.SessionID, operationID) { return } // A prompt already waiting to continue the chat (an earlier refusal's, // perhaps resending the operator's message) continues it; were it // refused again, that refusal schedules the next. for _, prompt := range h.queueFrame(refusal.SessionID).Prompts { if strings.HasPrefix(prompt.OperationID, chatAutoContinuePrefix) && prompt.OperationID != operationID { return } } text := strings.TrimSpace(refusal.Prompt) if text == "" { text = chatAutoContinueText } sendAt := refusal.ResetsAt.Add(chatAutoContinueMargin) if err := h.queueServerPrompt(ctx, broker, refusal.SessionID, operationID, text, sendAt); err != nil { log.Printf("claude auto-continue session=%s: queue the prompt: %v", refusal.SessionID, err) return } log.Printf("claude auto-continue session=%s: scheduled %s for %s", refusal.SessionID, operationID, sendAt.Format(time.RFC3339)) } // holdsQueued reports whether the session's queue (live, else durable) // holds operationID. func (h *chatHub) holdsQueued(sessionID, operationID string) bool { for _, prompt := range h.queueFrame(sessionID).Prompts { if prompt.OperationID == operationID { return true } } return false } // handleChatAutoContinue answers chat_auto_continue: it reads, or sets, the // auto-continue choice that applies to a chat. func handleChatAutoContinue(ctx context.Context, request protocol.Message, broker chatBroker, hub *chatHub, registry operatorRegistry, write func(protocol.Message) error) { body := request.ChatAutoContinue if body == nil || !validChatSessionID(body.SessionID) { _ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "a valid chat session id is required"}) return } directory := "" if registry != nil { if row, found, err := registry.OperatorSession(ctx, body.SessionID); err == nil && found { directory = row.Directory } } var ( on bool scope string err error ) if body.AutoContinue != nil { on = *body.AutoContinue scope, err = hub.setAutoContinue(ctx, broker, body.SessionID, directory, on) } else { on, scope, err = hub.autoContinue(ctx, broker, body.SessionID, directory) } if err != nil { _ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: err.Error()}) return } _ = write(protocol.Message{Type: protocol.ChatAutoContinueType, ID: request.ID, ChatAutoContinue: &protocol.ChatAutoContinue{SessionID: body.SessionID, AutoContinue: &on, Scope: scope}}) }