|
| 1 | +/* |
| 2 | + * Copyright (C) 2026 github.com/MaloneTalk |
| 3 | + * |
| 4 | + * This program is free software: you can redistribute it and/or modify |
| 5 | + * it under the terms of the GNU Affero General Public License as |
| 6 | + * published by the Free Software Foundation, either version 3 of the |
| 7 | + * License, or any later version. |
| 8 | + * |
| 9 | + * This program is distributed in the hope that it will be useful, |
| 10 | + * but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 11 | + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 12 | + * GNU Affero General Public License for more details. |
| 13 | + * |
| 14 | + * You should have received a copy of the GNU Affero General Public License |
| 15 | + * along with this program. If not, see <https://www.gnu.org/licenses/>. |
| 16 | + * limitations under the License. |
| 17 | + */ |
| 18 | +package io.github.malonetalk.agent; |
| 19 | + |
| 20 | +import io.agentscope.core.message.ContentBlock; |
| 21 | +import io.agentscope.core.message.Msg; |
| 22 | +import io.agentscope.core.message.MsgRole; |
| 23 | +import io.agentscope.core.message.TextBlock; |
| 24 | +import io.agentscope.core.message.ThinkingBlock; |
| 25 | +import io.agentscope.core.message.ToolResultBlock; |
| 26 | +import io.agentscope.core.message.ToolUseBlock; |
| 27 | +import io.agentscope.core.session.Session; |
| 28 | +import io.agentscope.core.session.mysql.MysqlSession; |
| 29 | +import io.agentscope.core.state.SessionKey; |
| 30 | +import io.agentscope.core.state.SimpleSessionKey; |
| 31 | +import io.github.malonetalk.dto.ChatStreamEvent; |
| 32 | +import io.github.malonetalk.dto.SessionInfo; |
| 33 | +import io.github.malonetalk.dto.TurnItem; |
| 34 | +import io.github.malonetalk.enums.ChatStreamEventType; |
| 35 | +import io.github.malonetalk.utils.MsgUtils; |
| 36 | +import lombok.extern.slf4j.Slf4j; |
| 37 | +import org.springframework.stereotype.Service; |
| 38 | + |
| 39 | +import javax.sql.DataSource; |
| 40 | +import java.sql.Connection; |
| 41 | +import java.sql.PreparedStatement; |
| 42 | +import java.sql.ResultSet; |
| 43 | +import java.util.ArrayList; |
| 44 | +import java.util.Collections; |
| 45 | +import java.util.HashMap; |
| 46 | +import java.util.List; |
| 47 | +import java.util.Map; |
| 48 | +import java.util.Set; |
| 49 | +import java.util.concurrent.ConcurrentHashMap; |
| 50 | +import java.util.stream.Collectors; |
| 51 | + |
| 52 | +@Slf4j |
| 53 | +@Service |
| 54 | +public class SessionService { |
| 55 | + |
| 56 | + private final DataSource dataSource; |
| 57 | + private final Map<String, Session> sessionCache = new ConcurrentHashMap<>(); |
| 58 | + |
| 59 | + public SessionService(DataSource dataSource) { |
| 60 | + this.dataSource = dataSource; |
| 61 | + } |
| 62 | + |
| 63 | + public Session getOrCreateSession(String sessionId) { |
| 64 | + return sessionCache.computeIfAbsent( |
| 65 | + sessionId, |
| 66 | + k -> new MysqlSession(dataSource, "data_agent", "agentscope_sessions", false)); |
| 67 | + } |
| 68 | + |
| 69 | + public List<Msg> getSessionDebug(String sessionId) { |
| 70 | + Session session = getOrCreateSession(sessionId); |
| 71 | + if (!session.exists(SimpleSessionKey.of(sessionId))) { |
| 72 | + return Collections.emptyList(); |
| 73 | + } |
| 74 | + return session.getList(SimpleSessionKey.of(sessionId), "memory_messages", Msg.class); |
| 75 | + } |
| 76 | + |
| 77 | + public List<TurnItem> getSessionHistory(String sessionId) { |
| 78 | + Session session = getOrCreateSession(sessionId); |
| 79 | + |
| 80 | + if (!session.exists(SimpleSessionKey.of(sessionId))) { |
| 81 | + return Collections.emptyList(); |
| 82 | + } |
| 83 | + |
| 84 | + List<Msg> messages = |
| 85 | + session.getList(SimpleSessionKey.of(sessionId), "memory_messages", Msg.class); |
| 86 | + |
| 87 | + List<TurnItem> turns = new ArrayList<>(); |
| 88 | + List<ContentBlock> agentBlocks = null; |
| 89 | + |
| 90 | + for (Msg msg : messages) { |
| 91 | + boolean isUser = msg.getRole() == MsgRole.USER; |
| 92 | + if (isUser) { |
| 93 | + if (agentBlocks != null) { |
| 94 | + turns.add(buildAgentTurn(agentBlocks)); |
| 95 | + agentBlocks = null; |
| 96 | + } |
| 97 | + String text = |
| 98 | + msg.getContent().stream() |
| 99 | + .filter(block -> block instanceof TextBlock) |
| 100 | + .map(block -> ((TextBlock) block).getText()) |
| 101 | + .filter(t -> t != null && !t.isEmpty()) |
| 102 | + .collect(Collectors.joining()); |
| 103 | + turns.add(new TurnItem(MsgRole.USER.name(), text, List.of())); |
| 104 | + } else { |
| 105 | + if (agentBlocks == null) { |
| 106 | + agentBlocks = new ArrayList<>(); |
| 107 | + } |
| 108 | + agentBlocks.addAll(msg.getContent()); |
| 109 | + } |
| 110 | + } |
| 111 | + if (agentBlocks != null) { |
| 112 | + turns.add(buildAgentTurn(agentBlocks)); |
| 113 | + } |
| 114 | + |
| 115 | + return turns; |
| 116 | + } |
| 117 | + |
| 118 | + private TurnItem buildAgentTurn(List<ContentBlock> blocks) { |
| 119 | + StringBuilder content = new StringBuilder(); |
| 120 | + List<ChatStreamEvent> traceSteps = new ArrayList<>(); |
| 121 | + |
| 122 | + for (ContentBlock block : blocks) { |
| 123 | + if (block instanceof TextBlock tb) { |
| 124 | + appendText(content, tb); |
| 125 | + } else if (block instanceof ThinkingBlock tb) { |
| 126 | + appendThinking(traceSteps, tb); |
| 127 | + } else if (block instanceof ToolUseBlock tub) { |
| 128 | + appendToolCall(traceSteps, tub); |
| 129 | + } else if (block instanceof ToolResultBlock trb) { |
| 130 | + appendToolResult(traceSteps, trb); |
| 131 | + } |
| 132 | + } |
| 133 | + |
| 134 | + return new TurnItem(MsgRole.ASSISTANT.name(), content.toString(), traceSteps); |
| 135 | + } |
| 136 | + |
| 137 | + private void appendText(StringBuilder content, TextBlock tb) { |
| 138 | + String text = tb.getText(); |
| 139 | + if (text != null && !text.isEmpty()) { |
| 140 | + content.append(text); |
| 141 | + } |
| 142 | + } |
| 143 | + |
| 144 | + private void appendThinking(List<ChatStreamEvent> traceSteps, ThinkingBlock tb) { |
| 145 | + String thinking = tb.getThinking(); |
| 146 | + if (thinking == null || thinking.isEmpty()) { |
| 147 | + return; |
| 148 | + } |
| 149 | + int lastIdx = traceSteps.size() - 1; |
| 150 | + if (lastIdx >= 0 && traceSteps.get(lastIdx).type() == ChatStreamEventType.THINKING) { |
| 151 | + String merged = |
| 152 | + (traceSteps.get(lastIdx).content() != null |
| 153 | + ? traceSteps.get(lastIdx).content() |
| 154 | + : "") |
| 155 | + + thinking; |
| 156 | + traceSteps.set(lastIdx, thinkingEvent(merged)); |
| 157 | + } else { |
| 158 | + traceSteps.add(thinkingEvent(thinking)); |
| 159 | + } |
| 160 | + } |
| 161 | + |
| 162 | + private void appendToolCall(List<ChatStreamEvent> traceSteps, ToolUseBlock tub) { |
| 163 | + traceSteps.add( |
| 164 | + new ChatStreamEvent( |
| 165 | + ChatStreamEventType.TOOL_CALL, |
| 166 | + null, |
| 167 | + false, |
| 168 | + null, |
| 169 | + new ChatStreamEvent.ToolCallInfo( |
| 170 | + tub.getId(), tub.getName(), tub.getInput()), |
| 171 | + null)); |
| 172 | + } |
| 173 | + |
| 174 | + private void appendToolResult(List<ChatStreamEvent> traceSteps, ToolResultBlock trb) { |
| 175 | + String outputText = |
| 176 | + trb.getOutput().stream() |
| 177 | + .filter(b -> b instanceof TextBlock) |
| 178 | + .map(b -> ((TextBlock) b).getText()) |
| 179 | + .filter(t -> t != null && !t.isEmpty()) |
| 180 | + .collect(Collectors.joining("\n")); |
| 181 | + traceSteps.add( |
| 182 | + new ChatStreamEvent( |
| 183 | + ChatStreamEventType.TOOL_RESULT, |
| 184 | + null, |
| 185 | + false, |
| 186 | + null, |
| 187 | + null, |
| 188 | + new ChatStreamEvent.ToolResultInfo( |
| 189 | + trb.getId(), trb.getName(), outputText))); |
| 190 | + } |
| 191 | + |
| 192 | + private static ChatStreamEvent thinkingEvent(String thinking) { |
| 193 | + return new ChatStreamEvent(ChatStreamEventType.THINKING, null, false, thinking, null, null); |
| 194 | + } |
| 195 | + |
| 196 | + public void clearSession(String sessionId) { |
| 197 | + Session session = sessionCache.remove(sessionId); |
| 198 | + if (session != null) { |
| 199 | + session.delete(SimpleSessionKey.of(sessionId)); |
| 200 | + } |
| 201 | + } |
| 202 | + |
| 203 | + public void clearAllSessions() { |
| 204 | + sessionCache.clear(); |
| 205 | + } |
| 206 | + |
| 207 | + public List<SessionInfo> listSessions() { |
| 208 | + MysqlSession session = |
| 209 | + new MysqlSession(dataSource, "data_agent", "agentscope_sessions", false); |
| 210 | + Set<SessionKey> keys = session.listSessionKeys(); |
| 211 | + |
| 212 | + if (keys == null || keys.isEmpty()) { |
| 213 | + return Collections.emptyList(); |
| 214 | + } |
| 215 | + |
| 216 | + Map<String, String[]> timestamps = new HashMap<>(); |
| 217 | + try (Connection conn = dataSource.getConnection(); |
| 218 | + PreparedStatement ps = |
| 219 | + conn.prepareStatement( |
| 220 | + "SELECT session_id, MIN(created_at), MAX(updated_at)" |
| 221 | + + " FROM agentscope_sessions GROUP BY session_id"); |
| 222 | + ResultSet rs = ps.executeQuery()) { |
| 223 | + while (rs.next()) { |
| 224 | + timestamps.put(rs.getString(1), new String[] {rs.getString(2), rs.getString(3)}); |
| 225 | + } |
| 226 | + } catch (Exception e) { |
| 227 | + log.error("Error listing session timestamps", e); |
| 228 | + } |
| 229 | + |
| 230 | + List<SessionInfo> result = new ArrayList<>(); |
| 231 | + for (SessionKey key : keys) { |
| 232 | + String sid = key.toIdentifier(); |
| 233 | + List<Msg> messages = session.getList(key, "memory_messages", Msg.class); |
| 234 | + |
| 235 | + String title = ""; |
| 236 | + if (messages != null) { |
| 237 | + for (Msg msg : messages) { |
| 238 | + if (msg.getRole() == MsgRole.USER) { |
| 239 | + title = MsgUtils.getTextContent(msg); |
| 240 | + if (title.length() > 30) { |
| 241 | + title = title.substring(0, 30); |
| 242 | + } |
| 243 | + break; |
| 244 | + } |
| 245 | + } |
| 246 | + } |
| 247 | + if (title.isEmpty()) { |
| 248 | + title = sid.length() > 20 ? sid.substring(0, 20) : sid; |
| 249 | + } |
| 250 | + |
| 251 | + String[] times = timestamps.getOrDefault(sid, new String[] {"", ""}); |
| 252 | + result.add(new SessionInfo(sid, title, times[0], times[1])); |
| 253 | + } |
| 254 | + |
| 255 | + result.sort((a, b) -> b.lastActiveAt().compareTo(a.lastActiveAt())); |
| 256 | + return result; |
| 257 | + } |
| 258 | +} |
0 commit comments