- One address rule (api/Address.kt): scheme in any case, host lower-cased, path, query and fragment dropped; an http:// address is answered at the address step (this app needs https). - User-Agent llembas-android/<version> on every request, and the same string as the device code's client_id (the server only stores and shows it). - A 401 of the instance's own (WWW-Authenticate: Bearer realm="lembas") marks the instance whose token it was as signed out: nothing more is asked with it, its pages stay underneath a page that offers the sign-in in one step, and nothing else is forgotten. A 403 stays the server's sentence; a 401 passed on from a provider behind /v1 signs nobody out. - Streams: 45 s of silence is a broken connection (the server's keepalive is every 15 s on all three routes); reconnect 1 s doubling to 60 s, jittered ±20 %, short again only after 30 s of health; a 429 waits for Retry-After. - A sentence for each failure: unreachable, timeout, certificate not trusted, not LLeMbas, "the server answered N", too old, too new. Sign-in polls end by their real reason and survive a dropped network or a restarting server. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
1003 lines
50 KiB
Kotlin
1003 lines
50 KiB
Kotlin
package eu.llembas.android.api
|
|
|
|
import kotlinx.coroutines.CoroutineStart
|
|
import kotlinx.coroutines.Dispatchers
|
|
import kotlinx.coroutines.awaitCancellation
|
|
import kotlinx.coroutines.ensureActive
|
|
import kotlinx.coroutines.launch
|
|
import kotlinx.coroutines.suspendCancellableCoroutine
|
|
import kotlinx.coroutines.withContext
|
|
import kotlinx.serialization.KSerializer
|
|
import kotlinx.serialization.json.JsonArray
|
|
import kotlinx.serialization.json.JsonNull
|
|
import kotlinx.serialization.json.JsonObject
|
|
import kotlinx.serialization.json.JsonPrimitive
|
|
import kotlinx.serialization.json.buildJsonObject
|
|
import kotlinx.serialization.json.put
|
|
import kotlinx.serialization.serializer
|
|
import okhttp3.Call
|
|
import okhttp3.Callback
|
|
import okhttp3.HttpUrl.Companion.toHttpUrl
|
|
import okhttp3.MediaType.Companion.toMediaType
|
|
import okhttp3.MultipartBody
|
|
import okhttp3.OkHttpClient
|
|
import okhttp3.Request
|
|
import okhttp3.RequestBody
|
|
import okhttp3.RequestBody.Companion.toRequestBody
|
|
import okhttp3.Response
|
|
import java.io.IOException
|
|
import java.io.OutputStream
|
|
import java.util.concurrent.TimeUnit
|
|
import kotlin.coroutines.resumeWithException
|
|
|
|
/** Where a new agent chat runs: a linked device ([LinkedDevice.id]) and a folder on it. */
|
|
data class AgentTarget(val device: String, val directory: String = "")
|
|
|
|
/**
|
|
* A refusal from the server, in its own words (`{"detail": "…"}`). [retryAfter] is the seconds a
|
|
* 429 asked the caller to wait (`Retry-After`), where it said so.
|
|
*/
|
|
class ApiException(val status: Int, message: String, val retryAfter: Long? = null) : IOException(message)
|
|
|
|
/** An address that answered, and is no LLeMbas instance: no discovery document, or another service's. */
|
|
class NotLembas : IOException("Not a LLeMbas instance.")
|
|
|
|
private val JSON = "application/json; charset=utf-8".toMediaType()
|
|
|
|
/** One HTTP client for the whole app: one connection pool, one TLS setup. */
|
|
val SharedHttp: OkHttpClient by lazy {
|
|
OkHttpClient.Builder()
|
|
.connectTimeout(15, TimeUnit.SECONDS)
|
|
.readTimeout(60, TimeUnit.SECONDS)
|
|
.writeTimeout(120, TimeUnit.SECONDS)
|
|
// Every request says which app asks, and a token the instance refuses is heard once, here.
|
|
.addInterceptor(Identity())
|
|
.build()
|
|
}
|
|
|
|
suspend fun Call.await(): Response = suspendCancellableCoroutine { cont ->
|
|
enqueue(
|
|
object : Callback {
|
|
override fun onResponse(call: Call, response: Response) = cont.resumeWith(Result.success(response))
|
|
|
|
override fun onFailure(call: Call, e: IOException) {
|
|
if (!cont.isCancelled) cont.resumeWithException(e)
|
|
}
|
|
},
|
|
)
|
|
cont.invokeOnCancellation { runCatching { cancel() } }
|
|
}
|
|
|
|
/** The calls that need no token: finding the instance and signing in. */
|
|
class Doorstep(private val http: OkHttpClient = SharedHttp) {
|
|
suspend fun discover(base: String): Discovery {
|
|
val response = http.newCall(Request.Builder().url("$base/.well-known/lembas.json").build()).await()
|
|
return response.use {
|
|
// No such document: something else lives at the address. Any other refusal -- a proxy
|
|
// whose server is down (502), a server that is starting -- is the server's answer,
|
|
// said with its number: it may well be a LLeMbas instance.
|
|
if (it.code == 404) throw NotLembas()
|
|
if (!it.isSuccessful) throw ApiException(it.code, "")
|
|
val text = it.body?.string().orEmpty()
|
|
// A page, or another program's JSON, is not the document either.
|
|
runCatching { LembasJson.decodeFromString(Discovery.serializer(), text) }.getOrNull() ?: throw NotLembas()
|
|
}
|
|
}
|
|
|
|
suspend fun deviceCode(url: String, deviceName: String, model: String): DeviceCode {
|
|
val body = buildJsonObject {
|
|
put("scope", "app models")
|
|
put("client_id", USER_AGENT)
|
|
put("device_name", deviceName)
|
|
put("device_host", model)
|
|
put("device_platform", "android")
|
|
}
|
|
val response = http.newCall(post(url, body)).await()
|
|
return response.use {
|
|
if (!it.isSuccessful) throw ApiException(it.code, detail(it))
|
|
LembasJson.decodeFromString(DeviceCode.serializer(), it.body!!.string())
|
|
}
|
|
}
|
|
|
|
/**
|
|
* One poll. A pending login is a 400 with `authorization_pending` -- not a failure. An answer
|
|
* that is no such document (a proxy's 502 page, a 429) is the server's refusal with its
|
|
* number, never "the code expired".
|
|
*/
|
|
suspend fun deviceToken(url: String, deviceCode: String): DeviceToken {
|
|
val body = buildJsonObject {
|
|
put("grant_type", "urn:ietf:params:oauth:grant-type:device_code")
|
|
put("device_code", deviceCode)
|
|
}
|
|
val response = http.newCall(post(url, body)).await()
|
|
return response.use {
|
|
val text = it.body?.string().orEmpty()
|
|
val said = runCatching { LembasJson.decodeFromString(DeviceToken.serializer(), text) }.getOrNull()
|
|
if (said != null && (said.accessToken != null || said.error != null)) return@use said
|
|
throw ApiException(it.code, refusal(text).orEmpty(), retryAfterSeconds(it.header("Retry-After")))
|
|
}
|
|
}
|
|
|
|
private fun post(url: String, body: JsonObject) = Request.Builder().url(url).post(body.toString().toRequestBody(JSON)).build()
|
|
}
|
|
|
|
private fun agentsJson(agents: AgentsSetting) = buildJsonObject {
|
|
put("min", agents.min)
|
|
put("max", agents.max)
|
|
}
|
|
|
|
internal fun detail(response: Response): String {
|
|
val text = runCatching { response.body?.string().orEmpty() }.getOrDefault("")
|
|
return refusal(text) ?: "The server answered ${response.code}."
|
|
}
|
|
|
|
/**
|
|
* The server's own sentence in a refusal's body: `detail` on `/api/v2`, OpenAI's shape
|
|
* (`error.message`) on `/v1`, where speech lives, and the sign-in's (`error_description`, RFC
|
|
* 8628). Null when the body says none of them.
|
|
*/
|
|
internal fun refusal(body: String): String? = runCatching {
|
|
val said = LembasJson.parseToJsonElement(body) as JsonObject
|
|
fun words(of: Any?): String? = (of as? JsonPrimitive)?.takeUnless { it is JsonNull }?.content?.ifBlank { null }
|
|
words(said["detail"]) ?: words((said["error"] as? JsonObject)?.get("message")) ?: words(said["error_description"])
|
|
}.getOrNull()
|
|
|
|
/**
|
|
* Everything the app asks one instance, with its token. Every call is the server's
|
|
* `/api/v2` (or `/v1` for speech), and every refusal comes back as an [ApiException]
|
|
* carrying the server's own sentence, which is what the app shows.
|
|
*/
|
|
class ApiClient(val base: String, private val token: String, val http: OkHttpClient = SharedHttp) {
|
|
private val v2 = "$base/api/v2"
|
|
|
|
fun authed(url: String): Request.Builder = Request.Builder().url(url).header("Authorization", "Bearer $token").header("Accept", "application/json")
|
|
|
|
private suspend fun <T> call(request: Request, serializer: KSerializer<T>): T = withContext(Dispatchers.IO) {
|
|
http.newCall(request).await().use { response ->
|
|
if (!response.isSuccessful) throw ApiException(response.code, detail(response))
|
|
LembasJson.decodeFromString(serializer, response.body!!.string())
|
|
}
|
|
}
|
|
|
|
private suspend fun empty(request: Request) = withContext(Dispatchers.IO) {
|
|
http.newCall(request).await().use { response ->
|
|
if (!response.isSuccessful) throw ApiException(response.code, detail(response))
|
|
}
|
|
}
|
|
|
|
private suspend inline fun <reified T> get(path: String): T = call(authed("$v2$path").get().build(), serializer())
|
|
|
|
private suspend inline fun <reified T> send(method: String, path: String, body: JsonObject?): T =
|
|
call(authed("$v2$path").method(method, (body ?: JsonObject(emptyMap())).toString().toRequestBody(JSON)).build(), serializer())
|
|
|
|
// --- Account -----------------------------------------------------------------------------
|
|
suspend fun me(): Me = get("/me")
|
|
|
|
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. 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<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
|
|
|
|
/** A new folder, at the top or inside [parentId] (`folder.manage`; nesting is capped). */
|
|
suspend fun createFolder(name: String, parentId: String? = null): Folder = send<FolderEnvelope>(
|
|
"POST",
|
|
"/folders",
|
|
buildJsonObject {
|
|
put("name", name)
|
|
if (parentId != null) put("parent_id", parentId)
|
|
},
|
|
).folder
|
|
|
|
/** Any of `name`, `parent_id`, `collapsed`. */
|
|
suspend fun updateFolder(id: String, changes: JsonObject): Folder = send<FolderEnvelope>("PATCH", "/folders/${segment(id)}", changes).folder
|
|
|
|
/** The folder and the folders inside it; their chats fall back to no folder. */
|
|
suspend fun deleteFolder(id: String) = empty(authed("$v2/folders/${segment(id)}").delete().build())
|
|
|
|
/** The app releases this server recommends; 404 from a server older than the route. */
|
|
suspend fun apps(): AppsInfo = get("/apps")
|
|
|
|
/**
|
|
* What `@` offers in an agent chat: the device's files matching [q], from the chat's
|
|
* directory ([chatId]) or, before the chat exists, from the folder chosen for it ([cwd]).
|
|
*/
|
|
suspend fun deviceFiles(deviceId: String, q: String, chatId: String? = null, cwd: String? = null): DeviceFiles = get(
|
|
"/devices/${segment(deviceId)}/files?q=${segment(q)}" +
|
|
chatId?.let { "&chat=${segment(it)}" }.orEmpty() +
|
|
cwd?.takeIf { chatId == null && it.isNotBlank() }?.let { "&cwd=${segment(it.trim())}" }.orEmpty(),
|
|
)
|
|
|
|
/** What `@` offers from the server for [q]: the chat's earlier attachments, files of the tree, a web address. */
|
|
suspend fun mentions(q: String, chatId: String? = null): Mentions = get("/mentions?q=${segment(q)}" + (chatId?.let { "&chat=${segment(it)}" } ?: ""))
|
|
|
|
/**
|
|
* Attach without uploading: a copy of an earlier attachment, a file of the tree as it is now,
|
|
* or a web page's text -- whichever [mention] is. 404 for what cannot be reached, 400 for a
|
|
* page that cannot be fetched.
|
|
*/
|
|
suspend fun attachFrom(mention: Mention, chatId: String? = null): Attachment = send<AttachmentEnvelope>(
|
|
"POST",
|
|
"/attachments/from",
|
|
buildJsonObject {
|
|
when (mention.kind) {
|
|
"attachment" -> put("attachment", mention.id)
|
|
"url" -> put("url", mention.url)
|
|
else -> put("path", mention.path)
|
|
}
|
|
chatId?.let { put("chat", it) }
|
|
},
|
|
).attachment
|
|
|
|
/** The web's search in JSON: chats by their words (and meaning, where indexed), files, memories. */
|
|
suspend fun search(q: String, within: String = "all", limit: Int = 20): SearchResults = get("/search?q=${segment(q)}&in=${segment(within)}&limit=$limit")
|
|
|
|
// --- Memory (`library.use`) -----------------------------------------------------------------
|
|
|
|
/** The person's memories, every data group, and the groups they may file one in. */
|
|
suspend fun memories(): MemoryList = get("/memories")
|
|
|
|
suspend fun addMemory(content: String, groupId: String? = null): Memory = send<MemoryEnvelope>(
|
|
"POST",
|
|
"/memories",
|
|
buildJsonObject {
|
|
put("content", content)
|
|
if (groupId != null) put("data_group_id", groupId)
|
|
},
|
|
).memory
|
|
|
|
suspend fun editMemory(id: String, content: String): Memory =
|
|
send<MemoryEnvelope>("PATCH", "/memories/${segment(id)}", buildJsonObject { put("content", content) }).memory
|
|
|
|
suspend fun forgetMemory(id: String) = empty(authed("$v2/memories/${segment(id)}").delete().build())
|
|
|
|
suspend fun devices(): List<LinkedDevice> = get<DeviceList>("/devices").devices
|
|
|
|
/**
|
|
* A directory on a linked device, for choosing where an agent chat or an Agentic schedule
|
|
* works; without a [path], the device's places. No listing is still an answer: its `code`
|
|
* and `error` say why.
|
|
*/
|
|
suspend fun deviceDirectories(deviceId: String, path: String? = null): DeviceDirectory =
|
|
get("/devices/${segment(deviceId)}/directories" + path?.takeIf { it.isNotEmpty() }?.let { "?path=" + segment(it) }.orEmpty())
|
|
|
|
/** The token revokes itself (`lembas logout`'s route). */
|
|
suspend fun signOut() = empty(authed("$base/api/v1/token").delete().build())
|
|
|
|
// --- Chats -------------------------------------------------------------------------------
|
|
suspend fun chats(kind: String = "", archived: Boolean = false, before: String? = null): ChatPage {
|
|
val url = "$v2/chats".toHttpUrl().newBuilder()
|
|
.addQueryParameter("archived", archived.toString())
|
|
.apply { if (kind.isNotEmpty()) addQueryParameter("kind", kind) }
|
|
.apply { before?.let { addQueryParameter("before", it) } }
|
|
.build()
|
|
return call(authed(url.toString()).get().build(), ChatPage.serializer())
|
|
}
|
|
|
|
suspend fun unread(): List<String> = get<Unread>("/chats/unread").unread
|
|
|
|
suspend fun chat(id: String): ChatDetail = get("/chats/$id")
|
|
|
|
suspend fun messages(chatId: String, before: String): MessagePage = get("/chats/$chatId/messages?before=$before")
|
|
|
|
suspend fun createChat(
|
|
text: String,
|
|
attachments: List<String> = emptyList(),
|
|
model: String? = null,
|
|
temporary: Boolean = false,
|
|
effort: String? = null,
|
|
mode: String? = null,
|
|
agent: AgentTarget? = null,
|
|
agents: AgentsSetting? = null,
|
|
forceTool: String? = null,
|
|
): NewChat = send(
|
|
"POST",
|
|
"/chats",
|
|
buildJsonObject {
|
|
put("text", text)
|
|
put("attachments", JsonArray(attachments.map { JsonPrimitive(it) }))
|
|
model?.let { put("model", it) }
|
|
effort?.let { put("effort", it) }
|
|
mode?.let { put("mode", it) }
|
|
agents?.let { put("agents", agentsJson(it)) }
|
|
put("temporary", temporary)
|
|
forceTool?.let { put("force_tool", it) }
|
|
put("client", CAPABILITIES)
|
|
// An agent chat runs on a linked device; an empty directory is the device's first
|
|
// allowed one. A device that is no longer linked makes it an ordinary chat on the
|
|
// server, rather than losing the message.
|
|
agent?.let {
|
|
put("kind", "agent")
|
|
put("device", it.device)
|
|
if (it.directory.isNotBlank()) put("directory", it.directory.trim())
|
|
}
|
|
},
|
|
)
|
|
|
|
/** A turn. [forceTool] makes the model call that tool (the server allows `image_generate` only). */
|
|
suspend fun sendMessage(chatId: String, text: String, attachments: List<String> = emptyList(), forceTool: String? = null): Turn = send(
|
|
"POST",
|
|
"/chats/$chatId/messages",
|
|
buildJsonObject {
|
|
put("text", text)
|
|
put("attachments", JsonArray(attachments.map { JsonPrimitive(it) }))
|
|
forceTool?.let { put("force_tool", it) }
|
|
put("client", CAPABILITIES)
|
|
},
|
|
)
|
|
|
|
suspend fun updateChat(chatId: String, changes: JsonObject): Chat = send<ChatEnvelope>("PATCH", "/chats/$chatId", changes).chat
|
|
|
|
/** The team's size, both ends at once: the server checks the pair (422 outside its bounds). */
|
|
suspend fun setAgents(chatId: String, agents: AgentsSetting): Chat = updateChat(chatId, buildJsonObject { put("agents", agentsJson(agents)) })
|
|
|
|
suspend fun deleteChat(chatId: String) = empty(authed("$v2/chats/$chatId").delete().build())
|
|
|
|
suspend fun stop(chatId: String, messageId: String) =
|
|
empty(authed("$v2/chats/$chatId/messages/$messageId/stop").post(ByteArray(0).toRequestBody(null)).build())
|
|
|
|
// Every request that can start a reply says what this app can do, as a message does: the
|
|
// server then knows who the reply is written for however it was asked for.
|
|
suspend fun edit(chatId: String, messageId: String, text: String): Turn = send(
|
|
"POST",
|
|
"/chats/$chatId/messages/$messageId/edit",
|
|
buildJsonObject {
|
|
put("text", text)
|
|
put("client", CAPABILITIES)
|
|
},
|
|
)
|
|
|
|
/**
|
|
* Send a message that waits (`queued`) now: the message as it is after, and the reply started
|
|
* for it, as a message sent answers. 409 in the instance's words while a reply is being
|
|
* written in the chat, and when the message no longer waits.
|
|
*/
|
|
suspend fun sendWaiting(chatId: String, messageId: String): Turn = send("POST", "/chats/$chatId/messages/${segment(messageId)}/send", DECLARED)
|
|
|
|
/** Withdraw a message that waits: its row is gone. 409 in words when it no longer waits, 404 when it is not there. */
|
|
suspend fun discardWaiting(chatId: String, messageId: String): Discarded =
|
|
call(authed("$v2/chats/$chatId/messages/${segment(messageId)}/discard").post(emptyBody()).build(), Discarded.serializer())
|
|
|
|
suspend fun regenerate(chatId: String, messageId: String): Turn = send("POST", "/chats/$chatId/messages/$messageId/regenerate", DECLARED)
|
|
|
|
suspend fun continueChat(chatId: String): Turn = send("POST", "/chats/$chatId/continue", DECLARED)
|
|
|
|
suspend fun executePlan(chatId: String): Turn = send("POST", "/chats/$chatId/plan/execute", DECLARED)
|
|
|
|
suspend fun answer(chatId: String, cardId: String, answer: CardAnswer) {
|
|
val body = LembasJson.encodeToString(CardAnswer.serializer(), answer).toRequestBody(JSON)
|
|
empty(authed("$v2/chats/$chatId/interactions/$cardId").post(body).build())
|
|
}
|
|
|
|
// --- The activity panel, background agents and the team -----------------------------------
|
|
|
|
/** Everything the panel shows; `context = false` leaves out the costly context count. */
|
|
suspend fun activity(chatId: String, context: Boolean = true): Activity = get<ActivityEnvelope>("/chats/$chatId/activity?context=$context").activity
|
|
|
|
/** The events route: an `activity` frame whenever the panel's facts change. */
|
|
fun activityEvents(chatId: String): Request = authed("$v2/chats/$chatId/activity/events").header("Accept", "text/event-stream").build()
|
|
|
|
/** One background agent and its whole conversation, read-only. `kind` is `member` or `job`. */
|
|
suspend fun agent(chatId: String, kind: String, id: String): AgentDetail = get("/chats/$chatId/agents/${segment(kind)}/${segment(id)}")
|
|
|
|
/** The chat's subagent tree and room (spec 3.4.0); a 404 from a server without it. */
|
|
suspend fun tree(chatId: String): TreeView = get("/chats/$chatId/tree")
|
|
|
|
/** A subagent's conversation by its id (`s1`), read-only; 409 while an agent chat's device is away. */
|
|
suspend fun subagentTranscript(chatId: String, id: String): SubagentTranscript = get("/chats/$chatId/subagents/${segment(id)}/transcript")
|
|
|
|
/** Stop a background agent (a member leaves the team with those under it). */
|
|
suspend fun stopAgent(chatId: String, kind: String, id: String): List<String> =
|
|
send<Stopped>("POST", "/chats/$chatId/agents/${segment(kind)}/${segment(id)}/stop", null).stopped
|
|
|
|
/**
|
|
* Summarise the earlier turns now and stop sending them (the activity sheet's Compact). The
|
|
* server refuses in its own words (409) while a reply is being written or with nothing to
|
|
* summarise; the transcript is read again after, for the divider it leaves.
|
|
*/
|
|
suspend fun compact(chatId: String) = empty(authed("$v2/chats/$chatId/compact").post(ByteArray(0).toRequestBody(null)).build())
|
|
|
|
suspend fun team(chatId: String, since: Int = 0): TeamView = get<TeamEnvelope>("/chats/$chatId/team?since=$since").team
|
|
|
|
suspend fun stopMember(chatId: String, name: String): List<String> = send<Stopped>("POST", "/chats/$chatId/team/${segment(name)}/stop", null).stopped
|
|
|
|
// --- Scheduled tasks (`/api/v2/schedules`; shapes in api/Schedules.kt) ----------------------
|
|
|
|
/** Every schedule of this person, newest first, each with its last run. */
|
|
suspend fun schedules(): List<Schedule> = get<ScheduleList>("/schedules").schedules
|
|
|
|
suspend fun schedule(id: String): Schedule = get<ScheduleEnvelope>("/schedules/${segment(id)}").schedule
|
|
|
|
/** A page of a schedule's runs, newest first; [before] is the last run's id of the page before. */
|
|
suspend fun scheduleRuns(id: String, before: String? = null, limit: Int = 20): ScheduleRuns =
|
|
get("/schedules/${segment(id)}/runs?limit=$limit" + (before?.let { "&before=${segment(it)}" } ?: ""))
|
|
|
|
/** One run and its result in full (Markdown a model wrote: untrusted). */
|
|
suspend fun scheduleRun(id: String, runId: String): RunResult = get("/schedules/${segment(id)}/runs/${segment(runId)}")
|
|
|
|
/** Words to a schedule: title, instruction, rule, the rule in words, the next runs. Saves nothing. */
|
|
suspend fun compileSchedule(words: String, model: String? = null): ScheduleCompiled = send(
|
|
"POST",
|
|
"/schedules/compile",
|
|
buildJsonObject {
|
|
put("text", words)
|
|
model?.let { put("model", it) }
|
|
},
|
|
)
|
|
|
|
/** A rule read back: cleaned, in words, and its next runs. An empty rule cannot run. */
|
|
suspend fun previewRule(rule: JsonObject): RulePreview = send("POST", "/schedules/preview", buildJsonObject { put("rule", rule) })
|
|
|
|
/**
|
|
* Save what the compile made of [words]: a new schedule (201), or with [id] the one being
|
|
* edited. The words go along as the schedule's `request`, so editing starts from them.
|
|
*/
|
|
suspend fun saveSchedule(
|
|
compiled: ScheduleCompiled,
|
|
words: String,
|
|
id: String? = null,
|
|
notify: String? = null,
|
|
notifyWhen: String = "",
|
|
where: WhereToRun = WhereToRun.Leave,
|
|
model: String? = null,
|
|
watch: WatchCommand? = null,
|
|
): Schedule {
|
|
val body = buildJsonObject {
|
|
// The type (spec 3.9.0): Agentic is a schedule with a computer, Chat one without. Left
|
|
// out where the form did not say, so a schedule is never moved by a form that did not read it.
|
|
when (where) {
|
|
WhereToRun.Leave -> Unit
|
|
|
|
WhereToRun.Server -> put("runs_on", JsonNull)
|
|
|
|
is WhereToRun.Computer -> {
|
|
put(
|
|
"runs_on",
|
|
buildJsonObject {
|
|
put("device", where.device)
|
|
put("cwd", where.cwd)
|
|
put("mode", where.mode)
|
|
where.approvalWaitMinutes?.let { put("approval_wait_minutes", it) }
|
|
},
|
|
)
|
|
}
|
|
}
|
|
// The model, where the form says one: empty is the folder's usual model for an
|
|
// Agentic schedule, asked of the computer as each run starts.
|
|
model?.let { put("model", it) }
|
|
// The watched command, where the form says one: none at all is "watch nothing".
|
|
watch?.let { said ->
|
|
if (said.command.isBlank()) {
|
|
put("watch", JsonNull)
|
|
} else {
|
|
put(
|
|
"watch",
|
|
buildJsonObject {
|
|
put("kind", "command")
|
|
put("command", said.command)
|
|
said.timeoutS?.let { put("timeout_s", it) }
|
|
},
|
|
)
|
|
}
|
|
}
|
|
put("title", compiled.title)
|
|
put("instruction", compiled.instruction)
|
|
put("rule", compiled.rule)
|
|
put("target", compiled.target)
|
|
if (id == null) put("request", words)
|
|
// Notify when (spec 3.8.0): left out where the form did not say, so an older server is sent nothing new.
|
|
if (notify != null) {
|
|
put("notify", notify)
|
|
// The person's own words, or none: an empty condition is the server's default, in its own words.
|
|
if (notify == "when") put("notify_when", notifyWhen.trim())
|
|
}
|
|
}
|
|
return if (id == null) {
|
|
send<ScheduleEnvelope>("POST", "/schedules", body).schedule
|
|
} else {
|
|
send<ScheduleEnvelope>("PATCH", "/schedules/${segment(id)}", body).schedule
|
|
}
|
|
}
|
|
|
|
// --- Reports (`schedule.use`) ---------------------------------------------------------------
|
|
|
|
/** The reports, newest first; [unread] only those not read yet, [schedule] only one schedule's. */
|
|
suspend fun reports(unread: Boolean = false, schedule: String? = null): List<Report> {
|
|
val asked = listOfNotNull(if (unread) "unread=1" else null, schedule?.let { "schedule=" + segment(it) }).joinToString("&")
|
|
return get<ReportList>(if (asked.isEmpty()) "/reports" else "/reports?" + asked).reports
|
|
}
|
|
|
|
/** How many reports are unread: the drawer's badge. */
|
|
suspend fun unreadReports(): Int = get<ReportList>("/reports?unread=1").unreadCount
|
|
|
|
/** One report with its body. Read as the report itself, or as `{report: …}` around it. */
|
|
suspend fun report(id: String): Report {
|
|
val answer = get<JsonObject>("/reports/${segment(id)}")
|
|
return LembasJson.decodeFromJsonElement(Report.serializer(), answer["report"] as? JsonObject ?: answer)
|
|
}
|
|
|
|
suspend fun readReport(id: String) = empty(authed("$v2/reports/${segment(id)}/read").post("{}".toRequestBody(JSON)).build())
|
|
|
|
suspend fun deleteReport(id: String) = empty(authed("$v2/reports/${segment(id)}").delete().build())
|
|
|
|
/** Continue the report as a conversation: the chat it is in, which stays under Reports. */
|
|
suspend fun replyToReport(id: String): String? = send<ReportReply>("POST", "/reports/${segment(id)}/reply", null).chatId
|
|
|
|
suspend fun pauseSchedule(id: String, paused: Boolean): Schedule =
|
|
send<ScheduleEnvelope>("POST", "/schedules/${segment(id)}/" + if (paused) "pause" else "resume", null).schedule
|
|
|
|
/** Run it now (202); the next scheduled run is not used up by this one. */
|
|
suspend fun runScheduleNow(id: String): ScheduleRun = send<RunEnvelope>("POST", "/schedules/${segment(id)}/run", null).run
|
|
|
|
/** Delete it; [keepChat] keeps the chat its results went to. */
|
|
suspend fun deleteSchedule(id: String, keepChat: Boolean = true) = empty(authed("$v2/schedules/${segment(id)}?keep_chat=$keepChat").delete().build())
|
|
|
|
/** The models scheduled work may run on, in the order they are tried, and which are free. */
|
|
suspend fun schedulingModels(): SchedulingModels = get("/schedules/models")
|
|
|
|
/** The person's narrowing of that list ([ids] empty: all of them). */
|
|
suspend fun chooseSchedulingModels(ids: List<String>): SchedulingModels =
|
|
send("PUT", "/schedules/models", buildJsonObject { put("models", JsonArray(ids.map { JsonPrimitive(it) })) })
|
|
|
|
/** The person's events route: a `schedules` frame with the whole list whenever it changes. */
|
|
fun events(): Request = authed("$v2/events").header("Accept", "text/event-stream").build()
|
|
|
|
// --- Model pictures --------------------------------------------------------------------------
|
|
|
|
/**
|
|
* A model's picture, with the token: only a path under the instance's own
|
|
* `/api/v2/models/images/` is fetched -- a list that named anything else, another host
|
|
* included, gets the initial instead. At most [IMAGE_MAX_BYTES]; null when there is none.
|
|
*/
|
|
suspend fun modelImage(path: String): ByteArray? = withContext(Dispatchers.IO) {
|
|
val url = modelImageUrl(base, path) ?: return@withContext null
|
|
http.newCall(authed(url).header("Accept", "image/*").get().build()).await().use {
|
|
if (!it.isSuccessful) return@use null
|
|
val body = it.body ?: return@use null
|
|
if (body.contentLength() > IMAGE_MAX_BYTES) return@use null
|
|
val bytes = body.source().use { source ->
|
|
source.request(IMAGE_MAX_BYTES + 1)
|
|
source.buffer.readByteArray(minOf(source.buffer.size, IMAGE_MAX_BYTES + 1))
|
|
}
|
|
bytes.takeIf { b -> b.size <= IMAGE_MAX_BYTES }
|
|
}
|
|
}
|
|
|
|
// --- Attachments -------------------------------------------------------------------------
|
|
suspend fun upload(name: String, mime: String, bytes: ByteArray, chatId: String? = null): Attachment {
|
|
val body = MultipartBody.Builder().setType(MultipartBody.FORM)
|
|
.addFormDataPart("file", name, bytes.toRequestBody(mime.toMediaType()))
|
|
.build()
|
|
val url = "$v2/attachments" + (chatId?.let { "?chat=$it" } ?: "")
|
|
return call(authed(url).post(body).build(), AttachmentEnvelope.serializer()).attachment
|
|
}
|
|
|
|
suspend fun attachmentBytes(id: String): ByteArray = withContext(Dispatchers.IO) {
|
|
http.newCall(authed("$v2/attachments/$id").get().build()).await().use {
|
|
if (!it.isSuccessful) throw ApiException(it.code, detail(it))
|
|
it.body!!.bytes()
|
|
}
|
|
}
|
|
|
|
// --- What a `show` card opens -------------------------------------------------------------
|
|
|
|
/**
|
|
* The text of a file a `show` card named, as the chat sees it now:
|
|
* `GET /api/v2/chats/{chat}/show?node=<node_id>&version=<version_id>` for a file in the tree,
|
|
* `?shown=<shown_id>` for the copy a linked device sent ([ShowCard.query]). The server rebuilds
|
|
* the chat's view and checks the path again, so a grant taken away since takes the file away
|
|
* too (404, in the server's words). `text/plain; charset=utf-8`, at most 1 MB: above it a 413,
|
|
* and a 415 for a file that is not text. Always plain text -- an HTML file is its source, and
|
|
* the app never asks for a page to render.
|
|
*/
|
|
suspend fun shownText(chatId: String, show: ShowCard): String = withContext(Dispatchers.IO) {
|
|
val url = "$v2/chats/$chatId/show".toHttpUrl().newBuilder()
|
|
.apply { show.query.forEach { (k, v) -> addQueryParameter(k, v) } }
|
|
.build()
|
|
http.newCall(authed(url.toString()).header("Accept", "text/plain").get().build()).await().use {
|
|
if (!it.isSuccessful) throw ApiException(it.code, detail(it))
|
|
val body = it.body!!
|
|
// The server shows at most 1 MB; anything much larger is not a file it meant.
|
|
if (body.contentLength() > SHOWN_MAX_BYTES) throw ApiException(413, "")
|
|
val bytes = body.source().use { source ->
|
|
source.request(SHOWN_MAX_BYTES + 1)
|
|
source.buffer.readByteArray(minOf(source.buffer.size, SHOWN_MAX_BYTES + 1))
|
|
}
|
|
if (bytes.size > SHOWN_MAX_BYTES) throw ApiException(413, "")
|
|
bytes.toString(Charsets.UTF_8)
|
|
}
|
|
}
|
|
|
|
// --- The person's files ------------------------------------------------------------------
|
|
|
|
/** A directory, as the person may see it (no chat's grants): `GET /api/v2/files?path=`. */
|
|
suspend fun files(path: String = "/"): FileListing {
|
|
val url = "$v2/files".toHttpUrl().newBuilder().addQueryParameter("path", path).build()
|
|
return call(authed(url.toString()).get().build(), FileListing.serializer())
|
|
}
|
|
|
|
/**
|
|
* A file's text: `GET /api/v2/files/content?path=`. A file the server will not hand over as
|
|
* text (not text, over 1 MB) is not an error: it comes back with `withheld` saying why.
|
|
*/
|
|
suspend fun fileContent(path: String): FileContent {
|
|
val url = "$v2/files/content".toHttpUrl().newBuilder().addQueryParameter("path", path).build()
|
|
return call(authed(url.toString()).get().build(), FileContent.serializer())
|
|
}
|
|
|
|
/**
|
|
* Where the file with node id [id] is now, after any rename or move: `GET /api/v2/files/node`.
|
|
* A file the person may not read and an id that names nothing are the same 404; an instance
|
|
* from before this route answers a 404 or a 405 of its own ([eu.llembas.android.ui.files.noSuchRoute]).
|
|
*/
|
|
suspend fun fileNode(id: String): FileNode = call(authed(filesUrl("/node", "id" to id)).get().build(), FileNode.serializer())
|
|
|
|
// --- The file manager's writes, the trash, versions and bytes ---------------------------------
|
|
// Each write answers the listing of the directory it changed; a refusal is the tree's own
|
|
// sentence (400), a path that cannot be read a 404, and both come back as an ApiException.
|
|
|
|
private fun filesUrl(path: String, vararg query: Pair<String, String?>): String = "$v2/files$path".toHttpUrl().newBuilder()
|
|
.apply { query.forEach { (name, value) -> if (value != null) addQueryParameter(name, value) } }
|
|
.build()
|
|
.toString()
|
|
|
|
suspend fun makeFolder(dir: String, name: String): FileListing = send(
|
|
"POST",
|
|
"/files/mkdir",
|
|
buildJsonObject {
|
|
put("path", dir)
|
|
put("name", name)
|
|
},
|
|
)
|
|
|
|
suspend fun renameFile(path: String, name: String): FileListing = send(
|
|
"POST",
|
|
"/files/rename",
|
|
buildJsonObject {
|
|
put("path", path)
|
|
put("name", name)
|
|
},
|
|
)
|
|
|
|
/** Copy [path] into the directory [to]; the answer's `copied` says what the copy is called. */
|
|
suspend fun copyFile(path: String, to: String, name: String? = null): FileListing = send(
|
|
"POST",
|
|
"/files/copy",
|
|
buildJsonObject {
|
|
put("path", path)
|
|
put("to", to)
|
|
name?.let { put("name", it) }
|
|
},
|
|
)
|
|
|
|
/**
|
|
* Move or copy [paths] into the directory [to], or delete them (to the trash): `op` is
|
|
* `move`, `copy` or `delete`. Each path is done by itself, so the answer is read for what
|
|
* failed even though the request succeeded.
|
|
*/
|
|
suspend fun batchFiles(op: String, paths: List<String>, to: String? = null): BatchAnswer = send(
|
|
"POST",
|
|
"/files/batch",
|
|
buildJsonObject {
|
|
put("op", op)
|
|
put("paths", JsonArray(paths.map { JsonPrimitive(it) }))
|
|
to?.let { put("to", it) }
|
|
},
|
|
)
|
|
|
|
/**
|
|
* 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. 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, 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)
|
|
}
|
|
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 new, empty text file called [name] in the directory [dir]; its path. Never over what
|
|
* is there: `create` has the instance refuse a taken name ([FileExists], its sentence), and
|
|
* because an instance from before `create` ignores the word and would empty the file, the
|
|
* directory is read first and a name it holds is refused here, with nothing sent.
|
|
*/
|
|
suspend fun newFile(dir: String, name: String): String {
|
|
val path = FileKinds.child(dir, name)
|
|
if (files(dir).entries.any { it.name == name.trim() || it.path == path }) throw FileExists("")
|
|
saveFile(path, "", create = true)
|
|
return path
|
|
}
|
|
|
|
/** 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())
|
|
}
|
|
// 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")
|
|
|
|
suspend fun restoreTrashed(id: String): TrashList = send("POST", "/files/restore", buildJsonObject { put("id", id) })
|
|
|
|
/** Remove for good: the one thing named, or with no [id] everything in the trash. */
|
|
suspend fun removeTrashed(id: String? = null): TrashList = call(authed(filesUrl("/trash", "id" to id)).delete().build(), TrashList.serializer())
|
|
|
|
suspend fun fileVersions(path: String): FileVersions = call(authed(filesUrl("/versions", "path" to path)).get().build(), FileVersions.serializer())
|
|
|
|
/** Make an older version the file again, as a new version: nothing is lost. */
|
|
suspend fun restoreVersion(path: String, version: String): FileVersions = send(
|
|
"POST",
|
|
"/files/versions/restore",
|
|
buildJsonObject {
|
|
put("path", path)
|
|
put("version", version)
|
|
},
|
|
)
|
|
|
|
/**
|
|
* Upload one file into the directory [dir], streamed: [body] writes the file's bytes as they
|
|
* are read, so a large file is never held in memory. A file over the instance's limit is a
|
|
* 413 whose sentence names it.
|
|
*/
|
|
suspend fun uploadFile(dir: String, name: String, body: RequestBody): FileListing {
|
|
val form = MultipartBody.Builder().setType(MultipartBody.FORM).addFormDataPart("files", name, body).build()
|
|
return call(authed(filesUrl("/upload", "path" to dir)).post(form).build(), FileListing.serializer())
|
|
}
|
|
|
|
/**
|
|
* 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 = 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}") } }
|
|
.get()
|
|
.build()
|
|
|
|
/** The request for [paths] (files and folders) as one zip. */
|
|
fun zipFiles(paths: List<String>): Request = authed("$v2/files/zip")
|
|
.header("Accept", "*/*")
|
|
.post(buildJsonObject { put("paths", JsonArray(paths.map { JsonPrimitive(it) })) }.toString().toRequestBody(JSON))
|
|
.build()
|
|
|
|
/**
|
|
* Run [request] and copy what it answers into [out] as it comes, saying how far it is
|
|
* ([progress]: bytes so far, and the total when the server said one, else -1). At most
|
|
* [most] bytes are taken: more than that is refused as a 413, with nothing more read.
|
|
*/
|
|
suspend fun download(request: Request, out: OutputStream, most: Long = Long.MAX_VALUE, progress: (done: Long, total: Long) -> Unit = { _, _ -> }): Long =
|
|
withContext(Dispatchers.IO) {
|
|
val call = http.newCall(request)
|
|
val finished = java.util.concurrent.atomic.AtomicBoolean(false)
|
|
// A read that waits for the server does not hear that the transfer was given up:
|
|
// the call is cancelled from beside it, which ends the read at once.
|
|
val watch = launch(start = CoroutineStart.UNDISPATCHED) {
|
|
try {
|
|
awaitCancellation()
|
|
} finally {
|
|
if (!finished.get()) call.cancel()
|
|
}
|
|
}
|
|
try {
|
|
call.await().use { response ->
|
|
if (!response.isSuccessful) throw ApiException(response.code, detail(response))
|
|
val body = response.body ?: throw ApiException(response.code, "")
|
|
val total = body.contentLength()
|
|
if (total > most) throw ApiException(413, "")
|
|
val buffer = ByteArray(64 * 1024)
|
|
var done = 0L
|
|
body.byteStream().use { stream ->
|
|
while (true) {
|
|
ensureActive()
|
|
val n = stream.read(buffer)
|
|
if (n < 0) break
|
|
done += n
|
|
if (done > most) throw ApiException(413, "")
|
|
out.write(buffer, 0, n)
|
|
progress(done, total)
|
|
}
|
|
}
|
|
out.flush()
|
|
done
|
|
}
|
|
} catch (e: IOException) {
|
|
// The read a cancelled call ends with is the cancelling, not a failure of the network.
|
|
ensureActive()
|
|
throw e
|
|
} finally {
|
|
// Ended by itself: the watcher is let go, and leaves the finished call alone.
|
|
finished.set(true)
|
|
watch.cancel()
|
|
}
|
|
}
|
|
|
|
/**
|
|
* The bytes `[from, to]` of a file, for a player or a table's first rows: a `Range` request,
|
|
* 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 = 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
|
|
response.body!!.source().use { source ->
|
|
source.request(want)
|
|
source.buffer.readByteArray(minOf(source.buffer.size, want))
|
|
}
|
|
}
|
|
|
|
/** A file of the tree in the web UI's own viewer (`/files/view`), for what the app does not draw. */
|
|
fun webFile(path: String): String = "$base/files/view".toHttpUrl().newBuilder().addQueryParameter("path", path).build().toString()
|
|
|
|
/** The same file in the web UI's viewer, which renders HTML in its sealed frame. */
|
|
fun webViewer(chatId: String, show: ShowCard): String = "$base/chat/$chatId/show".toHttpUrl().newBuilder()
|
|
.apply { show.query.forEach { (k, v) -> addQueryParameter(k, v) } }
|
|
.apply { if (show.line > 0) addQueryParameter("line", show.line.toString()) }
|
|
.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")
|
|
|
|
suspend fun registerPush(endpoint: String, p256dh: String, auth: String) {
|
|
val body = buildJsonObject {
|
|
put("endpoint", endpoint)
|
|
put("p256dh", p256dh)
|
|
put("auth", auth)
|
|
}
|
|
empty(authed("$v2/push").post(body.toString().toRequestBody(JSON)).build())
|
|
}
|
|
|
|
suspend fun forgetPush() = empty(authed("$v2/push").delete().build())
|
|
|
|
// --- Voice (/v1, the `models` scope) -----------------------------------------------------
|
|
|
|
/**
|
|
* Write a recording down. [media] says which chat it is for, so that the chat's model's
|
|
* connection may serve it with its own speech model (server 2.0.0-beta.15); a server before
|
|
* that reads only the fields it knows and answers from its one endpoint.
|
|
*/
|
|
suspend fun transcribe(wav: ByteArray, language: String? = null, media: MediaFor = MediaFor.DEFAULT): Heard = withContext(Dispatchers.IO) {
|
|
val body = MultipartBody.Builder().setType(MultipartBody.FORM)
|
|
.addFormDataPart("file", "speech.wav", wav.toRequestBody("audio/wav".toMediaType()))
|
|
.apply { transcriptionFields(language, media).forEach { (name, value) -> addFormDataPart(name, value) } }
|
|
.build()
|
|
http.newCall(authed("$base/v1/audio/transcriptions").post(body).build()).await().use {
|
|
if (!it.isSuccessful) throw ApiException(it.code, detail(it))
|
|
Heard(LembasJson.decodeFromString(Transcript.serializer(), it.body!!.string()).text, fallbackSource(it))
|
|
}
|
|
}
|
|
|
|
/** [text] as speech, for the chat [media] names (see [transcribe]). */
|
|
suspend fun speech(text: String, media: MediaFor = MediaFor.DEFAULT): Spoken = withContext(Dispatchers.IO) {
|
|
http.newCall(authed("$base/v1/audio/speech").post(speechBody(text, media).toString().toRequestBody(JSON)).build()).await().use {
|
|
if (!it.isSuccessful) throw ApiException(it.code, detail(it))
|
|
Spoken(it.body!!.bytes(), fallbackSource(it))
|
|
}
|
|
}
|
|
|
|
fun streamRequest(chatId: String, messageId: String): Request =
|
|
authed("$v2/chats/$chatId/messages/$messageId/stream").header("Accept", "text/event-stream").build()
|
|
|
|
companion object {
|
|
/**
|
|
* What this app can do, sent with every request that can start a reply (spec 3.6.0):
|
|
* the phone carries out `phone_action` calls the person confirms here, so the chat is
|
|
* offered the tool -- and a reply for the phone is one without pages to draw.
|
|
*/
|
|
private val CAPABILITIES = JsonArray(listOf(JsonPrimitive("phone_actions")))
|
|
|
|
/** The body of a request that says nothing else: the declaration alone. */
|
|
private val DECLARED = JsonObject(mapOf("client" to CAPABILITIES))
|
|
|
|
/** 1 MB, the server's own limit on a shown file, with room for a little more. */
|
|
const val SHOWN_MAX_BYTES = 1_100_000L
|
|
|
|
/** The transcription's form fields beside the file: the language, and which chat. */
|
|
fun transcriptionFields(language: String?, media: MediaFor): List<Pair<String, String>> = buildList {
|
|
language?.let { add("language" to it) }
|
|
media.chatId?.let { add("chat_id" to it) }
|
|
media.chatModel?.let { add("chat_model" to it) }
|
|
}
|
|
|
|
/** The body of a speech request: the words, the format, and which chat. */
|
|
fun speechBody(text: String, media: MediaFor): JsonObject = buildJsonObject {
|
|
put("input", text.take(20_000))
|
|
put("response_format", "mp3")
|
|
media.chatId?.let { put("chat_id", it) }
|
|
media.chatModel?.let { put("chat_model", it) }
|
|
}
|
|
|
|
/**
|
|
* The source that answered in place of the chat's own (`X-Lembas-Fallback`), by its name
|
|
* (`X-Lembas-Source`, percent-encoded: a header is Latin-1); null when the one expected
|
|
* answered, and from a server that says neither.
|
|
*/
|
|
fun fallbackSource(fallback: String?, source: String?): String? {
|
|
if (fallback.isNullOrBlank() || fallback == "0" || source.isNullOrBlank()) return null
|
|
return runCatching { java.net.URLDecoder.decode(source.replace("+", "%2B"), "UTF-8") }.getOrDefault(source).ifBlank { null }
|
|
}
|
|
|
|
private fun fallbackSource(response: Response): String? = fallbackSource(response.header("X-Lembas-Fallback"), response.header("X-Lembas-Source"))
|
|
|
|
fun emptyBody(): RequestBody = ByteArray(0).toRequestBody(null)
|
|
|
|
/** A model's picture is small; anything larger is not one. */
|
|
const val IMAGE_MAX_BYTES = 2_000_000L
|
|
|
|
private const val IMAGE_PATH = "/api/v2/models/images/"
|
|
|
|
/** The picture's URL on [base], or null for a path that is not one of the instance's pictures. */
|
|
fun modelImageUrl(base: String, path: String?): String? {
|
|
if (path.isNullOrBlank() || !path.startsWith(IMAGE_PATH)) return null
|
|
val name = path.removePrefix(IMAGE_PATH)
|
|
if (name.isEmpty() || !name.all { it.isLetterOrDigit() || it == '.' || it == '_' || it == '-' } || name.startsWith(".")) return null
|
|
return "$base$IMAGE_PATH$name"
|
|
}
|
|
|
|
/** One path segment, escaped: an agent's name or a job's id is a model's choice. */
|
|
fun segment(value: String): String = java.net.URLEncoder.encode(value, "UTF-8").replace("+", "%20")
|
|
}
|
|
}
|