The contract is pinned to the server's dev at d726573: generated media, jobs, a new file that must be new
CI / check (push) Canceled after 0s
CI / check (push) Canceled after 0s
contract/ from the server's dev head d726573 (104 files; six new: tool_media, media_job, media_job_done, media_job_failed, media_jobs, file_create_exists; `capability` on the four lists of models). Strings regenerated from the same commit: no sentence moved. The shapes and the calls for them: a tool call's `media` and `media_job`, a job read and cancelled, bytes by a file's node id or one version of a path, `create: true` on a save (409 `exists` is FileExists with the server's sentence), `GET /mcp`, and `capability` -- the lists every model picker and the assistant's setting are filled from keep only models a chat can be on. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
15 files changed
+728
-26
No files matched your search
@@ -155,15 +155,19 @@ class ApiClient(val base: String, private val token: String, val http: OkHttpCli
|
||||
|
||||
suspend fun models(chatId: String? = null): List<ModelInfo> = modelList(chatId).models
|
||||
|
||||
/** The models with the instance's subagent cap; with [chatId], whether each is offered subagents on that chat. */
|
||||
suspend fun modelList(chatId: String? = null): ModelList = get(if (chatId != null) "/models?chat=$chatId" else "/models")
|
||||
/**
|
||||
* The models with the instance's subagent cap; with [chatId], whether each is offered subagents
|
||||
* on that chat. Only models a chat can be on (`capability` `chat`): this list is what every
|
||||
* picker and the assistant's model setting are filled from.
|
||||
*/
|
||||
suspend fun modelList(chatId: String? = null): ModelList = get<ModelList>(if (chatId != null) "/models?chat=$chatId" else "/models").forChat()
|
||||
|
||||
/** The models for a new agent chat on [deviceId], with whether it may have subagents (`agent_subagents`). */
|
||||
suspend fun agentModelList(deviceId: String?, directory: String? = null): ModelList = get(
|
||||
suspend fun agentModelList(deviceId: String?, directory: String? = null): ModelList = get<ModelList>(
|
||||
"/models?kind=agent" + deviceId?.let { "&device=" + segment(it) }.orEmpty() +
|
||||
// With a directory (spec 3.9.0) the answer carries `start`: the model a chat there starts on.
|
||||
directory?.takeIf { deviceId != null && it.isNotBlank() }?.let { "&directory=" + segment(it.trim()) }.orEmpty(),
|
||||
)
|
||||
).forChat()
|
||||
|
||||
suspend fun folders(): List<Folder> = get<FolderList>("/folders").folders
|
||||
|
||||
@@ -659,26 +663,35 @@ class ApiClient(val base: String, private val token: String, val http: OkHttpCli
|
||||
* Save a text file. [base] is the `sha` the file had when it was opened: when it holds
|
||||
* something else by now the server writes nothing and this throws [SaveConflict] with its
|
||||
* sentence, unless [force]. Without a [base] nothing is compared, and a path with no file
|
||||
* makes one.
|
||||
* makes one. With [create] the file must be new: where something is already at the path the
|
||||
* server writes nothing (409, `exists`) and this throws [FileExists] with its sentence -- an
|
||||
* older server knows no `create` and writes as before.
|
||||
*/
|
||||
suspend fun saveFile(path: String, text: String, base: String? = null, force: Boolean = false): FileContent = withContext(Dispatchers.IO) {
|
||||
suspend fun saveFile(path: String, text: String, base: String? = null, force: Boolean = false, create: Boolean = false): FileContent {
|
||||
val body = buildJsonObject {
|
||||
put("path", path)
|
||||
put("text", text)
|
||||
base?.takeIf { it.isNotBlank() }?.let { put("base", it) }
|
||||
if (force) put("force", true)
|
||||
if (create) put("create", true)
|
||||
}
|
||||
http.newCall(authed("$v2/files/content").put(body.toString().toRequestBody(JSON)).build()).await().use { response ->
|
||||
val said = runCatching { response.body?.string().orEmpty() }.getOrDefault("")
|
||||
if (response.code == 409) {
|
||||
val conflict = runCatching { LembasJson.parseToJsonElement(said) as? JsonObject }.getOrNull() ?: JsonObject(emptyMap())
|
||||
if ((conflict["conflict"] as? JsonPrimitive)?.content == "true") {
|
||||
throw SaveConflict(refusal(said).orEmpty(), (conflict["sha"] as? JsonPrimitive)?.takeUnless { it is JsonNull }?.content.orEmpty())
|
||||
}
|
||||
val request = authed("$v2/files/content").put(body.toString().toRequestBody(JSON)).build()
|
||||
return withContext(Dispatchers.IO) { http.newCall(request).await().use { response -> saved(response) } }
|
||||
}
|
||||
|
||||
/** A save's answer: the file as it is now, or what refused it. */
|
||||
private fun saved(response: Response): FileContent {
|
||||
val said = runCatching { response.body?.string().orEmpty() }.getOrDefault("")
|
||||
if (response.code == 409) {
|
||||
val conflict = runCatching { LembasJson.parseToJsonElement(said) as? JsonObject }.getOrNull() ?: JsonObject(emptyMap())
|
||||
if ((conflict["conflict"] as? JsonPrimitive)?.content == "true") {
|
||||
throw SaveConflict(refusal(said).orEmpty(), (conflict["sha"] as? JsonPrimitive)?.takeUnless { it is JsonNull }?.content.orEmpty())
|
||||
}
|
||||
if (!response.isSuccessful) throw ApiException(response.code, refusal(said) ?: "The server answered ${response.code}.")
|
||||
LembasJson.decodeFromString(FileContent.serializer(), said)
|
||||
// A new file whose name is taken: nothing was written, and the sentence says what is there.
|
||||
if ((conflict["exists"] as? JsonPrimitive)?.content == "true") throw FileExists(refusal(said).orEmpty())
|
||||
}
|
||||
if (!response.isSuccessful) throw ApiException(response.code, refusal(said) ?: "The server answered ${response.code}.")
|
||||
return LembasJson.decodeFromString(FileContent.serializer(), said)
|
||||
}
|
||||
|
||||
suspend fun trash(): TrashList = get("/files/trash")
|
||||
@@ -714,12 +727,19 @@ class ApiClient(val base: String, private val token: String, val http: OkHttpCli
|
||||
* The request for a file's bytes (`/files/raw`), or for [range] of them. The token goes in
|
||||
* the Authorization header, as on every call: the address names the path and nothing else.
|
||||
*/
|
||||
fun rawFile(path: String, range: LongRange? = null, inline: Boolean = false): Request = authed(
|
||||
filesUrl(
|
||||
"/raw",
|
||||
"path" to path,
|
||||
"inline" to if (inline) "1" else null,
|
||||
),
|
||||
fun rawFile(path: String, range: LongRange? = null, inline: Boolean = false): Request = raw(Raw.Path(path), range, inline)
|
||||
|
||||
/**
|
||||
* The request for [what]'s bytes, or for [range] of them: a file of the tree by its path (one
|
||||
* [Raw.Path.version] of it, where named), a file by its node id wherever it is now, or a chat's
|
||||
* attachment. Always with the token in the header and never in the address.
|
||||
*/
|
||||
fun raw(what: Raw, range: LongRange? = null, inline: Boolean = false): Request = authed(
|
||||
when (what) {
|
||||
is Raw.Path -> filesUrl("/raw", "path" to what.path, "version" to what.version?.ifBlank { null }, "inline" to if (inline) "1" else null)
|
||||
is Raw.Node -> filesUrl("/raw", "node" to what.id, "inline" to if (inline) "1" else null)
|
||||
is Raw.Attached -> "$v2/attachments/${segment(what.id)}"
|
||||
},
|
||||
)
|
||||
.header("Accept", "*/*")
|
||||
.apply { range?.let { header("Range", "bytes=${it.first}-${it.last}") } }
|
||||
@@ -767,7 +787,10 @@ class ApiClient(val base: String, private val token: String, val http: OkHttpCli
|
||||
* blocking, on whatever thread asks (never the main one). A server that answers the whole
|
||||
* file to a range that does not start at 0 is refused rather than read from the wrong place.
|
||||
*/
|
||||
fun rawBytes(path: String, from: Long, to: Long): ByteArray = http.newCall(rawFile(path, from..to)).execute().use { response ->
|
||||
fun rawBytes(path: String, from: Long, to: Long): ByteArray = rawBytes(Raw.Path(path), from, to)
|
||||
|
||||
/** The same for any [Raw]: a file by its node id is read a piece at a time as one by its path is. */
|
||||
fun rawBytes(what: Raw, from: Long, to: Long): ByteArray = http.newCall(raw(what, from..to)).execute().use { response ->
|
||||
if (!response.isSuccessful) throw ApiException(response.code, detail(response))
|
||||
if (response.code != 206 && from > 0) throw ApiException(416, "")
|
||||
val want = to - from + 1
|
||||
@@ -787,6 +810,21 @@ class ApiClient(val base: String, private val token: String, val http: OkHttpCli
|
||||
.build()
|
||||
.toString()
|
||||
|
||||
// --- Generated media's jobs, and the MCP servers ----------------------------------------------
|
||||
|
||||
/** A chat's long generations, newest first (at most 50); with [active] only those under way. */
|
||||
suspend fun mediaJobs(chatId: String, active: Boolean = false): List<MediaJob> =
|
||||
get<MediaJobList>("/media/jobs?chat_id=${segment(chatId)}" + if (active) "&active=true" else "").jobs
|
||||
|
||||
/** One job as it stands; somebody else's, or one that is gone, is a 404 in the server's words. */
|
||||
suspend fun mediaJob(id: String): MediaJob = get("/media/jobs/${segment(id)}")
|
||||
|
||||
/** Stop a job: the job as it is after. One that has ended stays what it was, so this is safe to repeat. */
|
||||
suspend fun cancelMediaJob(id: String): MediaJob = call(authed("$v2/media/jobs/${segment(id)}").delete().build(), MediaJob.serializer())
|
||||
|
||||
/** The MCP servers whose tools this person's chats may be offered, and how each is signed in to. */
|
||||
suspend fun mcpServers(): List<McpServer> = get<McpServerList>("/mcp").servers
|
||||
|
||||
// --- Push --------------------------------------------------------------------------------
|
||||
suspend fun pushKey(): PushKey = get("/push")
|
||||
|
||||
|
||||
@@ -0,0 +1,167 @@
|
||||
package eu.llembas.android.api
|
||||
|
||||
import kotlinx.serialization.SerialName
|
||||
import kotlinx.serialization.Serializable
|
||||
|
||||
// What a model made, as the app is told of it (`contract/tool_media.json`, `media_job*.json`,
|
||||
// `mcp_servers.json`): a tool call's typed result, a long generation's job, and -- because they
|
||||
// arrived with the same server -- the instance's MCP servers and how each is signed in to.
|
||||
|
||||
/**
|
||||
* A file a tool call made: [kind] is what was asked for (`image`, `image_edit`, `video`, `music`,
|
||||
* `model3d`), and the file is in the person's Files at [path] -- a moment's truth, since they may
|
||||
* move it; [nodeId] names it wherever it is. Its bytes are `GET /files/raw?node=`. [width],
|
||||
* [height] and [seconds] are 0 where the server did not know them.
|
||||
*/
|
||||
@Serializable
|
||||
data class GeneratedMedia(
|
||||
val kind: String = "",
|
||||
val path: String = "",
|
||||
@SerialName("node_id") val nodeId: String = "",
|
||||
@SerialName("version_id") val versionId: String = "",
|
||||
val name: String = "",
|
||||
val mime: String = "",
|
||||
val size: Long = 0,
|
||||
val width: Int = 0,
|
||||
val height: Int = 0,
|
||||
val seconds: Double = 0.0,
|
||||
) {
|
||||
/** How the card shows it, by what was asked for: an unknown kind is its details, never a player. */
|
||||
val view: MediaView
|
||||
get() = when (kind) {
|
||||
"image", "image_edit" -> MediaView.Picture
|
||||
"video" -> MediaView.Video
|
||||
"music" -> MediaView.Sound
|
||||
else -> MediaView.Details
|
||||
}
|
||||
|
||||
/** What to call it: its name, else the last name of its path. */
|
||||
val title: String get() = name.ifBlank { FileKinds.name(path) }
|
||||
}
|
||||
|
||||
/** What a generated file's card is: a picture drawn, a player, or (a 3D model, anything unknown) the file's details. */
|
||||
enum class MediaView { Picture, Video, Sound, Details }
|
||||
|
||||
/** The job a tool call started (`media_job`): [state] as it was when the call returned. */
|
||||
@Serializable
|
||||
data class MediaJobRef(val id: String = "", val kind: String = "", val state: String = "")
|
||||
|
||||
/** What a finished job was counted as; an empty [currency] is the instance's own. */
|
||||
@Serializable
|
||||
data class MediaCost(val amount: Double = 0.0, val currency: String = "")
|
||||
|
||||
/**
|
||||
* A long generation (`GET /media/jobs/{id}`): `queued` and `running` are under way, `done` has
|
||||
* its [result], `failed`, `cancelled` and `expired` say why in [error] -- the server's sentence,
|
||||
* for the person. [seconds] is how long it has taken so far, or took. [told]: the chat was woken
|
||||
* with a reply about it.
|
||||
*/
|
||||
@Serializable
|
||||
data class MediaJob(
|
||||
val id: String = "",
|
||||
val kind: String = "",
|
||||
val state: String = "",
|
||||
val active: Boolean = false,
|
||||
@SerialName("chat_id") val chatId: String? = null,
|
||||
@SerialName("message_id") val messageId: String? = null,
|
||||
val source: String = "",
|
||||
val prompt: String = "",
|
||||
val started: String? = null,
|
||||
val ended: String? = null,
|
||||
val deadline: String? = null,
|
||||
val seconds: Double = 0.0,
|
||||
val error: String = "",
|
||||
val result: GeneratedMedia? = null,
|
||||
val cost: MediaCost? = null,
|
||||
val told: Boolean = false,
|
||||
) {
|
||||
/** Still to end: by the server's word, or by a state that is one of the two that are under way. */
|
||||
val underWay: Boolean get() = active || state in ACTIVE
|
||||
|
||||
/** Ended some way other than with a file. */
|
||||
val unsuccessful: Boolean get() = !underWay && state != DONE
|
||||
|
||||
companion object {
|
||||
val ACTIVE = setOf("queued", "running")
|
||||
const val DONE = "done"
|
||||
const val CANCELLED = "cancelled"
|
||||
|
||||
/** A job known only by the call that started it. */
|
||||
fun of(ref: MediaJobRef): MediaJob = MediaJob(id = ref.id, kind = ref.kind, state = ref.state, active = ref.state in ACTIVE)
|
||||
}
|
||||
}
|
||||
|
||||
@Serializable
|
||||
data class MediaJobList(val jobs: List<MediaJob> = emptyList())
|
||||
|
||||
/**
|
||||
* A new file that was not made because something is already called that (409, `exists: true`):
|
||||
* the server's sentence. Nothing was written.
|
||||
*/
|
||||
class FileExists(message: String) : java.io.IOException(message)
|
||||
|
||||
/**
|
||||
* How an MCP server is signed in to: [kind] `none`, `secret` or `oauth`; [state] `ready`,
|
||||
* `signed_in`, `signed_out` or `needs_signin`. [account] is who the provider says signed in -- a
|
||||
* stranger's text, drawn as plain text. [signinUrl] is a page of the instance to open in a
|
||||
* browser, where the person signs in to the instance itself with its cookie: the app's token is
|
||||
* never part of it.
|
||||
*/
|
||||
@Serializable
|
||||
data class McpAuth(
|
||||
val kind: String = "none",
|
||||
val state: String = "ready",
|
||||
val shared: Boolean = false,
|
||||
val account: String = "",
|
||||
@SerialName("expires_at") val expiresAt: String? = null,
|
||||
val renews: Boolean = false,
|
||||
@SerialName("signin_url") val signinUrl: String? = null,
|
||||
) {
|
||||
/** The server's tools are not offered until somebody signs in. */
|
||||
val needsSignIn: Boolean get() = state == "signed_out" || state == "needs_signin"
|
||||
}
|
||||
|
||||
@Serializable
|
||||
data class McpServer(val id: String = "", val slug: String = "", val name: String = "", val tools: Int = 0, val auth: McpAuth = McpAuth()) {
|
||||
val label: String get() = name.ifBlank { slug.ifBlank { id } }
|
||||
}
|
||||
|
||||
@Serializable
|
||||
data class McpServerList(val servers: List<McpServer> = emptyList())
|
||||
|
||||
/**
|
||||
* The address the browser is sent to for a sign-in: always a page of the instance the app is
|
||||
* signed in to ([base]). An address on that origin is taken as it is; a path alone, or an
|
||||
* address the instance wrote with another name for itself, is that path on [base] -- so nothing
|
||||
* the list says can send the person to another host. Null for no address, or one that is no
|
||||
* http(s) page.
|
||||
*/
|
||||
fun signInAddress(base: String, url: String?): String? {
|
||||
val said = url?.trim().orEmpty()
|
||||
if (said.isEmpty()) return null
|
||||
val want = runCatching { java.net.URI(said) }.getOrNull() ?: return null
|
||||
val home = runCatching { java.net.URI(base) }.getOrNull() ?: return null
|
||||
if (want.scheme != null && want.scheme.lowercase() !in setOf("http", "https")) return null
|
||||
val path = want.rawPath.orEmpty()
|
||||
if (!path.startsWith("/") || path.startsWith("//")) return null
|
||||
|
||||
fun port(u: java.net.URI) = when {
|
||||
u.port >= 0 -> u.port
|
||||
u.scheme.equals("https", true) -> 443
|
||||
else -> 80
|
||||
}
|
||||
val same = want.scheme != null && want.scheme.equals(home.scheme, true) && want.host != null && want.host.equals(home.host, true) &&
|
||||
port(want) == port(home) && want.userInfo == null
|
||||
return if (same) said else base.trimEnd('/') + path + want.rawQuery?.let { "?$it" }.orEmpty()
|
||||
}
|
||||
|
||||
/** Which bytes of the instance are asked for: a file of the tree (or one version of it), a file by its id, or a chat's attachment. */
|
||||
sealed interface Raw {
|
||||
data class Path(val path: String, val version: String? = null) : Raw
|
||||
|
||||
/** A file by its node id, wherever it is now: what a generated file's result carries. */
|
||||
data class Node(val id: String) : Raw
|
||||
|
||||
/** A chat's attachment. Answered whole: a player gets a copy, not a stream. */
|
||||
data class Attached(val id: String) : Raw
|
||||
}
|
||||
@@ -127,7 +127,16 @@ data class ModelInfo(
|
||||
val provider: String = "",
|
||||
/** The connection's name, for telling two models with one [id] apart. */
|
||||
val connection: String = "",
|
||||
/**
|
||||
* What the model is for (server 2.0.0-beta.17): `chat`, or a word for something a chat cannot
|
||||
* start on (`embedding`, and later `image`, `video`, …). A server that does not say it offers
|
||||
* only models to chat with.
|
||||
*/
|
||||
val capability: String = CHAT,
|
||||
) {
|
||||
/** Whether a chat can be on it: the one capability this app's pickers offer. An unknown word is not one. */
|
||||
val forChat: Boolean get() = capability == CHAT
|
||||
|
||||
/** What this model is chosen, kept and sent by: its [ref], or its [id] from a server without refs. */
|
||||
val key: String get() = ref.ifBlank { id }
|
||||
|
||||
@@ -162,9 +171,13 @@ data class ModelInfo(
|
||||
|
||||
companion object {
|
||||
val CONTROLS = setOf("none", "switch", "slider")
|
||||
const val CHAT = "chat"
|
||||
}
|
||||
}
|
||||
|
||||
/** The models a chat can be on, of a list: what every model picker and the assistant's model setting offer. */
|
||||
fun List<ModelInfo>.forChat(): List<ModelInfo> = filter { it.forChat }
|
||||
|
||||
/**
|
||||
* The model a name means, in a list: by its `ref`, else the first with that `id` -- which is
|
||||
* what a bare id names on the server too. So a name kept from before refs (a setting, a chat's
|
||||
@@ -212,7 +225,10 @@ data class ModelList(
|
||||
@SerialName("agent_subagents") val agentSubagents: AgentSubagents? = null,
|
||||
/** With `kind=agent`, a device and a directory (spec 3.9.0): the model a new agent chat there starts on. */
|
||||
val start: StartModel? = null,
|
||||
)
|
||||
) {
|
||||
/** The same answer with only the models a chat can be on. */
|
||||
fun forChat(): ModelList = if (models.all { it.forChat }) this else copy(models = models.forChat())
|
||||
}
|
||||
|
||||
/**
|
||||
* A new agent chat's Subagents fact (`/models?kind=agent&device=`): [offered] where the instance
|
||||
@@ -510,6 +526,10 @@ data class ToolCall(
|
||||
val show: ShowCard? = null,
|
||||
/** `image_generate`'s picture: the server's own attachment, by id, and its size. */
|
||||
val image: GeneratedImage? = null,
|
||||
/** The file the call made (a picture, video, music, a 3D model), which is in the person's Files. */
|
||||
val media: GeneratedMedia? = null,
|
||||
/** A generation that takes minutes: the job the call started, as it was when the call returned. */
|
||||
@SerialName("media_job") val mediaJob: MediaJobRef? = null,
|
||||
val block: ToolBlock = ToolBlock(),
|
||||
)
|
||||
|
||||
|
||||
Reference in new issue
Block a user