|
14 | 14 | import java.util.List; |
15 | 15 | import java.util.Map; |
16 | 16 | import java.util.Objects; |
| 17 | +import java.util.Optional; |
17 | 18 |
|
18 | 19 | /** |
19 | 20 | * OpenCode Server HTTP 客户端,封装 REST API。 |
@@ -68,6 +69,42 @@ public List<Session> listSessions() { |
68 | 69 | return getList("/session", new GenericType<List<Session>>() {}); |
69 | 70 | } |
70 | 71 |
|
| 72 | + /** |
| 73 | + * 分页/过滤列出 sessions,对齐 Hermes {@code listSessions(limit, offset, source, includeChildren)}。 |
| 74 | + * <p>OpenCode Server {@code GET /session} 支持 {@code search}、{@code limit}、{@code start} 查询参数, |
| 75 | + * 避免全量拉取后再内存过滤。</p> |
| 76 | + * |
| 77 | + * @param search 服务端关键字过滤(匹配 title 等),为 null 则不过滤 |
| 78 | + * @param limit 最大返回条数,为 null 则不限制 |
| 79 | + * @param start 分页偏移量,为 null 则从 0 开始 |
| 80 | + * @return 匹配的 session 列表 |
| 81 | + */ |
| 82 | + public List<Session> listSessions(String search, Integer limit, Integer start) { |
| 83 | + HttpRequest req = unirest.get(url("/session")); |
| 84 | + if (search != null) req.queryString("search", search); |
| 85 | + if (limit != null) req.queryString("limit", limit); |
| 86 | + if (start != null) req.queryString("start", start); |
| 87 | + HttpResponse<List<Session>> resp = req.asObject(new GenericType<List<Session>>() {}); |
| 88 | + checkSuccess(resp); |
| 89 | + return resp.getBody(); |
| 90 | + } |
| 91 | + |
| 92 | + /** |
| 93 | + * 按 title 精确查找 session,用于「先找现有 session、找不到再创建」的复用场景。 |
| 94 | + * <p>先用 {@code search} 在服务端预过滤(减少传输量),再在客户端精确匹配 title。</p> |
| 95 | + * |
| 96 | + * @param title 期望的 session title |
| 97 | + * @return 命中的第一个 session,未命中返回 {@link Optional#empty()} |
| 98 | + */ |
| 99 | + public Optional<Session> findSessionByTitle(String title) { |
| 100 | + if (title == null || title.isEmpty()) { |
| 101 | + return Optional.empty(); |
| 102 | + } |
| 103 | + return listSessions(title, 50, null).stream() |
| 104 | + .filter(s -> Objects.equals(title, s.getTitle())) |
| 105 | + .findFirst(); |
| 106 | + } |
| 107 | + |
71 | 108 | public boolean deleteSession(String sessionId) { |
72 | 109 | HttpResponse<String> resp = unirest.delete(url("/session/" + sessionId)).asString(); |
73 | 110 | return resp.isSuccess(); |
@@ -134,11 +171,15 @@ private <T> T get(String path, Class<T> type) { |
134 | 171 |
|
135 | 172 | private <T> T getList(String path, GenericType<T> genericType) { |
136 | 173 | HttpResponse<T> resp = unirest.get(url(path)).asObject(genericType); |
| 174 | + checkSuccess(resp); |
| 175 | + return resp.getBody(); |
| 176 | + } |
| 177 | + |
| 178 | + private void checkSuccess(HttpResponse<?> resp) { |
137 | 179 | if (!resp.isSuccess()) { |
138 | 180 | throw new OpenCodeHttpException(resp.getStatus(), |
139 | 181 | resp.getBody() != null ? resp.getBody().toString() : ""); |
140 | 182 | } |
141 | | - return resp.getBody(); |
142 | 183 | } |
143 | 184 |
|
144 | 185 | private <T> T post(String path, Object body, Class<T> type) { |
|
0 commit comments