|
| 1 | +package com.zawwar.zhub |
| 2 | + |
| 3 | +import kotlinx.coroutines.* |
| 4 | +import kotlinx.coroutines.flow.MutableSharedFlow |
| 5 | +import kotlinx.coroutines.flow.SharedFlow |
| 6 | +import kotlinx.coroutines.flow.asSharedFlow |
| 7 | +import kotlinx.serialization.json.JsonObject |
| 8 | +import kotlinx.serialization.json.JsonPrimitive |
| 9 | +import kotlinx.serialization.json.buildJsonObject |
| 10 | +import kotlinx.serialization.json.jsonPrimitive |
| 11 | +import okhttp3.* |
| 12 | +import java.util.concurrent.ConcurrentHashMap |
| 13 | +import java.util.concurrent.TimeUnit |
| 14 | + |
| 15 | +/** |
| 16 | + * Capability handler. Receives a JSON-shaped args object, returns a JSON-shaped result. |
| 17 | + * Suspending so the implementation can await native APIs (e.g., Termux IPC, intent |
| 18 | + * dispatch on Android, network calls, etc). |
| 19 | + */ |
| 20 | +typealias CapabilityHandler = suspend (JsonObject) -> JsonObject |
| 21 | + |
| 22 | +/** |
| 23 | + * Bidirectional zhub connection from a client (Loki, Telegram bot, web chat, ...) |
| 24 | + * to a published AI. Connects to `<hubUrl>/ws/connect`, registers the client's |
| 25 | + * capability manifest, then: |
| 26 | + * - Allows the client to call `chat(...)` on the AI through the hub. |
| 27 | + * - Listens for invoke-request envelopes and dispatches them to registered handlers. |
| 28 | + * |
| 29 | + * Lifecycle: |
| 30 | + * val conn = ZhubConnection.connect(...) |
| 31 | + * conn.events.collect { ... } // optional: observe lifecycle |
| 32 | + * val response = conn.chat(messages) // talk to the AI |
| 33 | + * conn.close() // graceful shutdown |
| 34 | + */ |
| 35 | +class ZhubConnection private constructor( |
| 36 | + val aiName: String, |
| 37 | + val apiKey: String, |
| 38 | + val hubUrl: String, |
| 39 | + val clientManifest: Manifest, |
| 40 | + private val capabilities: Map<String, Pair<JsonObject, CapabilityHandler>>, |
| 41 | + private val scope: CoroutineScope, |
| 42 | +) { |
| 43 | + private val client = OkHttpClient.Builder() |
| 44 | + .pingInterval(20, TimeUnit.SECONDS) |
| 45 | + .readTimeout(0, TimeUnit.MILLISECONDS) |
| 46 | + .build() |
| 47 | + |
| 48 | + private var webSocket: WebSocket? = null |
| 49 | + private val pending = ConcurrentHashMap<String, CompletableDeferred<JsonObject>>() |
| 50 | + private val _events = MutableSharedFlow<ConnectionEvent>(replay = 0, extraBufferCapacity = 64) |
| 51 | + val events: SharedFlow<ConnectionEvent> = _events.asSharedFlow() |
| 52 | + |
| 53 | + private fun start() { |
| 54 | + val wsUrl = toWsUrl(hubUrl, "/ws/connect") |
| 55 | + val request = Request.Builder().url(wsUrl).build() |
| 56 | + webSocket = client.newWebSocket(request, object : WebSocketListener() { |
| 57 | + override fun onOpen(ws: WebSocket, response: Response) { |
| 58 | + ws.send(registerConnectionEnvelope(aiName, apiKey, clientManifest).toJson()) |
| 59 | + scope.launch { _events.emit(ConnectionEvent.Opened) } |
| 60 | + } |
| 61 | + |
| 62 | + override fun onMessage(ws: WebSocket, text: String) { |
| 63 | + scope.launch { handleMessage(ws, text) } |
| 64 | + } |
| 65 | + |
| 66 | + override fun onFailure(ws: WebSocket, t: Throwable, response: Response?) { |
| 67 | + scope.launch { _events.emit(ConnectionEvent.Failed(t)) } |
| 68 | + } |
| 69 | + |
| 70 | + override fun onClosing(ws: WebSocket, code: Int, reason: String) { |
| 71 | + ws.close(code, reason) |
| 72 | + } |
| 73 | + |
| 74 | + override fun onClosed(ws: WebSocket, code: Int, reason: String) { |
| 75 | + scope.launch { _events.emit(ConnectionEvent.Closed(code, reason)) } |
| 76 | + } |
| 77 | + }) |
| 78 | + } |
| 79 | + |
| 80 | + private suspend fun handleMessage(ws: WebSocket, text: String) { |
| 81 | + val env = try { |
| 82 | + Envelope.fromJson(text) |
| 83 | + } catch (t: Throwable) { |
| 84 | + _events.emit(ConnectionEvent.MalformedPayload(text, t)) |
| 85 | + return |
| 86 | + } |
| 87 | + when (env.type) { |
| 88 | + "registered" -> _events.emit(ConnectionEvent.Registered) |
| 89 | + "chat-response" -> { |
| 90 | + pending.remove(env.request_id)?.complete(env.payload) |
| 91 | + } |
| 92 | + "invoke-request" -> { |
| 93 | + val capability = env.payload["capability"]?.jsonPrimitive?.content ?: return |
| 94 | + val args = env.payload["args"] as? JsonObject ?: JsonObject(emptyMap()) |
| 95 | + val handler = capabilities[capability]?.second |
| 96 | + if (handler == null) { |
| 97 | + ws.send(invokeResultEnvelope(env.request_id, false, error = "capability '$capability' not exposed").toJson()) |
| 98 | + return |
| 99 | + } |
| 100 | + try { |
| 101 | + val result = handler(args) |
| 102 | + ws.send(invokeResultEnvelope(env.request_id, true, result = result).toJson()) |
| 103 | + } catch (t: Throwable) { |
| 104 | + ws.send(invokeResultEnvelope(env.request_id, false, error = t.message ?: t.javaClass.simpleName).toJson()) |
| 105 | + } |
| 106 | + } |
| 107 | + "error" -> { |
| 108 | + _events.emit(ConnectionEvent.HubError(env.payload.toString())) |
| 109 | + val code = env.payload["code"]?.jsonPrimitive?.content |
| 110 | + if (code == "register_failed") { |
| 111 | + pending.values.forEach { it.completeExceptionally(AuthException(env.payload.toString())) } |
| 112 | + pending.clear() |
| 113 | + } |
| 114 | + } |
| 115 | + "ping" -> { |
| 116 | + ws.send(Envelope(type = "pong", request_id = env.request_id).toJson()) |
| 117 | + } |
| 118 | + } |
| 119 | + } |
| 120 | + |
| 121 | + /** Send a chat request to the AI through the hub. Suspending. Times out at [timeoutMs]. */ |
| 122 | + suspend fun chat( |
| 123 | + messages: List<Map<String, String>>, |
| 124 | + model: String = "default", |
| 125 | + temperature: Double = 0.4, |
| 126 | + maxTokens: Int = 4096, |
| 127 | + timeoutMs: Long = 60_000, |
| 128 | + ): String = withTimeout(timeoutMs) { |
| 129 | + val ws = webSocket ?: throw ZhubConnectionException("not connected") |
| 130 | + val env = chatRequestEnvelope(messages, model, temperature, maxTokens) |
| 131 | + val deferred = CompletableDeferred<JsonObject>() |
| 132 | + pending[env.request_id] = deferred |
| 133 | + try { |
| 134 | + ws.send(env.toJson()) |
| 135 | + val payload = deferred.await() |
| 136 | + payload["text"]?.jsonPrimitive?.content ?: "" |
| 137 | + } finally { |
| 138 | + pending.remove(env.request_id) |
| 139 | + } |
| 140 | + } |
| 141 | + |
| 142 | + fun close() { |
| 143 | + webSocket?.close(1000, "client closing") |
| 144 | + client.dispatcher.executorService.shutdown() |
| 145 | + } |
| 146 | + |
| 147 | + sealed class ConnectionEvent { |
| 148 | + object Opened : ConnectionEvent() |
| 149 | + object Registered : ConnectionEvent() |
| 150 | + data class Closed(val code: Int, val reason: String) : ConnectionEvent() |
| 151 | + data class Failed(val cause: Throwable) : ConnectionEvent() |
| 152 | + data class HubError(val payload: String) : ConnectionEvent() |
| 153 | + data class MalformedPayload(val raw: String, val cause: Throwable) : ConnectionEvent() |
| 154 | + } |
| 155 | + |
| 156 | + companion object { |
| 157 | + /** |
| 158 | + * Connect a client to a published AI and expose capabilities back to it. |
| 159 | + * |
| 160 | + * @param aiName The AI's registered name on the hub. |
| 161 | + * @param apiKey The bearer key returned to the publisher at register time. |
| 162 | + * @param hubUrl Hub URL (http://, https://, ws://, or wss://). |
| 163 | + * @param description Human-readable description of this client. |
| 164 | + * @param operator Who runs this client. |
| 165 | + * @param capabilities Map of capabilityName -> (jsonSchemaForArgs, handler). |
| 166 | + * @param scope Coroutine scope. Defaults to Dispatchers.Default + a SupervisorJob. |
| 167 | + */ |
| 168 | + fun connect( |
| 169 | + aiName: String, |
| 170 | + apiKey: String, |
| 171 | + hubUrl: String = "ws://localhost:8080", |
| 172 | + description: String = "", |
| 173 | + operator: String = "", |
| 174 | + capabilities: Map<String, Pair<JsonObject, CapabilityHandler>>, |
| 175 | + scope: CoroutineScope = CoroutineScope(Dispatchers.Default + SupervisorJob()), |
| 176 | + ): ZhubConnection { |
| 177 | + val capList = capabilities.map { (name, pair) -> |
| 178 | + Capability(name = name, description = "", schema = pair.first) |
| 179 | + } |
| 180 | + val manifest = Manifest( |
| 181 | + name = "$aiName-client", |
| 182 | + description = description.ifEmpty { "client of $aiName" }, |
| 183 | + operator = operator, |
| 184 | + capabilities = capList, |
| 185 | + ) |
| 186 | + val conn = ZhubConnection( |
| 187 | + aiName = aiName, |
| 188 | + apiKey = apiKey, |
| 189 | + hubUrl = hubUrl, |
| 190 | + clientManifest = manifest, |
| 191 | + capabilities = capabilities, |
| 192 | + scope = scope, |
| 193 | + ) |
| 194 | + conn.start() |
| 195 | + return conn |
| 196 | + } |
| 197 | + |
| 198 | + private fun toWsUrl(input: String, path: String): String { |
| 199 | + val replaced = when { |
| 200 | + input.startsWith("https://") -> "wss://" + input.removePrefix("https://") |
| 201 | + input.startsWith("http://") -> "ws://" + input.removePrefix("http://") |
| 202 | + else -> input |
| 203 | + } |
| 204 | + return if (replaced.endsWith("/")) replaced + path.removePrefix("/") else replaced + path |
| 205 | + } |
| 206 | + } |
| 207 | +} |
| 208 | + |
| 209 | +/** Convenience top-level for parity with Python's `from zhub import connect`. */ |
| 210 | +fun connect( |
| 211 | + aiName: String, |
| 212 | + apiKey: String, |
| 213 | + hubUrl: String = "ws://localhost:8080", |
| 214 | + description: String = "", |
| 215 | + operator: String = "", |
| 216 | + capabilities: Map<String, Pair<JsonObject, CapabilityHandler>>, |
| 217 | + scope: CoroutineScope = CoroutineScope(Dispatchers.Default + SupervisorJob()), |
| 218 | +): ZhubConnection = ZhubConnection.connect(aiName, apiKey, hubUrl, description, operator, capabilities, scope) |
0 commit comments