miaopanel
1package store
2
3import (
4 "context"
5 "database/sql"
6 "errors"
7 "fmt"
8 "time"
9)
10
11// AISession is one chat conversation owned by a panel user.
12type AISession struct {
13 ID string `json:"id"`
14 UserID int64 `json:"-"`
15 Title string `json:"title"`
16 CreatedAt int64 `json:"created_at"`
17 UpdatedAt int64 `json:"updated_at"`
18 MessageCount int `json:"message_count"`
19}
20
21// AIMessage is one message in a conversation. Assistant messages may carry the
22// raw OpenAI tool_calls JSON; tool results are stored as separate rows so the
23// history can be replayed verbatim to the provider.
24type AIMessage struct {
25 ID int64 `json:"id"`
26 SessionID string `json:"session_id"`
27 Role string `json:"role"`
28 Content string `json:"content"`
29 ToolCalls string `json:"tool_calls,omitempty"`
30 ToolCallID string `json:"tool_call_id,omitempty"`
31 Name string `json:"name,omitempty"`
32 Status string `json:"status"`
33 CreatedAt int64 `json:"created_at"`
34}
35
36// AIAction is a mutating tool call waiting for (or carrying) user approval.
37type AIAction struct {
38 ID string `json:"id"`
39 SessionID string `json:"session_id"`
40 MessageID int64 `json:"message_id"`
41 ToolCallID string `json:"tool_call_id"`
42 ToolName string `json:"tool_name"`
43 Arguments string `json:"arguments"`
44 Summary string `json:"summary"`
45 Risk string `json:"risk"`
46 Status string `json:"status"`
47 Result string `json:"result"`
48 UserID int64 `json:"-"`
49 CreatedAt int64 `json:"created_at"`
50 ExpiresAt int64 `json:"expires_at"`
51 DecidedAt int64 `json:"decided_at"`
52 ExecutedAt int64 `json:"executed_at"`
53}
54
55const aiSessionColumns = `id, user_id, title, created_at, updated_at, message_count`
56const aiMessageColumns = `id, session_id, role, content, tool_calls, tool_call_id, name, status, created_at`
57const aiActionColumns = `id, session_id, message_id, tool_call_id, tool_name, arguments,
58 summary, risk, status, result, user_id, created_at, expires_at, decided_at, executed_at`
59
60// CreateAISession inserts a conversation.
61func (s *Store) CreateAISession(ctx context.Context, sess *AISession) error {
62 now := time.Now().Unix()
63 if sess.CreatedAt == 0 {
64 sess.CreatedAt = now
65 }
66 if sess.UpdatedAt == 0 {
67 sess.UpdatedAt = now
68 }
69 _, err := s.db.ExecContext(ctx,
70 `INSERT INTO ai_sessions(id, user_id, title, created_at, updated_at, message_count)
71 VALUES(?,?,?,?,?,?)`,
72 sess.ID, sess.UserID, sess.Title, sess.CreatedAt, sess.UpdatedAt, sess.MessageCount)
73 return err
74}
75
76func scanAISession(row interface{ Scan(...any) error }) (*AISession, error) {
77 var v AISession
78 err := row.Scan(&v.ID, &v.UserID, &v.Title, &v.CreatedAt, &v.UpdatedAt, &v.MessageCount)
79 if errors.Is(err, sql.ErrNoRows) {
80 return nil, ErrNotFound
81 }
82 if err != nil {
83 return nil, err
84 }
85 return &v, nil
86}
87
88// ListAISessions returns the newest conversations of one user.
89func (s *Store) ListAISessions(ctx context.Context, userID int64, limit int) ([]*AISession, error) {
90 if limit <= 0 || limit > 100 {
91 limit = 50
92 }
93 rows, err := s.db.QueryContext(ctx,
94 `SELECT `+aiSessionColumns+` FROM ai_sessions
95 WHERE user_id = ? ORDER BY updated_at DESC, created_at DESC LIMIT ?`,
96 userID, limit)
97 if err != nil {
98 return nil, err
99 }
100 defer rows.Close()
101 out := make([]*AISession, 0, limit)
102 for rows.Next() {
103 v, err := scanAISession(rows)
104 if err != nil {
105 return nil, err
106 }
107 out = append(out, v)
108 }
109 return out, rows.Err()
110}
111
112// AISessionByID loads one conversation owned by userID.
113func (s *Store) AISessionByID(ctx context.Context, id string, userID int64) (*AISession, error) {
114 row := s.db.QueryRowContext(ctx,
115 `SELECT `+aiSessionColumns+` FROM ai_sessions WHERE id = ? AND user_id = ?`, id, userID)
116 return scanAISession(row)
117}
118
119// RenameAISession updates the sidebar title.
120func (s *Store) RenameAISession(ctx context.Context, id string, userID int64, title string) error {
121 res, err := s.db.ExecContext(ctx,
122 `UPDATE ai_sessions SET title = ?, updated_at = ? WHERE id = ? AND user_id = ?`,
123 title, time.Now().Unix(), id, userID)
124 if err != nil {
125 return err
126 }
127 if n, _ := res.RowsAffected(); n == 0 {
128 return ErrNotFound
129 }
130 return nil
131}
132
133// DeleteAISession removes a conversation; messages and actions cascade.
134func (s *Store) DeleteAISession(ctx context.Context, id string, userID int64) error {
135 res, err := s.db.ExecContext(ctx, `DELETE FROM ai_sessions WHERE id = ? AND user_id = ?`, id, userID)
136 if err != nil {
137 return err
138 }
139 if n, _ := res.RowsAffected(); n == 0 {
140 return ErrNotFound
141 }
142 return nil
143}
144
145// AppendAIMessage stores one message and bumps the conversation counters.
146func (s *Store) AppendAIMessage(ctx context.Context, m *AIMessage) (int64, error) {
147 now := time.Now().Unix()
148 if m.CreatedAt == 0 {
149 m.CreatedAt = now
150 }
151 if m.Status == "" {
152 m.Status = "ok"
153 }
154 tx, err := s.db.BeginTx(ctx, nil)
155 if err != nil {
156 return 0, err
157 }
158 defer tx.Rollback()
159
160 res, err := tx.ExecContext(ctx,
161 `INSERT INTO ai_messages(session_id, role, content, tool_calls, tool_call_id, name, status, created_at)
162 VALUES(?,?,?,?,?,?,?,?)`,
163 m.SessionID, m.Role, m.Content, m.ToolCalls, m.ToolCallID, m.Name, m.Status, m.CreatedAt)
164 if err != nil {
165 return 0, err
166 }
167 id, err := res.LastInsertId()
168 if err != nil {
169 return 0, err
170 }
171 if _, err := tx.ExecContext(ctx,
172 `UPDATE ai_sessions SET updated_at = ?, message_count = message_count + 1 WHERE id = ?`,
173 now, m.SessionID); err != nil {
174 return 0, err
175 }
176 if err := tx.Commit(); err != nil {
177 return 0, err
178 }
179 m.ID = id
180 return id, nil
181}
182
183func scanAIMessage(row interface{ Scan(...any) error }) (*AIMessage, error) {
184 var v AIMessage
185 err := row.Scan(&v.ID, &v.SessionID, &v.Role, &v.Content, &v.ToolCalls,
186 &v.ToolCallID, &v.Name, &v.Status, &v.CreatedAt)
187 if errors.Is(err, sql.ErrNoRows) {
188 return nil, ErrNotFound
189 }
190 if err != nil {
191 return nil, err
192 }
193 return &v, nil
194}
195
196// ListAIMessages returns messages after afterID in display order.
197func (s *Store) ListAIMessages(ctx context.Context, sessionID string, afterID int64, limit int) ([]*AIMessage, error) {
198 if limit <= 0 || limit > 200 {
199 limit = 100
200 }
201 rows, err := s.db.QueryContext(ctx,
202 `SELECT `+aiMessageColumns+` FROM ai_messages
203 WHERE session_id = ? AND id > ? ORDER BY id ASC LIMIT ?`,
204 sessionID, afterID, limit)
205 if err != nil {
206 return nil, err
207 }
208 defer rows.Close()
209 out := make([]*AIMessage, 0, limit)
210 for rows.Next() {
211 v, err := scanAIMessage(rows)
212 if err != nil {
213 return nil, err
214 }
215 out = append(out, v)
216 }
217 return out, rows.Err()
218}
219
220// RecentAIMessages returns the newest limit messages in ascending order.
221func (s *Store) RecentAIMessages(ctx context.Context, sessionID string, limit int) ([]*AIMessage, error) {
222 if limit <= 0 || limit > 200 {
223 limit = 30
224 }
225 rows, err := s.db.QueryContext(ctx,
226 `SELECT `+aiMessageColumns+` FROM ai_messages
227 WHERE session_id = ? ORDER BY id DESC LIMIT ?`, sessionID, limit)
228 if err != nil {
229 return nil, err
230 }
231 defer rows.Close()
232 rev := make([]*AIMessage, 0, limit)
233 for rows.Next() {
234 v, err := scanAIMessage(rows)
235 if err != nil {
236 return nil, err
237 }
238 rev = append(rev, v)
239 }
240 out := make([]*AIMessage, 0, len(rev))
241 for i := len(rev) - 1; i >= 0; i-- {
242 out = append(out, rev[i])
243 }
244 return out, rows.Err()
245}
246
247// UpdateAIMessageStatus applies a message state such as error or aborted.
248func (s *Store) UpdateAIMessageStatus(ctx context.Context, id int64, status string) error {
249 _, err := s.db.ExecContext(ctx, `UPDATE ai_messages SET status = ? WHERE id = ?`, status, id)
250 return err
251}
252
253// CreateAIAction stores a tool call that needs human approval.
254func (s *Store) CreateAIAction(ctx context.Context, a *AIAction) error {
255 now := time.Now().Unix()
256 if a.CreatedAt == 0 {
257 a.CreatedAt = now
258 }
259 if a.ExpiresAt == 0 {
260 a.ExpiresAt = now + 600
261 }
262 if a.Status == "" {
263 a.Status = "pending"
264 }
265 _, err := s.db.ExecContext(ctx,
266 `INSERT INTO ai_actions(id, session_id, message_id, tool_call_id, tool_name, arguments,
267 summary, risk, status, result, user_id, created_at, expires_at, decided_at, executed_at)
268 VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
269 a.ID, a.SessionID, a.MessageID, a.ToolCallID, a.ToolName, a.Arguments,
270 a.Summary, a.Risk, a.Status, a.Result, a.UserID, a.CreatedAt, a.ExpiresAt,
271 a.DecidedAt, a.ExecutedAt)
272 return err
273}
274
275func scanAIAction(row interface{ Scan(...any) error }) (*AIAction, error) {
276 var v AIAction
277 err := row.Scan(&v.ID, &v.SessionID, &v.MessageID, &v.ToolCallID, &v.ToolName,
278 &v.Arguments, &v.Summary, &v.Risk, &v.Status, &v.Result, &v.UserID,
279 &v.CreatedAt, &v.ExpiresAt, &v.DecidedAt, &v.ExecutedAt)
280 if errors.Is(err, sql.ErrNoRows) {
281 return nil, ErrNotFound
282 }
283 if err != nil {
284 return nil, err
285 }
286 return &v, nil
287}
288
289// AIActionByID loads one pending or historical action.
290func (s *Store) AIActionByID(ctx context.Context, id string) (*AIAction, error) {
291 row := s.db.QueryRowContext(ctx, `SELECT `+aiActionColumns+` FROM ai_actions WHERE id = ?`, id)
292 return scanAIAction(row)
293}
294
295// PendingAIActions lists the approvals still blocking one conversation.
296func (s *Store) PendingAIActions(ctx context.Context, sessionID string) ([]*AIAction, error) {
297 rows, err := s.db.QueryContext(ctx,
298 `SELECT `+aiActionColumns+` FROM ai_actions
299 WHERE session_id = ? AND status = 'pending' ORDER BY created_at ASC, id ASC`, sessionID)
300 if err != nil {
301 return nil, err
302 }
303 defer rows.Close()
304 out := []*AIAction{}
305 for rows.Next() {
306 v, err := scanAIAction(rows)
307 if err != nil {
308 return nil, err
309 }
310 out = append(out, v)
311 }
312 return out, rows.Err()
313}
314
315// ResolveAIAction atomically claims a pending action for the given user.
316// It returns false when the action is missing, expired or already decided.
317func (s *Store) ResolveAIAction(ctx context.Context, id string, userID int64, status string) (bool, error) {
318 now := time.Now().Unix()
319 res, err := s.db.ExecContext(ctx,
320 `UPDATE ai_actions SET status = ?, decided_at = ?
321 WHERE id = ? AND user_id = ? AND status = 'pending' AND expires_at >= ?`,
322 status, now, id, userID, now)
323 if err != nil {
324 return false, err
325 }
326 n, err := res.RowsAffected()
327 if err != nil {
328 return false, err
329 }
330 return n > 0, nil
331}
332
333// FinishAIAction records the execution result.
334func (s *Store) FinishAIAction(ctx context.Context, id, status, result string) error {
335 _, err := s.db.ExecContext(ctx,
336 `UPDATE ai_actions SET status = ?, result = ?, executed_at = ? WHERE id = ?`,
337 status, result, time.Now().Unix(), id)
338 return err
339}
340
341// ExpireAIActions closes approvals that were left untouched for too long.
342func (s *Store) ExpireAIActions(ctx context.Context, now int64) (int64, error) {
343 res, err := s.db.ExecContext(ctx,
344 `UPDATE ai_actions SET status = 'expired' WHERE status = 'pending' AND expires_at < ?`, now)
345 if err != nil {
346 return 0, err
347 }
348 return res.RowsAffected()
349}
350
351// DeleteOldAISessions keeps the database bounded by removing old conversations.
352func (s *Store) DeleteOldAISessions(ctx context.Context, before int64) (int64, error) {
353 if before <= 0 {
354 return 0, fmt.Errorf("缺少时间边界")
355 }
356 res, err := s.db.ExecContext(ctx, `DELETE FROM ai_sessions WHERE updated_at < ?`, before)
357 if err != nil {
358 return 0, err
359 }
360 return res.RowsAffected()
361}