Help us shape the future of Go! Take the 2026 Go Developer Survey

session

package
v1.7.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 13, 2026 License: AGPL-3.0 Imports: 7 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type EventType

type EventType string

EventType 标记 Message 的特殊事件类型。普通消息为零值 EventNormal。

取值含义: - EventNormal: 正常消息 - EventCompression: 上下文压缩边界 - EventUserStopped: 用户手动停止(context.Canceled) - EventSystemInterrupted: 后端主动中断(MaxTurns/死循环检测/工具连续失败) - EventError: 服务商错误(HTTP 4xx/5xx/网络/超时)

const (
	EventNormal            EventType = ""
	EventCompression       EventType = "compression"
	EventUserStopped       EventType = "user_stopped"
	EventSystemInterrupted EventType = "system_interrupted"
	EventError             EventType = "error"
)

type ListSessionsOptions

type ListSessionsOptions struct {
	PageParams storage.PageParams
	Search     string // 空=全部,非空=按消息内容 LIKE 模糊匹配
}

ListSessionsOptions 是 ListSessions 的可选参数。

type Message

type Message struct {
	ID              int64  `gorm:"column:id;primaryKey;autoIncrement"                            json:"id"`
	SessionID       string `gorm:"column:session_id;index;not null"                             json:"session_id"`
	TurnID          int    `gorm:"column:turn_id;not null;default:0;index"                      json:"turn_id"` // 所属 turn,回退时直接 DELETE WHERE turn_id
	Role            string `gorm:"column:role;not null"                                          json:"role"`   // "system" | "user" | "assistant" | "tool"
	Content         string `gorm:"column:content;not null"                                       json:"content"`
	ThinkingContent string `gorm:"column:thinking_content"                                     json:"thinking_content,omitempty"`
	TokenCount      int    `gorm:"column:token_count;not null;default:0"                        json:"token_count"`
	ExtraMetadata   string `gorm:"column:extra_metadata"                                         json:"extra_metadata,omitempty"` // JSON:tool_calls / tool_call_id / display_text 等
	Version         int    `gorm:"column:version;not null;default:1;index"                      json:"version"`                   // 压缩代数,查询时 = session.active_version
	ToAPI           bool   `gorm:"column:to_api;not null;default:0;index"                       json:"to_api"`                    // LLM context 是否需要此消息。注:default:0 原因同上,子 agent 的 ToAPI=false 不能被默认值覆盖
	ToFrontend      bool   `gorm:"column:to_frontend;not null;default:0;index"                  json:"to_frontend"`               // 前端是否需要渲染此消息。注:default:0 必须与 Go false 一致,否则 GORM 跳过零值时 DB 填入默认值 1 导致泄漏
	// EventType 取值见上方 EventType 常量定义。
	EventType EventType `gorm:"column:event_type"                                             json:"event_type,omitempty"`
	AgentType string    `gorm:"column:agent_type;not null;default:'main';index"              json:"agent_type"`            // "main" | "review" | "memory"
	SubTaskID string    `gorm:"column:sub_task_id;index"                                     json:"sub_task_id,omitempty"` // run_subagent 的 tool call ID,前端路由子 Agent 消息用
	CreatedAt time.Time `gorm:"column:created_at;autoCreateTime;index"                       json:"created_at"`
}

Message 是对话中的单条消息,append-only,永不修改永不删除。

to_api 和 to_frontend 由写入方独立决定,不由 role 推导。四种 role 都可能有任意的可见性组合。 version 标记该消息属于第几代上下文构建,配合 Session.active_version 做查询过滤。 event_type 标记特殊事件,取值见 EventType 常量,普通消息为空。

func (Message) TableName

func (Message) TableName() string

func (*Message) ToAPIFormat

func (m *Message) ToAPIFormat(logger *slog.Logger) map[string]any

ToAPIFormat 转为 OpenAI Chat Completions 兼容的消息格式。 从 ExtraMetadata 提取 tool_calls、thinking_content、tool_call_id 拼入对应字段。

type Session

type Session struct {
	SessionID       string    `gorm:"column:session_id;primaryKey"                                 json:"session_id"`
	NovelID         int64     `gorm:"column:novel_id;index:idx_sessions_novel;not null"            json:"novel_id"`
	Title           string    `gorm:"column:title;not null;default:''"                            json:"title"`
	Model           string    `gorm:"column:model;not null;default:deepseek-v4-pro"               json:"model"`
	ReasoningEffort string    `gorm:"column:reasoning_effort"                                      json:"reasoning_effort,omitempty"` // "high" | "max" | "",DeepSeek 推理深度
	Summary         string    `gorm:"column:summary;not null;default:''"                          json:"summary"`                     // 最新压缩摘要,每次压缩全量替换
	PendingChanges  string    `gorm:"column:pending_changes"                                       json:"pending_changes,omitempty"`  // JSON,待确认的编辑变更列表
	ExtraMetadata   string    `gorm:"column:extra_metadata"                                        json:"extra_metadata,omitempty"`   // JSON,扩展槽
	ActiveVersion   int       `gorm:"column:active_version;not null;default:1"                    json:"active_version"`              // 当前活跃的上下文代数
	LastTurnID      int       `gorm:"column:last_turn_id;not null;default:0"                      json:"last_turn_id"`                // 最后一个 turn 的编号,原子自增
	Usage           string    `gorm:"column:usage"                                                 json:"usage,omitempty"`            // JSON,最近一次 LLM 调用的 token 用量
	CreatedAt       time.Time `gorm:"column:created_at;autoCreateTime"                            json:"created_at"`
	UpdatedAt       time.Time `gorm:"column:updated_at;autoUpdateTime;index:idx_sessions_novel"   json:"updated_at"`
}

Session 是对话会话的元数据容器。 不持有 messages——消息通过 Store 按 to_api/to_frontend/version 三条路径独立查询。 active_version 配合 Message.version 实现上下文压缩和版本级回滚,压缩不删旧消息。

func (Session) TableName

func (Session) TableName() string

type Store

type Store struct {
	DB *gorm.DB
	// contains filtered or unexported fields
}

Store 管理 Session/Message 持久化。DB 导出供调用方做简单 CRUD(Create/First/Append)。

func NewStore

func NewStore(db *gorm.DB, logger *slog.Logger) *Store

NewStore 创建 session 存储。

func (*Store) BumpActiveVersion

func (s *Store) BumpActiveVersion(ctx context.Context, sessionID string) (int, error)

BumpActiveVersion 递增 active_version 并返回新值。

func (*Store) Delete

func (s *Store) Delete(ctx context.Context, sessionID string) error

Delete 删除一个 session 及其全部关联数据:messages、operation_log。 单事务内执行,保证原子性。

sessions 与 messages 表本身在 skipOperLog 名单内,不走 operation_log; operation_log 的清理用裸 DELETE(Table 模式无 Schema,不经 callback), 因此整个删除过程不产生新的日志记录,符合"session 删除不可回滚"的语义。 清理 operation_log 的原因:该 session 产生的领域元数据操作日志强绑定 session_id, session 删除后成为孤儿(回滚第一步即查 sessions.last_turn_id),无保留意义。

func (*Store) GetAllMessages

func (s *Store) GetAllMessages(ctx context.Context, sessionID string) ([]Message, error)

GetAllMessages 返回全部消息,审计/回退用。

func (*Store) GetMessagesForAPI

func (s *Store) GetMessagesForAPI(ctx context.Context, sessionID string, version int) ([]Message, error)

GetMessagesForAPI 返回 LLM context 所需的消息。

func (*Store) GetMessagesForFrontend

func (s *Store) GetMessagesForFrontend(ctx context.Context, sessionID string) ([]Message, error)

GetMessagesForFrontend 返回前端展示所需的消息。

func (*Store) GetSession

func (s *Store) GetSession(ctx context.Context, sessionID string) (*Session, error)

GetSession 按 session_id 加载单个 session。

func (*Store) ListSessions

func (s *Store) ListSessions(ctx context.Context, novelID int64, opts ListSessionsOptions) (*storage.PageResult[Session], error)

ListSessions 按小说列出会话,updated_at 倒序,分页。Search 非空时搜索消息内容。

func (*Store) NextTurn

func (s *Store) NextTurn(ctx context.Context, sessionID string) (int, error)

NextTurn 原子递增 last_turn_id 并返回新值。 agent loop 在每个 turn 开始时调用,一步完成递增 + 持久化。

func (*Store) UpdateSessionMeta

func (s *Store) UpdateSessionMeta(ctx context.Context, sessionID, title, model, reasoningEffort string) error

UpdateSessionMeta 增量更新标题、模型、推理深度。空字符串不更新。

func (*Store) UpdateSessionUsage

func (s *Store) UpdateSessionUsage(ctx context.Context, sessionID, usageJSON string) error

UpdateSessionUsage 更新最近一次 LLM 的 token 用量。

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL