Files
agentik/server
subochev 5f0e0da361 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.
2026-09-22 05:21:01 +03:00
..

:server — HTTP/SSE фасад для :proto (KMP, JVM-only)

Что это

Ktor-маршрут, экспонирующий Agent из :proto в виде JSON-API: POST /agentik/conversations, POST /agentik/conversations/:id/send, GET /agentik/conversations/:id/events (SSE), GET /health, GET /agentik/conversations.

  • stateful — сервер не принимает полную историю, только новые сообщения. История хранится там, где развёрнут Agent.
  • декларативно — interface Agent → HTTP; никакой магии, никаких обёрток. Контракт и сериализация — тоже декларативные (kotlinx-json с snake_case-дискриминаторами).

Решает: позволяет собрать любой собственный front-end (CLI/TUI/Web/ IRC/MCP) общаясь с одним сервером по стабильному wire-контракту.

Где используется

  • :standalone подключает Route.agentikAgent(agent) в свой embedded Netty engine.
  • Любые клиенты (наши :client, :agentik-cli, или внешние web-фронтенды) идут через этот контракт.

Как подключить

// build.gradle.kts (KMP JVM target)
plugins { id("pw.binom.agentik.server-conventions") version "0.1.0" }
dependencies {
    api("pw.binom.agentik:server:0.1.0")
    api("pw.binom.agentik:proto:0.1.0")
}

// ваш код:
fun Application.module(agent: Agent) {
    install(ContentNegotiation) { json(agentikJson) }
    install(SSE)
    routing {
        route("/agentik") { agentikAgent(agent) }
    }
}

Версии

gradle/libs.versions.toml → [versions] agentik-server.

Эндпоинты (path по умолчанию /agentik, через agentikAgent(agent, "/my"))

Метод Путь Что делает
POST /conversations Создать диалог (body: {title?})
GET /conversations Список диалогов (по ?offset=&limit=)
GET /conversations/:id Снимок диалога + count
GET /conversations/:id/messages История сообщений (по ?after=)
POST /conversations/:id/rename Переименовать (body: {title})
DELETE /conversations/:id Удалить
POST /conversations/:id/send Send-флоу (body: {content:[…]} → SSE)
GET /conversations/:id/events Live подписка (SSE)
POST /conversations/:id/interrupt Прервать текущий send()

Content-Type: text/event-stream всегда для SSE, ноль-лишних заголовков. Сообщения: event: <name> (message, start_reasoning, start_response, append_text, append_image, end, interrupted, error) + data: <JSON>.

Тесты

./gradlew :server:jvmTest

Покрывают: маппинг JSON ↔ Event, SSE framing, error-handling, 404 / 400 ответы, корректную обработку Instant в kotlinx-datetime.

Чего здесь НЕТ

  • Никакого LLM-кода, tool-вызовов, прерываний. Только mapping Agent ↔ HTTP.
  • Никакой БД, никакого storage. Это задача Agent-имплементации.
  • Никакого CORS-конфига по умолчанию — добавляйте на свой engine.

Текущий статус

Используется продакшеном. Wire-контракт стабильный; новые Event'ы добавляются только с snake_case-дискриминаторами и строго обратно совместимо.