AppendEvent 实现 session.Service 接口
(ctx context.Context, sessionID string, event *session.Event)
| 205 | |
| 206 | // AppendEvent 实现 session.Service 接口 |
| 207 | func (s *Service) AppendEvent(ctx context.Context, sessionID string, event *session.Event) error { |
| 208 | return s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error { |
| 209 | // 1. 序列化事件内容 |
| 210 | contentJSON, err := json.Marshal(event.Content) |
| 211 | if err != nil { |
| 212 | return fmt.Errorf("marshal content: %w", err) |
| 213 | } |
| 214 | |
| 215 | // 2. 序列化事件动作 |
| 216 | var actionsJSON []byte |
| 217 | if event.Actions.StateDelta != nil || event.Actions.ArtifactDelta != nil { |
| 218 | actionsJSON, err = json.Marshal(event.Actions) |
| 219 | if err != nil { |
| 220 | return fmt.Errorf("marshal actions: %w", err) |
| 221 | } |
| 222 | } |
| 223 | |
| 224 | // 3. 序列化元数据 |
| 225 | var metadataJSON []byte |
| 226 | if len(event.Metadata) > 0 { |
| 227 | metadataJSON, err = json.Marshal(event.Metadata) |
| 228 | if err != nil { |
| 229 | return fmt.Errorf("marshal metadata: %w", err) |
| 230 | } |
| 231 | } |
| 232 | |
| 233 | // 4. 创建事件记录 |
| 234 | eventModel := &EventModel{ |
| 235 | ID: event.ID, |
| 236 | SessionID: sessionID, |
| 237 | InvocationID: event.InvocationID, |
| 238 | Branch: event.Branch, |
| 239 | Author: event.Author, |
| 240 | AgentID: event.AgentID, |
| 241 | Timestamp: event.Timestamp, |
| 242 | Content: contentJSON, |
| 243 | Actions: actionsJSON, |
| 244 | LongRunningToolIDs: event.LongRunningToolIDs, |
| 245 | Metadata: metadataJSON, |
| 246 | } |
| 247 | |
| 248 | if err := tx.Create(eventModel).Error; err != nil { |
| 249 | return fmt.Errorf("create event: %w", err) |
| 250 | } |
| 251 | |
| 252 | // 5. 应用状态变更(StateDelta) |
| 253 | if len(event.Actions.StateDelta) > 0 { |
| 254 | for key, value := range event.Actions.StateDelta { |
| 255 | scope, actualKey := parseStateKey(key) |
| 256 | |
| 257 | // 序列化值 |
| 258 | valueJSON, err := json.Marshal(value) |
| 259 | if err != nil { |
| 260 | return fmt.Errorf("marshal state value: %w", err) |
| 261 | } |
| 262 | |
| 263 | now := time.Now() |
| 264 |
nothing calls this directly
no test coverage detected