|
| 1 | +using ClawSharp.Core.Sessions; |
| 2 | +using Microsoft.Data.Sqlite; |
| 3 | +using System.Text.Json; |
| 4 | + |
| 5 | +namespace ClawSharp.Agent; |
| 6 | + |
| 7 | +/// <summary> |
| 8 | +/// SQLite-backed session manager with conversation history persistence. |
| 9 | +/// </summary> |
| 10 | +public class SqliteSessionManager : ISessionManager, IAsyncDisposable |
| 11 | +{ |
| 12 | + private readonly string _connectionString; |
| 13 | + private readonly SqliteConnection _connection; |
| 14 | + private readonly JsonSerializerOptions _jsonOptions = new() |
| 15 | + { |
| 16 | + PropertyNamingPolicy = JsonNamingPolicy.CamelCase |
| 17 | + }; |
| 18 | + private bool _disposed; |
| 19 | + |
| 20 | + public SqliteSessionManager(string connectionString) |
| 21 | + { |
| 22 | + // Handle various connection string formats |
| 23 | + _connectionString = connectionString switch |
| 24 | + { |
| 25 | + ":memory:" => "Data Source=file::memory:?cache=shared", |
| 26 | + _ when !connectionString.Contains("Data Source=", StringComparison.OrdinalIgnoreCase) |
| 27 | + => $"Data Source={connectionString}", |
| 28 | + _ => connectionString |
| 29 | + }; |
| 30 | + |
| 31 | + _connection = new SqliteConnection(_connectionString); |
| 32 | + _connection.Open(); |
| 33 | + InitializeSchema(); |
| 34 | + } |
| 35 | + |
| 36 | + private void InitializeSchema() |
| 37 | + { |
| 38 | + using var cmd = _connection.CreateCommand(); |
| 39 | + cmd.CommandText = """ |
| 40 | + CREATE TABLE IF NOT EXISTS sessions ( |
| 41 | + session_key TEXT PRIMARY KEY, |
| 42 | + channel TEXT NOT NULL, |
| 43 | + chat_id TEXT NOT NULL, |
| 44 | + history_json TEXT NOT NULL DEFAULT '[]', |
| 45 | + summary TEXT, |
| 46 | + created TEXT NOT NULL, |
| 47 | + last_active TEXT NOT NULL |
| 48 | + ); |
| 49 | + CREATE INDEX IF NOT EXISTS idx_sessions_channel_chat ON sessions(channel, chat_id); |
| 50 | + """; |
| 51 | + cmd.ExecuteNonQuery(); |
| 52 | + } |
| 53 | + |
| 54 | + public async Task<SessionContext> GetOrCreateAsync(string sessionKey, string channel, string chatId, CancellationToken ct = default) |
| 55 | + { |
| 56 | + await using var cmd = _connection.CreateCommand(); |
| 57 | + cmd.CommandText = """ |
| 58 | + SELECT session_key, channel, chat_id, history_json, summary, created, last_active |
| 59 | + FROM sessions WHERE session_key = @sessionKey |
| 60 | + """; |
| 61 | + cmd.Parameters.AddWithValue("@sessionKey", sessionKey); |
| 62 | + |
| 63 | + await using var reader = await cmd.ExecuteReaderAsync(ct); |
| 64 | + if (await reader.ReadAsync(ct)) |
| 65 | + { |
| 66 | + return ReadSession(reader); |
| 67 | + } |
| 68 | + |
| 69 | + // Create new session |
| 70 | + var now = DateTimeOffset.UtcNow.ToString("O"); |
| 71 | + await using var insertCmd = _connection.CreateCommand(); |
| 72 | + insertCmd.CommandText = """ |
| 73 | + INSERT INTO sessions (session_key, channel, chat_id, history_json, created, last_active) |
| 74 | + VALUES (@sessionKey, @channel, @chatId, @historyJson, @created, @lastActive) |
| 75 | + """; |
| 76 | + insertCmd.Parameters.AddWithValue("@sessionKey", sessionKey); |
| 77 | + insertCmd.Parameters.AddWithValue("@channel", channel); |
| 78 | + insertCmd.Parameters.AddWithValue("@chatId", chatId); |
| 79 | + insertCmd.Parameters.AddWithValue("@historyJson", "[]"); |
| 80 | + insertCmd.Parameters.AddWithValue("@created", now); |
| 81 | + insertCmd.Parameters.AddWithValue("@lastActive", now); |
| 82 | + |
| 83 | + await insertCmd.ExecuteNonQueryAsync(ct); |
| 84 | + |
| 85 | + return new SessionContext |
| 86 | + { |
| 87 | + SessionKey = sessionKey, |
| 88 | + Channel = channel, |
| 89 | + ChatId = chatId, |
| 90 | + History = [], |
| 91 | + Created = DateTimeOffset.UtcNow, |
| 92 | + LastActive = DateTimeOffset.UtcNow |
| 93 | + }; |
| 94 | + } |
| 95 | + |
| 96 | + public async Task SaveAsync(SessionContext session, CancellationToken ct = default) |
| 97 | + { |
| 98 | + var historyJson = JsonSerializer.Serialize(session.History, _jsonOptions); |
| 99 | + var now = DateTimeOffset.UtcNow.ToString("O"); |
| 100 | + |
| 101 | + await using var cmd = _connection.CreateCommand(); |
| 102 | + cmd.CommandText = """ |
| 103 | + INSERT INTO sessions (session_key, channel, chat_id, history_json, summary, created, last_active) |
| 104 | + VALUES (@sessionKey, @channel, @chatId, @historyJson, @summary, @created, @lastActive) |
| 105 | + ON CONFLICT(session_key) DO UPDATE SET |
| 106 | + history_json = @historyJson, |
| 107 | + summary = @summary, |
| 108 | + last_active = @lastActive |
| 109 | + """; |
| 110 | + cmd.Parameters.AddWithValue("@sessionKey", session.SessionKey); |
| 111 | + cmd.Parameters.AddWithValue("@channel", session.Channel); |
| 112 | + cmd.Parameters.AddWithValue("@chatId", session.ChatId); |
| 113 | + cmd.Parameters.AddWithValue("@historyJson", historyJson); |
| 114 | + cmd.Parameters.AddWithValue("@summary", session.Summary ?? (object)DBNull.Value); |
| 115 | + cmd.Parameters.AddWithValue("@created", session.Created.ToString("O")); |
| 116 | + cmd.Parameters.AddWithValue("@lastActive", now); |
| 117 | + |
| 118 | + await cmd.ExecuteNonQueryAsync(ct); |
| 119 | + } |
| 120 | + |
| 121 | + public async Task<IReadOnlyList<SessionContext>> ListAsync(CancellationToken ct = default) |
| 122 | + { |
| 123 | + await using var cmd = _connection.CreateCommand(); |
| 124 | + cmd.CommandText = """ |
| 125 | + SELECT session_key, channel, chat_id, history_json, summary, created, last_active |
| 126 | + FROM sessions ORDER BY last_active DESC |
| 127 | + """; |
| 128 | + |
| 129 | + var results = new List<SessionContext>(); |
| 130 | + await using var reader = await cmd.ExecuteReaderAsync(ct); |
| 131 | + while (await reader.ReadAsync(ct)) |
| 132 | + { |
| 133 | + results.Add(ReadSession(reader)); |
| 134 | + } |
| 135 | + return results; |
| 136 | + } |
| 137 | + |
| 138 | + public async Task DeleteAsync(string sessionKey, CancellationToken ct = default) |
| 139 | + { |
| 140 | + await using var cmd = _connection.CreateCommand(); |
| 141 | + cmd.CommandText = "DELETE FROM sessions WHERE session_key = @sessionKey"; |
| 142 | + cmd.Parameters.AddWithValue("@sessionKey", sessionKey); |
| 143 | + |
| 144 | + await cmd.ExecuteNonQueryAsync(ct); |
| 145 | + } |
| 146 | + |
| 147 | + /// <summary> |
| 148 | + /// Clears all sessions. Useful for testing. |
| 149 | + /// </summary> |
| 150 | + public async Task ClearAllAsync(CancellationToken ct = default) |
| 151 | + { |
| 152 | + await using var cmd = _connection.CreateCommand(); |
| 153 | + cmd.CommandText = "DELETE FROM sessions"; |
| 154 | + await cmd.ExecuteNonQueryAsync(ct); |
| 155 | + } |
| 156 | + |
| 157 | + private SessionContext ReadSession(SqliteDataReader reader) |
| 158 | + { |
| 159 | + var sessionKey = reader.GetString(0); |
| 160 | + var channel = reader.GetString(1); |
| 161 | + var chatId = reader.GetString(2); |
| 162 | + var historyJson = reader.GetString(3); |
| 163 | + var summary = reader.IsDBNull(4) ? null : reader.GetString(4); |
| 164 | + var created = DateTimeOffset.Parse(reader.GetString(5)); |
| 165 | + var lastActive = DateTimeOffset.Parse(reader.GetString(6)); |
| 166 | + |
| 167 | + var history = JsonSerializer.Deserialize<List<ClawSharp.Core.Providers.LlmMessage>>(historyJson, _jsonOptions) ?? []; |
| 168 | + |
| 169 | + return new SessionContext |
| 170 | + { |
| 171 | + SessionKey = sessionKey, |
| 172 | + Channel = channel, |
| 173 | + ChatId = chatId, |
| 174 | + History = history, |
| 175 | + Summary = summary, |
| 176 | + Created = created, |
| 177 | + LastActive = lastActive |
| 178 | + }; |
| 179 | + } |
| 180 | + |
| 181 | + public async ValueTask DisposeAsync() |
| 182 | + { |
| 183 | + if (!_disposed) |
| 184 | + { |
| 185 | + await _connection.CloseAsync(); |
| 186 | + await _connection.DisposeAsync(); |
| 187 | + _disposed = true; |
| 188 | + } |
| 189 | + } |
| 190 | +} |
0 commit comments