feat(client): client-side caching for conversation list via agent.outbox events

Adds `agent.conversationStore` (read-only view on `conversation` table) to
the :proto Agent interface, plus `agent.renameConversation(id, title?)`
command. Client-side cache in :client is built from a snapshot
(`remote.listFlow(0)` → `local.upsert(...)`) + live updates via
`outbox.agentEvents()` (Created/Deleted/Renamed/Touched).

Changes:
- :journal-api — split `ConversationStore` (read-only: get/list) and
  `MutableConversationStore` (CRUD: upsert/delete/rename/touch);
  `ConversationStore` gained `listFlow` (cold-flow paging via `list`).
- :outbox-api — `AgentEvent.Touched(date, id, updatedAt)` event so
  client cache stays fresh after `send()` (which bumps `updatedAt`).
- :proto.Agent — added `conversationStore: ConversationStore` property,
  added `renameConversation(id, title?): Instant?` command, removed
  `getConversations(offset, limit)` (now: `conversationStore.list(...)`).
- :server — `GET /conversations` now returns `List<ConversationRecord>`
  (lightweight metadata, no handle/image-support flags); `PATCH
  /conversations/{id}` uses `agent.renameConversation` and returns
  the updated `ConversationRecord`.
- :journal-inmemory — expanded targets to jvm+macos+linux+mingw (matches
  :client); moved `InMemoryMutableConversationStore` here from
  :storage-inmemory so :client can use it without pulling ios targets.
- :storage-inmemory — depends on :journal-inmemory.
- :storage-ksqlite — pre-staged rename `KsqliteConversationStore` →
  `KsqliteMutableConversationStore` to match the new interface split.
- :standalone — `ChatAgent` exposes `conversationStore` as a read-only
  view of its `mutableConversationStore`; emits `AgentEvent.Touched`
  after each `send()` (after `conversationStore.touch(id, ts)`).
- :client — new `HttpConversationStore` (read-only HTTP impl);
  `AgentikAgent` wraps the agent with `wrapWithLocalConversationCache`
  so the client sees an in-memory cache (snapshot + outbox events)
  instead of direct HTTP. Cache scope + HttpClient + background job
  all cancelled in `agent.close()`.
- :client/README — new «Кэш списка бесед» section with the
  `listFlow → upsert` / `agentEvents → apply` pattern and a note that
  `conversationStore` is read-only (writes only via Agent commands).

All 96 jvmTest tasks green.
This commit is contained in:
2026-09-22 05:21:01 +03:00
parent acb4ee6186
commit 5f0e0da361
29 changed files with 424 additions and 135 deletions
@@ -1,7 +1,6 @@
package pw.binom.agentik.proto
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import pw.binom.agentik.journal.ConversationStore
import pw.binom.agentik.journal.JournalStore
import pw.binom.agentik.outbox.OutboxStore
import kotlin.time.Instant
@@ -13,11 +12,16 @@ import kotlin.time.Instant
* [createConversation] возвращает [Conversation], который сам хранит историю
* и которому отправляют ходы через [Conversation.send].
*
* **Хранилища вынесены в [Agent.journal] и [Agent.outbox]**: оба read-only.
* События больше НЕ часть [Agent] (раньше были `events()`/`allEvents()`) —
* они теперь живут в [outbox] как `OutboxStore.events(after)` /
* `outbox.agentEvents(after)`. Это даёт единый путь для всех read-операций
* по хранилищу и убирает дублирование между протоколом и хранилищем.
* **Хранилища вынесены в [Agent.journal], [Agent.outbox] и
* [Agent.conversationStore]**: все три read-only views. События живут
* в [outbox] как `OutboxStore.events(after)` / `outbox.agentEvents(after)`.
* Это даёт единый путь для всех read-операций по хранилищу и убирает
* дублирование между протоколом и хранилищем.
*
* **Команды** (create / delete / rename) живут прямо на [Agent]. Они
* шлются клиентом и выполняются сервером — клиент **не** пишет в стор
* напрямую. Клиентский кэш [conversationStore] обновляется через
* `outbox.agentEvents()` (Created / Deleted / Renamed / Touched).
*/
interface Agent : AutoCloseable {
@@ -59,6 +63,22 @@ interface Agent : AutoCloseable {
*/
val outbox: OutboxStore
/**
* Read-only view на `conversation` table (id + title + timestamps).
*
* Используется HTTP-фасадом `:server` для endpoint'а
* `GET /{path}/conversations?offset=&limit=` — внешние клиенты
* получают лёгкую метадату (без handle'ов и image-support флагов)
* для рендера списка диалогов. Для активной работы (send / interrupt)
* клиент отдельно получает handle через [getConversation].
*
* **Read-only**: write-доступ только через `MutableConversationStore`
* внутри ChatAgent, не через [Agent] interface. Клиент модифицирует
* диалоги командами: [createConversation] / [deleteConversation] /
* [renameConversation].
*/
val conversationStore: ConversationStore
/** Создаёт новый stateful-диалог с агентом. */
fun createConversation(temp: Boolean): Conversation
@@ -68,19 +88,11 @@ interface Agent : AutoCloseable {
/** Удаляет диалог. Возвращает `true`, если диалог существовал и удалён. */
suspend fun deleteConversation(id: String): Boolean
/** Страница диалогов: не более [limit] штук, начиная с [offset]-го. */
suspend fun getConversations(offset: Int, limit: Int): List<Conversation>
/** Все диалоги, начиная с [offset], как поток: подгружает по [PAGE_SIZE] за раз. */
fun getConversations(offset: Int = 0): Flow<Conversation> = flow {
var skip = offset
while (true) {
val page = getConversations(skip, PAGE_SIZE)
if (page.isEmpty()) break
page.forEach { emit(it) }
skip += page.size
}
}
/**
* Переименовывает диалог; `null` для сброса заголовка. Возвращает новый
* `updatedAt` или `null`, если диалог не найден.
*/
suspend fun renameConversation(id: String, title: String?): Instant?
companion object {