package eu.llembas.android.api import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable import kotlinx.serialization.json.Json import kotlinx.serialization.json.JsonElement import kotlinx.serialization.json.JsonObject /** * The server's `/api/v2` shapes. Mirrors `api/v2/serialise.py` on the server; every class here * is exercised against the pinned `contract/` files by `ContractTest`, so a field the * server renamed fails a test here rather than on a phone. * * Unknown fields are ignored: adding a field is not a new API version, and an older app must * keep reading a newer server. */ val LembasJson = Json { ignoreUnknownKeys = true explicitNulls = false coerceInputValues = true isLenient = false } @Serializable data class Discovery( val service: String = "", val version: String = "", val name: String = "", @SerialName("base_url") val baseUrl: String = "", /** The device link's protocol: 3 from LLeMbas 2.0 on, which is what this app needs. */ val protocol: Int = 0, val protocols: List = emptyList(), @SerialName("app_api") val appApi: Int = 0, val login: Login = Login(), val scopes: List = emptyList(), ) { @Serializable data class Login(val device: DeviceLogin = DeviceLogin()) @Serializable data class DeviceLogin(val code: String = "", val token: String = "", val verify: String = "") } @Serializable data class DeviceCode( @SerialName("device_code") val deviceCode: String, @SerialName("user_code") val userCode: String, @SerialName("verification_uri") val verificationUri: String = "", @SerialName("verification_uri_complete") val verificationUriComplete: String = "", val interval: Int = 5, @SerialName("expires_in") val expiresIn: Int = 600, ) @Serializable data class DeviceToken( @SerialName("access_token") val accessToken: String? = null, val scope: String = "", val error: String? = null, val account: Account? = null, ) @Serializable data class Account(val id: String = "", val name: String = "", val email: String = "") @Serializable data class Me( val api: Int = 0, val version: String = "", val account: Account = Account(), val language: String = "", val theme: String = "", @SerialName("default_model") val defaultModel: String? = null, val permissions: Map = emptyMap(), val services: Map = emptyMap(), ) { /** * The language the app follows by default (`i18n.for_user`: the account's choice, else the * instance's); null when the server said none, so a kept earlier answer stands. */ val accountLanguage: String? get() = language.ifBlank { null } /** * The instance's speech-to-text, through the server (the assistant's LLeMbas voice input): * true or false as the server said it, null when it did not say. */ val speechToText: Boolean? get() = services["stt"] val hasSpeechToText: Boolean get() = speechToText == true /** The instance's text-to-speech (the assistant's voice reply, Read aloud). */ val hasTextToSpeech: Boolean get() = services["tts"] == true /** The instance makes pictures for this person (`image_generate`, in a chat). */ val hasImages: Boolean get() = services["images"] == true } @Serializable data class ModelInfo( val id: String, val name: String = "", val vision: Boolean = false, val tools: Boolean = false, val efforts: List = emptyList(), /** Whether the model's server stops thinking when asked: only then is `off` a level. */ @SerialName("thinking_switch") val thinkingSwitch: Boolean = false, /** The levels a chat offers, in order (harness spec 3.2.0): `off` first when switchable. */ val levels: List = emptyList(), /** The level a chat starts at when none was chosen. */ val effort: String = "", /** How the level is chosen: `none`, `switch` (Thinking on or off) or `slider`. */ val control: String = "", /** How many requests the model's server answers at once; null for no stated limit. */ val parallel: Int? = null, val context: Int = 0, /** The picture's path on the instance (`/api/v2/models/images/…`), read with the token. */ val image: String? = null, val default: Boolean = false, /** Whether a new chat on this model is offered subagents (server 2.0.0-beta.7); null from an older one. */ val subagents: SubagentsOffer? = null, ) { /** * The levels, for a server that says them; an older one said only `efforts`, offered after * an `off` that meant "the model's default" -- as the app showed it before. */ val offered: List get() = levels.ifEmpty { if (efforts.isEmpty()) emptyList() else listOf("off") + efforts } /** Which control the composer draws, by the server's word or, from an older one, by the count. */ val levelControl: String get() = control.takeIf { it in CONTROLS } ?: when { offered.size <= 1 -> "none" offered.size == 2 && "off" in offered -> "switch" else -> "slider" } /** The level in force: [chosen] when this model offers it, else its start level. */ fun level(chosen: String?): String = chosen?.takeIf { it in offered } ?: effort.takeIf { it in offered } ?: offered.firstOrNull { it != "off" } ?: offered.firstOrNull().orEmpty() /** For the Thinking switch: the level that is "on" (the one that is not `off`). */ val onLevel: String get() = offered.firstOrNull { it != "off" } ?: effort /** * Whether a new chat on this model is offered subagents: the server's word * (`subagents.offered`) when it says it. An older server did not, and then the app guesses * from the model alone: it serves two requests at once (`parallel` ≥ 2, or no stated * limit) and takes tools. */ val mayHaveTeam: Boolean get() = subagents?.offered ?: (tools && (parallel == null || parallel >= 2)) companion object { val CONTROLS = setOf("none", "switch", "slider") } } @Serializable data class ModelList( val models: List = emptyList(), /** The instance's cap on a chat's subagents (server 2.0.0-beta.7); null from an older one. */ @SerialName("subagents_cap") val subagentsCap: Int? = null, /** With `kind=agent` (spec 3.4.0 §14): whether a new agent chat may have subagents. */ @SerialName("agent_subagents") val agentSubagents: AgentSubagents? = null, ) /** * A new agent chat's Subagents fact (`/models?kind=agent&device=`): [offered] where the instance * and the person allow them; [deviceRuns] whether the chosen device runs them (it lists `agents` * and `tree`), null while it is not linked or none was named. */ @Serializable data class AgentSubagents(val offered: Boolean = false, @SerialName("device_runs") val deviceRuns: Boolean? = null) /** * Whether subagents are offered (harness spec 3.3.0, `subagents.md` §4): [offered] when * subagents are on and at least one model could serve; [namedOnly] when only a model the person * names in the chat could -- the chat's own serves one request at a time -- and the setting then * says so. [cap] is the instance's most, on a chat (not on a model). */ @Serializable data class SubagentsOffer(val offered: Boolean = false, @SerialName("named_only") val namedOnly: Boolean = false, val cap: Int? = null) @Serializable data class Folder( val id: String, val name: String = "", @SerialName("parent_id") val parentId: String? = null, val kind: String = "", val position: Int = 0, val collapsed: Boolean = false, ) @Serializable data class FolderEnvelope(val folder: Folder) /** * One hit of `GET /api/v2/search`: a chat (by [id]), a file (by [path]) or a memory. [snippet] is * plain text -- a chat's may be model output -- and [marks] the `[start, end)` ranges matched in it. */ @Serializable data class SearchHit( val kind: String = "", val id: String? = null, val title: String = "", val snippet: String = "", val marks: List> = emptyList(), val archived: Boolean = false, val agent: Boolean = false, val path: String? = null, ) @Serializable data class SearchGroup(val kind: String = "", val more: Boolean = false, val hits: List = emptyList()) @Serializable data class SearchResults( val q: String = "", @SerialName("in") val within: String = "", val offered: List = emptyList(), val results: List = emptyList(), ) { fun hits(kind: String): List = results.firstOrNull { it.kind == kind }?.hits.orEmpty() } /** One app release the server recommends (`GET /api/v2/apps`), with the page its files are on. */ @Serializable data class AppRelease(val version: String = "", val tag: String = "", val channel: String = "", val page: String = "") @Serializable data class ServerChannel(val version: String = "", val channel: String = "") /** * Which release of each app goes with this server: a stable server names only a stable app, a * beta server the newer of the app's stable and beta. Null for an app it recommends none of. */ @Serializable data class AppsInfo(val server: ServerChannel = ServerChannel(), val apps: Map = emptyMap()) { val android: AppRelease? get() = apps["android"] } /** A data group: whose records a memory is kept among. */ @Serializable data class DataGroup(val id: String = "", val name: String = "") /** * One memory (`/api/v2/memories`, Settings › Memory on the web): its text, who wrote it (`user` * or `model` -- a model's is model output, drawn as plain text), and its data group. */ @Serializable data class Memory( val id: String, val content: String = "", val author: String = "", @SerialName("data_group") val dataGroup: DataGroup = DataGroup(), @SerialName("created_at") val createdAt: String? = null, @SerialName("updated_at") val updatedAt: String? = null, ) { val byModel: Boolean get() = author == "model" } @Serializable data class MemoryList(val memories: List = emptyList(), val groups: List = emptyList()) @Serializable data class MemoryEnvelope(val memory: Memory) @Serializable data class FolderList(val folders: List = emptyList()) @Serializable data class Device(@SerialName("token_id") val tokenId: String? = null, val directory: String = "") @Serializable data class LinkedDevice(val id: String, val name: String = "", val host: String = "", val platform: String = "") @Serializable data class DeviceList(val devices: List = emptyList()) @Serializable data class Chat( val id: String, val kind: String = "chat", val title: String = "", val model: String = "", @SerialName("folder_id") val folderId: String? = null, val pinned: Boolean = false, val archived: Boolean = false, val temporary: Boolean = false, val unread: Boolean = false, val running: Boolean = false, val mode: String = "", val effort: String? = null, val device: Device? = null, /** An agent chat's session on its device (`lembas -s ` continues it); null until opened. */ @SerialName("device_session_id") val deviceSessionId: String? = null, @SerialName("parent_chat_id") val parentChatId: String? = null, @SerialName("created_at") val createdAt: String? = null, @SerialName("updated_at") val updatedAt: String? = null, @SerialName("system_prompt") val systemPrompt: String? = null, val plan: JsonObject? = null, /** The team's size: how many agents, its own included, the chat may have. */ val agents: AgentsSetting? = null, /** Whether this chat is offered subagents, and the cap (server 2.0.0-beta.7); null from an older one. */ val subagents: SubagentsOffer? = null, ) { val isAgent: Boolean get() = kind == "agent" } /** A chat's `agents {min, max}` (harness spec 3.2.0): `1 ≤ min ≤ max ≤` the instance's cap. */ @Serializable data class AgentsSetting(val min: Int = 1, val max: Int = 4) { companion object { /** The spec's default cap; an instance may set it lower, and then refuses past it (422). */ const val CAP = 32 } } @Serializable data class ChatPage(val chats: List = emptyList(), val more: Boolean = false) @Serializable data class ChatDetail(val chat: Chat, val messages: List = emptyList(), val more: Boolean = false, val live: String? = null) @Serializable data class MessagePage(val messages: List = emptyList(), val more: Boolean = false) @Serializable data class Unread(val unread: List = emptyList()) @Serializable data class Attachment( val id: String, val name: String = "", val mime: String = "", val size: Long = 0, val kind: String = "", val image: Boolean = false, val width: Int = 0, val height: Int = 0, ) @Serializable data class AttachmentEnvelope(val attachment: Attachment) @Serializable data class Metrics( @SerialName("prompt_tokens") val promptTokens: Int = 0, @SerialName("completion_tokens") val completionTokens: Int = 0, @SerialName("total_tokens") val totalTokens: Int = 0, @SerialName("context_tokens") val contextTokens: Int = 0, @SerialName("context_limit") val contextLimit: Int = 0, val estimated: Boolean = false, @SerialName("elapsed_ms") val elapsedMs: Long = 0, val rounds: Int = 1, @SerialName("thinking_ms") val thinkingMs: Long = 0, val percent: Int = 0, @SerialName("tok_s") val tokPerSecond: Double = 0.0, ) @Serializable data class ToolBlock(val kind: String = "tool", val title: String = "", val chips: List = emptyList(), val added: Int = 0, val removed: Int = 0) /** One tool call. What the tool wrote varies by tool, so the free-form parts stay JSON. */ @Serializable data class ToolCall( val id: String? = null, val name: String = "", val kind: String? = null, val status: String? = null, val args: JsonElement? = null, val query: String? = null, val purpose: String? = null, val why: String? = null, val text: String? = null, val error: String? = null, val detail: JsonElement? = null, val results: JsonElement? = null, val diff: String? = null, val exit: Int? = null, val hits: Int? = null, /** How long the call took, in milliseconds (spec 3.7.0: `tool_end`'s `ms`); null where it was not kept. */ val ms: Long? = null, val path: String? = null, val truncated: Boolean = false, val job: JsonElement? = null, val children: List? = null, /** The `show` tool's card: a file put in front of the person. Never its text. */ val show: ShowCard? = null, /** `image_generate`'s picture: the server's own attachment, by id, and its size. */ val image: GeneratedImage? = null, val block: ToolBlock = ToolBlock(), ) /** * A picture the instance made (`event["image"]`): an attachment of the chat's owner, fetched * with the token from `GET /api/v2/attachments/{id}` and nowhere else. Its size is known before * it loads, so the space it takes does not jump. */ @Serializable data class GeneratedImage(val id: String = "", val width: Int = 0, val height: Int = 0) /** * What a `show` call put in front of the person (`event["show"]`, harness spec 3.0.0): the * file's name and where it is, never its contents -- the viewer fetches those. A file from the * chat's own tree names its node and version; a file a linked device sent names the copy the * server kept (`shown_id`), with the tree's two ids empty. */ @Serializable data class ShowCard( val path: String = "", val name: String = "", /** `markdown`, `code`, `text` or `html`; anything else is read as `text`. */ val kind: String = "text", val language: String = "", val line: Int = 0, @SerialName("node_id") val nodeId: String = "", @SerialName("version_id") val versionId: String = "", val sha: String = "", val size: Long = 0, val mime: String = "", val source: String = "", @SerialName("shown_id") val shownId: String = "", ) { /** The kind the viewer draws: an unknown one is plain text, never something richer. */ val viewKind: String get() = if (kind in VIEW_KINDS) kind else "text" /** Which file, as the server's viewer routes take it: the device's copy, or node and version. */ val query: List> get() = if (shownId.isNotEmpty()) listOf("shown" to shownId) else listOf("node" to nodeId, "version" to versionId) companion object { val VIEW_KINDS = setOf("markdown", "code", "text", "html") } } // --- The person's files (`GET /files`, `GET /files/content`) ---------------------------------- /** One entry of a directory: `kind` is `file`, `dir` or `mount`. */ @Serializable data class FileEntry( val name: String = "", val path: String = "", val kind: String = "file", val size: Long = 0, val mime: String = "", @SerialName("updated_at") val updatedAt: String? = null, ) { /** A directory or a mount: something to open as a listing, not in the viewer. */ val isFolder: Boolean get() = kind == "dir" || kind == "mount" } /** A directory, through the person's own access. `parent` is null at `/`. */ @Serializable data class FileListing(val path: String = "/", val parent: String? = null, val entries: List = emptyList()) /** Why a file's text did not come: `reason` is `not_text` or `too_large`; `message` says it. */ @Serializable data class Withheld(val reason: String = "", val message: String = "") /** * A file's text, as the explorer's viewer reads it. An HTML file is its source, never rendered; * a file that is not text or is over 1 MB has an empty [text] and says why in [withheld]. */ @Serializable data class FileContent( val path: String = "", val name: String = "", val size: Long = 0, val mime: String = "", val kind: String = "text", val language: String = "", val sha: String = "", val text: String = "", val withheld: Withheld? = null, ) { /** The kind the viewer draws, by the `show` card's rule: anything unknown is plain text. */ val viewKind: String get() = if (kind in ShowCard.VIEW_KINDS) kind else "text" } @Serializable data class SteerNote(val id: String = "", val text: String = "") /** One step of a reply: `thinking`, `text`, `tools` or `steer`. */ @Serializable data class Step( val index: Int = 0, val kind: String, val open: Boolean = false, val text: String? = null, val label: String? = null, val markdown: String? = null, val calls: List = emptyList(), val messages: List = emptyList(), ) @Serializable data class Message( val id: String, val role: String, @SerialName("created_at") val createdAt: String? = null, val complete: Boolean = true, val stopped: Boolean = false, val error: String? = null, val queued: Boolean = false, val machine: Boolean = false, val origin: String = "", val model: String? = null, val attachments: List = emptyList(), val text: String? = null, val steps: List = emptyList(), val plan: JsonObject? = null, val metrics: Metrics? = null, /** A prompt queued behind a running reply: `{phase: queued, since, ahead}`; null otherwise. */ val progress: Progress? = null, ) { val isUser: Boolean get() = role == "user" } @Serializable data class Turn(val message: Message? = null, val reply: Message? = null) @Serializable data class NewChat(val chat: Chat, val message: Message? = null, val reply: Message? = null) @Serializable data class ChatEnvelope(val chat: Chat) @Serializable data class Option(val label: String, val description: String = "", val recommended: Boolean = false) @Serializable data class CardItem( val index: Int = 0, val key: String, val kind: String, val tool: String = "", val title: String = "", val header: String = "", val detail: String = "", val reason: String = "", val purpose: String = "", val options: List